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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-goal-delegate",
3
- "version": "0.2.0",
4
- "description": "Bounded delegation for Pi: one self-contained goal, a fresh child agent, and a contract that says when it is done and what proves it.",
3
+ "version": "0.3.1",
4
+ "description": "Bounded delegation for Pi: one goal, a fresh child agent, and a return value that says verified or not. Waits inline by default; wait: false returns a live handle.",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
7
7
  "author": "Zhuocheng-Lang <2435060515@st.usst.edu.cn>",
@@ -1,74 +1,158 @@
1
1
  ---
2
2
  name: delegate
3
- description: Hand a self-contained goal to a fresh child agent under a verification contract, then let its completion wake the session. Use when the work needs many turns in a clean context, when you fan out parallel goals through codemode, when a goal outlives one Pi session, or when a task needs evidence rather than a claim.
3
+ description: Hand one goal to a fresh child agent with its own context window and a verification gate, and get the verified outcome back. Use when a task splits into two or more independent workstreams, when an exploration or build loop would take more than about fifteen tool calls in the parent context, or when a mechanical job can run on a cheaper model under a verify command. Waits inline by default; wait false returns a live handle.
4
4
  ---
5
5
 
6
6
  # Delegation
7
7
 
8
- A delegation hands one goal to a fresh child Pi process with no conversation history, a budget, and a completion contract. The parent gets a handle in about a second. The child completion wakes the session as a `delegate-completion` message.
8
+ A delegation hands one goal to a fresh Pi child process with its own context
9
+ window, budget, and completion contract. `delegate_start` returns the verified
10
+ outcome. You run the fan-out in `codemode` and read the results in the same
11
+ script.
9
12
 
10
- ## Decide before you delegate
13
+ ## When to delegate
11
14
 
12
- Delegate when all three hold:
15
+ Delegate as soon as one of these is true. Each one is decidable from the request
16
+ in seconds, before any work starts:
13
17
 
14
- - The goal is self-contained: you can state it without this conversation.
15
- - The work needs many turns in a clean context (the measured median is 110 turns and 18 minutes).
16
- - A command, test, or diff can verify the result.
18
+ - **Fan-out >= 2.** The task splits into two or more independent workstreams:
19
+ several documents or modules rewritten, separate subsystems audited, unrelated
20
+ test suites fixed. One workstream is not a reason to delegate.
21
+ - **Long loop in a clean context.** Exploration, reverse engineering,
22
+ build-and-fix iteration, or verification that will take more than about fifteen
23
+ tool calls. The child absorbs the search noise; you get the verdict.
24
+ - **Cheaper mechanical execution.** A well-specified rename, migration, doc
25
+ rewrite, or test backfill can run on a faster or cheaper `model` with a
26
+ `verify` command deciding whether the work counts.
17
27
 
18
- When a task takes one tool call, needs user input at each step, or requires this conversation, work inline.
28
+ Do the work inline when the change is a one-to-five-call edit, when it needs
29
+ back-and-forth with the user, or when it touches uncommitted state the child
30
+ would collide with.
19
31
 
20
32
  ## Write the contract
21
33
 
