@deathbeam/pi-delegate 0.0.40 → 0.0.42

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/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,10 +27,12 @@ import {
26
27
  SPINNER_INTERVAL_MS,
27
28
  statusText,
28
29
  tally,
30
+ textParts,
29
31
  toolLayout,
32
+ toolLines,
30
33
  widgetJobs,
31
34
  } from "./format.ts";
32
- import { priorActivity, runChild } from "./child.ts";
35
+ import { runChild, sessionMessages } from "./child.ts";
33
36
  import { createJobStore, type DelegateJob, lastToolCall, type InspectJob } from "./store.ts";
34
37
  import {
35
38
  applyClone,
@@ -50,6 +53,8 @@ type SteerDetails = Pick<
50
53
  elapsedMs: number;
51
54
  };
52
55
 
56
+ type RenderContext = { expanded: boolean; isError: boolean; keyHint: KeybindingHints["keyHint"] };
57
+
53
58
  const DELEGATION_TOOLS = new Set([
54
59
  "delegate",
55
60
  "delegate_apply",
@@ -75,13 +80,13 @@ function jobId(value: unknown): string {
75
80
  .trim()
76
81
  .replace(/^job\s+/i, "");
77
82
  }
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;
83
+ /** Strict models inject literal "null" for optional params they omit; treat it as absent. */
84
+ function optional<T>(value: T): T | undefined {
85
+ return (value as unknown) === null || value === "null" ? undefined : value;
81
86
  }
82
87
 
83
- function resultText(result: { content: readonly { type: string; text?: string }[] }): string {
84
- return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
88
+ function resultText(result: { content: unknown }): string {
89
+ return textParts(result.content).join("\n");
85
90
  }
86
91
 
87
92
  /** One resolution path for launches and swaps; the error names the requested model. */
@@ -103,6 +108,23 @@ function jobRow(theme: Theme, job: InspectJob, now: number): string {
103
108
 
104
109
  export default function (pi: ExtensionAPI) {
105
110
  const store = createJobStore(pi.appendEntry);
111
+ // A cancelled child can outlive its job row; a revive waits for it so two children never share a pinned session.
112
+ const exiting = new Map<string, Promise<void>>();
113
+
114
+ /** Waits for a cancelled child to exit; a child that never closes must not block steering forever. */
115
+ const waitForExit = async (id: string) => {
116
+ const closed = exiting.get(id);
117
+ if (!closed) return;
118
+ let timer: ReturnType<typeof setTimeout> | undefined;
119
+ const timeout = new Promise<"timeout">((resolve) => {
120
+ timer = setTimeout(() => resolve("timeout"), 6_000);
121
+ timer.unref();
122
+ });
123
+ const result = await Promise.race([closed.then(() => "closed" as const), timeout]);
124
+ clearTimeout(timer);
125
+ if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; call delegate_steer again.`);
126
+ };
127
+
106
128
  let ticker: ReturnType<typeof setInterval> | undefined;
107
129
  // Prompts are read once; drift happens one quick search at a time, so count it and nudge at 5, 10, 20, ...
108
130
  let directCalls = 0;
@@ -114,10 +136,27 @@ export default function (pi: ExtensionAPI) {
114
136
  return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
115
137
  };
116
138
 
139
+ /** The renderCall shared by every delegate tool: identity plus an optional payload. */
140
+ const callRenderer =
141
+ (toolName: string, identity: (args: any, theme: Theme) => string, payload: (args: any) => string = () => "") =>
142
+ (args: any, theme: Theme, context: RenderContext) =>
143
+ toolLayout(toolName, identity(args, theme), payload(args), theme, context.expanded, context.keyHint);
144
+
145
+ /** The job-id tools all identify the job the same way. */
146
+ const idCall = (toolName: string, payload: (args: any) => string = () => "") =>
147
+ callRenderer(toolName, (args, theme) => jobTarget(args?.id, theme), payload);
148
+
149
+ /** The mark is the call's outcome, not the job's status; a one-line header covers the simple tools. */
150
+ const headerResult = (tail: string) => (result: any, _options: any, theme: Theme, context: RenderContext) => {
151
+ const details = result.details as { id: string; agent: string } | undefined;
152
+ const body = resultText(result);
153
+ if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
154
+ return new Text(`\n${resultHeader(theme, details, tail)}`, 0, 0);
155
+ };
156
+
117
157
  /** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
118
158
  const jobsInClone = (clone: string) => store.all().filter((job) => job.isolation?.clone === clone);
119
159
 
120
- /** A job that still has a clone; throws explaining why it has none. */
121
160
  const clonedJob = (id: string) => {
122
161
  const job = store.findOrThrow(id);
123
162
  const isolation = job.isolation;
@@ -149,7 +188,6 @@ export default function (pi: ExtensionAPI) {
149
188
 
150
189
  const refreshWidget = (ctx: ExtensionContext) => {
151
190
  if (!ctx.hasUI) return;
152
- store.notify();
153
191
  const jobs = store.live();
154
192
  if (jobs.length === 0) {
155
193
  ctx.ui.setWidget(WIDGET_KEY, undefined);
@@ -165,11 +203,9 @@ export default function (pi: ExtensionAPI) {
165
203
  const { tool, result } = lastToolCall(job);
166
204
  if (tool)
167
205
  lines.push(
168
- ` ${theme.fg("toolTitle", theme.bold(tool.text))}${tool.detail ? ` ${theme.fg("accent", tool.detail)}` : ""}`,
169
- );
170
- if (result?.text)
171
- lines.push(
172
- ` ${theme.fg("muted", "↳")} ${theme.fg(result.isError ? "error" : "toolOutput", result.text)}`,
206
+ ...toolLines(theme, tool.name, tool.detail, result?.text, result?.isError).map(
207
+ (line) => ` ${line}`,
208
+ ),
173
209
  );
174
210
  }
175
211
  if (hidden) lines.push(` ${theme.fg("muted", `… ${hidden} more running · /delegate to view all`)}`);
@@ -198,16 +234,13 @@ export default function (pi: ExtensionAPI) {
198
234
  id: job.id,
199
235
  agent: job.agent,
200
236
  description: job.description,
201
- model: job.model,
202
237
  toolCalls: job.toolCalls,
203
238
  contextTokens: job.contextTokens,
204
239
  contextWindow: job.contextWindow,
205
240
  elapsedMs: elapsedMs(job),
206
241
  output: withIsolation(output ?? "", job.isolation),
207
242
  error,
208
- status: job.status,
209
243
  isolation: job.isolation,
210
- cloneClosed: job.cloneClosed,
211
244
  };
212
245
  // Idle: this starts a new turn. Streaming: steer the report in at the next turn boundary;
213
246
  // a follow-up waits for a run end that a parent stuck polling may never reach.
@@ -227,6 +260,8 @@ export default function (pi: ExtensionAPI) {
227
260
  signal: AbortSignal | undefined,
228
261
  prompt = task,
229
262
  ) => {
263
+ const entrypoint = process.argv[1];
264
+ if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
230
265
  const { model, thinking } = mustResolveModel(fields.model, ctx, agent.model);
231
266
  const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
232
267
  (tool) => !DELEGATION_TOOLS.has(tool),
@@ -245,7 +280,7 @@ export default function (pi: ExtensionAPI) {
245
280
  task,
246
281
  model: displayModel,
247
282
  status: "running",
248
- activity: prior ? priorActivity(DELEGATE_SESSION_DIR, prior.id) : [],
283
+ messages: prior ? sessionMessages(DELEGATE_SESSION_DIR, prior.id) : [],
249
284
  tools,
250
285
  toolCalls: 0,
251
286
  startedAt: Date.now(),
@@ -256,14 +291,10 @@ export default function (pi: ExtensionAPI) {
256
291
  const details: DelegateDetails = {
257
292
  id: job.id,
258
293
  agent: job.agent,
259
- description: job.description,
260
- task: job.task,
261
294
  model: displayModel,
262
295
  tools,
263
296
  background: ctx.hasUI,
264
- status: job.status,
265
297
  isolation: job.isolation,
266
- cloneClosed: job.cloneClosed,
267
298
  };
268
299
  const args = [
269
300
  "--session-id",
@@ -277,8 +308,6 @@ export default function (pi: ExtensionAPI) {
277
308
  ];
278
309
  if (thinking) args.push("--thinking", thinking);
279
310
  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
311
  const cwd = isolation ? cloneCwd(isolation, ctx.cwd) : ctx.cwd;
283
312
  if (isolation)
284
313
  args.push(
@@ -301,6 +330,11 @@ export default function (pi: ExtensionAPI) {
301
330
  );
302
331
  job.steer = run.steer;
303
332
  job.swapModel = run.swapModel;
333
+ const closed = new Promise<void>((resolve) => child.once("close", () => resolve()));
334
+ exiting.set(job.id, closed);
335
+ void closed.then(() => {
336
+ if (exiting.get(job.id) === closed) exiting.delete(job.id);
337
+ });
304
338
  if (!details.background) {
305
339
  try {
306
340
  const output = await run.done;
@@ -360,7 +394,7 @@ export default function (pi: ExtensionAPI) {
360
394
  store.clear();
361
395
  });
362
396
 
363
- // Rebuilt from the active branch, like pi's todo example; abandoned branches are alternative histories.
397
+ // Rebuilt from the active branch: abandoned branches are alternative histories.
364
398
  const restoreSession = (ctx: ExtensionContext) => {
365
399
  const interrupted = store.restore(ctx.sessionManager.getBranch());
366
400
  // Custom entries never reach the model, so announce the interrupted jobs as a steered message.
@@ -426,7 +460,7 @@ export default function (pi: ExtensionAPI) {
426
460
  return container;
427
461
  });
428
462
 
429
- registerInspector(pi, store);
463
+ registerInspector(pi, store, DELEGATE_SESSION_DIR);
430
464
 
431
465
  const agentList = agentsFor(process.cwd()).map((agent) => {
432
466
  const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
@@ -437,27 +471,27 @@ export default function (pi: ExtensionAPI) {
437
471
  name: "delegate",
438
472
  label: "Delegate",
439
473
  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.",
474
+ "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
475
  "",
442
476
  "Available agents:",
443
477
  ...agentList,
444
478
  "",
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).",
479
+ "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
480
  "",
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.",
481
+ "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
482
  "",
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.",
483
+ "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
484
  "",
451
485
  "To follow up on or redirect an existing job, see delegate_steer.",
452
486
  ].join("\n"),
453
487
  promptSnippet:
454
488
  "Delegate a focused task to a background agent with its own context; only its report comes back, as a later follow-up message",
455
489
  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.",
490
+ "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.",
491
+ "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
492
  "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.",
493
+ "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.",
494
+ "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
495
  "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
496
  ],
463
497
  parameters: Type.Object({
@@ -482,10 +516,11 @@ export default function (pi: ExtensionAPI) {
482
516
  ),
483
517
  }),
484
518
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
485
- const params = dropNulls(rawParams);
486
- const { agent: agentName, description, task, model, isolated } = params;
519
+ const { agent: agentName, description, task } = rawParams;
487
520
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
488
- const cloneId = jobId(params.clone);
521
+ const model = optional(rawParams.model);
522
+ const isolated = optional(rawParams.isolated);
523
+ const cloneId = jobId(optional(rawParams.clone));
489
524
  if (cloneId && isolated === false) throw new Error("clone always runs isolated; omit isolated: false.");
490
525
  const clone = cloneId ? clonedJob(cloneId).isolation : undefined;
491
526
  const agent = agentByName(ctx.cwd, agentName);
@@ -493,24 +528,21 @@ export default function (pi: ExtensionAPI) {
493
528
  return runDelegate(ctx, agent, undefined, { description, model, isolated: effective, clone }, task, signal);
494
529
  },
495
530
 
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
- },
531
+ renderCall: callRenderer(
532
+ "delegate",
533
+ (args, theme) => {
534
+ const agent = argText(args?.agent).trim();
535
+ const description = argText(args?.description).trim();
536
+ const identity = [
537
+ agent ? theme.fg("toolTitle", theme.bold(agent)) : "",
538
+ description ? theme.fg("accent", description) : "",
539
+ ]
540
+ .filter(Boolean)
541
+ .join(" ");
542
+ return identity || theme.fg("muted", "…");
543
+ },
544
+ (args) => argText(args?.task),
545
+ ),
514
546
 
515
547
  renderResult(result, { expanded }, theme, context) {
516
548
  const details = result.details as DelegateDetails | undefined;
@@ -548,15 +580,15 @@ export default function (pi: ExtensionAPI) {
548
580
  ),
549
581
  }),
550
582
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
551
- const params = dropNulls(rawParams);
552
- const id = jobId(params.id);
583
+ const id = jobId(rawParams.id);
584
+ const model = optional(rawParams.model);
553
585
  const running = store.liveJob(id);
554
586
  if (running) {
555
587
  // A live job without steer would fall into the revive path and double-spawn its pinned session.
556
588
  if (!running.steer) throw new Error(`No steerable delegate job "${id}".`);
557
589
  try {
558
- if (params.model) await swapModel(running, params.model, ctx);
559
- await running.steer(params.message);
590
+ if (model) await swapModel(running, model, ctx);
591
+ await running.steer(rawParams.message);
560
592
  } catch (error) {
561
593
  // The swap or steer await can outlast the job (a model ack waits up to 30s); raw child errors are cryptic.
562
594
  if (!store.liveJob(id))
@@ -569,7 +601,7 @@ export default function (pi: ExtensionAPI) {
569
601
  id: running.id,
570
602
  agent: running.agent,
571
603
  description: running.description,
572
- message: params.message,
604
+ message: rawParams.message,
573
605
  toolCalls: running.toolCalls,
574
606
  contextTokens: running.contextTokens,
575
607
  contextWindow: running.contextWindow,
@@ -585,8 +617,9 @@ export default function (pi: ExtensionAPI) {
585
617
  details,
586
618
  };
587
619
  }
620
+ await waitForExit(id);
588
621
  const prior = store.findOrThrow(id);
589
- // An applied or discarded clone cannot be continued; a revive would run in the main tree.
622
+ // A parallel apply/discard can close the clone while we wait; re-check before spawning in the main tree.
590
623
  if (prior.cloneClosed)
591
624
  throw new Error(
592
625
  `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 +631,16 @@ export default function (pi: ExtensionAPI) {
598
631
  prior,
599
632
  {
600
633
  description: prior.description,
601
- model: params.model ?? prior.model,
634
+ model: model ?? prior.model,
602
635
  isolated: Boolean(prior.isolation),
603
636
  },
604
637
  prior.task,
605
638
  signal,
606
- params.message,
639
+ rawParams.message,
607
640
  );
608
641
  },
609
642
 
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
- },
643
+ renderCall: idCall("delegate_steer", (args) => argText(args?.message)),
620
644
 
621
645
  renderResult(result, { expanded }, theme, context) {
622
646
  const details = result.details as SteerDetails | DelegateDetails | undefined;
@@ -657,25 +681,9 @@ export default function (pi: ExtensionAPI) {
657
681
  details: { id: job.id, agent: job.agent },
658
682
  };
659
683
  },
684
+ renderCall: idCall("delegate_cancel"),
660
685
 
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
- },
686
+ renderResult: headerResult("cancellation requested"),
679
687
  });
680
688
 
681
689
  pi.registerTool({
@@ -688,8 +696,7 @@ export default function (pi: ExtensionAPI) {
688
696
  id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
689
697
  }),
690
698
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
691
- const params = dropNulls(rawParams);
692
- const id = jobId(params.id);
699
+ const id = jobId(rawParams.id);
693
700
  const { job, isolation } = clonedJob(id);
694
701
  requireIdleClone(isolation);
695
702
  const result = applyClone(isolation);
@@ -704,6 +711,7 @@ export default function (pi: ExtensionAPI) {
704
711
  );
705
712
  }
706
713
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
714
+ const capped = result.kind === "applied" ? capDiff(result.diff) : { diff: undefined, note: undefined };
707
715
  closeClone(isolation);
708
716
  return {
709
717
  content: [
@@ -715,23 +723,13 @@ export default function (pi: ExtensionAPI) {
715
723
  : `Applied the changes of delegate "${job.agent}" (job ${job.id}) to the main tree:${stat}\n(clone removed)`,
716
724
  },
717
725
  ],
718
- details: { id: job.id, agent: job.agent, diff: result.kind === "applied" ? result.diff : undefined },
726
+ details: { id: job.id, agent: job.agent, diff: capped.diff, diffNote: capped.note },
719
727
  };
720
728
  },
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
-
729
+ renderCall: idCall("delegate_apply"),
733
730
  renderResult(result, { expanded }, theme, context) {
734
- const details = result.details as { id: string; agent: string; diff?: string } | undefined;
731
+ const details = result.details as
732
+ { id: string; agent: string; diff?: string; diffNote?: string } | undefined;
735
733
  const body = resultText(result);
736
734
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
737
735
  const header = `\n${resultHeader(theme, details, "changes applied")}`;
@@ -740,6 +738,8 @@ export default function (pi: ExtensionAPI) {
740
738
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
741
739
  const { shown, hidden } = capLines(diff.split("\n"), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
742
740
  if (hidden) shown.push(moreLines(theme, hidden, context.keyHint));
741
+ // The truncation note is plain text: piDiff would otherwise number it as a context line.
742
+ if (details.diffNote) shown.push(theme.fg("muted", details.diffNote));
743
743
  const container = new Container();
744
744
  container.addChild(new Text(header, 0, 0));
745
745
  container.addChild(new Spacer(1));
@@ -758,8 +758,7 @@ export default function (pi: ExtensionAPI) {
758
758
  id: Type.String({ description: "Job id of an isolated delegate; any job id that ran in the clone works." }),
759
759
  }),
760
760
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
761
- const params = dropNulls(rawParams);
762
- const id = jobId(params.id);
761
+ const id = jobId(rawParams.id);
763
762
  const { job, isolation } = clonedJob(id);
764
763
  requireIdleClone(isolation);
765
764
  closeClone(isolation);
@@ -773,24 +772,8 @@ export default function (pi: ExtensionAPI) {
773
772
  details: { id: job.id, agent: job.agent, discarded: true },
774
773
  };
775
774
  },
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
- },
775
+ renderCall: idCall("delegate_discard"),
776
+ renderResult: headerResult("clone discarded"),
794
777
  });
795
778
 
796
779
  pi.registerTool({
@@ -806,7 +789,7 @@ export default function (pi: ExtensionAPI) {
806
789
  const running = jobs.filter((job) => job.status === "running").length;
807
790
  const lastActivity = (job: InspectJob) => {
808
791
  const { tool } = lastToolCall(job);
809
- return job.status === "running" && tool ? ` · ${tool.text}${tool.detail ? ` ${tool.detail}` : ""}` : "";
792
+ return job.status === "running" && tool ? ` · ${tool.name}${tool.detail ? ` ${tool.detail}` : ""}` : "";
810
793
  };
811
794
  const lines = jobs.map((job) => {
812
795
  const tag = isolationWords(job);