@deathbeam/pi-delegate 0.0.39 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -44,7 +44,7 @@ Explore the codebase and report relevant paths.
44
44
  ```
45
45
 
46
46
  - `name` is required and must be unique
47
- - `descripion` is required
47
+ - `description` is required
48
48
  - `tools` is optional, a comma-separated list of tool names. Defaults to the session tools.
49
49
  - `model` is optional, a tier name or `provider/model[:thinking]`. Defaults to the session model.
50
50
  - `isolated` is optional, defaults to `false`. See [Isolation](#isolation).
package/agents.ts CHANGED
@@ -80,7 +80,7 @@ function loadAgents(dir: string): AgentFile[] {
80
80
  return agents;
81
81
  }
82
82
 
83
- export function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
83
+ function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
84
84
  const dirs = [BUNDLED_AGENT_DIR, DEFAULT_AGENT_DIR, ...stringList(configuredDirs)].map((dir) =>
85
85
  expandPath(dir, cwd),
86
86
  );
package/child.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
2
  import { readdirSync, readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { limitOutput, resultPreview, toolCallDetail } from "./format.ts";
4
+ import { limitOutput, resultPreview, textParts, toolCallDetail } from "./format.ts";
5
5
 
6
6
  type Child = ChildProcessWithoutNullStreams;
7
7
 
@@ -157,7 +157,7 @@ export function runChild(
157
157
  case "message_end": {
158
158
  const role = event.message?.role;
159
159
  if (role !== "assistant" && role !== "user") return;
160
- const text = transcriptText(event.message.content).join("");
160
+ const text = textParts(event.message.content).join("");
161
161
  if (role === "assistant") {
162
162
  childError = event.message.errorMessage;
163
163
  if (text) liveText = text;
@@ -170,7 +170,8 @@ export function runChild(
170
170
  return;
171
171
  }
172
172
  case "agent_settled":
173
- finish(0);
173
+ // A run the child aborted itself (an extension's abort or compaction) is not the task's answer.
174
+ finish(0, event.aborted ? new Error("Delegate run was aborted before it finished") : undefined);
174
175
  return;
175
176
  case "extension_ui_request":
176
177
  if (["select", "confirm", "input", "editor"].includes(event.method)) {
@@ -297,16 +298,6 @@ export function runChild(
297
298
  };
298
299
  }
299
300
 
300
- /** Text parts of a message's content, in order. */
301
- function transcriptText(content: unknown): string[] {
302
- if (typeof content === "string") return [content];
303
- if (!Array.isArray(content)) return [];
304
- return content
305
- .map((part) => (part && typeof part === "object" ? (part as { type?: string; text?: string }) : {}))
306
- .filter((part) => part.type === "text" && typeof part.text === "string")
307
- .map((part) => part.text!);
308
- }
309
-
310
301
  /**
311
302
  * Replays the child's persisted transcript as the activity a revived job continues from, so the
312
303
  * inspector keeps the old history. A missing or unreadable transcript seeds nothing: the revive
@@ -359,7 +350,7 @@ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
359
350
  continue;
360
351
  }
361
352
  // Assistant text lands before its tool calls, matching the live event order.
362
- const text = transcriptText(message.content).join("");
353
+ const text = textParts(message.content).join("");
363
354
  if (text) activity.push({ kind: message.role, text });
364
355
  if (message.role !== "assistant") continue;
365
356
  for (const part of Array.isArray(message.content) ? message.content : []) {
package/format.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { getMarkdownTheme, keyHint, type Theme } from "@earendil-works/pi-coding-agent";
1
+ import { getMarkdownTheme, type KeybindingHints, type Theme } from "@earendil-works/pi-coding-agent";
2
2
  import {
3
3
  type Component,
4
4
  Container,
@@ -65,7 +65,6 @@ export const STATUS_COLORS = {
65
65
  const WIDGET_MAX_JOBS = 5;
66
66
  export const COLLAPSED_OUTPUT_LINES = 10;
67
67
  const MAX_OUTPUT_BYTES = 50 * 1024;
68
- const EXPANDED_PAD = " ";
69
68
 
70
69
  /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
71
70
  function statusIcon(status: JobStatus, now = Date.now()): string {
@@ -130,13 +129,9 @@ export function elapsedMs(job: { startedAt: number; endedAt?: number }, now = Da
130
129
  return (job.endedAt ?? now) - job.startedAt;
131
130
  }
132
131
 
133
- /** Summed wall-clock across jobs; running jobs tick from `now`. Parallel jobs each count their full span. */
134
- export function totalElapsedMs(jobs: { startedAt: number; endedAt?: number }[], now = Date.now()): number {
135
- return jobs.reduce((sum, job) => sum + elapsedMs(job, now), 0);
136
- }
137
-
138
132
  export function tally(running: number, all: { startedAt: number; endedAt?: number }[], now = Date.now()): string {
139
- return `${running} running · ${all.length} total · ${formatDuration(totalElapsedMs(all, now))}`;
133
+ const total = all.reduce((sum, job) => sum + elapsedMs(job, now), 0);
134
+ return `${running} running · ${all.length} total · ${formatDuration(total)}`;
140
135
  }
141
136
 
142
137
  export function toolCallDetail(toolName: string, args: unknown): string {
@@ -161,12 +156,6 @@ export function toolCallDetail(toolName: string, args: unknown): string {
161
156
  return "";
162
157
  }
163
158
  }
164
-
165
- /** Expanded launch metadata; the call renderer shows the task. */
166
- export function launchDetails(info: { model?: string; tools: string[] }): string[] {
167
- return [`${EXPANDED_PAD}Model: ${info.model ?? "default"}`, `${EXPANDED_PAD}Tools: ${formatTools(info.tools)}`];
168
- }
169
-
170
159
  /** Caps a preview at `maxLines`; callers report the hidden count their own way. */
171
160
  export function capLines<T>(lines: T[], maxLines: number): { shown: T[]; hidden: number } {
172
161
  if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
@@ -190,14 +179,26 @@ export function limitOutput(text: string, maxBytes = MAX_OUTPUT_BYTES): string {
190
179
  return `${buffer.subarray(0, end).toString("utf8")}\n\n[Output truncated: ${buffer.length - end} bytes omitted.]`;
191
180
  }
192
181
 
193
- export function resultPreview(result: unknown, maxChars = 120): string | undefined {
194
- const content = (result as { content?: unknown })?.content;
195
- if (!Array.isArray(content)) return undefined;
196
- const text = content
197
- .map((part) => (part as { type?: string; text?: string }) ?? {})
182
+ /** Caps a diff for storage, keeping the truncation note out of the patch so diff renderers never parse it. */
183
+ export function capDiff(text: string): { diff: string; note?: string } {
184
+ const capped = limitOutput(text);
185
+ if (capped === text) return { diff: text };
186
+ const at = capped.lastIndexOf("\n\n[Output truncated: ");
187
+ return { diff: capped.slice(0, at), note: capped.slice(at + 2) };
188
+ }
189
+
190
+ /** The text parts of a message or tool result's content, in order. */
191
+ export function textParts(content: unknown): string[] {
192
+ if (typeof content === "string") return [content];
193
+ if (!Array.isArray(content)) return [];
194
+ return content
195
+ .map((part) => (part && typeof part === "object" ? (part as { type?: string; text?: string }) : {}))
198
196
  .filter((part) => part.type === "text" && typeof part.text === "string")
199
- .map((part) => part.text as string)
200
- .join("\n");
197
+ .map((part) => part.text!);
198
+ }
199
+
200
+ export function resultPreview(result: unknown, maxChars = 120): string | undefined {
201
+ const text = textParts((result as { content?: unknown })?.content).join("\n");
201
202
  const line = text
202
203
  .split("\n")
203
204
  .find((candidate) => candidate.trim())
@@ -224,7 +225,14 @@ export function piDiff(unified: string): string {
224
225
  let hunkSeen = false;
225
226
  let oldNum = 0;
226
227
  let newNum = 0;
227
- let width = 1;
228
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
229
+ // One width for the whole diff, so hunks and files line up.
230
+ const width = Math.max(
231
+ 1,
232
+ ...[...unified.matchAll(new RegExp(HUNK, "gm"))].map(
233
+ ([, os, oc, ns, nc]) => String(Math.max(+os! + (+oc! || 1), +ns! + (+nc! || 1)) - 1).length,
234
+ ),
235
+ );
228
236
  const header = () => {
229
237
  if (!pathShown) {
230
238
  out.push(path);
@@ -239,16 +247,9 @@ export function piDiff(unified: string): string {
239
247
  hunkSeen = false;
240
248
  continue;
241
249
  }
242
- const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
250
+ const hunk = HUNK.exec(line);
243
251
  if (hunk) {
244
- const [, oldStart, oldCount, newStart, newCount] = hunk;
245
- // The width comes free from the hunk header's last line number on each side.
246
- width = String(
247
- Math.max(
248
- Number(oldStart) + (Number(oldCount) || 1) - 1,
249
- Number(newStart) + (Number(newCount) || 1) - 1,
250
- ),
251
- ).length;
252
+ const [, oldStart, , newStart] = hunk;
252
253
  header();
253
254
  if (hunkSeen) out.push(` ${"".padStart(width, " ")} ...`);
254
255
  hunkSeen = true;
@@ -301,14 +302,20 @@ export function resultFallback(body: string, theme: Theme, isError: boolean): Te
301
302
  return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
302
303
  }
303
304
 
304
- export function moreLines(theme: Theme, hidden: number): string {
305
+ export function moreLines(theme: Theme, hidden: number, keyHint: KeybindingHints["keyHint"]): string {
305
306
  return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
306
307
  }
307
308
 
308
- export function appendOutput(container: Container, body: string, expanded: boolean, theme: Theme): void {
309
+ export function appendOutput(
310
+ container: Container,
311
+ body: string,
312
+ expanded: boolean,
313
+ theme: Theme,
314
+ keyHint: KeybindingHints["keyHint"],
315
+ ): void {
309
316
  const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
310
317
  container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
311
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
318
+ if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden, keyHint), 0, 0));
312
319
  }
313
320
 
314
321
  export function toolLayout(
@@ -317,6 +324,7 @@ export function toolLayout(
317
324
  payload: string,
318
325
  theme: Theme,
319
326
  expanded: boolean,
327
+ keyHint: KeybindingHints["keyHint"],
320
328
  ): Component {
321
329
  const container = new Container();
322
330
  if (toolName)
@@ -337,7 +345,7 @@ export function toolLayout(
337
345
  render: (width) => {
338
346
  // Wrapping turns one long line into many, so the cap counts rendered rows, not source lines.
339
347
  const { shown, hidden } = capLines(body.render(width), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
340
- return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden), width)] : shown;
348
+ return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden, keyHint), width)] : shown;
341
349
  },
342
350
  invalidate: () => body.invalidate(),
343
351
  });
@@ -368,6 +376,7 @@ export function launchResult(
368
376
  status: string,
369
377
  expanded: boolean,
370
378
  theme: Theme,
379
+ keyHint: KeybindingHints["keyHint"],
371
380
  ): Component {
372
381
  const container = new Container();
373
382
  // The mark is the call's outcome (launch succeeded); job progress stays in the widget and report.
@@ -375,9 +384,13 @@ export function launchResult(
375
384
  // The call body already carries the task; only the launch metadata is new here.
376
385
  if (expanded)
377
386
  container.addChild(
378
- new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
387
+ new Text(
388
+ theme.fg("muted", ` Model: ${details.model ?? "default"}\n Tools: ${formatTools(details.tools)}`),
389
+ 0,
390
+ 0,
391
+ ),
379
392
  );
380
393
  // Background results arrive as their own message; headless runs still show the output here.
381
- if (!details.background && body) appendOutput(container, body, expanded, theme);
394
+ if (!details.background && body) appendOutput(container, body, expanded, theme, keyHint);
382
395
  return container;
383
396
  }
package/index.ts CHANGED
@@ -2,11 +2,12 @@ import { spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { Type } from "typebox";
5
- import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
5
+ import type { ExtensionAPI, ExtensionContext, KeybindingHints, Theme } from "@earendil-works/pi-coding-agent";
6
6
  import { getAgentDir, renderDiff } from "@earendil-works/pi-coding-agent";
7
7
  import { Container, Spacer, Text } from "@earendil-works/pi-tui";
8
8
  import {
9
9
  appendOutput,
10
+ capDiff,
10
11
  capLines,
11
12
  COLLAPSED_OUTPUT_LINES,
12
13
  type DelegateDetails,
@@ -26,6 +27,7 @@ import {
26
27
  SPINNER_INTERVAL_MS,
27
28
  statusText,
28
29
  tally,
30
+ textParts,
29
31
  toolLayout,
30
32
  widgetJobs,
31
33
  } from "./format.ts";
@@ -50,6 +52,8 @@ type SteerDetails = Pick<
50
52
  elapsedMs: number;
51
53
  };
52
54
 
55
+ type RenderContext = { expanded: boolean; isError: boolean; keyHint: KeybindingHints["keyHint"] };
56
+
53
57
  const DELEGATION_TOOLS = new Set([
54
58
  "delegate",
55
59
  "delegate_apply",
@@ -75,13 +79,13 @@ function jobId(value: unknown): string {
75
79
  .trim()
76
80
  .replace(/^job\s+/i, "");
77
81
  }
78
- /** Strict models inject literal "null" for optional params they omit; drop it before reading any. */
79
- function dropNulls<T extends Record<string, unknown>>(raw: T): T {
80
- return Object.fromEntries(Object.entries(raw).filter(([, value]) => value !== null && value !== "null")) as T;
82
+ /** Strict models inject literal "null" for optional params they omit; treat it as absent. */
83
+ function optional<T>(value: T): T | undefined {
84
+ return (value as unknown) === null || value === "null" ? undefined : value;
81
85
  }
82
86
 
83
- function resultText(result: { content: readonly { type: string; text?: string }[] }): string {
84
- return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
87
+ function resultText(result: { content: unknown }): string {
88
+ return textParts(result.content).join("\n");
85
89
  }
86
90
 
87
91
  /** One resolution path for launches and swaps; the error names the requested model. */
@@ -103,6 +107,23 @@ function jobRow(theme: Theme, job: InspectJob, now: number): string {
103
107
 
104
108
  export default function (pi: ExtensionAPI) {
105
109
  const store = createJobStore(pi.appendEntry);
110
+ // A cancelled child can outlive its job row; a revive waits for it so two children never share a pinned session.
111
+ const exiting = new Map<string, Promise<void>>();
112
+
113
+ /** Waits for a cancelled child to exit; a child that never closes must not block steering forever. */
114
+ const waitForExit = async (id: string) => {
115
+ const closed = exiting.get(id);
116
+ if (!closed) return;
117
+ let timer: ReturnType<typeof setTimeout> | undefined;
118
+ const timeout = new Promise<"timeout">((resolve) => {
119
+ timer = setTimeout(() => resolve("timeout"), 6_000);
120
+ timer.unref();
121
+ });
122
+ const result = await Promise.race([closed.then(() => "closed" as const), timeout]);
123
+ clearTimeout(timer);
124
+ if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; call delegate_steer again.`);
125
+ };
126
+
106
127
  let ticker: ReturnType<typeof setInterval> | undefined;