22
- Each parameter has a schema in `delegate_start`. Shape the contract fields and overrides as follows:
23
-
24
- - **goal**: Name the target artifact in one imperative objective: `"Make pnpm test pass in packages/app"` instead of `"look at the tests"`.
25
- - **doneWhen**: State a falsifiable condition: a command exits 0, a test passes, or a file has specific content.
26
- - **verify**: Pass the single command that proves the goal. It gates `delegate_complete`. A failure returns the output to the live child for repair. After a passing claim, the parent independently re-runs the command with the same dropped-environment policy. A parent failure turns the run into `unverified`.
27
- - **resultSchema**: Pass a JSON Schema so codemode gets deterministic structured output. `delegate_start` refuses an unusable schema (an unresolved `$ref`) up front instead of letting it fail every completion. The child must then supply `delegate_complete({ summary, evidence, result })`. `delegate_complete` rejects an invalid result shape and keeps the run alive.
28
- - **context**: Include only non-discoverable facts: prior decisions, exact paths, constraints, and files to leave unchanged. Omit conversation transcripts.
29
- - **Overrides**:
30
- - When the work is read-only or restricted, pass `tools` (for example `"read,grep"`).
31
- - When the task is mechanical, pass a cheaper `model` (`provider/id`). Without `model`, the parent passes its own session model explicitly.
32
- - When a refactor exceeds the 90th-percentile budget (150 turns, 60 minutes), raise `maxTurns`. Split a slow goal instead of raising `timeoutMinutes`.
33
- - When the run must survive closing Pi, pass `scope: "workspace"`. Only a later session in the same directory re-adopts it.
34
- - When the host cannot answer permission asks or must exclude ambient extensions, skills, MCP servers, and context files, pass `isolated: true`.
35
- - When two children would edit the same tree, pass `worktree: true`. Each gets its own checkout and branch. Read `outcome.integration` for status, diff stat, `changes.patch`, and `applyCheck`. Nothing is auto-committed or merged.
36
- - When the child must decompose its goal, pass `maxDepth` (0-3). Default 0 disables nested delegation. A child stays within the parent's depth, spend, and deadline limits.
37
- - When the goal continues earlier work, pass `resumeFrom` with the previous run id instead of repeating its context. A worktree-backed run resumes in the same checkout. `resumedFrom` records the lineage. The new run gets a fresh budget.
38
- - When a run needs a spend cap, pass `maxCostUsd`. A run that crosses the cap ends as `limit`. The cap applies to one run only. A child's cap stays at or below its parent's cap. The platform sums no caps across the tree.
34
+ `goal` is the only required argument. Everything else is a sparse input or lives
35
+ in `options`.
36
+
37
+ - **goal**: name the artifact and the end state. "Make pnpm test pass in
38
+ packages/app", not "look at the tests".
39
+ - **doneWhen**: a falsifiable condition: a command exits 0, a test passes, a file
40
+ has specific content.
41
+ - **verify**: the one command that proves the goal. It gates
42
+ `delegate_complete` inside the child; a failure returns the output to the live
43
+ child for repair. After the child claims completion the parent re-runs the same
44
+ command with the same dropped environment. A parent-side failure turns the run
45
+ into `unverified`.
46
+ - **context**: only facts the child cannot discover: prior decisions, exact
47
+ paths, constraints, files to leave alone. No transcripts.
48
+ - **worktree: true** when two children would edit the same tree.
49
+
50
+ `options` carries the rest:
51
+
52
+ - `model` for a cheaper or different provider (`provider/id`). Without it the
53
+ parent passes its own session model explicitly.
54
+ - `tools` as a read-only allowlist, for example `"read,grep"`.
55
+ - `resultSchema` for a validated structured result, so a `codemode` fan-out can
56
+ aggregate JSON instead of prose.
57
+ - `maxTurns` when the work exceeds the 150-turn default. Split a slow goal
58
+ instead of raising `timeoutMinutes`.
59
+ - `scope: "workspace"` when the run must outlive Pi. Only a later session in the
60
+ same directory re-adopts it.
61
+ - `isolated: true` when the host cannot answer permission asks, or when ambient
62
+ extensions, skills, MCP servers, and context files must not reach the child.
63
+ - `maxDepth` (0-3) when the child must decompose its goal. A child stays inside
64
+ the parent's depth, spend, and deadline limits.
65
+ - `resumeFrom` with a previous run id to continue that child's context instead of
66
+ repeating it. The resumed run gets a fresh budget and, when the first run had
67
+ one, the same worktree.
68
+ - `maxCostUsd` for a per-run spend cap. A run that crosses it ends as `limit`.
69
+
70
+ A known option name written at the top level is lifted into `options`, so either
71
+ shape works.
72
+
73
+ ## Two modes
74
+
75
+ ### Inline (default)
76
+
77
+ `delegate_start` holds the call open until the child settles and returns the
78
+ outcome. The wait is capped by the run's own `timeoutMinutes`, so it cannot
79
+ outlive the delegation.
39
80
 
