pi-goal-delegate 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +89 -0
- package/README.md +391 -296
- package/package.json +2 -2
- package/skills/delegate/SKILL.md +128 -44
- package/src/command.ts +88 -27
- package/src/contract.ts +9 -0
- package/src/doctor.ts +385 -0
- package/src/index.ts +426 -303
- package/src/registry.ts +31 -8
- package/src/result-schema.ts +23 -12
- package/src/retention.ts +87 -26
- package/src/run.ts +20 -11
- package/src/spawn.ts +1 -1
- package/src/verify.ts +13 -0
package/src/index.ts
CHANGED
|
@@ -1,11 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* delegate -
|
|
2
|
+
* delegate - one goal, one fresh child agent, one verified outcome.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Four primitives on the same seam pi-async-shell uses:
|
|
5
5
|
*
|
|
6
|
-
* delegate_start
|
|
7
|
-
*
|
|
8
|
-
* delegate_await narrow the wait for this tool call (<= 50s, never cancels)
|
|
6
|
+
* delegate_start run one goal in a child and return its verified outcome
|
|
7
|
+
* delegate_status list this session's runs, or wait for named ones
|
|
9
8
|
* delegate_send hand a running child one message, read at its next turn
|
|
10
9
|
* delegate_cancel ladder + containment verdict
|
|
11
10
|
* (child side) delegate_complete, delegate_blocked
|
|
@@ -14,9 +13,17 @@
|
|
|
14
13
|
* extension owns the contract with the child: what goal, what evidence, what
|
|
15
14
|
* budget, and how it ends. It supervises no other process.
|
|
16
15
|
*
|
|
16
|
+
* The wait is inline by default. Every recorded delegation ran longer than a
|
|
17
|
+
* minute, so a bounded wait in tens of seconds could never report a result and
|
|
18
|
+
* pushed callers into cross-turn polling; under pi-goal that polling was a live
|
|
19
|
+
* continuation loop. `wait: false` still returns a handle in about a second for
|
|
20
|
+
* a caller that has other work to do, and the detached supervisor means an
|
|
21
|
+
* interrupted wait never interrupts the child.
|
|
22
|
+
*
|
|
17
23
|
* Layout:
|
|
18
24
|
* index.ts tool and command registration (discovered by Pi)
|
|
19
25
|
* command.ts /delegate for the TUI
|
|
26
|
+
* doctor.ts the installation and health self-check
|
|
20
27
|
* registry.ts handles, claims, coalesced completion, admission gate, /reload handoff
|
|
21
28
|
* run.ts admission, live tail, cancellation ladder, sealed outcome
|
|
22
29
|
* spawn.ts run directory layout, child argv, detached supervisor spawn
|
|
@@ -27,7 +34,7 @@
|
|
|
27
34
|
* verify.ts the parent's own check on a completion claim
|
|
28
35
|
* worktree.ts a checkout of its own for a child that asks for one
|
|
29
36
|
* contract.ts statuses, budgets, breakers, prompt text shared by both sides
|
|
30
|
-
* retention.ts reclaim run records by age, count and bytes
|
|
37
|
+
* retention.ts reclaim run records by age, count and bytes, and report the plan
|
|
31
38
|
*
|
|
32
39
|
* Artifacts per run: <agentDir>/delegate/<runId>/{spec,meta,state,result,outcome}.json
|
|
33
40
|
* plus child.jsonl, control.jsonl, child.log, inbox.jsonl, owner.lock,
|
|
@@ -48,99 +55,135 @@ import {
|
|
|
48
55
|
MAX_MAX_DEPTH,
|
|
49
56
|
MAX_MAX_TURNS,
|
|
50
57
|
MAX_TIMEOUT_MINUTES,
|
|
58
|
+
MAX_WAIT_MS,
|
|
51
59
|
SPEC_ENV,
|
|
52
60
|
type RunSpec,
|
|
53
61
|
} from "./contract.ts";
|
|
62
|
+
import { runDoctor, startupWarning, type DoctorReport } from "./doctor.ts";
|
|
54
63
|
import {
|
|
55
64
|
acquireRegistry,
|
|
56
65
|
discardHandoff,
|
|
57
66
|
forgetRegistry,
|
|
58
67
|
maxCostUsd,
|
|
68
|
+
maxLive,
|
|
59
69
|
publishHandoff,
|
|
60
70
|
type RegistryHost,
|
|
61
71
|
} from "./registry.ts";
|
|
62
72
|
import type { RunRegistry } from "./registry.ts";
|
|
63
73
|
import { formatOutcome, type RunHandle, type RunOutcome } from "./run.ts";
|
|
74
|
+
import { scanRetention } from "./retention.ts";
|
|
64
75
|
import { auditResultSchema } from "./result-schema.ts";
|
|
65
|
-
import { readJson } from "./spawn.ts";
|
|
76
|
+
import { delegateRoot, readJson } from "./spawn.ts";
|
|
66
77
|
import { gitAvailable } from "./worktree.ts";
|
|
67
78
|
|
|
68
79
|
const STATUS_KEY = "delegate";
|
|
69
|
-
const DEFAULT_INLINE_SETTLE_MS = 1000;
|
|
70
|
-
const MAX_INLINE_SETTLE_MS = 10_000;
|
|
71
|
-
|
|
72
|
-
const usageSchema = Type.Object({
|
|
73
|
-
input: Type.Number(),
|
|
74
|
-
output: Type.Number(),
|
|
75
|
-
cacheRead: Type.Number(),
|
|
76
|
-
cacheWrite: Type.Number(),
|
|
77
|
-
totalTokens: Type.Number(),
|
|
78
|
-
cost: Type.Number(),
|
|
79
|
-
});
|
|
80
80
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
81
|
+
/**
|
|
82
|
+
* The knobs that are not worth the decision surface of a top-level parameter.
|
|
83
|
+
*
|
|
84
|
+
* They all exist, they all matter to somebody, and none of them changes the
|
|
85
|
+
* answer to "should I delegate". One optional object keeps the primary call at
|
|
86
|
+
* seven inputs while keeping every capability.
|
|
87
|
+
*/
|
|
88
|
+
const OPTION_KEYS = [
|
|
89
|
+
"cwd",
|
|
90
|
+
"isolated",
|
|
91
|
+
"maxCostUsd",
|
|
92
|
+
"maxDepth",
|
|
93
|
+
"maxTurns",
|
|
94
|
+
"model",
|
|
95
|
+
"resultSchema",
|
|
96
|
+
"resumeFrom",
|
|
97
|
+
"scope",
|
|
98
|
+
"timeoutMinutes",
|
|
99
|
+
"tools",
|
|
100
|
+
] as const;
|
|
89
101
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
102
|
+
interface StartOptionsInput {
|
|
103
|
+
maxTurns?: number;
|
|
104
|
+
timeoutMinutes?: number;
|
|
105
|
+
maxCostUsd?: number;
|
|
106
|
+
maxDepth?: number;
|
|
107
|
+
model?: string;
|
|
108
|
+
tools?: string;
|
|
109
|
+
cwd?: string;
|
|
110
|
+
scope?: string;
|
|
111
|
+
isolated?: boolean;
|
|
112
|
+
resumeFrom?: string;
|
|
113
|
+
resultSchema?: Record<string, unknown>;
|
|
114
|
+
}
|
|
96
115
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
applyCheck: Type.Optional(Type.Object({ ok: Type.Boolean(), output: Type.String() })),
|
|
107
|
-
error: Type.Optional(Type.String()),
|
|
108
|
-
});
|
|
116
|
+
interface StartParameters {
|
|
117
|
+
goal: string;
|
|
118
|
+
doneWhen?: string;
|
|
119
|
+
verify?: string;
|
|
120
|
+
context?: string;
|
|
121
|
+
wait?: boolean;
|
|
122
|
+
worktree?: boolean;
|
|
123
|
+
options?: StartOptionsInput;
|
|
124
|
+
}
|
|
109
125
|
|
|
110
|
-
|
|
126
|
+
/**
|
|
127
|
+
* Lift a known option written at the top level into `options`.
|
|
128
|
+
*
|
|
129
|
+
* A model that has just been told about `timeoutMinutes` will sometimes put it
|
|
130
|
+
* beside `goal` rather than inside the bag. That is a near miss, not a mistake
|
|
131
|
+
* worth a failed call: the declared location wins on a conflict, and everything
|
|
132
|
+
* else moves. The input is never mutated, and an input with nothing to lift is
|
|
133
|
+
* returned as it came in, which is the common case.
|
|
134
|
+
*/
|
|
135
|
+
export type StartArguments = Record<string, unknown>;
|
|
136
|
+
|
|
137
|
+
export function normalizeStartArguments(raw: unknown): StartArguments {
|
|
138
|
+
// The boundary narrows, once: everything past this point is a plain record
|
|
139
|
+
// whose known keys are read by the handler, and an argument list that is not
|
|
140
|
+
// a record becomes an empty one, which fails the missing-goal check.
|
|
141
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
142
|
+
const input = raw as StartArguments;
|
|
143
|
+
const declared = input.options;
|
|
144
|
+
const nested: Record<string, unknown> =
|
|
145
|
+
declared && typeof declared === "object" && !Array.isArray(declared) ? { ...(declared as Record<string, unknown>) } : {};
|
|
146
|
+
let lifted = false;
|
|
147
|
+
for (const key of OPTION_KEYS) {
|
|
148
|
+
const given = input[key];
|
|
149
|
+
if (given === undefined) continue;
|
|
150
|
+
if (nested[key] === undefined) nested[key] = given;
|
|
151
|
+
lifted = true;
|
|
152
|
+
}
|
|
153
|
+
if (!lifted) return input;
|
|
154
|
+
const copy: StartArguments = { ...input };
|
|
155
|
+
for (const key of OPTION_KEYS) delete copy[key];
|
|
156
|
+
copy.options = nested;
|
|
157
|
+
return copy;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The declared shape of one run, as a codemode caller branches on it.
|
|
162
|
+
*
|
|
163
|
+
* A projection, not a transcription: the outcome carries more fields than this
|
|
164
|
+
* (usage, containment, the worktree integration record), and they are documented
|
|
165
|
+
* in the README. Declaring all of them in three tools cost more context than the
|
|
166
|
+
* whole rest of the surface.
|
|
167
|
+
*/
|
|
168
|
+
const runSchema = Type.Object({
|
|
111
169
|
runId: Type.String(),
|
|
112
|
-
runDir: Type.String(),
|
|
113
|
-
goal: Type.String(),
|
|
114
170
|
status: Type.String(),
|
|
171
|
+
verified: Type.Union([Type.Boolean(), Type.Literal("not-run")]),
|
|
115
172
|
turns: Type.Number(),
|
|
116
173
|
maxTurns: Type.Number(),
|
|
117
|
-
toolCalls: Type.Number(),
|
|
118
|
-
durationMs: Type.Number(),
|
|
119
|
-
summary: Type.String(),
|
|
120
|
-
evidence: Type.Optional(Type.String()),
|
|
121
|
-
needs: Type.Optional(Type.String()),
|
|
122
|
-
result: Type.Optional(Type.Any()),
|
|
123
|
-
childVerification: Type.Optional(verificationSchema),
|
|
124
|
-
resumedFrom: Type.Optional(Type.String()),
|
|
125
|
-
verified: Type.Union([Type.Boolean(), Type.Literal("not-run")]),
|
|
126
|
-
verification: Type.Optional(verificationSchema),
|
|
127
|
-
sessionFile: Type.Optional(Type.String()),
|
|
128
|
-
resumeSession: Type.Optional(Type.String()),
|
|
129
|
-
model: Type.Optional(Type.String()),
|
|
130
|
-
modelSource: Type.String(),
|
|
131
|
-
usage: usageSchema,
|
|
132
|
-
exitCode: Type.Union([Type.Number(), Type.Null()]),
|
|
133
|
-
signal: Type.Union([Type.String(), Type.Null()]),
|
|
134
|
-
containment: Type.String(),
|
|
135
|
-
containmentVerdict: Type.Optional(Type.String()),
|
|
136
|
-
leakedPids: Type.Optional(Type.Array(Type.Number())),
|
|
137
|
-
logCapReached: Type.Optional(Type.Boolean()),
|
|
138
174
|
settledInline: Type.Optional(Type.Boolean()),
|
|
139
|
-
|
|
140
|
-
integration: Type.Optional(integrationSchema),
|
|
175
|
+
result: Type.Optional(Type.Any()),
|
|
141
176
|
error: Type.Optional(Type.String()),
|
|
142
177
|
});
|
|
143
178
|
|
|
179
|
+
const listRowSchema = Type.Object({
|
|
180
|
+
runId: Type.String(),
|
|
181
|
+
status: Type.String(),
|
|
182
|
+
verified: Type.String(),
|
|
183
|
+
turns: Type.Number(),
|
|
184
|
+
goal: Type.String(),
|
|
185
|
+
});
|
|
186
|
+
|
|
144
187
|
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
|
|
145
188
|
|
|
146
189
|
/**
|
|
@@ -152,7 +195,45 @@ function asJson(value: unknown): Json {
|
|
|
152
195
|
}
|
|
153
196
|
|
|
154
197
|
function modelLabel(ctx: ExtensionContext): string | undefined {
|
|
155
|
-
return ctx.model ?
|
|
198
|
+
return ctx.model ? ctx.model.provider + "/" + ctx.model.id : undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The active pi-goal contract's id, when Goal mode is running.
|
|
203
|
+
*
|
|
204
|
+
* Under an active /goal, ending a turn without `goal_wait` starts automatic
|
|
205
|
+
* continuation while the child is still working. Knowing the id lets a handle
|
|
206
|
+
* that comes back name the exact call that pauses Goal mode instead of
|
|
207
|
+
* describing the problem.
|
|
208
|
+
*/
|
|
209
|
+
function activeGoalId(ctx: ExtensionContext): string | undefined {
|
|
210
|
+
try {
|
|
211
|
+
const entries = ctx.sessionManager?.getBranch?.() ?? ctx.sessionManager?.getEntries?.() ?? [];
|
|
212
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
213
|
+
const entry = entries[index] as
|
|
214
|
+
| {
|
|
215
|
+
type?: string;
|
|
216
|
+
customType?: string;
|
|
217
|
+
data?: { goal?: { id?: unknown; status?: unknown } };
|
|
218
|
+
details?: { state?: unknown; goalId?: unknown };
|
|
219
|
+
}
|
|
220
|
+
| undefined;
|
|
221
|
+
if (!entry || typeof entry !== "object") continue;
|
|
222
|
+
if (entry.type === "custom" && entry.customType === "goal-state") {
|
|
223
|
+
const goal = entry.data?.goal;
|
|
224
|
+
if (!goal || typeof goal !== "object") return undefined;
|
|
225
|
+
return goal.status === "active" && typeof goal.id === "string" && goal.id ? goal.id : undefined;
|
|
226
|
+
}
|
|
227
|
+
if (entry.type === "custom_message" && entry.customType === "goal-contract") {
|
|
228
|
+
return entry.details?.state === "active" && typeof entry.details.goalId === "string" && entry.details.goalId
|
|
229
|
+
? entry.details.goalId
|
|
230
|
+
: undefined;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
} catch {
|
|
234
|
+
// Session projection is optional in minimal test harnesses.
|
|
235
|
+
}
|
|
236
|
+
return undefined;
|
|
156
237
|
}
|
|
157
238
|
|
|
158
239
|
/** A uniform shape for a run that may still be live. */
|
|
@@ -183,7 +264,7 @@ function view(handle: RunHandle): RunOutcome {
|
|
|
183
264
|
export function containmentLine(verdict: string | undefined, leaked: number[] | undefined): string {
|
|
184
265
|
if (verdict === "gone") return "Containment: verified gone. No process from the run survived.";
|
|
185
266
|
if (verdict === "leaked") {
|
|
186
|
-
return
|
|
267
|
+
return "Containment: LEAKED. " + (leaked?.length ?? 0) + " process(es) survived the fence: " + (leaked ?? []).join(", ");
|
|
187
268
|
}
|
|
188
269
|
if (verdict === "unproven") {
|
|
189
270
|
return "Containment: UNPROVEN. This platform exposes no process table, so absence could not be proven. Do not report the tree as gone.";
|
|
@@ -191,6 +272,61 @@ export function containmentLine(verdict: string | undefined, leaked: number[] |
|
|
|
191
272
|
return "Containment: not measured (nothing was cancelled).";
|
|
192
273
|
}
|
|
193
274
|
|
|
275
|
+
/** One compact row, for the listing view. */
|
|
276
|
+
interface RunRow {
|
|
277
|
+
runId: string;
|
|
278
|
+
status: string;
|
|
279
|
+
verified: string;
|
|
280
|
+
turns: number;
|
|
281
|
+
maxTurns: number;
|
|
282
|
+
durationMs: number;
|
|
283
|
+
goal: string;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** The listing a status call with no run ids reports. Claims nothing. */
|
|
287
|
+
function describeSession(registry: RunRegistry): { lines: string[]; rows: RunRow[]; total: number; live: number } {
|
|
288
|
+
const total = registry.list().length;
|
|
289
|
+
const live = registry.liveIds().length;
|
|
290
|
+
const rows = registry.list().map(rowOf);
|
|
291
|
+
const lines = registry.lines();
|
|
292
|
+
if (lines.length > 0) return { lines, rows, total, live };
|
|
293
|
+
const records = scanRetention({ root: delegateRoot() }).total;
|
|
294
|
+
const spend = maxCostUsd();
|
|
295
|
+
lines.push(
|
|
296
|
+
"No delegations in this session.",
|
|
297
|
+
"Run root: " + delegateRoot() + " · " + records + " record(s) on disk",
|
|
298
|
+
"Limits: max live " + maxLive() + " · spend cap " + (spend > 0 ? "$" + spend : "off"),
|
|
299
|
+
);
|
|
300
|
+
return { lines, rows, total, live };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function rowOf(handle: RunHandle): RunRow {
|
|
304
|
+
const outcome = handle.outcome;
|
|
305
|
+
return {
|
|
306
|
+
runId: handle.runId,
|
|
307
|
+
status: outcome?.status ?? handle.status,
|
|
308
|
+
verified: String(outcome?.verified ?? "not-run"),
|
|
309
|
+
turns: outcome?.turns ?? handle.progress.turns,
|
|
310
|
+
maxTurns: handle.maxTurns,
|
|
311
|
+
durationMs: outcome?.durationMs ?? Date.now() - handle.startedAt,
|
|
312
|
+
goal: handle.goal,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* The run ids a status call names.
|
|
318
|
+
*
|
|
319
|
+
* No ids is the listing case and names nothing; `"all"` means every run that is
|
|
320
|
+
* live right now, because waiting for a run that already settled is a read, not
|
|
321
|
+
* a wait.
|
|
322
|
+
*/
|
|
323
|
+
function namedRuns(registry: RunRegistry, requested: string | string[] | undefined): string[] {
|
|
324
|
+
if (requested === "all") return registry.liveIds();
|
|
325
|
+
if (Array.isArray(requested)) return requested;
|
|
326
|
+
if (requested) return [requested];
|
|
327
|
+
return [];
|
|
328
|
+
}
|
|
329
|
+
|
|
194
330
|
export default function delegateExtension(pi: ExtensionAPI) {
|
|
195
331
|
// A child may decompose only when its contract explicitly leaves depth. An
|
|
196
332
|
// unreadable spec fails closed, and old records retain the original depth 0.
|
|
@@ -249,130 +385,80 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
249
385
|
name: "delegate_start",
|
|
250
386
|
label: "Delegate Goal",
|
|
251
387
|
description:
|
|
252
|
-
"
|
|
253
|
-
promptSnippet: "
|
|
388
|
+
"Run one goal in a fresh child Pi process and return its verified outcome. Use it for two or more independent workstreams, a long exploration or build loop that would flood this context, or a mechanical job on a cheaper model. Waits inline by default; wait: false returns a handle in about a second.",
|
|
389
|
+
promptSnippet: "Run a goal in a fresh child agent and get the verified outcome back",
|
|
254
390
|
promptGuidelines: [
|
|
255
|
-
"
|
|
256
|
-
"
|
|
257
|
-
"Pass
|
|
258
|
-
"
|
|
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.",
|
|
261
|
-
"When the child needs a cheaper model or a different provider, pass model explicitly.",
|
|
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.",
|
|
391
|
+
"Delegate when a task splits into two or more independent workstreams, or when a loop would take more than about fifteen tool calls here.",
|
|
392
|
+
"Fan out in one codemode script with Promise.all, and raise that script's timeout_ms above the runs: the default wait is the run's own budget.",
|
|
393
|
+
"Pass verify with the command that proves the goal, worktree: true when parallel children edit tracked files, and model for mechanical work.",
|
|
394
|
+
"wait: false returns a handle: end the turn for the delegate-completion message, or under /goal call goal_wait with the goal_id the result prints.",
|
|
263
395
|
],
|
|
264
396
|
parameters: Type.Object({
|
|
265
|
-
goal: Type.String({ description: "One
|
|
266
|
-
doneWhen: Type.Optional(
|
|
267
|
-
Type.String({
|
|
268
|
-
description: "Verifiable completion criteria: a command exits 0, a test passes, or a file exists with specific content.",
|
|
269
|
-
}),
|
|
270
|
-
),
|
|
271
|
-
context: Type.Optional(
|
|
272
|
-
Type.String({
|
|
273
|
-
maxLength: 4000,
|
|
274
|
-
description: "Facts the child cannot discover from the repository: prior decisions, paths, constraints, and files to leave unchanged.",
|
|
275
|
-
}),
|
|
276
|
-
),
|
|
397
|
+
goal: Type.String({ description: "One objective, stated so it stands without this conversation." }),
|
|
398
|
+
doneWhen: Type.Optional(Type.String({ description: "A command exits 0, a test passes, a file has specific content." })),
|
|
277
399
|
verify: Type.Optional(
|
|
278
400
|
Type.String({
|
|
279
|
-
description:
|
|
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.",
|
|
286
|
-
}),
|
|
287
|
-
),
|
|
288
|
-
maxTurns: Type.Optional(
|
|
289
|
-
Type.Integer({
|
|
290
|
-
minimum: 1,
|
|
291
|
-
maximum: MAX_MAX_TURNS,
|
|
292
|
-
description: "Maximum model turns (one assistant response plus its tool calls). Default 150.",
|
|
293
|
-
}),
|
|
294
|
-
),
|
|
295
|
-
timeoutMinutes: Type.Optional(
|
|
296
|
-
Type.Number({
|
|
297
|
-
minimum: 1,
|
|
298
|
-
maximum: MAX_TIMEOUT_MINUTES,
|
|
299
|
-
description: "Wall-clock limit in minutes. Default 60. Enforced by both parent and child.",
|
|
300
|
-
}),
|
|
301
|
-
),
|
|
302
|
-
maxCostUsd: Type.Optional(
|
|
303
|
-
Type.Number({
|
|
304
|
-
minimum: 0,
|
|
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.",
|
|
314
|
-
}),
|
|
315
|
-
),
|
|
316
|
-
model: Type.Optional(
|
|
317
|
-
Type.String({ description: "Child model as provider/id. Defaults to the parent session model, passed explicitly with --model." }),
|
|
318
|
-
),
|
|
319
|
-
tools: Type.Optional(
|
|
320
|
-
Type.String({
|
|
321
|
-
description: "Comma-separated tool allowlist for the child, for example read,bash,edit,write. delegate_complete and delegate_blocked are always kept.",
|
|
401
|
+
description: "Command that gates delegate_complete in the child, then is re-run by the parent. A failed parent run makes the outcome unverified.",
|
|
322
402
|
}),
|
|
323
403
|
),
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
Type.String({
|
|
327
|
-
description: "session (default) reaps the child on session exit and survives /reload. workspace lets the child outlive Pi for re-adoption in the same directory.",
|
|
328
|
-
}),
|
|
404
|
+
context: Type.Optional(
|
|
405
|
+
Type.String({ maxLength: 4000, description: "Only what the child cannot discover: decisions, paths, constraints, files to leave alone." }),
|
|
329
406
|
),
|
|
330
|
-
|
|
407
|
+
wait: Type.Optional(
|
|
331
408
|
Type.Boolean({
|
|
332
|
-
description:
|
|
333
|
-
"Start the child without ambient extensions, skills, MCP servers, and context files, keeping only protocol and built-in tools. Default false.",
|
|
409
|
+
description: "Hold the call until the child settles and return its outcome (default true, capped by timeoutMinutes). false returns a live handle as soon as it is admitted.",
|
|
334
410
|
}),
|
|
335
411
|
),
|
|
336
412
|
worktree: Type.Optional(
|
|
337
|
-
Type.Boolean({
|
|
338
|
-
description:
|
|
339
|
-
"Give the child its own git worktree and branch (delegate/<runId>), so parallel children cannot overwrite each other's files. Requires git. Default false.",
|
|
340
|
-
}),
|
|
341
|
-
),
|
|
342
|
-
resumeFrom: Type.Optional(
|
|
343
|
-
Type.String({
|
|
344
|
-
description:
|
|
345
|
-
"Continue a previous child instead of starting cold: a run id whose child session is reused, or a session file path. Default none.",
|
|
346
|
-
}),
|
|
413
|
+
Type.Boolean({ description: "Give the child its own git worktree and branch, so parallel children cannot overwrite each other. Requires git." }),
|
|
347
414
|
),
|
|
348
|
-
|
|
349
|
-
Type.
|
|
350
|
-
minimum:
|
|
351
|
-
|
|
352
|
-
|
|
415
|
+
options: Type.Optional(
|
|
416
|
+
Type.Object({
|
|
417
|
+
maxTurns: Type.Optional(Type.Integer({ minimum: 1, maximum: MAX_MAX_TURNS, description: "Model turns. Default 150." })),
|
|
418
|
+
timeoutMinutes: Type.Optional(
|
|
419
|
+
Type.Number({ minimum: 1, maximum: MAX_TIMEOUT_MINUTES, description: "Wall-clock cap, and the ceiling on the wait. Default 60." }),
|
|
420
|
+
),
|
|
421
|
+
maxCostUsd: Type.Optional(Type.Number({ minimum: 0, description: "Spend cap for this run, in USD. 0 disables it." })),
|
|
422
|
+
maxDepth: Type.Optional(Type.Integer({ minimum: 0, maximum: MAX_MAX_DEPTH, description: "Delegation-tree depth; 0 disables nested delegation." })),
|
|
423
|
+
model: Type.Optional(Type.String({ description: "Child model as provider/id. Defaults to this session's model." })),
|
|
424
|
+
tools: Type.Optional(Type.String({ description: "Child tool allowlist, e.g. read,grep. Protocol tools and codemode are always kept." })),
|
|
425
|
+
cwd: Type.Optional(Type.String({ description: "Child working directory. Defaults to the session directory." })),
|
|
426
|
+
scope: Type.Optional(Type.String({ description: "session (default) dies with Pi; workspace outlives Pi and is re-adopted." })),
|
|
427
|
+
isolated: Type.Optional(Type.Boolean({ description: "Drop ambient extensions, skills, MCP servers, and context files." })),
|
|
428
|
+
resumeFrom: Type.Optional(Type.String({ description: "Continue a previous run: a run id or a session file. Fresh budget." })),
|
|
429
|
+
resultSchema: Type.Optional(
|
|
430
|
+
Type.Record(Type.String(), Type.Any(), { description: "JSON Schema for the structured result delegate_complete must return." }),
|
|
431
|
+
),
|
|
353
432
|
}),
|
|
354
433
|
),
|
|
355
434
|
}),
|
|
356
|
-
outputSchema:
|
|
357
|
-
|
|
435
|
+
outputSchema: runSchema,
|
|
436
|
+
prepareArguments: (args: unknown) => normalizeStartArguments(args) as never,
|
|
437
|
+
async execute(_toolCallId, rawParams, signal, onUpdate, ctx) {
|
|
438
|
+
// SAFETY: Pi validated these arguments against the schema above, and
|
|
439
|
+
// normalizeStartArguments moved a known option into its declared place.
|
|
440
|
+
// The one thing the schema cannot promise is a non-empty goal, which the
|
|
441
|
+
// next check does.
|
|
442
|
+
const params = normalizeStartArguments(rawParams) as unknown as StartParameters;
|
|
443
|
+
const options = params.options ?? {};
|
|
358
444
|
const goal = params.goal?.trim();
|
|
359
445
|
if (!goal) throw new Error("delegate_start needs a non-empty goal.");
|
|
360
|
-
if (
|
|
446
|
+
if (options.scope && options.scope !== "session" && options.scope !== "workspace") {
|
|
361
447
|
throw new Error("scope must be session or workspace.");
|
|
362
448
|
}
|
|
363
449
|
if (params.worktree && !gitAvailable()) {
|
|
364
450
|
throw new Error("worktree: true needs git on PATH, and git did not run.");
|
|
365
451
|
}
|
|
366
|
-
if (
|
|
367
|
-
const problem = auditResultSchema(
|
|
452
|
+
if (options.resultSchema) {
|
|
453
|
+
const problem = auditResultSchema(options.resultSchema);
|
|
368
454
|
if (problem) throw new Error(problem);
|
|
369
455
|
}
|
|
370
456
|
const inheritedMaxDepth = parentSpec?.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
371
|
-
const requestedMaxDepth =
|
|
457
|
+
const requestedMaxDepth = options.maxDepth ?? inheritedMaxDepth;
|
|
372
458
|
if (!Number.isInteger(requestedMaxDepth) || requestedMaxDepth < 0 || requestedMaxDepth > MAX_MAX_DEPTH) {
|
|
373
|
-
throw new Error(
|
|
459
|
+
throw new Error("maxDepth must be an integer from 0 to " + MAX_MAX_DEPTH + ".");
|
|
374
460
|
}
|
|
375
|
-
const spendCap =
|
|
461
|
+
const spendCap = options.maxCostUsd ?? (parentSpec ? (parentSpec.maxCostUsd ?? 0) : maxCostUsd());
|
|
376
462
|
// The attenuation rule lives in contract.ts, so this check and the one
|
|
377
463
|
// registry.start() runs cannot drift into two different answers.
|
|
378
464
|
const refusal = attenuationRefusal(
|
|
@@ -380,10 +466,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
380
466
|
{ maxDepth: requestedMaxDepth, maxCostUsd: spendCap },
|
|
381
467
|
);
|
|
382
468
|
if (refusal) throw new Error(refusal);
|
|
383
|
-
const cwd =
|
|
469
|
+
const cwd = options.cwd ? resolve(ctx.cwd, options.cwd) : ctx.cwd;
|
|
384
470
|
const registry = registryFor(ctx);
|
|
385
|
-
const maxTurns =
|
|
386
|
-
const timeoutMinutes =
|
|
471
|
+
const maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
472
|
+
const timeoutMinutes = options.timeoutMinutes ?? DEFAULT_TIMEOUT_MINUTES;
|
|
473
|
+
// One knob decides the mode, and the run's own budget decides the ceiling:
|
|
474
|
+
// a call can never wait longer than the delegation it waits for. A handle
|
|
475
|
+
// is a handle, so `wait: false` does not hold the call at all: a start
|
|
476
|
+
// that cannot spawn has already failed synchronously by the time
|
|
477
|
+
// registry.start() returns.
|
|
478
|
+
const inlineSettleMs = params.wait === false ? 0 : Math.round(timeoutMinutes * 60_000);
|
|
387
479
|
const handle = await registry.start({
|
|
388
480
|
goal,
|
|
389
481
|
doneWhen: params.doneWhen,
|
|
@@ -392,41 +484,65 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
392
484
|
maxTurns,
|
|
393
485
|
timeoutMinutes,
|
|
394
486
|
maxCostUsd: spendCap,
|
|
395
|
-
resultSchema:
|
|
487
|
+
resultSchema: options.resultSchema,
|
|
396
488
|
maxDepth: requestedMaxDepth,
|
|
397
|
-
model:
|
|
398
|
-
tools:
|
|
489
|
+
model: options.model,
|
|
490
|
+
tools: options.tools,
|
|
399
491
|
cwd,
|
|
400
|
-
scope:
|
|
401
|
-
isolated:
|
|
492
|
+
scope: options.scope === "workspace" ? "workspace" : "session",
|
|
493
|
+
isolated: options.isolated,
|
|
402
494
|
worktree: params.worktree,
|
|
403
|
-
resumeFrom:
|
|
404
|
-
inlineSettleMs
|
|
405
|
-
|
|
406
|
-
|
|
495
|
+
resumeFrom: options.resumeFrom,
|
|
496
|
+
inlineSettleMs,
|
|
497
|
+
signal,
|
|
498
|
+
// `handle` is not assigned yet when the watch reports its first turn.
|
|
499
|
+
// The run id comes from the callback, so this closure never reads a
|
|
500
|
+
// value that start() has not returned.
|
|
501
|
+
onProgress: (progress, _status, runId) => {
|
|
502
|
+
const preview = progress.lastText ? " · " + progress.lastText.slice(0, 90) : "";
|
|
407
503
|
onUpdate?.({
|
|
408
|
-
content: [{ type: "text", text:
|
|
409
|
-
details: { runId
|
|
504
|
+
content: [{ type: "text", text: "delegate " + progress.turns + "/" + maxTurns + " turns" + preview }],
|
|
505
|
+
details: { runId, turns: progress.turns, maxTurns },
|
|
410
506
|
});
|
|
411
507
|
refreshStatus(ctx, registry);
|
|
412
508
|
},
|
|
413
509
|
});
|
|
414
510
|
refreshStatus(ctx, registry);
|
|
415
511
|
const settled = Boolean(handle.outcome);
|
|
416
|
-
const
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
512
|
+
const goalId = settled ? undefined : activeGoalId(ctx);
|
|
513
|
+
const awaitHint = 'delegate_status({ runIds: "' + handle.runId + '", waitMs: 600000 })';
|
|
514
|
+
const nextStep = goalId
|
|
515
|
+
? "Goal mode (" + goalId + ") is active, so ending this turn continues automatically while the child runs. Either come back with " +
|
|
516
|
+
awaitHint +
|
|
517
|
+
' in a script whose timeout_ms covers it, or call goal_wait({ goal_id: "' +
|
|
518
|
+
goalId +
|
|
519
|
+
'", reason: "Waiting for delegation ' +
|
|
520
|
+
handle.runId +
|
|
521
|
+
'" }) alone to pause Goal mode until the delegate-completion message wakes it.'
|
|
522
|
+
: "Returning the handle. End the turn and its delegate-completion message wakes you, or call " +
|
|
523
|
+
awaitHint +
|
|
524
|
+
" inside a script whose timeout_ms covers it. To redirect it, delegate_send.";
|
|
525
|
+
if (handle.outcome) {
|
|
526
|
+
return {
|
|
527
|
+
content: [{ type: "text" as const, text: formatOutcome(handle.outcome) }],
|
|
528
|
+
structuredContent: asJson({ ...handle.outcome, settledInline: settled }),
|
|
529
|
+
details: { runId: handle.runId, status: handle.outcome.status, turns: handle.outcome.turns, maxTurns },
|
|
530
|
+
isError: isFailure(handle.outcome.status),
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
const verifyNote = params.verify ? ", verified by " + params.verify : "";
|
|
534
|
+
const text = [
|
|
535
|
+
"delegate started · " + handle.runId + " · " + (handle.model ?? "default model"),
|
|
536
|
+
"Goal: " + goal,
|
|
537
|
+
"Budget: " + maxTurns + " turns, " + timeoutMinutes + " minutes" + verifyNote,
|
|
538
|
+
...(handle.resumeSession ? ["Continues session: " + handle.resumeSession] : []),
|
|
539
|
+
"",
|
|
540
|
+
nextStep,
|
|
541
|
+
].join("\n");
|
|
426
542
|
const outcome = view(handle);
|
|
427
543
|
return {
|
|
428
544
|
content: [{ type: "text" as const, text }],
|
|
429
|
-
structuredContent: asJson({ ...outcome, settledInline:
|
|
545
|
+
structuredContent: asJson({ ...outcome, settledInline: false }),
|
|
430
546
|
details: { runId: handle.runId, status: outcome.status, turns: outcome.turns, maxTurns },
|
|
431
547
|
isError: isFailure(outcome.status),
|
|
432
548
|
};
|
|
@@ -434,121 +550,118 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
434
550
|
});
|
|
435
551
|
|
|
436
552
|
pi.registerTool({
|
|
437
|
-
name: "
|
|
438
|
-
label: "
|
|
553
|
+
name: "delegate_status",
|
|
554
|
+
label: "Delegations",
|
|
439
555
|
description:
|
|
440
|
-
"List
|
|
441
|
-
promptSnippet: "List
|
|
556
|
+
"List this session's delegations, or wait for named runs to settle and read their outcomes. Naming run ids claims the settles this call reports, so they are not announced again; a call with no runIds is a read that claims nothing and cancels nothing.",
|
|
557
|
+
promptSnippet: "List or wait for delegated runs without cancelling them",
|
|
442
558
|
promptGuidelines: [
|
|
443
|
-
|
|
444
|
-
"
|
|
559
|
+
'Pass runIds (or "all") with waitMs to collect background runs; omit runIds to list what exists and claim nothing.',
|
|
560
|
+
"waitMs never cancels a run and is capped at four hours: raise the codemode script's timeout_ms above it.",
|
|
445
561
|
],
|
|
446
562
|
parameters: Type.Object({
|
|
447
|
-
|
|
448
|
-
Type.
|
|
449
|
-
|
|
450
|
-
}),
|
|
451
|
-
outputSchema: Type.Object({
|
|
452
|
-
runs: Type.Array(
|
|
453
|
-
Type.Object({
|
|
454
|
-
runId: Type.String(),
|
|
455
|
-
status: Type.String(),
|
|
456
|
-
scope: Type.String(),
|
|
457
|
-
turns: Type.Number(),
|
|
458
|
-
maxTurns: Type.Number(),
|
|
459
|
-
durationMs: Type.Number(),
|
|
460
|
-
goal: Type.String(),
|
|
461
|
-
verified: Type.String(),
|
|
462
|
-
resumeSession: Type.Optional(Type.String()),
|
|
463
|
-
worktree: Type.Optional(Type.String()),
|
|
464
|
-
}),
|
|
465
|
-
),
|
|
466
|
-
live: Type.Number(),
|
|
467
|
-
note: Type.Optional(Type.String()),
|
|
468
|
-
}),
|
|
469
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
470
|
-
const registry = registryFor(ctx);
|
|
471
|
-
const includeSettled = params.includeSettled ?? true;
|
|
472
|
-
const handles = registry.list().filter((handle) => includeSettled || !handle.outcome);
|
|
473
|
-
refreshStatus(ctx, registry);
|
|
474
|
-
const runs = handles.map((handle) => {
|
|
475
|
-
const outcome = handle.outcome;
|
|
476
|
-
return {
|
|
477
|
-
runId: handle.runId,
|
|
478
|
-
status: outcome?.status ?? handle.status,
|
|
479
|
-
scope: handle.scope,
|
|
480
|
-
turns: outcome?.turns ?? handle.progress.turns,
|
|
481
|
-
maxTurns: handle.maxTurns,
|
|
482
|
-
durationMs: outcome?.durationMs ?? Date.now() - handle.startedAt,
|
|
483
|
-
goal: handle.goal,
|
|
484
|
-
verified: String(outcome?.verified ?? "not-run"),
|
|
485
|
-
resumeSession: outcome?.sessionFile ?? handle.resumeSession,
|
|
486
|
-
worktree: outcome?.worktree?.path,
|
|
487
|
-
};
|
|
488
|
-
});
|
|
489
|
-
const live = registry.runningCount;
|
|
490
|
-
const lines = registry.lines();
|
|
491
|
-
const text =
|
|
492
|
-
lines.length === 0
|
|
493
|
-
? "No delegations in this session."
|
|
494
|
-
: [`${live} live · ${lines.length} total`, "", ...lines].join("\n");
|
|
495
|
-
return {
|
|
496
|
-
content: [{ type: "text" as const, text }],
|
|
497
|
-
structuredContent: asJson({ runs, live }),
|
|
498
|
-
details: { live, total: lines.length },
|
|
499
|
-
};
|
|
500
|
-
},
|
|
501
|
-
});
|
|
502
|
-
|
|
503
|
-
pi.registerTool({
|
|
504
|
-
name: "delegate_await",
|
|
505
|
-
label: "Await Delegations",
|
|
506
|
-
description:
|
|
507
|
-
"Wait up to waitMs (max 50000) for one or more delegations to settle, or pass waitMs 0 for a point-in-time snapshot. Expiry never cancels the child. A settle reported here is claimed and will not trigger a duplicate delegate-completion message.",
|
|
508
|
-
promptSnippet: "Wait briefly for delegated goals, or snapshot their state",
|
|
509
|
-
promptGuidelines: [
|
|
510
|
-
"Call delegate_await only when the next action in the same turn depends on the result. For multi-minute runs, end the turn instead.",
|
|
511
|
-
"Pass waitMs 0 to snapshot live progress without blocking.",
|
|
512
|
-
],
|
|
513
|
-
parameters: Type.Object({
|
|
514
|
-
runIds: Type.Union([Type.String(), Type.Array(Type.String())], { description: "One run id or an array of run ids." }),
|
|
515
|
-
mode: Type.Optional(Type.String({ description: "all (default) waits for every run, any returns when one settles." })),
|
|
516
|
-
waitMs: Type.Optional(
|
|
517
|
-
Type.Integer({
|
|
518
|
-
minimum: 0,
|
|
519
|
-
maximum: 50000,
|
|
520
|
-
description: "Bounded wait in milliseconds. Default 30000. Expiry cancels nothing.",
|
|
563
|
+
runIds: Type.Optional(
|
|
564
|
+
Type.Union([Type.String(), Type.Array(Type.String())], {
|
|
565
|
+
description: 'One run id, an array, or "all" for every live run. Omit to list this session.',
|
|
521
566
|
}),
|
|
522
567
|
),
|
|
568
|
+
mode: Type.Optional(Type.String({ description: "all (default) waits for every named run; any returns at the first settle." })),
|
|
569
|
+
waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: MAX_WAIT_MS, description: "0 is a snapshot (default). Above 0, wait up to this many ms." })),
|
|
523
570
|
}),
|
|
524
571
|
outputSchema: Type.Object({
|
|
572
|
+
total: Type.Number(),
|
|
573
|
+
live: Type.Number(),
|
|
525
574
|
settled: Type.Boolean(),
|
|
526
575
|
timedOutWaiting: Type.Boolean(),
|
|
527
|
-
outcomes: Type.Array(
|
|
528
|
-
stillRunning: Type.Array(
|
|
576
|
+
outcomes: Type.Array(runSchema),
|
|
577
|
+
stillRunning: Type.Array(runSchema),
|
|
578
|
+
runs: Type.Array(listRowSchema),
|
|
529
579
|
unknown: Type.Array(Type.String()),
|
|
530
580
|
note: Type.Optional(Type.String()),
|
|
531
581
|
}),
|
|
532
582
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
533
583
|
const registry = registryFor(ctx);
|
|
534
|
-
const
|
|
535
|
-
const
|
|
536
|
-
const
|
|
584
|
+
const requested = params.runIds;
|
|
585
|
+
const all = requested === "all";
|
|
586
|
+
const named = namedRuns(registry, requested);
|
|
587
|
+
const total = registry.list().length;
|
|
537
588
|
refreshStatus(ctx, registry);
|
|
589
|
+
|
|
590
|
+
// No run ids is a listing. Reporting a settle and announcing it are one
|
|
591
|
+
// event or the other, never both, so a read claims nothing.
|
|
592
|
+
if (!all && named.length === 0) {
|
|
593
|
+
const listing = describeSession(registry);
|
|
594
|
+
const lines = [...listing.lines];
|
|
595
|
+
if ((params.waitMs ?? 0) > 0) {
|
|
596
|
+
lines.push('waitMs was ignored: pass runIds or "all" to wait for something.');
|
|
597
|
+
}
|
|
598
|
+
return {
|
|
599
|
+
content: [{ type: "text" as const, text: lines.join("\n") }],
|
|
600
|
+
structuredContent: asJson({
|
|
601
|
+
total: listing.total,
|
|
602
|
+
live: listing.live,
|
|
603
|
+
settled: false,
|
|
604
|
+
timedOutWaiting: false,
|
|
605
|
+
outcomes: [],
|
|
606
|
+
stillRunning: [],
|
|
607
|
+
runs: listing.rows,
|
|
608
|
+
unknown: [],
|
|
609
|
+
}),
|
|
610
|
+
details: { total: listing.total, live: listing.live },
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (named.length === 0) {
|
|
615
|
+
// "all" with nothing live: a wait that names no run is a wait that
|
|
616
|
+
// returns at once, and saying so is clearer than an empty result.
|
|
617
|
+
return {
|
|
618
|
+
content: [{ type: "text" as const, text: "No live delegations to wait for." }],
|
|
619
|
+
structuredContent: asJson({
|
|
620
|
+
total,
|
|
621
|
+
live: 0,
|
|
622
|
+
settled: false,
|
|
623
|
+
timedOutWaiting: false,
|
|
624
|
+
outcomes: [],
|
|
625
|
+
stillRunning: [],
|
|
626
|
+
runs: [],
|
|
627
|
+
unknown: [],
|
|
628
|
+
note: "Nothing was live. Pass a settled run id to read its outcome.",
|
|
629
|
+
}),
|
|
630
|
+
details: { total, live: 0 },
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const result = await registry.awaitRuns({
|
|
635
|
+
runIds: named,
|
|
636
|
+
mode: params.mode === "any" ? "any" : "all",
|
|
637
|
+
waitMs: params.waitMs ?? 0,
|
|
638
|
+
signal,
|
|
639
|
+
claim: true,
|
|
640
|
+
});
|
|
538
641
|
const lines = result.outcomes.map((outcome) => formatOutcome(outcome));
|
|
539
642
|
if (result.stillRunning.length > 0) {
|
|
540
643
|
lines.push("", "Still running:");
|
|
541
644
|
for (const outcome of result.stillRunning) {
|
|
542
|
-
lines.push(
|
|
645
|
+
lines.push(" " + outcome.runId + " · " + outcome.status + " · " + outcome.turns + " turns");
|
|
543
646
|
}
|
|
544
647
|
}
|
|
545
|
-
if (result.unknown.length > 0) lines.push("",
|
|
648
|
+
if (result.unknown.length > 0) lines.push("", "Unknown runs: " + result.unknown.join(", "));
|
|
546
649
|
if (result.note) lines.push("", result.note);
|
|
547
650
|
if (lines.length === 0) lines.push("No delegation matched those run ids.");
|
|
548
651
|
const anyFailure = result.outcomes.some((outcome) => isFailure(outcome.status));
|
|
549
652
|
return {
|
|
550
653
|
content: [{ type: "text" as const, text: lines.join("\n") }],
|
|
551
|
-
structuredContent: asJson(
|
|
654
|
+
structuredContent: asJson({
|
|
655
|
+
total,
|
|
656
|
+
live: registry.liveIds().length,
|
|
657
|
+
settled: result.settled,
|
|
658
|
+
timedOutWaiting: result.timedOutWaiting,
|
|
659
|
+
outcomes: result.outcomes,
|
|
660
|
+
stillRunning: result.stillRunning,
|
|
661
|
+
runs: [],
|
|
662
|
+
unknown: result.unknown,
|
|
663
|
+
note: result.note,
|
|
664
|
+
}),
|
|
552
665
|
details: { settled: result.settled, timedOutWaiting: result.timedOutWaiting },
|
|
553
666
|
isError: anyFailure,
|
|
554
667
|
};
|
|
@@ -559,27 +672,23 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
559
672
|
name: "delegate_send",
|
|
560
673
|
label: "Send To Delegation",
|
|
561
674
|
description:
|
|
562
|
-
"Hand a running delegated child one message. The child reads it at its next turn start
|
|
675
|
+
"Hand a running delegated child one message. The child reads it at its next turn start as direction for the existing work, not as a new goal. Delivered through the run directory, so it works across /reload and across processes.",
|
|
563
676
|
promptSnippet: "Send one message to a running delegation",
|
|
564
677
|
promptGuidelines: [
|
|
565
678
|
"Use delegate_send to correct course on a running child instead of cancelling and starting again.",
|
|
566
|
-
"A message is not a question: the child cannot answer, and it cannot be interrupted mid-turn.",
|
|
679
|
+
"A message is not a question: the child cannot answer it, and it cannot be interrupted mid-turn.",
|
|
567
680
|
],
|
|
568
681
|
parameters: Type.Object({
|
|
569
682
|
runId: Type.String({ description: "The run to message." }),
|
|
570
683
|
text: Type.String({ maxLength: 8000, description: "What the child should do differently, in one or two sentences." }),
|
|
571
684
|
}),
|
|
572
|
-
outputSchema: Type.Object({
|
|
573
|
-
ok: Type.Boolean(),
|
|
574
|
-
runId: Type.String(),
|
|
575
|
-
error: Type.Optional(Type.String()),
|
|
576
|
-
}),
|
|
685
|
+
outputSchema: Type.Object({ ok: Type.Boolean(), runId: Type.String(), error: Type.Optional(Type.String()) }),
|
|
577
686
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
578
687
|
const registry = registryFor(ctx);
|
|
579
688
|
const result = registry.send(params.runId, params.text);
|
|
580
689
|
const text = result.ok
|
|
581
|
-
?
|
|
582
|
-
:
|
|
690
|
+
? "Sent to " + params.runId + ". The child reads it at its next turn start."
|
|
691
|
+
: "Could not send to " + params.runId + ": " + (result.error ?? "unknown error") + ".";
|
|
583
692
|
return {
|
|
584
693
|
content: [{ type: "text" as const, text }],
|
|
585
694
|
structuredContent: asJson({ ok: result.ok, runId: params.runId, error: result.error }),
|
|
@@ -593,19 +702,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
593
702
|
name: "delegate_cancel",
|
|
594
703
|
label: "Cancel Delegations",
|
|
595
704
|
description:
|
|
596
|
-
"Stop running delegations with a graceful signal, a grace period, a process-tree fence, and a containment verdict.
|
|
597
|
-
promptSnippet: "Cancel delegated
|
|
705
|
+
"Stop running delegations with a graceful signal, a grace period, a process-tree fence, and a containment verdict. 'gone' means the tree was observed absent; where no process table exists the verdict is 'unproven', never a claim.",
|
|
706
|
+
promptSnippet: "Cancel delegated runs and report what was proven about the tree",
|
|
598
707
|
promptGuidelines: [
|
|
599
|
-
"When a delegation is no longer needed or is stuck,
|
|
600
|
-
"Report
|
|
708
|
+
"When a delegation is no longer needed or is stuck, cancel it instead of waiting out its budget.",
|
|
709
|
+
"Report containment as measured: 'unproven' means this platform cannot prove absence, so do not describe the tree as gone.",
|
|
601
710
|
],
|
|
602
711
|
parameters: Type.Object({
|
|
603
|
-
runIds: Type.Union([Type.String(), Type.Array(Type.String())], { description:
|
|
712
|
+
runIds: Type.Union([Type.String(), Type.Array(Type.String())], { description: 'One run id, an array of run ids, or "all" for every live run.' }),
|
|
604
713
|
graceMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30000, description: "Grace period between the graceful signal and the fence. Default 3000." })),
|
|
605
714
|
}),
|
|
606
715
|
outputSchema: Type.Object({
|
|
607
716
|
containment: Type.String(),
|
|
608
|
-
outcomes: Type.Array(
|
|
717
|
+
outcomes: Type.Array(runSchema),
|
|
609
718
|
unknown: Type.Array(Type.String()),
|
|
610
719
|
note: Type.Optional(Type.String()),
|
|
611
720
|
}),
|
|
@@ -613,9 +722,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
613
722
|
const registry = registryFor(ctx);
|
|
614
723
|
const requested = Array.isArray(params.runIds) ? params.runIds : [params.runIds];
|
|
615
724
|
const all = requested.length === 1 && requested[0] === "all";
|
|
616
|
-
const runIds = all
|
|
617
|
-
? registry.list().filter((handle) => !handle.outcome).map((handle) => handle.runId)
|
|
618
|
-
: requested;
|
|
725
|
+
const runIds = all ? registry.liveIds() : requested;
|
|
619
726
|
if (runIds.length === 0) {
|
|
620
727
|
return {
|
|
621
728
|
content: [{ type: "text" as const, text: "No running delegations to cancel." }],
|
|
@@ -632,9 +739,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
632
739
|
content: [{ type: "text" as const, text: lines.join("\n") }],
|
|
633
740
|
structuredContent: asJson(result),
|
|
634
741
|
details: { containment: result.containment },
|
|
635
|
-
// A cancellation that leaked is a failed cancellation. Reporting it
|
|
636
|
-
//
|
|
637
|
-
// `unproven` as `gone`.
|
|
742
|
+
// A cancellation that leaked is a failed cancellation. Reporting it as a
|
|
743
|
+
// clean tool result is the same class of bug as reporting unproven as gone.
|
|
638
744
|
isError: result.containment === "leaked",
|
|
639
745
|
};
|
|
640
746
|
},
|
|
@@ -648,6 +754,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
648
754
|
maxCostUsd: parentSpec?.maxCostUsd ?? DEFAULT_MAX_COST_USD,
|
|
649
755
|
maxDepth: parentSpec?.maxDepth ?? DEFAULT_MAX_DEPTH,
|
|
650
756
|
},
|
|
757
|
+
doctor: (ctx): DoctorReport =>
|
|
758
|
+
runDoctor({
|
|
759
|
+
registry: registryFor(ctx),
|
|
760
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
761
|
+
cwd: ctx.cwd,
|
|
762
|
+
isChild: Boolean(parentSpecPath),
|
|
763
|
+
}),
|
|
651
764
|
});
|
|
652
765
|
|
|
653
766
|
pi.on("session_start", async (event, ctx) => {
|
|
@@ -660,10 +773,20 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
660
773
|
// child that exits minutes later; pruning deleted records no child owns.
|
|
661
774
|
// Both belong to the session that owns the machine, not to a child.
|
|
662
775
|
if (parentSpec) return;
|
|
776
|
+
// The one installation failure worth announcing: an unwritable record root
|
|
777
|
+
// used to surface days later as a start that failed for an unrelated reason.
|
|
778
|
+
const warning = startupWarning();
|
|
779
|
+
if (warning) {
|
|
780
|
+
try {
|
|
781
|
+
ctx.ui.notify(warning, "warning");
|
|
782
|
+
} catch {
|
|
783
|
+
// a non-interactive session has no footer to write to
|
|
784
|
+
}
|
|
785
|
+
}
|
|
663
786
|
const adopted = await registry.adoptExisting();
|
|
664
787
|
if (adopted.length > 0) {
|
|
665
788
|
try {
|
|
666
|
-
ctx.ui.notify(
|
|
789
|
+
ctx.ui.notify("delegate: re-adopted " + adopted.length + " workspace run(s)", "info");
|
|
667
790
|
} catch {
|
|
668
791
|
// a non-interactive session has no footer to write to
|
|
669
792
|
}
|