107
128
  // Prompts are read once; drift happens one quick search at a time, so count it and nudge at 5, 10, 20, ...
108
129
  let directCalls = 0;
@@ -114,6 +135,24 @@ export default function (pi: ExtensionAPI) {
114
135
  return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
115
136
  };
116
137
 
138
+ /** The renderCall shared by every delegate tool: identity plus an optional payload. */
139
+ const callRenderer =
140
+ (toolName: string, identity: (args: any, theme: Theme) => string, payload: (args: any) => string = () => "") =>
141
+ (args: any, theme: Theme, context: RenderContext) =>
142
+ toolLayout(toolName, identity(args, theme), payload(args), theme, context.expanded, context.keyHint);
143
+
144
+ /** The job-id tools all identify the job the same way. */
145
+ const idCall = (toolName: string, payload: (args: any) => string = () => "") =>
146
+ callRenderer(toolName, (args, theme) => jobTarget(args?.id, theme), payload);
147
+
148
+ /** The mark is the call's outcome, not the job's status; a one-line header covers the simple tools. */
149
+ const headerResult = (tail: string) => (result: any, _options: any, theme: Theme, context: RenderContext) => {
150
+ const details = result.details as { id: string; agent: string } | undefined;
151
+ const body = resultText(result);
152
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
153
+ return new Text(`\n${resultHeader(theme, details, tail)}`, 0, 0);
154
+ };
155
+
117
156
  /** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
118
157
  const jobsInClone = (clone: string) => store.all().filter((job) => job.isolation?.clone === clone);
119
158
 
@@ -227,6 +266,8 @@ export default function (pi: ExtensionAPI) {
227
266
  signal: AbortSignal | undefined,
228
267
  prompt = task,
229
268
  ) => {
269
+ const entrypoint = process.argv[1];
270
+ if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
230
271
  const { model, thinking } = mustResolveModel(fields.model, ctx, agent.model);
231
272
  const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
232
273
  (tool) => !DELEGATION_TOOLS.has(tool),
@@ -277,8 +318,6 @@ export default function (pi: ExtensionAPI) {
277
318
  ];
278
319
  if (thinking) args.push("--thinking", thinking);
279
320
  if (agent.prompt) args.push("--append-system-prompt", agent.prompt);
280
- const entrypoint = process.argv[1];
281
- if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
282
321
  const cwd = isolation ? cloneCwd(isolation, ctx.cwd) : ctx.cwd;
283
322
  if (isolation)
284
323
  args.push(
@@ -301,6 +340,11 @@ export default function (pi: ExtensionAPI) {
301
340
  );
302
341
  job.steer = run.steer;
303
342
  job.swapModel = run.swapModel;
343
+ const closed = new Promise<void>((resolve) => child.once("close", () => resolve()));
344
+ exiting.set(job.id, closed);
345
+ void closed.then(() => {
346
+ if (exiting.get(job.id) === closed) exiting.delete(job.id);
347
+ });
304
348
  if (!details.background) {
305
349
  try {
306
350
  const output = await run.done;
@@ -383,7 +427,8 @@ export default function (pi: ExtensionAPI) {
383
427
  pi.on("session_start", (_event, ctx) => restoreSession(ctx));
384
428
  pi.on("session_tree", (_event, ctx) => restoreSession(ctx));
385
429
 
386
- pi.on("before_agent_start", () => {
430
+ pi.on("before_agent_start", (event) => {
431
+ if (event.messageType !== "user") return;
387
432
  directCalls = 0;
388
433
  nextReminder = FIRST_REMINDER_AT;
389
434
  });
@@ -410,7 +455,7 @@ export default function (pi: ExtensionAPI) {
410
455
  );
411
456
  });
412
457
 
413
- pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded }, theme) => {
458
+ pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded, keyHint }, theme) => {
414
459
  const report = message.details as DelegateReport | undefined;
415
460
  if (!report?.agent) return undefined;
416
461
  const container = new Container();
@@ -420,7 +465,7 @@ export default function (pi: ExtensionAPI) {
420
465
  if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
421
466
  else if (report.output) {
422
467
  container.addChild(new Spacer(1));
423
- appendOutput(container, report.output, expanded, theme);
468
+ appendOutput(container, report.output, expanded, theme, keyHint);
424
469
  }
425
470
  return container;
426
471
  });
@@ -436,27 +481,27 @@ export default function (pi: ExtensionAPI) {
436
481
  name: "delegate",
437
482
  label: "Delegate",
438
483
  description: [
439
- "Start a delegate: a background run of one of the agents below on one focused task. Returns a job id immediately; the report arrives later as a follow-up message.",
484
+ "Start a delegate: a background run of one of the agents below on one focused task. Returns a job id immediately; its report arrives as a follow-up message.",
440
485
  "",
441
486
  "Available agents:",
442
487
  ...agentList,
443
488
  "",
444
- "A delegate gets the project instructions but not this conversation: it cannot see the user's request, the files you read, or your decisions. Write `task` as a self-contained brief: the goal and why, what you already know (paths, symbols, errors), scope and constraints, whether to edit files or only report, and what to return (format, length, path:line evidence).",
489
+ "A delegate gets the project instructions but not this conversation. Write `task` as a self-contained brief: the goal and why it matters, what you know (paths, symbols, errors), scope and constraints, whether to edit or only report, and what to return (format, length, path:line evidence).",
445
490
  "",
446
- "With isolated: true, the delegate runs in an isolated git clone at .pi/worktrees/<job id>, starting from the main tree exactly as it is now, uncommitted and untracked files included. It never touches the main tree and may commit freely; delegate_apply brings its changes back, delegate_discard drops them.",
491
+ "With isolated: true, the delegate runs in a git clone at .pi/worktrees/<job id>, starting from the main tree as it is now, uncommitted and untracked files included. It never touches the main tree and may commit freely; delegate_apply brings its changes back, delegate_discard drops them.",
447
492
  "",
448
- "To run another delegate in an isolated job's clone, pass that job id as `clone`. delegate_apply or delegate_discard with any job id from that clone acts on the whole clone, and only one job can run in a clone at a time.",
493
+ "Pass an isolated job id as `clone` to run another delegate in its clone. delegate_apply or delegate_discard with any job id from that clone acts on the whole clone, and only one job runs in a clone at a time.",
449
494
  "",
450
495
  "To follow up on or redirect an existing job, see delegate_steer.",
451
496
  ].join("\n"),
452
497
  promptSnippet:
453
498
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
454
499
  promptGuidelines: [
455
- "You are the orchestrator, and delegating is your default: plan, split the work, brief delegates, and integrate their reports. Delegate on your own initiative. Your context is the scarce resource: everything you read stays in it, is re-sent with every later request, and brings compaction closer. A delegate works in a fresh context, often on a cheaper model, and returns only its report.",
456
- "Delegate exploration, research, implementation beyond a small edit, build/test/debug loops, and reviews. Work directly only for reading one known file or the lines you are about to edit, one targeted search, a small edit (about 30 lines in one file), a quick verification (one test run or one cited line), or a command the user asked you to run. Shell one-liners and scripts that search or read code count as exploration, not quick commands.",
500
+ "You are the orchestrator: plan, split the work, brief delegates, and integrate their reports. Delegate on your own initiative. Your context is the scarce resource: everything you read stays in it, is re-sent with every request, and brings compaction closer. A delegate works in a fresh context, often on a cheaper model, and returns only its report.",
501
+ "Delegate exploration, research, implementation beyond a small edit, build/test/debug loops, and reviews. Work directly only for reading one known file or the lines you are about to edit, one targeted search, a small edit (about 30 lines in one file), a quick verification (one test run or one cited line), or a command the user asked you to run. Shell one-liners and scripts that search or read code count as exploration.",
457
502
  "Your failure mode is drifting into doing the work yourself, one quick search at a time. Decide what to delegate before your first exploratory call; if one targeted search does not settle it, delegate the rest.",
458
- "Start every independent delegate before waiting on any, ideally in one message. Trust reports instead of repeating their searches; check only what you act on. If a report falls short, delegate a follow-up that names the gap instead of redoing the work yourself.",
459
- "While delegates run, stay outside their scopes. When a report is the next dependency, end your turn with a brief waiting status. Completion will wake you.",
503
+ "Start every independent delegate before waiting on any, ideally in one message. Trust reports instead of repeating their searches; check only what you act on. If a report falls short, delegate a follow-up that names the gap.",
504
+ "While delegates run, stay outside their scopes. When a report is the next dependency, end your turn with a brief waiting status; completion will wake you.",
460
505
  "Read every required delegate report before claiming the task is done. Never sleep, poll, or call any tool solely to wait (including `bash` with `true`, `echo`, or `sleep 0`). Use delegate_list only for a one-time status check.",
461
506
  ],
462
507
  parameters: Type.Object({
@@ -481,10 +526,11 @@ export default function (pi: ExtensionAPI) {
481
526
  ),
482
527
  }),
483
528
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
484
- const params = dropNulls(rawParams);
485
- const { agent: agentName, description, task, model, isolated } = params;
529
+ const { agent: agentName, description, task } = rawParams;
486
530
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
487
- const cloneId = jobId(params.clone);
531
+ const model = optional(rawParams.model);
532
+ const isolated = optional(rawParams.isolated);
533
+ const cloneId = jobId(optional(rawParams.clone));
488
534
  if (cloneId && isolated === false) throw new Error("clone always runs isolated; omit isolated: false.");
489
535
  const clone = cloneId ? clonedJob(cloneId).isolation : undefined;
490
536
  const agent = agentByName(ctx.cwd, agentName);
@@ -492,23 +538,21 @@ export default function (pi: ExtensionAPI) {
492
538
  return runDelegate(ctx, agent, undefined, { description, model, isolated: effective, clone }, task, signal);
493
539
  },
494
540
 
495
- renderCall(args, theme, context) {
496
- const agent = argText(args?.agent).trim();
497
- const description = argText(args?.description).trim();
498
- const identity = [
499
- agent ? theme.fg("toolTitle", theme.bold(agent)) : "",
500
- description ? theme.fg("accent", description) : "",
501
- ]
502
- .filter(Boolean)
503
- .join(" ");
504
- return toolLayout(
505
- "delegate",
506
- identity || theme.fg("muted", "…"),
507
- argText(args?.task),
508
- theme,
509
- context.expanded,
510
- );
511
- },
541
+ renderCall: callRenderer(
542
+ "delegate",
543
+ (args, theme) => {
544
+ const agent = argText(args?.agent).trim();
545
+ const description = argText(args?.description).trim();
546
+ const identity = [
547
+ agent ? theme.fg("toolTitle", theme.bold(agent)) : "",
548
+ description ? theme.fg("accent", description) : "",
549
+ ]
550
+ .filter(Boolean)
551
+ .join(" ");
552
+ return identity || theme.fg("muted", "…");
553
+ },
554
+ (args) => argText(args?.task),
555
+ ),
512
556
 
513
557
  renderResult(result, { expanded }, theme, context) {
514
558
  const details = result.details as DelegateDetails | undefined;
@@ -520,6 +564,7 @@ export default function (pi: ExtensionAPI) {
520
564
  details.background ? "started in background" : "completed",
521
565
  expanded,
522
566
  theme,
567
+ context.keyHint,
523
568
  );
524
569
  },
525
570
  });
@@ -545,15 +590,15 @@ export default function (pi: ExtensionAPI) {
545
590
  ),
546
591
  }),
547
592
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
548
- const params = dropNulls(rawParams);
549
- const id = jobId(params.id);
593
+ const id = jobId(rawParams.id);
594
+ const model = optional(rawParams.model);
550
595
  const running = store.liveJob(id);
551
596
  if (running) {
552
597
  // A live job without steer would fall into the revive path and double-spawn its pinned session.
553
598
  if (!running.steer) throw new Error(`No steerable delegate job "${id}".`);
554
599
  try {
555
- if (params.model) await swapModel(running, params.model, ctx);
556
- await running.steer(params.message);
600
+ if (model) await swapModel(running, model, ctx);
601
+ await running.steer(rawParams.message);
557
602
  } catch (error) {
558
603
  // The swap or steer await can outlast the job (a model ack waits up to 30s); raw child errors are cryptic.
559
604
  if (!store.liveJob(id))
@@ -566,7 +611,7 @@ export default function (pi: ExtensionAPI) {
566
611
  id: running.id,
567
612
  agent: running.agent,
568
613
  description: running.description,
569
- message: params.message,
614
+ message: rawParams.message,
570
615
  toolCalls: running.toolCalls,
571
616
  contextTokens: running.contextTokens,
572
617
  contextWindow: running.contextWindow,
@@ -582,8 +627,9 @@ export default function (pi: ExtensionAPI) {
582
627
  details,
583
628
  };
584
629
  }
630
+ await waitForExit(id);
585
631
  const prior = store.findOrThrow(id);
586
- // An applied or discarded clone cannot be continued; a revive would run in the main tree.
632
+ // A parallel apply/discard can close the clone while we wait; re-check before spawning in the main tree.
587
633
  if (prior.cloneClosed)
588
634
  throw new Error(
589
635
  `The isolated clone of delegate job "${id}" was already applied or discarded; delegate_steer cannot continue it. Start a fresh delegate with a condensed brief instead.`,
@@ -595,24 +641,16 @@ export default function (pi: ExtensionAPI) {
595
641
  prior,
596
642
  {
597
643
  description: prior.description,
598
- model: params.model ?? prior.model,
644
+ model: model ?? prior.model,
599
645
  isolated: Boolean(prior.isolation),
600
646
  },
601
647
  prior.task,
602
648
  signal,
603
- params.message,
649
+ rawParams.message,
604
650
  );
605
651
  },
606
652
 
607
- renderCall(args, theme, context) {
608
- return toolLayout(
609
- "delegate_steer",
610
- jobTarget(args?.id, theme),
611
- argText(args?.message),
612
- theme,
613
- context.expanded,
614
- );
615
- },
653
+ renderCall: idCall("delegate_steer", (args) => argText(args?.message)),
616
654
 
617
655
  renderResult(result, { expanded }, theme, context) {
618
656
  const details = result.details as SteerDetails | DelegateDetails | undefined;
@@ -625,6 +663,7 @@ export default function (pi: ExtensionAPI) {
625
663
  details.background ? "revived in background" : "revived",
626
664
  expanded,
627
665
  theme,
666
+ context.keyHint,
628
667
  );
629
668
  },
630
669
  });
@@ -652,18 +691,9 @@ export default function (pi: ExtensionAPI) {
652
691
  details: { id: job.id, agent: job.agent },
653
692
  };
654
693
  },
694
+ renderCall: idCall("delegate_cancel"),
655
695
 
656
- renderCall(args, theme, context) {
657
- return toolLayout("delegate_cancel", jobTarget(args?.id, theme), "", theme, context.expanded);
658
- },
659
-
660
- renderResult(result, _options, theme, context) {
661
- const details = result.details as { id: string; agent: string } | undefined;
662
- const body = resultText(result);
663
- if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
664
- // The mark is the call's outcome (cancellation requested), not the job's cancelled status.
665
- return new Text(`\n${resultHeader(theme, details, "cancellation requested")}`, 0, 0);
666
- },
696
+ renderResult: headerResult("cancellation requested"),
667
697
  });
668
698
 
669
699
  pi.registerTool({
@@ -676,8 +706,7 @@ export default function (pi: ExtensionAPI) {
676
706
  id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
677
707
  }),
678
708
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
679
- const params = dropNulls(rawParams);
680
- const id = jobId(params.id);
709
+ const id = jobId(rawParams.id);
681
710
  const { job, isolation } = clonedJob(id);
682
711
  requireIdleClone(isolation);
683
712
  const result = applyClone(isolation);
@@ -692,6 +721,7 @@ export default function (pi: ExtensionAPI) {
692
721
  );
693
722
  }
694
723
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
724
+ const capped = result.kind === "applied" ? capDiff(result.diff) : { diff: undefined, note: undefined };
695
725
  closeClone(isolation);
696
726
  return {
697
727
  content: [
@@ -703,16 +733,13 @@ export default function (pi: ExtensionAPI) {
703
733
  : `Applied the changes of delegate "${job.agent}" (job ${job.id}) to the main tree:${stat}\n(clone removed)`,
704
734
  },
705
735
  ],
706
- details: { id: job.id, agent: job.agent, diff: result.kind === "applied" ? result.diff : undefined },
736
+ details: { id: job.id, agent: job.agent, diff: capped.diff, diffNote: capped.note },
707
737
  };
708
738
  },
709
-
710
- renderCall(args, theme, context) {
711
- return toolLayout("delegate_apply", jobTarget(args?.id, theme), "", theme, context.expanded);
712
- },
713
-
739
+ renderCall: idCall("delegate_apply"),
714
740
  renderResult(result, { expanded }, theme, context) {
715
- const details = result.details as { id: string; agent: string; diff?: string } | undefined;
741
+ const details = result.details as
742
+ { id: string; agent: string; diff?: string; diffNote?: string } | undefined;
716
743
  const body = resultText(result);
717
744
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
718
745
  const header = `\n${resultHeader(theme, details, "changes applied")}`;
@@ -720,7 +747,9 @@ export default function (pi: ExtensionAPI) {
720
747
  if (!diff) return new Text(header, 0, 0);
721
748
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
722
749
  const { shown, hidden } = capLines(diff.split("\n"), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
723
- if (hidden) shown.push(moreLines(theme, hidden));
750
+ if (hidden) shown.push(moreLines(theme, hidden, context.keyHint));
751
+ // The truncation note is plain text: piDiff would otherwise number it as a context line.
752
+ if (details.diffNote) shown.push(theme.fg("muted", details.diffNote));
724
753
  const container = new Container();
725
754
  container.addChild(new Text(header, 0, 0));
726
755
  container.addChild(new Spacer(1));
@@ -739,8 +768,7 @@ export default function (pi: ExtensionAPI) {
739
768
  id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
740
769
  }),
741
770
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
742
- const params = dropNulls(rawParams);
743
- const id = jobId(params.id);
771
+ const id = jobId(rawParams.id);
744
772
  const { job, isolation } = clonedJob(id);
745
773
  requireIdleClone(isolation);
746
774
  closeClone(isolation);
@@ -754,17 +782,8 @@ export default function (pi: ExtensionAPI) {
754
782
  details: { id: job.id, agent: job.agent, discarded: true },
755
783
  };
756
784
  },
757
-
758
- renderCall(args, theme, context) {
759
- return toolLayout("delegate_discard", jobTarget(args?.id, theme), "", theme, context.expanded);
760
- },
761
-
762
- renderResult(result, _options, theme, context) {
763
- const details = result.details as { id: string; agent: string; discarded?: boolean } | undefined;
764
- const body = resultText(result);
765
- if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
766
- return new Text(`\n${resultHeader(theme, details, "clone discarded")}`, 0, 0);
767
- },
785
+ renderCall: idCall("delegate_discard"),
786
+ renderResult: headerResult("clone discarded"),
768
787
  });
769
788
 
770
789
  pi.registerTool({
@@ -790,7 +809,8 @@ export default function (pi: ExtensionAPI) {
790
809
  content: [
791
810
  { type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
792
811
  ],
793
- details: { jobs: jobs.map(store.snapshot) },
812
+ // Rows render from the fields; the activity history stays in the store, not in every list result.
813
+ details: { jobs: jobs.map(store.summary) },
794
814
  };
795
815
  },
796
816
  renderResult(result, _options, theme, context) {
package/inspector.ts CHANGED
@@ -1,5 +1,12 @@
1
- import { type ExtensionAPI, getMarkdownTheme, keyHint, rawKeyHint } from "@earendil-works/pi-coding-agent";
2
- import { HStack, Markdown, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
1
+ import { type ExtensionAPI, getMarkdownTheme, rawKeyHint } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ HStack,
4
+ type Keybinding,
5
+ Markdown,
6
+ matchesKey,
7
+ truncateToWidth,
8
+ wrapTextWithAnsi,
9
+ } from "@earendil-works/pi-tui";
3
10
  import type { ChildActivity } from "./child.ts";
4
11
  import { elapsedMs, formatTools, jobIdentity, STATUS_COLORS, statusText, tally, usageStats } from "./format.ts";
5
12
  import type { InspectJob, JobStore } from "./store.ts";
@@ -27,6 +34,9 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
27
34
  let historyWidth = 1;
28
35
  let markdown = new WeakMap<ChildActivity, Markdown>();
29
36
  const jobs = () => store.all();
37
+ // Format hints from the injected manager; an imported copy would not see the user's keybindings.
38
+ const hint = (id: Keybinding, description: string) =>
39
+ rawKeyHint(keys.getKeys(id).join("/"), description);
30
40
  // Fixed rows: title, top rule, bottom rule, footer.
31
41
  const bodyHeight = () => Math.max(0, tui.terminal.rows - 4);
32
42
  const toolsLines = (job: InspectJob, width: number) =>
@@ -146,7 +156,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
146
156
  const footer = truncateToWidth(
147
157
  theme.fg(
148
158
  "dim",
149
- `${keyHint("tui.select.up", "up")} · ${keyHint("tui.select.down", "down")} · ${rawKeyHint("←/→", "switch pane")} · ${keyHint("tui.select.cancel", "close")}`,
159
+ `${hint("tui.select.up", "up")} · ${hint("tui.select.down", "down")} · ${rawKeyHint("←/→", "switch pane")} · ${hint("tui.select.cancel", "close")}`,
150
160
  ),
151
161
  width,
152
162
  );
package/isolation.ts CHANGED
@@ -116,13 +116,17 @@ export function cloneCwd(iso: IsolationState, cwd: string): string {
116
116
  /** Clone location plus a stat of everything the delegate changed, for the job's report. */