40
- ## Steer instead of restarting
81
+ ```js
82
+ // @options: {"timeout_ms": 1800000}
83
+ // goal: fan out two verified delegations and return their outcomes
84
+ const goals = [
85
+ { goal: "Make pnpm test pass in packages/api", verify: "pnpm --dir packages/api test", worktree: true },
86
+ { goal: "Make pnpm test pass in packages/web", verify: "pnpm --dir packages/web test", worktree: true },
87
+ ];
88
+ const outcomes = await Promise.all(goals.map((g) => tools.delegate_start(g)));
89
+ return outcomes.map(({ runId, status, verified, summary, integration }) => ({
90
+ runId, status, verified, summary, patch: integration?.patchPath,
91
+ }));
92
+ ```
41
93
 
42
- `delegate_send(runId, text)` hands a running child one message. The child reads it at its next turn start. Pi queues it with `deliverAs: "steer"`, so it lands before the next model call instead of waiting for settle. Correcting course costs one call. Restarting costs the whole budget and the context.
94
+ Raise `timeout_ms` to cover the whole fan-out. A `codemode` script has no
95
+ deadline unless its header sets one, and a host default of 60 seconds cuts any
96
+ real delegation short.
43
97
 
44
- ## At most a few at once
98
+ If the script deadline or an abort cuts the wait, the child is **not** cancelled.
99
+ The call returns a live handle, and the completion is delivered later as a
100
+ `delegate-completion` message.
101
+
102
+ ### Background handle (`wait: false`)
103
+
104
+ Use it when you want to keep working or let the session go idle.
105
+
106
+ - **Ordinary session**: start the runs, then end the turn. One coalesced
107
+ `delegate-completion` message wakes the session when they settle.
108
+ - **Active `/goal`**: do not end the turn bare. Goal mode continues
109
+ automatically while the child is still running. Either keep the default
110
+ `wait: true`, or call `goal_wait({ goal_id, reason })` alone so Goal mode
111
+ pauses until `delegate-completion` arrives. When `delegate_start` returns a
112
+ live handle under Goal mode it prints the exact `goal_wait` call with the
113
+ current goal id.
45
114
 
46
- One session keeps `PI_DELEGATE_MAX_LIVE` delegations live, four by default. `delegate_start` refuses a larger fan-out and names the live runs. Fan out in waves, or raise the limit deliberately.
115
+ ## Collect outcomes
47
116
 
48
- ## Fan out in codemode, wait outside it
117
+ `delegate_status` inspects and optionally waits:
49
118
 
50
119
  ```js
51
- const goals = [
52
- { goal: "Make pnpm test pass in packages/api", doneWhen: "pnpm --dir packages/api test exits 0" },
53
- { goal: "Make pnpm test pass in packages/web", doneWhen: "pnpm --dir packages/web test exits 0" },
54
- ];
55
- const handles = await Promise.all(goals.map((goal) => tools.delegate_start(goal)));
56
- return handles.map((handle) => handle.runId);
57
- // End the turn. One coalesced delegate-completion message wakes you when they settle.
120
+ const all = await tools.delegate_status({}); // list, claims nothing
121
+ const one = await tools.delegate_status({ runIds: runId }); // claims that run
122
+ const done = await tools.delegate_status({ runIds, waitMs: 600_000 });
123
+ const first = await tools.delegate_status({ runIds, mode: "any", waitMs: 600_000 });
58
124
  ```
59
125
 
60
- Keep each codemode script to at most one `delegate_await` call within the 60-second script budget. When a goal takes minutes, end the turn after `delegate_start` instead of looping on `delegate_await`.
126
+ ## Steer instead of restarting
127
+
128
+ `delegate_send(runId, text)` hands a running child one message. It reads it at its
129
+ next turn start, queued as a steer message before the next model call. Correcting
130
+ course costs one call; a restart costs the whole budget and the context.
131
+
132
+ ## At most a few at once
133
+
134
+ One session keeps `PI_DELEGATE_MAX_LIVE` delegations live, four by default.
135
+ `delegate_start` refuses a larger fan-out and names the live runs. Fan out in
136
+ waves, or raise the limit deliberately.
61
137
 
