pi-goal-delegate 0.1.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 +147 -0
- package/README.md +409 -280
- package/package.json +2 -2
- package/skills/delegate/SKILL.md +128 -47
- package/src/command.ts +124 -32
- package/src/contract.ts +137 -11
- package/src/doctor.ts +385 -0
- package/src/events.ts +22 -1
- package/src/index.ts +466 -271
- package/src/registry.ts +108 -29
- package/src/result-schema.ts +143 -0
- package/src/retention.ts +132 -34
- package/src/run.ts +93 -21
- package/src/spawn.ts +6 -2
- package/src/supervisor.mjs +113 -4
- package/src/verify.ts +16 -1
- package/src/worker.ts +128 -59
- package/src/worktree.ts +107 -3
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,10 +34,11 @@
|
|
|
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
|
-
* plus child.jsonl, child.log, inbox.jsonl, owner.lock
|
|
40
|
+
* plus child.jsonl, control.jsonl, child.log, inbox.jsonl, owner.lock,
|
|
41
|
+
* and changes.patch for a worktree run with changes.
|
|
34
42
|
*/
|
|
35
43
|
|
|
36
44
|
import { resolve } from "node:path";
|
|
@@ -38,84 +46,144 @@ import { Type } from "typebox";
|
|
|
38
46
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
39
47
|
import { registerDelegateCommand } from "./command.ts";
|
|
40
48
|
import {
|
|
49
|
+
attenuationRefusal,
|
|
41
50
|
DEFAULT_MAX_COST_USD,
|
|
51
|
+
DEFAULT_MAX_DEPTH,
|
|
42
52
|
DEFAULT_MAX_TURNS,
|
|
43
53
|
DEFAULT_TIMEOUT_MINUTES,
|
|
44
54
|
isFailure,
|
|
55
|
+
MAX_MAX_DEPTH,
|
|
45
56
|
MAX_MAX_TURNS,
|
|
46
57
|
MAX_TIMEOUT_MINUTES,
|
|
58
|
+
MAX_WAIT_MS,
|
|
47
59
|
SPEC_ENV,
|
|
60
|
+
type RunSpec,
|
|
48
61
|
} from "./contract.ts";
|
|
62
|
+
import { runDoctor, startupWarning, type DoctorReport } from "./doctor.ts";
|
|
49
63
|
import {
|
|
50
64
|
acquireRegistry,
|
|
51
65
|
discardHandoff,
|
|
52
66
|
forgetRegistry,
|
|
53
67
|
maxCostUsd,
|
|
68
|
+
maxLive,
|
|
54
69
|
publishHandoff,
|
|
55
70
|
type RegistryHost,
|
|
56
71
|
} from "./registry.ts";
|
|
57
72
|
import type { RunRegistry } from "./registry.ts";
|
|
58
73
|
import { formatOutcome, type RunHandle, type RunOutcome } from "./run.ts";
|
|
74
|
+
import { scanRetention } from "./retention.ts";
|
|
75
|
+
import { auditResultSchema } from "./result-schema.ts";
|
|
76
|
+
import { delegateRoot, readJson } from "./spawn.ts";
|
|
59
77
|
import { gitAvailable } from "./worktree.ts";
|
|
60
78
|
|
|
61
79
|
const STATUS_KEY = "delegate";
|
|
62
|
-
const DEFAULT_INLINE_SETTLE_MS = 1000;
|
|
63
|
-
const MAX_INLINE_SETTLE_MS = 10_000;
|
|
64
|
-
|
|
65
|
-
const usageSchema = Type.Object({
|
|
66
|
-
input: Type.Number(),
|
|
67
|
-
output: Type.Number(),
|
|
68
|
-
cacheRead: Type.Number(),
|
|
69
|
-
cacheWrite: Type.Number(),
|
|
70
|
-
totalTokens: Type.Number(),
|
|
71
|
-
cost: Type.Number(),
|
|
72
|
-
});
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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;
|
|
82
101
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
+
}
|
|
115
|
+
|
|
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
|
+
}
|
|
125
|
+
|
|
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
|
+
}
|
|
88
159
|
|
|
89
|
-
|
|
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({
|
|
90
169
|
runId: Type.String(),
|
|
91
|
-
runDir: Type.String(),
|
|
92
|
-
goal: Type.String(),
|
|
93
170
|
status: Type.String(),
|
|
171
|
+
verified: Type.Union([Type.Boolean(), Type.Literal("not-run")]),
|
|
94
172
|
turns: Type.Number(),
|
|
95
173
|
maxTurns: Type.Number(),
|
|
96
|
-
toolCalls: Type.Number(),
|
|
97
|
-
durationMs: Type.Number(),
|
|
98
|
-
summary: Type.String(),
|
|
99
|
-
evidence: Type.Optional(Type.String()),
|
|
100
|
-
needs: Type.Optional(Type.String()),
|
|
101
|
-
verified: Type.Union([Type.Boolean(), Type.Literal("not-run")]),
|
|
102
|
-
verification: Type.Optional(verificationSchema),
|
|
103
|
-
sessionFile: Type.Optional(Type.String()),
|
|
104
|
-
resumeSession: Type.Optional(Type.String()),
|
|
105
|
-
model: Type.Optional(Type.String()),
|
|
106
|
-
modelSource: Type.String(),
|
|
107
|
-
usage: usageSchema,
|
|
108
|
-
exitCode: Type.Union([Type.Number(), Type.Null()]),
|
|
109
|
-
signal: Type.Union([Type.String(), Type.Null()]),
|
|
110
|
-
containment: Type.String(),
|
|
111
|
-
containmentVerdict: Type.Optional(Type.String()),
|
|
112
|
-
leakedPids: Type.Optional(Type.Array(Type.Number())),
|
|
113
|
-
logCapReached: Type.Optional(Type.Boolean()),
|
|
114
174
|
settledInline: Type.Optional(Type.Boolean()),
|
|
115
|
-
|
|
175
|
+
result: Type.Optional(Type.Any()),
|
|
116
176
|
error: Type.Optional(Type.String()),
|
|
117
177
|
});
|
|
118
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
|
+
|
|
119
187
|
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
|
|
120
188
|
|
|
121
189
|
/**
|
|
@@ -127,7 +195,45 @@ function asJson(value: unknown): Json {
|
|
|
127
195
|
}
|
|
128
196
|
|
|
129
197
|
function modelLabel(ctx: ExtensionContext): string | undefined {
|
|
130
|
-
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;
|
|
131
237
|
}
|
|
132
238
|
|
|
133
239
|
/** A uniform shape for a run that may still be live. */
|
|
@@ -158,7 +264,7 @@ function view(handle: RunHandle): RunOutcome {
|
|
|
158
264
|
export function containmentLine(verdict: string | undefined, leaked: number[] | undefined): string {
|
|
159
265
|
if (verdict === "gone") return "Containment: verified gone. No process from the run survived.";
|
|
160
266
|
if (verdict === "leaked") {
|
|
161
|
-
return
|
|
267
|
+
return "Containment: LEAKED. " + (leaked?.length ?? 0) + " process(es) survived the fence: " + (leaked ?? []).join(", ");
|
|
162
268
|
}
|
|
163
269
|
if (verdict === "unproven") {
|
|
164
270
|
return "Containment: UNPROVEN. This platform exposes no process table, so absence could not be proven. Do not report the tree as gone.";
|
|
@@ -166,11 +272,68 @@ export function containmentLine(verdict: string | undefined, leaked: number[] |
|
|
|
166
272
|
return "Containment: not measured (nothing was cancelled).";
|
|
167
273
|
}
|
|
168
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
|
+
|
|
169
330
|
export default function delegateExtension(pi: ExtensionAPI) {
|
|
170
|
-
//
|
|
171
|
-
//
|
|
172
|
-
|
|
173
|
-
|
|
331
|
+
// A child may decompose only when its contract explicitly leaves depth. An
|
|
332
|
+
// unreadable spec fails closed, and old records retain the original depth 0.
|
|
333
|
+
const parentSpecPath = process.env[SPEC_ENV];
|
|
334
|
+
const parentSpecRecord = parentSpecPath ? readJson<RunSpec>(parentSpecPath) : undefined;
|
|
335
|
+
const parentSpec = parentSpecRecord?.kind === "ok" ? parentSpecRecord.value : undefined;
|
|
336
|
+
if (parentSpecPath && (!parentSpec || (parentSpec.depth ?? 0) >= (parentSpec.maxDepth ?? DEFAULT_MAX_DEPTH))) return;
|
|
174
337
|
|
|
175
338
|
// The registry belongs to the session directory. A child's cwd is a property
|
|
176
339
|
// of one run, not of the registry: binding it here would let a
|
|
@@ -181,6 +344,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
181
344
|
thinking: pi.getThinkingLevel(),
|
|
182
345
|
parentModel: modelLabel(ctx),
|
|
183
346
|
activeTools: pi.getActiveTools(),
|
|
347
|
+
depth: parentSpec?.depth,
|
|
348
|
+
maxDepth: parentSpec?.maxDepth,
|
|
349
|
+
deadline: parentSpec?.deadline,
|
|
350
|
+
maxCostUsd: parentSpec?.maxCostUsd,
|
|
184
351
|
deliver: (message) => {
|
|
185
352
|
pi.sendMessage(
|
|
186
353
|
{
|
|
@@ -218,109 +385,97 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
218
385
|
name: "delegate_start",
|
|
219
386
|
label: "Delegate Goal",
|
|
220
387
|
description:
|
|
221
|
-
"
|
|
222
|
-
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",
|
|
223
390
|
promptGuidelines: [
|
|
224
|
-
"
|
|
225
|
-
"
|
|
226
|
-
"Pass
|
|
227
|
-
"
|
|
228
|
-
"When the child needs a cheaper model or a different provider, pass model explicitly.",
|
|
229
|
-
"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.",
|
|
230
395
|
],
|
|
231
396
|
parameters: Type.Object({
|
|
232
|
-
goal: Type.String({ description: "One
|
|
233
|
-
doneWhen: Type.Optional(
|
|
234
|
-
Type.String({
|
|
235
|
-
description: "Verifiable completion criteria: a command exits 0, a test passes, or a file exists with specific content.",
|
|
236
|
-
}),
|
|
237
|
-
),
|
|
238
|
-
context: Type.Optional(
|
|
239
|
-
Type.String({
|
|
240
|
-
maxLength: 4000,
|
|
241
|
-
description: "Facts the child cannot discover from the repository: prior decisions, paths, constraints, and files to leave unchanged.",
|
|
242
|
-
}),
|
|
243
|
-
),
|
|
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." })),
|
|
244
399
|
verify: Type.Optional(
|
|
245
400
|
Type.String({
|
|
246
|
-
description:
|
|
247
|
-
"A shell command that proves the goal, run by the parent in the child's directory after the child reports complete. Exit 0 is the proof; anything else reports the run as unverified.",
|
|
248
|
-
}),
|
|
249
|
-
),
|
|
250
|
-
maxTurns: Type.Optional(
|
|
251
|
-
Type.Integer({
|
|
252
|
-
minimum: 1,
|
|
253
|
-
maximum: MAX_MAX_TURNS,
|
|
254
|
-
description: "Maximum model turns (one assistant response plus its tool calls). Default 150.",
|
|
255
|
-
}),
|
|
256
|
-
),
|
|
257
|
-
timeoutMinutes: Type.Optional(
|
|
258
|
-
Type.Number({
|
|
259
|
-
minimum: 1,
|
|
260
|
-
maximum: MAX_TIMEOUT_MINUTES,
|
|
261
|
-
description: "Wall-clock limit in minutes. Default 60. Enforced by both parent and child.",
|
|
262
|
-
}),
|
|
263
|
-
),
|
|
264
|
-
maxCostUsd: Type.Optional(
|
|
265
|
-
Type.Number({
|
|
266
|
-
minimum: 0,
|
|
267
|
-
description: "Cumulative spend cap in US dollars, from provider usage cost. 0 disables it. Defaults to PI_DELEGATE_MAX_COST_USD.",
|
|
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.",
|
|
268
402
|
}),
|
|
269
403
|
),
|
|
270
|
-
|
|
271
|
-
Type.String({ description: "
|
|
272
|
-
),
|
|
273
|
-
tools: Type.Optional(
|
|
274
|
-
Type.String({
|
|
275
|
-
description: "Comma-separated tool allowlist for the child, for example read,bash,edit,write. delegate_complete and delegate_blocked are always kept.",
|
|
276
|
-
}),
|
|
277
|
-
),
|
|
278
|
-
cwd: Type.Optional(Type.String({ description: "Working directory for the child. Defaults to the session directory." })),
|
|
279
|
-
scope: Type.Optional(
|
|
280
|
-
Type.String({
|
|
281
|
-
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.",
|
|
282
|
-
}),
|
|
404
|
+
context: Type.Optional(
|
|
405
|
+
Type.String({ maxLength: 4000, description: "Only what the child cannot discover: decisions, paths, constraints, files to leave alone." }),
|
|
283
406
|
),
|
|
284
|
-
|
|
407
|
+
wait: Type.Optional(
|
|
285
408
|
Type.Boolean({
|
|
286
|
-
description:
|
|
287
|
-
"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.",
|
|
288
410
|
}),
|
|
289
411
|
),
|
|
290
412
|
worktree: Type.Optional(
|
|
291
|
-
Type.Boolean({
|
|
292
|
-
description:
|
|
293
|
-
"Give the child its own git worktree and branch (delegate/<runId>), so parallel children cannot overwrite each other's files. Requires git. Default false.",
|
|
294
|
-
}),
|
|
413
|
+
Type.Boolean({ description: "Give the child its own git worktree and branch, so parallel children cannot overwrite each other. Requires git." }),
|
|
295
414
|
),
|
|
296
|
-
|
|
297
|
-
Type.
|
|
298
|
-
description:
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
description: "
|
|
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
|
+
),
|
|
307
432
|
}),
|
|
308
433
|
),
|
|
309
434
|
}),
|
|
310
|
-
outputSchema:
|
|
311
|
-
|
|
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 ?? {};
|
|
312
444
|
const goal = params.goal?.trim();
|
|
313
445
|
if (!goal) throw new Error("delegate_start needs a non-empty goal.");
|
|
314
|
-
if (
|
|
446
|
+
if (options.scope && options.scope !== "session" && options.scope !== "workspace") {
|
|
315
447
|
throw new Error("scope must be session or workspace.");
|
|
316
448
|
}
|
|
317
449
|
if (params.worktree && !gitAvailable()) {
|
|
318
450
|
throw new Error("worktree: true needs git on PATH, and git did not run.");
|
|
319
451
|
}
|
|
320
|
-
|
|
452
|
+
if (options.resultSchema) {
|
|
453
|
+
const problem = auditResultSchema(options.resultSchema);
|
|
454
|
+
if (problem) throw new Error(problem);
|
|
455
|
+
}
|
|
456
|
+
const inheritedMaxDepth = parentSpec?.maxDepth ?? DEFAULT_MAX_DEPTH;
|
|
457
|
+
const requestedMaxDepth = options.maxDepth ?? inheritedMaxDepth;
|
|
458
|
+
if (!Number.isInteger(requestedMaxDepth) || requestedMaxDepth < 0 || requestedMaxDepth > MAX_MAX_DEPTH) {
|
|
459
|
+
throw new Error("maxDepth must be an integer from 0 to " + MAX_MAX_DEPTH + ".");
|
|
460
|
+
}
|
|
461
|
+
const spendCap = options.maxCostUsd ?? (parentSpec ? (parentSpec.maxCostUsd ?? 0) : maxCostUsd());
|
|
462
|
+
// The attenuation rule lives in contract.ts, so this check and the one
|
|
463
|
+
// registry.start() runs cannot drift into two different answers.
|
|
464
|
+
const refusal = attenuationRefusal(
|
|
465
|
+
{ depth: parentSpec?.depth, maxDepth: parentSpec?.maxDepth, maxCostUsd: parentSpec?.maxCostUsd },
|
|
466
|
+
{ maxDepth: requestedMaxDepth, maxCostUsd: spendCap },
|
|
467
|
+
);
|
|
468
|
+
if (refusal) throw new Error(refusal);
|
|
469
|
+
const cwd = options.cwd ? resolve(ctx.cwd, options.cwd) : ctx.cwd;
|
|
321
470
|
const registry = registryFor(ctx);
|
|
322
|
-
const maxTurns =
|
|
323
|
-
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);
|
|
324
479
|
const handle = await registry.start({
|
|
325
480
|
goal,
|
|
326
481
|
doneWhen: params.doneWhen,
|
|
@@ -328,40 +483,66 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
328
483
|
verify: params.verify ? { command: params.verify } : undefined,
|
|
329
484
|
maxTurns,
|
|
330
485
|
timeoutMinutes,
|
|
331
|
-
maxCostUsd:
|
|
332
|
-
|
|
333
|
-
|
|
486
|
+
maxCostUsd: spendCap,
|
|
487
|
+
resultSchema: options.resultSchema,
|
|
488
|
+
maxDepth: requestedMaxDepth,
|
|
489
|
+
model: options.model,
|
|
490
|
+
tools: options.tools,
|
|
334
491
|
cwd,
|
|
335
|
-
scope:
|
|
336
|
-
isolated:
|
|
492
|
+
scope: options.scope === "workspace" ? "workspace" : "session",
|
|
493
|
+
isolated: options.isolated,
|
|
337
494
|
worktree: params.worktree,
|
|
338
|
-
resumeFrom:
|
|
339
|
-
inlineSettleMs
|
|
340
|
-
|
|
341
|
-
|
|
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) : "";
|
|
342
503
|
onUpdate?.({
|
|
343
|
-
content: [{ type: "text", text:
|
|
344
|
-
details: { runId
|
|
504
|
+
content: [{ type: "text", text: "delegate " + progress.turns + "/" + maxTurns + " turns" + preview }],
|
|
505
|
+
details: { runId, turns: progress.turns, maxTurns },
|
|
345
506
|
});
|
|
346
507
|
refreshStatus(ctx, registry);
|
|
347
508
|
},
|
|
348
509
|
});
|
|
349
510
|
refreshStatus(ctx, registry);
|
|
350
511
|
const settled = Boolean(handle.outcome);
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
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");
|
|
361
542
|
const outcome = view(handle);
|
|
362
543
|
return {
|
|
363
544
|
content: [{ type: "text" as const, text }],
|
|
364
|
-
structuredContent: asJson({ ...outcome, settledInline:
|
|
545
|
+
structuredContent: asJson({ ...outcome, settledInline: false }),
|
|
365
546
|
details: { runId: handle.runId, status: outcome.status, turns: outcome.turns, maxTurns },
|
|
366
547
|
isError: isFailure(outcome.status),
|
|
367
548
|
};
|
|
@@ -369,121 +550,118 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
369
550
|
});
|
|
370
551
|
|
|
371
552
|
pi.registerTool({
|
|
372
|
-
name: "
|
|
373
|
-
label: "
|
|
374
|
-
description:
|
|
375
|
-
"List every delegation this session knows about, live or settled, with status, turns, cost, and how a completion was verified. Reading a run's state does not claim or cancel it.",
|
|
376
|
-
promptSnippet: "List delegations in this session without waiting on them",
|
|
377
|
-
promptGuidelines: [
|
|
378
|
-
"Call delegate_list to see what is already running before starting more work, and to recover a run id without waiting.",
|
|
379
|
-
"A listed run is not consumed: unlike delegate_await, listing never claims the completion message.",
|
|
380
|
-
],
|
|
381
|
-
parameters: Type.Object({
|
|
382
|
-
includeSettled: Type.Optional(
|
|
383
|
-
Type.Boolean({ description: "Include runs that already settled. Default true." }),
|
|
384
|
-
),
|
|
385
|
-
}),
|
|
386
|
-
outputSchema: Type.Object({
|
|
387
|
-
runs: Type.Array(
|
|
388
|
-
Type.Object({
|
|
389
|
-
runId: Type.String(),
|
|
390
|
-
status: Type.String(),
|
|
391
|
-
scope: Type.String(),
|
|
392
|
-
turns: Type.Number(),
|
|
393
|
-
maxTurns: Type.Number(),
|
|
394
|
-
durationMs: Type.Number(),
|
|
395
|
-
goal: Type.String(),
|
|
396
|
-
verified: Type.String(),
|
|
397
|
-
resumeSession: Type.Optional(Type.String()),
|
|
398
|
-
worktree: Type.Optional(Type.String()),
|
|
399
|
-
}),
|
|
400
|
-
),
|
|
401
|
-
live: Type.Number(),
|
|
402
|
-
note: Type.Optional(Type.String()),
|
|
403
|
-
}),
|
|
404
|
-
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
405
|
-
const registry = registryFor(ctx);
|
|
406
|
-
const includeSettled = params.includeSettled ?? true;
|
|
407
|
-
const handles = registry.list().filter((handle) => includeSettled || !handle.outcome);
|
|
408
|
-
refreshStatus(ctx, registry);
|
|
409
|
-
const runs = handles.map((handle) => {
|
|
410
|
-
const outcome = handle.outcome;
|
|
411
|
-
return {
|
|
412
|
-
runId: handle.runId,
|
|
413
|
-
status: outcome?.status ?? handle.status,
|
|
414
|
-
scope: handle.scope,
|
|
415
|
-
turns: outcome?.turns ?? handle.progress.turns,
|
|
416
|
-
maxTurns: handle.maxTurns,
|
|
417
|
-
durationMs: outcome?.durationMs ?? Date.now() - handle.startedAt,
|
|
418
|
-
goal: handle.goal,
|
|
419
|
-
verified: String(outcome?.verified ?? "not-run"),
|
|
420
|
-
resumeSession: outcome?.sessionFile ?? handle.resumeSession,
|
|
421
|
-
worktree: outcome?.worktree?.path,
|
|
422
|
-
};
|
|
423
|
-
});
|
|
424
|
-
const live = registry.runningCount;
|
|
425
|
-
const lines = registry.lines();
|
|
426
|
-
const text =
|
|
427
|
-
lines.length === 0
|
|
428
|
-
? "No delegations in this session."
|
|
429
|
-
: [`${live} live · ${lines.length} total`, "", ...lines].join("\n");
|
|
430
|
-
return {
|
|
431
|
-
content: [{ type: "text" as const, text }],
|
|
432
|
-
structuredContent: asJson({ runs, live }),
|
|
433
|
-
details: { live, total: lines.length },
|
|
434
|
-
};
|
|
435
|
-
},
|
|
436
|
-
});
|
|
437
|
-
|
|
438
|
-
pi.registerTool({
|
|
439
|
-
name: "delegate_await",
|
|
440
|
-
label: "Await Delegations",
|
|
553
|
+
name: "delegate_status",
|
|
554
|
+
label: "Delegations",
|
|
441
555
|
description:
|
|
442
|
-
"
|
|
443
|
-
promptSnippet: "
|
|
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",
|
|
444
558
|
promptGuidelines: [
|
|
445
|
-
|
|
446
|
-
"
|
|
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.",
|
|
447
561
|
],
|
|
448
562
|
parameters: Type.Object({
|
|
449
|
-
runIds: Type.
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
Type.Integer({
|
|
453
|
-
minimum: 0,
|
|
454
|
-
maximum: 50000,
|
|
455
|
-
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.',
|
|
456
566
|
}),
|
|
457
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." })),
|
|
458
570
|
}),
|
|
459
571
|
outputSchema: Type.Object({
|
|
572
|
+
total: Type.Number(),
|
|
573
|
+
live: Type.Number(),
|
|
460
574
|
settled: Type.Boolean(),
|
|
461
575
|
timedOutWaiting: Type.Boolean(),
|
|
462
|
-
outcomes: Type.Array(
|
|
463
|
-
stillRunning: Type.Array(
|
|
576
|
+
outcomes: Type.Array(runSchema),
|
|
577
|
+
stillRunning: Type.Array(runSchema),
|
|
578
|
+
runs: Type.Array(listRowSchema),
|
|
464
579
|
unknown: Type.Array(Type.String()),
|
|
465
580
|
note: Type.Optional(Type.String()),
|
|
466
581
|
}),
|
|
467
582
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
468
583
|
const registry = registryFor(ctx);
|
|
469
|
-
const
|
|
470
|
-
const
|
|
471
|
-
const
|
|
584
|
+
const requested = params.runIds;
|
|
585
|
+
const all = requested === "all";
|
|
586
|
+
const named = namedRuns(registry, requested);
|
|
587
|
+
const total = registry.list().length;
|
|
472
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
|
+
});
|
|
473
641
|
const lines = result.outcomes.map((outcome) => formatOutcome(outcome));
|
|
474
642
|
if (result.stillRunning.length > 0) {
|
|
475
643
|
lines.push("", "Still running:");
|
|
476
644
|
for (const outcome of result.stillRunning) {
|
|
477
|
-
lines.push(
|
|
645
|
+
lines.push(" " + outcome.runId + " · " + outcome.status + " · " + outcome.turns + " turns");
|
|
478
646
|
}
|
|
479
647
|
}
|
|
480
|
-
if (result.unknown.length > 0) lines.push("",
|
|
648
|
+
if (result.unknown.length > 0) lines.push("", "Unknown runs: " + result.unknown.join(", "));
|
|
481
649
|
if (result.note) lines.push("", result.note);
|
|
482
650
|
if (lines.length === 0) lines.push("No delegation matched those run ids.");
|
|
483
651
|
const anyFailure = result.outcomes.some((outcome) => isFailure(outcome.status));
|
|
484
652
|
return {
|
|
485
653
|
content: [{ type: "text" as const, text: lines.join("\n") }],
|
|
486
|
-
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
|
+
}),
|
|
487
665
|
details: { settled: result.settled, timedOutWaiting: result.timedOutWaiting },
|
|
488
666
|
isError: anyFailure,
|
|
489
667
|
};
|
|
@@ -494,27 +672,23 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
494
672
|
name: "delegate_send",
|
|
495
673
|
label: "Send To Delegation",
|
|
496
674
|
description:
|
|
497
|
-
"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.",
|
|
498
676
|
promptSnippet: "Send one message to a running delegation",
|
|
499
677
|
promptGuidelines: [
|
|
500
678
|
"Use delegate_send to correct course on a running child instead of cancelling and starting again.",
|
|
501
|
-
"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.",
|
|
502
680
|
],
|
|
503
681
|
parameters: Type.Object({
|
|
504
682
|
runId: Type.String({ description: "The run to message." }),
|
|
505
683
|
text: Type.String({ maxLength: 8000, description: "What the child should do differently, in one or two sentences." }),
|
|
506
684
|
}),
|
|
507
|
-
outputSchema: Type.Object({
|
|
508
|
-
ok: Type.Boolean(),
|
|
509
|
-
runId: Type.String(),
|
|
510
|
-
error: Type.Optional(Type.String()),
|
|
511
|
-
}),
|
|
685
|
+
outputSchema: Type.Object({ ok: Type.Boolean(), runId: Type.String(), error: Type.Optional(Type.String()) }),
|
|
512
686
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
513
687
|
const registry = registryFor(ctx);
|
|
514
688
|
const result = registry.send(params.runId, params.text);
|
|
515
689
|
const text = result.ok
|
|
516
|
-
?
|
|
517
|
-
:
|
|
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") + ".";
|
|
518
692
|
return {
|
|
519
693
|
content: [{ type: "text" as const, text }],
|
|
520
694
|
structuredContent: asJson({ ok: result.ok, runId: params.runId, error: result.error }),
|
|
@@ -528,19 +702,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
528
702
|
name: "delegate_cancel",
|
|
529
703
|
label: "Cancel Delegations",
|
|
530
704
|
description:
|
|
531
|
-
"Stop running delegations with a graceful signal, a grace period, a process-tree fence, and a containment verdict.
|
|
532
|
-
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",
|
|
533
707
|
promptGuidelines: [
|
|
534
|
-
"When a delegation is no longer needed or is stuck,
|
|
535
|
-
"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.",
|
|
536
710
|
],
|
|
537
711
|
parameters: Type.Object({
|
|
538
|
-
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.' }),
|
|
539
713
|
graceMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 30000, description: "Grace period between the graceful signal and the fence. Default 3000." })),
|
|
540
714
|
}),
|
|
541
715
|
outputSchema: Type.Object({
|
|
542
716
|
containment: Type.String(),
|
|
543
|
-
outcomes: Type.Array(
|
|
717
|
+
outcomes: Type.Array(runSchema),
|
|
544
718
|
unknown: Type.Array(Type.String()),
|
|
545
719
|
note: Type.Optional(Type.String()),
|
|
546
720
|
}),
|
|
@@ -548,9 +722,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
548
722
|
const registry = registryFor(ctx);
|
|
549
723
|
const requested = Array.isArray(params.runIds) ? params.runIds : [params.runIds];
|
|
550
724
|
const all = requested.length === 1 && requested[0] === "all";
|
|
551
|
-
const runIds = all
|
|
552
|
-
? registry.list().filter((handle) => !handle.outcome).map((handle) => handle.runId)
|
|
553
|
-
: requested;
|
|
725
|
+
const runIds = all ? registry.liveIds() : requested;
|
|
554
726
|
if (runIds.length === 0) {
|
|
555
727
|
return {
|
|
556
728
|
content: [{ type: "text" as const, text: "No running delegations to cancel." }],
|
|
@@ -567,9 +739,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
567
739
|
content: [{ type: "text" as const, text: lines.join("\n") }],
|
|
568
740
|
structuredContent: asJson(result),
|
|
569
741
|
details: { containment: result.containment },
|
|
570
|
-
// A cancellation that leaked is a failed cancellation. Reporting it
|
|
571
|
-
//
|
|
572
|
-
// `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.
|
|
573
744
|
isError: result.containment === "leaked",
|
|
574
745
|
};
|
|
575
746
|
},
|
|
@@ -580,18 +751,42 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
580
751
|
defaults: {
|
|
581
752
|
maxTurns: DEFAULT_MAX_TURNS,
|
|
582
753
|
timeoutMinutes: DEFAULT_TIMEOUT_MINUTES,
|
|
583
|
-
maxCostUsd: DEFAULT_MAX_COST_USD,
|
|
754
|
+
maxCostUsd: parentSpec?.maxCostUsd ?? DEFAULT_MAX_COST_USD,
|
|
755
|
+
maxDepth: parentSpec?.maxDepth ?? DEFAULT_MAX_DEPTH,
|
|
584
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
|
+
}),
|
|
585
764
|
});
|
|
586
765
|
|
|
587
766
|
pi.on("session_start", async (event, ctx) => {
|
|
588
767
|
const registry = registryFor(ctx);
|
|
589
768
|
refreshStatus(ctx, registry);
|
|
590
769
|
if (event.reason === "reload") return;
|
|
770
|
+
// A delegated child shares the record root with its parent, and its own
|
|
771
|
+
// session is a short-lived one. Adopting here claimed a workspace run the
|
|
772
|
+
// real session was supposed to report, and consumed its verdict inside a
|
|
773
|
+
// child that exits minutes later; pruning deleted records no child owns.
|
|
774
|
+
// Both belong to the session that owns the machine, not to a child.
|
|
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
|
+
}
|
|
591
786
|
const adopted = await registry.adoptExisting();
|
|
592
787
|
if (adopted.length > 0) {
|
|
593
788
|
try {
|
|
594
|
-
ctx.ui.notify(
|
|
789
|
+
ctx.ui.notify("delegate: re-adopted " + adopted.length + " workspace run(s)", "info");
|
|
595
790
|
} catch {
|
|
596
791
|
// a non-interactive session has no footer to write to
|
|
597
792
|
}
|