117
117
  export function isolationSummary(iso: IsolationState): string {
118
118
  const lines = [`Isolated clone: ${iso.clone}`];
119
+ const indexFile = join(iso.clone, ".git", "pi-delegate-summary-index");
119
120
  try {
120
- // Staging first pulls uncommitted and untracked changes into the stat.
121
- git(["add", "-A"], { cwd: iso.clone });
122
- const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone }).trimEnd();
121
+ // A scratch index stages uncommitted and untracked changes for the stat without touching the clone's own index.
122
+ git(["read-tree", "HEAD"], { cwd: iso.clone, indexFile });
123
+ git(["add", "-A"], { cwd: iso.clone, indexFile });
124
+ const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone, indexFile }).trimEnd();
123
125
  if (stat) lines.push(`Changes in this clone:\n${stat}`);
124
126
  } catch {
125
127
  // The clone may already be applied or gone; the path alone still says where the work lives.
128
+ } finally {
129
+ rmSync(indexFile, { force: true });
126
130
  }
127
131
  return lines.join("\n");
128
132
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.39",
3
+ "version": "0.0.41",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/store.ts CHANGED
@@ -57,12 +57,22 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
57
57
  const stale = history.findIndex((item) => item.id === id);
58
58
  if (stale >= 0) history.splice(stale, 1);