62
138
  ## Handle the outcome
63
139
 
64
140
  | Status | Meaning | Next action |
65
141
  |---|---|---|
66
- | `complete` | The child passed its completion gate. `verified: true` means the parent's independent `verify` run also passed. `"not-run"` means the parent supplied no `verify` command. Structured output is in `result`. | With `verified: true`, report success and consume `result` directly. With `"not-run"`, verify the `evidence` or `result` yourself first. |
67
- | `unverified` | The child claimed completion and the parent's `verify` command failed. | Read `verification.output`. The work is not done, whatever the child said. |
68
- | `blocked` | The child needs a decision, credential, or fact. It is in `needs`, not `evidence`. | Start a new delegation with the answer in `context`, or ask the user. |
69
- | `no_progress` | A circuit breaker fired: repeated call, repeated failure, or two identical idle turns. | Narrow the goal or change the approach instead of restarting the same goal. |
142
+ | `complete` | The child passed its completion gate. `verified: true` means the parent's own `verify` run also passed; `"not-run"` means no verify command was given. Structured output is in `result`. | With `verified: true`, report success and use `result` directly. With `"not-run"`, check the evidence yourself. |
143
+ | `unverified` | The child claimed completion and the parent's `verify` run failed. | Read `verification.output`. The work is not done, whatever the child said. |
144
+ | `blocked` | The child needs a decision, credential, or fact. It is in `needs`. | Start a new run with the answer in `context`, or ask the user. |
145
+ | `no_progress` | A circuit breaker fired: repeated call, repeated failure, or two identical idle turns. | Narrow the goal or change the approach; do not restart the same goal. |
70
146
  | `limit` | The turn budget or the spend cap ran out before a verdict. | Raise `maxTurns`/`maxCostUsd` or split the goal. |
71
147
  | `timeout` | The wall clock ran out and the fence stopped the child. | Split the goal into smaller parts. |
72
- | `aborted` | A caller ran `delegate_cancel`. | Stop tracking the run. Read `containment`: `gone` is proof, `leaked` names the survivors, `unproven` means the platform cannot prove absence — report it as unproven. |
73
- | `error` | Spawn failure, child crash, provider error, or missing verdict. | Read `<runDir>/child.log` or `<runDir>/outcome.json` to diagnose the failure. |
148
+ | `aborted` | Something called `delegate_cancel`. | Read `containment`: `gone` is proof, `leaked` names the survivors, `unproven` means this platform cannot prove absence. Report it as unproven. |
149
+ | `error` | Spawn failure, child crash, provider error, or no verdict. | Read `<runDir>/child.log` or `<runDir>/outcome.json`. |
74
150
  | `lost` | An adopted workspace record has no exit and no provable liveness. | Inspect `<runDir>` and re-delegate the remaining work. |
151
+
152
+ ## When nothing works
153
+
154
+ `delegate_status` with no runs prints the run root and the record count. If a run
155
+ you started is missing, compare that path with where you expected records to be.
156
+ A human can run `/delegate doctor` for a full installation check: run root
157
+ writability, the child launcher, git, retention plan, limits, and containment
158
+ mode.
package/src/command.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * /delegate read <id|prefix> one run in full
7
7
  * /delegate log <id|prefix> the tail of the child output
8
8
  * /delegate cancel <id|prefix|all> stop runs
9
+ * /delegate doctor check this installation
9
10
  *
10
11
  * The command is a second front end for the same registry the delegate_* tools
11
12
  * use, so it accepts the same options and enforces the same limits. Anything the
@@ -16,6 +17,7 @@
16
17
  import { join, resolve } from "node:path";
17
18
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
18
19
  import { MAX_MAX_DEPTH, MAX_MAX_TURNS, MAX_TIMEOUT_MINUTES, shortGoal } from "./contract.ts";
