@deathbeam/pi-delegate 0.0.40 → 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;
@@ -298,16 +298,6 @@ export function runChild(
298
298
  };
299
299
  }
300
300
 
301
- /** Text parts of a message's content, in order. */
302
- function transcriptText(content: unknown): string[] {
303
- if (typeof content === "string") return [content];
304
- if (!Array.isArray(content)) return [];
305
- return content
306
- .map((part) => (part && typeof part === "object" ? (part as { type?: string; text?: string }) : {}))
307
- .filter((part) => part.type === "text" && typeof part.text === "string")
308
- .map((part) => part.text!);
309
- }
310
-
311
301
  /**
312
302
  * Replays the child's persisted transcript as the activity a revived job continues from, so the
313
303
  * inspector keeps the old history. A missing or unreadable transcript seeds nothing: the revive
@@ -360,7 +350,7 @@ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
360
350
  continue;
361
351
  }
362
352
  // Assistant text lands before its tool calls, matching the live event order.
363
- const text = transcriptText(message.content).join("");
353
+ const text = textParts(message.content).join("");
364
354
  if (text) activity.push({ kind: message.role, text });
365
355
  if (message.role !== "assistant") continue;
366
356
  for (const part of Array.isArray(message.content) ? message.content : []) {
package/format.ts CHANGED
@@ -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;
@@ -383,7 +384,11 @@ export function launchResult(
383
384
  // The call body already carries the task; only the launch metadata is new here.
384
385
  if (expanded)
385
386
  container.addChild(
386
- 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
+ ),
387
392
  );
388
393
  // Background results arrive as their own message; headless runs still show the output here.
389
394
  if (!details.background && body) appendOutput(container, body, expanded, theme, keyHint);
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;
@@ -437,27 +481,27 @@ export default function (pi: ExtensionAPI) {
437
481
  name: "delegate",
438
482
  label: "Delegate",
439
483
  description: [
440
- "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.",
441
485
  "",
442
486
  "Available agents:",
443
487
  ...agentList,
444
488
  "",
445
- "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).",
446
490
  "",
447
- "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.",
448
492
  "",
449
- "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.",
450
494
  "",
451
495
  "To follow up on or redirect an existing job, see delegate_steer.",
452
496
  ].join("\n"),
453
497
  promptSnippet:
454
498
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
455
499
  promptGuidelines: [
456
- "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.",
457
- "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.",
458
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.",
459
- "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.",
460
- "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.",
461
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.",
462
506
  ],
463
507
  parameters: Type.Object({
@@ -482,10 +526,11 @@ export default function (pi: ExtensionAPI) {
482
526
  ),
483
527
  }),
484
528
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
485
- const params = dropNulls(rawParams);
486
- const { agent: agentName, description, task, model, isolated } = params;
529
+ const { agent: agentName, description, task } = rawParams;
487
530
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
488
- const cloneId = jobId(params.clone);
531
+ const model = optional(rawParams.model);
532
+ const isolated = optional(rawParams.isolated);
533
+ const cloneId = jobId(optional(rawParams.clone));
489
534
  if (cloneId && isolated === false) throw new Error("clone always runs isolated; omit isolated: false.");
490
535
  const clone = cloneId ? clonedJob(cloneId).isolation : undefined;
491
536
  const agent = agentByName(ctx.cwd, agentName);
@@ -493,24 +538,21 @@ export default function (pi: ExtensionAPI) {
493
538
  return runDelegate(ctx, agent, undefined, { description, model, isolated: effective, clone }, task, signal);
494
539
  },
495
540
 
496
- renderCall(args, theme, context) {
497
- const agent = argText(args?.agent).trim();
498
- const description = argText(args?.description).trim();
499
- const identity = [
500
- agent ? theme.fg("toolTitle", theme.bold(agent)) : "",
501
- description ? theme.fg("accent", description) : "",
502
- ]
503
- .filter(Boolean)
504
- .join(" ");
505
- return toolLayout(
506
- "delegate",
507
- identity || theme.fg("muted", "…"),
508
- argText(args?.task),
509
- theme,
510
- context.expanded,
511
- context.keyHint,
512
- );
513
- },
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
+ ),
514
556
 
515
557
  renderResult(result, { expanded }, theme, context) {
516
558
  const details = result.details as DelegateDetails | undefined;
@@ -548,15 +590,15 @@ export default function (pi: ExtensionAPI) {
548
590
  ),
549
591
  }),
550
592
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
551
- const params = dropNulls(rawParams);
552
- const id = jobId(params.id);
593
+ const id = jobId(rawParams.id);
594
+ const model = optional(rawParams.model);
553
595
  const running = store.liveJob(id);
554
596
  if (running) {
555
597
  // A live job without steer would fall into the revive path and double-spawn its pinned session.
556
598
  if (!running.steer) throw new Error(`No steerable delegate job "${id}".`);
557
599
  try {
558
- if (params.model) await swapModel(running, params.model, ctx);
559
- await running.steer(params.message);
600
+ if (model) await swapModel(running, model, ctx);
601
+ await running.steer(rawParams.message);
560
602
  } catch (error) {
561
603
  // The swap or steer await can outlast the job (a model ack waits up to 30s); raw child errors are cryptic.
562
604
  if (!store.liveJob(id))
@@ -569,7 +611,7 @@ export default function (pi: ExtensionAPI) {
569
611
  id: running.id,
570
612
  agent: running.agent,
571
613
  description: running.description,
572
- message: params.message,
614
+ message: rawParams.message,
573
615
  toolCalls: running.toolCalls,
574
616
  contextTokens: running.contextTokens,
575
617
  contextWindow: running.contextWindow,
@@ -585,8 +627,9 @@ export default function (pi: ExtensionAPI) {
585
627
  details,
586
628
  };
587
629
  }
630
+ await waitForExit(id);
588
631
  const prior = store.findOrThrow(id);
589
- // 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.
590
633
  if (prior.cloneClosed)
591
634
  throw new Error(
592
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.`,
@@ -598,25 +641,16 @@ export default function (pi: ExtensionAPI) {
598
641
  prior,
599
642
  {
600
643
  description: prior.description,
601
- model: params.model ?? prior.model,
644
+ model: model ?? prior.model,
602
645
  isolated: Boolean(prior.isolation),
603
646
  },
604
647
  prior.task,
605
648
  signal,
606
- params.message,
649
+ rawParams.message,
607
650
  );
608
651
  },
609
652
 
610
- renderCall(args, theme, context) {
611
- return toolLayout(
612
- "delegate_steer",
613
- jobTarget(args?.id, theme),
614
- argText(args?.message),
615
- theme,
616
- context.expanded,
617
- context.keyHint,
618
- );
619
- },
653
+ renderCall: idCall("delegate_steer", (args) => argText(args?.message)),
620
654
 
621
655
  renderResult(result, { expanded }, theme, context) {
622
656
  const details = result.details as SteerDetails | DelegateDetails | undefined;
@@ -657,25 +691,9 @@ export default function (pi: ExtensionAPI) {
657
691
  details: { id: job.id, agent: job.agent },
658
692
  };
659
693
  },
694
+ renderCall: idCall("delegate_cancel"),
660
695
 
661
- renderCall(args, theme, context) {
662
- return toolLayout(
663
- "delegate_cancel",
664
- jobTarget(args?.id, theme),
665
- "",
666
- theme,
667
- context.expanded,
668
- context.keyHint,
669
- );
670
- },
671
-
672
- renderResult(result, _options, theme, context) {
673
- const details = result.details as { id: string; agent: string } | undefined;
674
- const body = resultText(result);
675
- if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
676
- // The mark is the call's outcome (cancellation requested), not the job's cancelled status.
677
- return new Text(`\n${resultHeader(theme, details, "cancellation requested")}`, 0, 0);
678
- },
696
+ renderResult: headerResult("cancellation requested"),
679
697
  });
680
698
 
681
699
  pi.registerTool({
@@ -688,8 +706,7 @@ export default function (pi: ExtensionAPI) {
688
706
  id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
689
707
  }),
690
708
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
691
- const params = dropNulls(rawParams);
692
- const id = jobId(params.id);
709
+ const id = jobId(rawParams.id);
693
710
  const { job, isolation } = clonedJob(id);
694
711
  requireIdleClone(isolation);
695
712
  const result = applyClone(isolation);
@@ -704,6 +721,7 @@ export default function (pi: ExtensionAPI) {
704
721
  );
705
722
  }
706
723
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
724
+ const capped = result.kind === "applied" ? capDiff(result.diff) : { diff: undefined, note: undefined };
707
725
  closeClone(isolation);
708
726
  return {
709
727
  content: [
@@ -715,23 +733,13 @@ export default function (pi: ExtensionAPI) {
715
733
  : `Applied the changes of delegate "${job.agent}" (job ${job.id}) to the main tree:${stat}\n(clone removed)`,
716
734
  },
717
735
  ],
718
- 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 },
719
737
  };
720
738
  },
721
-
722
- renderCall(args, theme, context) {
723
- return toolLayout(
724
- "delegate_apply",
725
- jobTarget(args?.id, theme),
726
- "",
727
- theme,
728
- context.expanded,
729
- context.keyHint,
730
- );
731
- },
732
-
739
+ renderCall: idCall("delegate_apply"),
733
740
  renderResult(result, { expanded }, theme, context) {
734
- 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;
735
743
  const body = resultText(result);
736
744
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
737
745
  const header = `\n${resultHeader(theme, details, "changes applied")}`;
@@ -740,6 +748,8 @@ export default function (pi: ExtensionAPI) {
740
748
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
741
749
  const { shown, hidden } = capLines(diff.split("\n"), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
742
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));
743
753
  const container = new Container();
744
754
  container.addChild(new Text(header, 0, 0));
745
755
  container.addChild(new Spacer(1));
@@ -758,8 +768,7 @@ export default function (pi: ExtensionAPI) {
758
768
  id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
759
769
  }),
760
770
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
761
- const params = dropNulls(rawParams);
762
- const id = jobId(params.id);
771
+ const id = jobId(rawParams.id);
763
772
  const { job, isolation } = clonedJob(id);
764
773
  requireIdleClone(isolation);
765
774
  closeClone(isolation);
@@ -773,24 +782,8 @@ export default function (pi: ExtensionAPI) {
773
782
  details: { id: job.id, agent: job.agent, discarded: true },
774
783
  };
775
784
  },
776
-
777
- renderCall(args, theme, context) {
778
- return toolLayout(
779
- "delegate_discard",
780
- jobTarget(args?.id, theme),
781
- "",
782
- theme,
783
- context.expanded,
784
- context.keyHint,
785
- );
786
- },
787
-
788
- renderResult(result, _options, theme, context) {
789
- const details = result.details as { id: string; agent: string; discarded?: boolean } | undefined;
790
- const body = resultText(result);
791
- if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
792
- return new Text(`\n${resultHeader(theme, details, "clone discarded")}`, 0, 0);
793
- },
785
+ renderCall: idCall("delegate_discard"),
786
+ renderResult: headerResult("clone discarded"),
794
787
  });
795
788
 
796
789
  pi.registerTool({
@@ -816,7 +809,8 @@ export default function (pi: ExtensionAPI) {
816
809
  content: [
817
810
  { type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
818
811
  ],
819
- 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) },
820
814
  };
821
815
  },
822
816
  renderResult(result, _options, theme, context) {
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.40",
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;