59
59
  };
60
+ const commit = (entry: InspectJob) => {
61
+ drop(entry.id);
62
+ history.unshift(entry);
63
+ append(JOB_ENTRY, snapshot(entry));
64
+ notify();
65
+ };
60
66
  const find = (id: string) => running.get(id) ?? history.find((item) => item.id === id);
67
+ const plain = (job: InspectJob) => {
68
+ const { controller, steer, swapModel, ...rest } = job as InspectJob & Partial<DelegateJob>;
69
+ return rest;
70
+ };
61
71
  /** The serializable form of a job: runtime handles stay out. */
62
72
  const snapshot = (job: InspectJob): InspectJob => {
63
- const { controller, steer, swapModel, ...plain } = job as InspectJob & Partial<DelegateJob>;
73
+ const rest = plain(job);
64
74
  // Copy activity: the live job keeps appending to its own array after the launch snapshot.
65
- return { ...plain, activity: [...plain.activity] };
75
+ return { ...rest, activity: [...rest.activity] };
66
76
  };
67
77
  const addActivity = (job: DelegateJob, activity: ChildActivity) => {
68
78
  const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
@@ -84,6 +94,8 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
84
94
  live: (): DelegateJob[] => [...running.values()],
85
95
  find,
86
96
  snapshot,
97
+ /** A row for delegate_list: the snapshot without the activity history a list result never renders. */
98
+ summary: (job: InspectJob): InspectJob => ({ ...plain(job), activity: [] }),
87
99
  /** A job by id; the common "unknown delegate job" failure lives here so every tool phrases it alike. */
88
100
  findOrThrow: (id: string): InspectJob => {
89
101
  const job = find(id);
@@ -110,20 +122,11 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
110
122
  running.delete(job.id);
111
123
  job.status = status;
112
124
  if (detail) addActivity(job, { kind: "status", text: detail });
113
- const entry: InspectJob = { ...snapshot(job), endedAt: Date.now() };
114
- drop(entry.id);
115
- history.unshift(entry);
116
- append(JOB_ENTRY, entry);
117
- notify();
125
+ commit({ ...snapshot(job), endedAt: Date.now() });
118
126
  return true;
119
127
  },
120
128
  /** Appends a corrected entry for a finished job changed after completion (isolation applied, discarded, or re-based). */
121
- save: (job: InspectJob) => {
122
- drop(job.id);
123
- history.unshift(job);
124
- append(JOB_ENTRY, snapshot(job));
125
- notify();
126
- },
129
+ save: (job: InspectJob) => commit(job),
127
130
  /** Rebuilds history from the branch and returns the jobs it marked interrupted. */
128
131
  restore: (branch: readonly unknown[]): InspectJob[] => {
129
132
  history.length = 0;