20
+ import { formatDoctor, type DoctorReport } from "./doctor.ts";
19
21
  import { readTail } from "./events.ts";
20
22
  import { auditResultSchema } from "./result-schema.ts";
21
23
  import type { RunRegistry } from "./registry.ts";
@@ -30,6 +32,17 @@ export interface DelegateCommandOptions {
30
32
  /** The registry of the session this command runs in. */
31
33
  registryFor: (ctx: ExtensionCommandContext) => RunRegistry;
32
34
  defaults: { maxTurns: number; timeoutMinutes: number; maxCostUsd?: number; maxDepth?: number };
35
+ /** The installation self-check, supplied by the extension that owns the tools. */
36
+ doctor?: (ctx: ExtensionCommandContext) => DoctorReport;
37
+ /**
38
+ * Where a session without a UI writes.
39
+ *
40
+ * A dependency rather than `process.stdout.write`: a test that replaces the
41
+ * process stream also replaces whatever protocol the host is speaking on it,
42
+ * and a test that silently eats the runner's own events is a test that never
43
+ * reports whether it passed.
44
+ */
45
+ write?: (line: string) => void;
33
46
  }
34
47
 
35
48
  const USAGE = [
@@ -51,10 +64,12 @@ const USAGE = [
51
64
  " --worktree give the child its own git worktree and branch",
52
65
  " --resume <id|session> continue a previous child session",
53
66
  " --cwd <dir> child working directory, relative to the session directory",
67
+ " --wait hold the turn open until the run settles (the default in print mode)",
68
+ " --background return as soon as the run is admitted (the default in the TUI)",
54
69
  "",
55
70
  "Put -- on its own to end options when the goal itself contains --words.",
56
71
  "",
57
- "Other: /delegate list · /delegate read <id> · /delegate log <id> · /delegate send <id> <text> · /delegate cancel <id|prefix|all>",
72
+ "Other: /delegate list · /delegate read <id> · /delegate log <id> · /delegate send <id> <text> · /delegate cancel <id|prefix|all> · /delegate doctor",
58
73
  ].join("\n");
59
74
 
60
75
  const KNOWN_FLAGS = new Set([
@@ -73,10 +88,12 @@ const KNOWN_FLAGS = new Set([
73
88
  "worktree",
74
89
  "resume",
75
90
  "cwd",
91
+ "wait",
92
+ "background",
76
93
  ]);
77
94
 
78
95
  /** Flags that stand alone; their value is their presence. */
79
- const BOOLEAN_FLAGS = new Set(["isolated", "worktree"]);
96
+ const BOOLEAN_FLAGS = new Set(["isolated", "worktree", "wait", "background"]);
80
97
 
81
98
  /** Split on whitespace, honouring single and double quotes. */
82
99
  function tokenize(input: string): string[] {
@@ -182,7 +199,14 @@ function booleanFlag(value: string | undefined, fallback: boolean, name: string)
182
199
  throw new Error(`--${name} takes true or false.`);
183
200
  }
184
201
 
185
- function emit(ctx: ExtensionCommandContext, text: string, level: "info" | "warning" | "error" = "info") {
202
+ function emit(
203
+ ctx: ExtensionCommandContext,
204
+ text: string,
205
+ level: "info" | "warning" | "error" = "info",
206
+ write: (line: string) => void = (line) => {
207
+ process.stdout.write(`${line}\n`);
208
+ },
209
+ ) {
186
210
  if (ctx.mode === "tui" || ctx.mode === "rpc") {
187
211
  try {
188
212
  ctx.ui.notify(text, level);
@@ -191,10 +215,13 @@ function emit(ctx: ExtensionCommandContext, text: string, level: "info" | "warni
191
215
  }
192
216
  return;
193
217
  }
194
- process.stdout.write(`${text}\n`);
218
+ write(text);
195
219
  }
196
220
 
197
221
  export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateCommandOptions) {
222
+ /** Every line this command prints, through the sink the host supplied. */
223
+ const emitTo = (ctx: ExtensionCommandContext, text: string, level: "info" | "warning" | "error" = "info"): void =>
224
+ emit(ctx, text, level, options.write);
198
225
  const pane = (ctx: ExtensionCommandContext) => {
199
226
  try {
200
227
  const registry = options.registryFor(ctx);
@@ -227,24 +254,24 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
227
254
  const registry = options.registryFor(ctx);
228
255
  const lines = registry.lines();
229
256
  if (lines.length === 0) {
230
- emit(ctx, `No delegations in this session.\n\n${USAGE}`);
257
+ emitTo(ctx, `No delegations in this session.\n\n${USAGE}`);
231
258
  return;
232
259
  }
233
260
  if (ctx.mode !== "tui") {
234
- emit(ctx, ["Delegations:", ...lines].join("\n"));
261
+ emitTo(ctx, ["Delegations:", ...lines].join("\n"));
235
262
  return;
236
263
  }
237
264
  const choice = await ctx.ui.select("Delegations", ["(close)", ...lines]);
238
265
  if (!choice || choice === "(close)") return;
239
266
  const runId = choice.split(" · ")[0];
240
- emit(ctx, (runId ? registry.describe(runId) : undefined) ?? "No such run.");
267
+ emitTo(ctx, (runId ? registry.describe(runId) : undefined) ?? "No such run.");
241
268
  };
242
269
 
243
270
  /** /delegate read: one run in full. */
244
271
  const describeTarget = (ctx: ExtensionCommandContext, target: string) => {
245
272
  const registry = options.registryFor(ctx);
246
273
  const runId = targetRun(registry, target);
247
- emit(ctx, runId ? (registry.describe(runId) ?? "No such run.") : "No matching run.");
274
+ emitTo(ctx, runId ? (registry.describe(runId) ?? "No such run.") : "No matching run.");
248
275
  };
249
276
 
250
277
  /** /delegate log: the tail of the child stderr, read from the end. */
@@ -253,14 +280,14 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
253
280
  const runId = targetRun(registry, target);
254
281
  const handle: RunHandle | undefined = runId ? registry.get(runId) : undefined;
255
282
  if (!handle) {
256
- emit(ctx, "No matching run.", "error");
283
+ emitTo(ctx, "No matching run.", "error");
257
284
  return;
258
285
  }
259
286
  try {
260
287
  const log = (await readTail(join(handle.runDir, "child.log"), LOG_TAIL_BYTES)).trim();
261
- emit(ctx, log ? log.split("\n").slice(-40).join("\n") : "(no child stderr)");
288
+ emitTo(ctx, log ? log.split("\n").slice(-40).join("\n") : "(no child stderr)");
262
289
  } catch {
263
- emit(ctx, "(no child log yet)");
290
+ emitTo(ctx, "(no child log yet)");
264
291
  }
265
292
  };
266
293
 
@@ -274,7 +301,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
274
301
  const registry = options.registryFor(ctx);
275
302
  const running = registry.list().filter((handle) => !handle.outcome);
276
303
  if (running.length === 0) {
277
- emit(ctx, "No running delegations to cancel.");
304
+ emitTo(ctx, "No running delegations to cancel.");
278
305
  return;
279
306
  }
280
307
  let runIds: string[];
@@ -286,7 +313,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
286
313
  } else {
287
314
  const runId = resolveId(registry, target);
288
315
  if (!runId) {
289
- emit(ctx, `No matching run: ${target}`, "error");
316
+ emitTo(ctx, `No matching run: ${target}`, "error");
290
317
  return;
291
318
  }
292
319
  runIds = [runId];
@@ -294,13 +321,13 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
294
321
  const result = await registry.cancelRuns({ runIds });
295
322
  pane(ctx);
296
323
  for (const outcome of result.outcomes) {
297
- emit(ctx, formatOutcome(outcome), outcome.status === "aborted" ? "warning" : "info");
324
+ emitTo(ctx, formatOutcome(outcome), outcome.status === "aborted" ? "warning" : "info");
298
325
  }
299
- if (result.containment === "leaked") emit(ctx, "WARNING: some descendants survived the fence.", "error");
326
+ if (result.containment === "leaked") emitTo(ctx, "WARNING: some descendants survived the fence.", "error");
300
327
  if (result.containment === "unproven") {
301
- emit(ctx, "Containment unproven: this platform exposes no process table, so absence could not be verified.", "warning");
328
+ emitTo(ctx, "Containment unproven: this platform exposes no process table, so absence could not be verified.", "warning");
302
329
  }
303
- if (result.unknown.length > 0) emit(ctx, `Unknown runs: ${result.unknown.join(", ")}`, "error");
330
+ if (result.unknown.length > 0) emitTo(ctx, `Unknown runs: ${result.unknown.join(", ")}`, "error");
304
331
  };
305
332
 
306
333
  /** /delegate send <id|prefix> <text>: hand a running child one message. */
@@ -309,17 +336,17 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
309
336
  const [target = "", ...rest] = raw.split(/\s+/u);
310
337
  const text = rest.join(" ").trim();
311
338
  if (!target || !text) {
312
- emit(ctx, "Usage: /delegate send <id|prefix> <text>", "error");
339
+ emitTo(ctx, "Usage: /delegate send <id|prefix> <text>", "error");
313
340
  return;
314
341
  }
315
342
  const runId = resolveId(registry, target);
316
343
  if (!runId) {
317
- emit(ctx, `No matching run: ${target}`, "error");
344
+ emitTo(ctx, `No matching run: ${target}`, "error");
318
345
  return;
319
346
  }
320
347
  const result = registry.send(runId, text);
321
348
  pane(ctx);
322
- emit(
349
+ emitTo(
323
350
  ctx,
324
351
  result.ok
325
352
  ? `Sent to ${runId}. The child reads it at its next turn start.`
@@ -328,6 +355,30 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
328
355
  );
329
356
  };
330
357
 
358
+ /**
359
+ * /delegate doctor: the installation self-check.
360
+ *
361
+ * A check that cannot run is reported as the failure it is, not as a crash:
362
+ * the command a user runs when nothing works must not be the command that
363
+ * throws.
364
+ */
365
+ const report = (ctx: ExtensionCommandContext) => {
366
+ if (!options.doctor) {
367
+ emitTo(ctx, "This host did not register the delegate tools, so there is nothing to check.", "error");
368
+ return;
369
+ }
370
+ let text: string;
371
+ let ok = false;
372
+ try {
373
+ const result = options.doctor(ctx);
374
+ text = formatDoctor(result);
375
+ ok = result.ok;
376
+ } catch (error) {
377
+ text = "delegate doctor failed before it could check anything: " + (error as Error).message;
378
+ }
379
+ emitTo(ctx, text, ok ? "info" : "error");
380
+ };
381
+
331
382
  /** /delegate <goal> [options]: parse, bound, admit, then report. */
332
383
  const start = async (ctx: ExtensionCommandContext, raw: string) => {
333
384
  const registry = options.registryFor(ctx);
@@ -335,11 +386,11 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
335
386
  try {
336
387
  parsed = parseInvocation(raw);
337
388
  } catch (error) {
338
- emit(ctx, `${(error as Error).message}\n\n${USAGE}`, "error");
389
+ emitTo(ctx, `${(error as Error).message}\n\n${USAGE}`, "error");
339
390
  return;
340
391
  }
341
392
  if (!parsed.goal) {
342
- emit(ctx, USAGE, "error");
393
+ emitTo(ctx, USAGE, "error");
343
394
  return;
344
395
  }
345
396
 
@@ -351,7 +402,12 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
351
402
  let scope: "session" | "workspace";
352
403
  let isolated: boolean;
353
404
  let worktree: boolean;
405
+ // Undefined means "whatever the session mode implies": a TUI keeps working
406
+ // and takes the completion message, print mode has nothing else to live for.
407
+ let waitMode: boolean | undefined;
354
408
  try {
409
+ if (parsed.flags.background === "true") waitMode = false;
410
+ else if (parsed.flags.wait === "true") waitMode = true;
355
411
  maxCostUsd = parsed.flags.cost === undefined
356
412
  ? (options.defaults.maxCostUsd ?? 0)
357
413
  : boundedNumber(parsed.flags.cost, 0, "cost", { min: 0, max: 10_000 });
@@ -394,7 +450,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
394
450
  scope = requestedScope === "workspace" ? "workspace" : "session";
395
451
  isolated = booleanFlag(parsed.flags.isolated, false, "isolated");
396
452
  } catch (error) {
397
- emit(ctx, (error as Error).message, "error");
453
+ emitTo(ctx, (error as Error).message, "error");
398
454
  return;
399
455
  }
400
456
 
@@ -419,10 +475,13 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
419
475
  isolated,
420
476
  worktree,
421
477
  resumeFrom: parsed.flags.resume,
478
+ // The command waits on `handle.done` when it waits at all, so the
479
+ // registry's own admission window would only delay the first draw.
480
+ inlineSettleMs: 0,
422
481
  onProgress: () => pane(ctx),
423
482
  });
424
483
  pane(ctx);
425
- emit(
484
+ emitTo(
426
485
  ctx,
427
486
  [
428
487
  `delegate started · ${handle.runId}`,
@@ -432,15 +491,15 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
432
491
  ].join("\n"),
433
492
  );
434
493
 
435
- if (ctx.mode === "tui") {
494
+ if (!(waitMode ?? ctx.mode !== "tui")) {
436
495
  // Nothing keeps a print-mode process alive for a session-scoped run, so
437
- // only the interactive path returns immediately.
496
+ // only the interactive path returns immediately by default.
438
497
  void handle.done.then(() => pane(ctx));
439
498
  return;
440
499
  }
441
500
  const outcome = await handle.done;
442
501
  pane(ctx);
443
- emit(ctx, formatOutcome(outcome), outcome.status === "complete" ? "info" : "warning");
502
+ emitTo(ctx, formatOutcome(outcome), outcome.status === "complete" ? "info" : "warning");
444
503
  };
445
504
 
446
505
  pi.registerCommand("delegate", {
@@ -452,6 +511,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
452
511
  { value: "log", label: "log", description: "Tail the child output of one run" },
453
512
  { value: "send", label: "send", description: "Send a message to a running run" },
454
513
  { value: "cancel", label: "cancel", description: "Cancel runs" },
514
+ { value: "doctor", label: "doctor", description: "Check this installation and report what is wrong" },
455
515
  ];
456
516
  const filtered = items.filter((item) => item.value.startsWith(prefix));
457
517
  return filtered.length > 0 ? filtered : null;
@@ -470,6 +530,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
470
530
  if (first === "log") return tailLog(ctx, raw.slice("log".length).trim());
471
531
  if (first === "cancel") return cancelTarget(ctx, raw.slice("cancel".length).trim());
472
532
  if (first === "send") return sendTarget(ctx, raw.slice("send".length).trim());
533
+ if (first === "doctor") return report(ctx);
473
534
  return start(ctx, raw);
474
535
  },
475
536
  });
package/src/contract.ts CHANGED
@@ -23,6 +23,15 @@ export const MAX_MAX_TURNS = 500;
23
23
  export const DEFAULT_TIMEOUT_MINUTES = 60;
24
24
  export const MAX_TIMEOUT_MINUTES = 240;
25
25
 
26
+ /**
27
+ * The ceiling on a tool-call wait: the ceiling on a delegation itself.
28
+ *
29
+ * A wait that outlives the run it waits for is a wait that cannot report a
30
+ * result, so the two limits are the same number. `codemode` scripts accept
31
+ * `timeout_ms` up to 2^31-1, so nothing above this module had to cap it.
32
+ */
33
+ export const MAX_WAIT_MS = MAX_TIMEOUT_MINUTES * 60_000;
34
+
26
35
  /**
27
36
  * Delegation depth is the number of further child levels a run tree may create.
28
37
  * Zero preserves the original one-level default. An explicit cap enables task