@deathbeam/pi-delegate 0.0.38 → 0.0.40

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/child.ts CHANGED
@@ -5,12 +5,6 @@ import { limitOutput, resultPreview, toolCallDetail } from "./format.ts";
5
5
 
6
6
  type Child = ChildProcessWithoutNullStreams;
7
7
 
8
- function usageTokens(usage: any): number | undefined {
9
- if (!usage) return undefined;
10
- const tokens = usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
11
- return tokens > 0 ? tokens : undefined;
12
- }
13
-
14
8
  export type ChildActivity = {
15
9
  kind: "tool" | "result" | "assistant" | "user" | "status";
16
10
  text: string;
@@ -30,6 +24,12 @@ type ChildRun = {
30
24
  swapModel: (provider: string, modelId: string, level?: string, onModelSet?: () => void) => Promise<void>;
31
25
  };
32
26
 
27
+ function usageTokens(usage: any): number | undefined {
28
+ if (!usage) return undefined;
29
+ const tokens = usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
30
+ return tokens > 0 ? tokens : undefined;
31
+ }
32
+
33
33
  /** Run one RPC child, keeping its writer serialized so backpressure and EPIPE reach the caller. */
34
34
  export function runChild(
35
35
  child: Child,
@@ -157,14 +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 content = event.message.content;
161
- const text =
162
- typeof content === "string"
163
- ? content
164
- : (content
165
- ?.filter((part: any) => part.type === "text")
166
- .map((part: any) => part.text ?? "")
167
- .join("") ?? "");
160
+ const text = transcriptText(event.message.content).join("");
168
161
  if (role === "assistant") {
169
162
  childError = event.message.errorMessage;
170
163
  if (text) liveText = text;
@@ -177,7 +170,8 @@ export function runChild(
177
170
  return;
178
171
  }
179
172
  case "agent_settled":
180
- 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);
181
175
  return;
182
176
  case "extension_ui_request":
183
177
  if (["select", "confirm", "input", "editor"].includes(event.method)) {
@@ -304,7 +298,7 @@ export function runChild(
304
298
  };
305
299
  }
306
300
 
307
- /** Text content of a persisted transcript message, in part order. */
301
+ /** Text parts of a message's content, in order. */
308
302
  function transcriptText(content: unknown): string[] {
309
303
  if (typeof content === "string") return [content];
310
304
  if (!Array.isArray(content)) return [];
@@ -331,7 +325,7 @@ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
331
325
  return [];
332
326
  }
333
327
  if (!sessionFile) return [];
334
- let lines: string[] = [];
328
+ let lines: string[];
335
329
  try {
336
330
  lines = readFileSync(join(sessionDir, sessionFile), "utf8").split("\n");
337
331
  } catch {
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,
@@ -32,6 +32,20 @@ export type DelegateReport = {
32
32
  cloneClosed?: boolean;
33
33
  };
34
34
 
35
+ /** The isolation state to show for a job: pending means its clone still holds unapplied work. */
36
+ export type IsolationMark = "isolated" | "pending";
37
+
38
+ type IsolationStateFields = {
39
+ isolation?: unknown;
40
+ cloneClosed?: boolean;
41
+ status?: string;
42
+ };
43
+
44
+ export type DelegateDetails = Pick<
45
+ DelegateJob,
46
+ "id" | "agent" | "description" | "task" | "model" | "tools" | "status" | "isolation" | "cloneClosed"
47
+ > & { background: boolean };
48
+
35
49
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
36
50
  export const SPINNER_INTERVAL_MS = 100;
37
51
  const STATUS_ICONS = {
@@ -64,15 +78,6 @@ export function statusText(theme: Theme, status: JobStatus, now = Date.now()): s
64
78
  return theme.fg(STATUS_COLORS[status], statusIcon(status, now));
65
79
  }
66
80
 
67
- /** The isolation state to show for a job: pending means its clone still holds unapplied work. */
68
- export type IsolationMark = "isolated" | "pending";
69
-
70
- type IsolationStateFields = {
71
- isolation?: unknown;
72
- cloneClosed?: boolean;
73
- status?: string;
74
- };
75
-
76
81
  /** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
77
82
  export function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
78
83
  if (!job.isolation) return undefined;
@@ -291,24 +296,25 @@ export function widgetJobs<T>(jobs: T[]): { shown: T[]; hidden: number } {
291
296
  return { shown, hidden: jobs.length - shown.length };
292
297
  }
293
298
 
294
- export type DelegateDetails = Pick<
295
- DelegateJob,
296
- "id" | "agent" | "description" | "task" | "model" | "tools" | "status" | "isolation" | "cloneClosed"
297
- > & { background: boolean };
298
-
299
299
  export function resultFallback(body: string, theme: Theme, isError: boolean): Text {
300
300
  const mark = statusText(theme, isError ? "failed" : "done");
301
301
  return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
302
302
  }
303
303
 
304
- export function moreLines(theme: Theme, hidden: number): string {
304
+ export function moreLines(theme: Theme, hidden: number, keyHint: KeybindingHints["keyHint"]): string {
305
305
  return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
306
306
  }
307
307
 
308
- export function appendOutput(container: Container, body: string, expanded: boolean, theme: Theme): void {
308
+ export function appendOutput(
309
+ container: Container,
310
+ body: string,
311
+ expanded: boolean,
312
+ theme: Theme,
313
+ keyHint: KeybindingHints["keyHint"],
314
+ ): void {
309
315
  const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
310
316
  container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
311
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
317
+ if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden, keyHint), 0, 0));
312
318
  }
313
319
 
314
320
  export function toolLayout(
@@ -317,6 +323,7 @@ export function toolLayout(
317
323
  payload: string,
318
324
  theme: Theme,
319
325
  expanded: boolean,
326
+ keyHint: KeybindingHints["keyHint"],
320
327
  ): Component {
321
328
  const container = new Container();
322
329
  if (toolName)
@@ -337,7 +344,7 @@ export function toolLayout(
337
344
  render: (width) => {
338
345
  // Wrapping turns one long line into many, so the cap counts rendered rows, not source lines.
339
346
  const { shown, hidden } = capLines(body.render(width), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
340
- return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden), width)] : shown;
347
+ return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden, keyHint), width)] : shown;
341
348
  },
342
349
  invalidate: () => body.invalidate(),
343
350
  });
@@ -368,6 +375,7 @@ export function launchResult(
368
375
  status: string,
369
376
  expanded: boolean,
370
377
  theme: Theme,
378
+ keyHint: KeybindingHints["keyHint"],
371
379
  ): Component {
372
380
  const container = new Container();
373
381
  // The mark is the call's outcome (launch succeeded); job progress stays in the widget and report.
@@ -378,6 +386,6 @@ export function launchResult(
378
386
  new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
379
387
  );
380
388
  // Background results arrive as their own message; headless runs still show the output here.
381
- if (!details.background && body) appendOutput(container, body, expanded, theme);
389
+ if (!details.background && body) appendOutput(container, body, expanded, theme, keyHint);
382
390
  return container;
383
391
  }
package/index.ts CHANGED
@@ -96,6 +96,11 @@ function withIsolation(output: string, isolation: IsolationState | undefined): s
96
96
  return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
97
97
  }
98
98
 
99
+ /** Status icon, identity, and the muted detail line: the row the widget and delegate_list both show. */
100
+ function jobRow(theme: Theme, job: InspectJob, now: number): string {
101
+ return `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, elapsedMs(job, now)))}`;
102
+ }
103
+
99
104
  export default function (pi: ExtensionAPI) {
100
105
  const store = createJobStore(pi.appendEntry);
101
106
  let ticker: ReturnType<typeof setInterval> | undefined;
@@ -112,7 +117,7 @@ export default function (pi: ExtensionAPI) {
112
117
  /** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
113
118
  const jobsInClone = (clone: string) => store.all().filter((job) => job.isolation?.clone === clone);
114
119
 
115
- /** A job that still has a clone; any job id that ran in a clone is a handle on it. */
120
+ /** A job that still has a clone; throws explaining why it has none. */
116
121
  const clonedJob = (id: string) => {
117
122
  const job = store.findOrThrow(id);
118
123
  const isolation = job.isolation;
@@ -153,14 +158,10 @@ export default function (pi: ExtensionAPI) {
153
158
  const theme = ctx.ui.theme;
154
159
  const now = Date.now();
155
160
  const { shown, hidden } = widgetJobs(jobs);
156
- const lines: string[] = [];
157
- const all = store.all();
158
- const counts = tally(jobs.length, all, now);
159
- lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
161
+ const counts = tally(jobs.length, store.all(), now);
162
+ const lines = [`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`];
160
163
  for (const job of shown) {
161
- lines.push(
162
- `${statusText(theme, "running", now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, elapsedMs(job, now)))}`,
163
- );
164
+ lines.push(jobRow(theme, job, now));
164
165
  const { tool, result } = lastToolCall(job);
165
166
  if (tool)
166
167
  lines.push(
@@ -181,7 +182,6 @@ export default function (pi: ExtensionAPI) {
181
182
  });
182
183
  };
183
184
 
184
- // The ticker animates spinners exactly while live jobs exist.
185
185
  const syncTicker = (ctx: ExtensionContext) => {
186
186
  if (store.live().length > 0) ticker ??= setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
187
187
  else if (ticker) {
@@ -383,7 +383,8 @@ export default function (pi: ExtensionAPI) {
383
383
  pi.on("session_start", (_event, ctx) => restoreSession(ctx));
384
384
  pi.on("session_tree", (_event, ctx) => restoreSession(ctx));
385
385
 
386
- pi.on("before_agent_start", () => {
386
+ pi.on("before_agent_start", (event) => {
387
+ if (event.messageType !== "user") return;
387
388
  directCalls = 0;
388
389
  nextReminder = FIRST_REMINDER_AT;
389
390
  });
@@ -410,7 +411,7 @@ export default function (pi: ExtensionAPI) {
410
411
  );
411
412
  });
412
413
 
413
- pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded }, theme) => {
414
+ pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded, keyHint }, theme) => {
414
415
  const report = message.details as DelegateReport | undefined;
415
416
  if (!report?.agent) return undefined;
416
417
  const container = new Container();
@@ -420,15 +421,14 @@ export default function (pi: ExtensionAPI) {
420
421
  if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
421
422
  else if (report.output) {
422
423
  container.addChild(new Spacer(1));
423
- appendOutput(container, report.output, expanded, theme);
424
+ appendOutput(container, report.output, expanded, theme, keyHint);
424
425
  }
425
426
  return container;
426
427
  });
427
428
 
428
429
  registerInspector(pi, store);
429
430
 
430
- const cwd = process.cwd();
431
- const agentList = agentsFor(cwd).map((agent) => {
431
+ const agentList = agentsFor(process.cwd()).map((agent) => {
432
432
  const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
433
433
  return `- ${agent.name}${qualifiers ? ` (${qualifiers})` : ""}: ${agent.description}`;
434
434
  });
@@ -508,6 +508,7 @@ export default function (pi: ExtensionAPI) {
508
508
  argText(args?.task),
509
509
  theme,
510
510
  context.expanded,
511
+ context.keyHint,
511
512
  );
512
513
  },
513
514
 
@@ -521,6 +522,7 @@ export default function (pi: ExtensionAPI) {
521
522
  details.background ? "started in background" : "completed",
522
523
  expanded,
523
524
  theme,
525
+ context.keyHint,
524
526
  );
525
527
  },
526
528
  });
@@ -612,6 +614,7 @@ export default function (pi: ExtensionAPI) {
612
614
  argText(args?.message),
613
615
  theme,
614
616
  context.expanded,
617
+ context.keyHint,
615
618
  );
616
619
  },
617
620
 
@@ -626,6 +629,7 @@ export default function (pi: ExtensionAPI) {
626
629
  details.background ? "revived in background" : "revived",
627
630
  expanded,
628
631
  theme,
632
+ context.keyHint,
629
633
  );
630
634
  },
631
635
  });
@@ -655,7 +659,14 @@ export default function (pi: ExtensionAPI) {
655
659
  },
656
660
 
657
661
  renderCall(args, theme, context) {
658
- return toolLayout("delegate_cancel", jobTarget(args?.id, theme), "", theme, context.expanded);
662
+ return toolLayout(
663
+ "delegate_cancel",
664
+ jobTarget(args?.id, theme),
665
+ "",
666
+ theme,
667
+ context.expanded,
668
+ context.keyHint,
669
+ );
659
670
  },
660
671
 
661
672
  renderResult(result, _options, theme, context) {
@@ -709,7 +720,14 @@ export default function (pi: ExtensionAPI) {
709
720
  },
710
721
 
711
722
  renderCall(args, theme, context) {
712
- return toolLayout("delegate_apply", jobTarget(args?.id, theme), "", theme, context.expanded);
723
+ return toolLayout(
724
+ "delegate_apply",
725
+ jobTarget(args?.id, theme),
726
+ "",
727
+ theme,
728
+ context.expanded,
729
+ context.keyHint,
730
+ );
713
731
  },
714
732
 
715
733
  renderResult(result, { expanded }, theme, context) {
@@ -721,7 +739,7 @@ export default function (pi: ExtensionAPI) {
721
739
  if (!diff) return new Text(header, 0, 0);
722
740
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
723
741
  const { shown, hidden } = capLines(diff.split("\n"), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
724
- if (hidden) shown.push(moreLines(theme, hidden));
742
+ if (hidden) shown.push(moreLines(theme, hidden, context.keyHint));
725
743
  const container = new Container();
726
744
  container.addChild(new Text(header, 0, 0));
727
745
  container.addChild(new Spacer(1));
@@ -757,7 +775,14 @@ export default function (pi: ExtensionAPI) {
757
775
  },
758
776
 
759
777
  renderCall(args, theme, context) {
760
- return toolLayout("delegate_discard", jobTarget(args?.id, theme), "", theme, context.expanded);
778
+ return toolLayout(
779
+ "delegate_discard",
780
+ jobTarget(args?.id, theme),
781
+ "",
782
+ theme,
783
+ context.expanded,
784
+ context.keyHint,
785
+ );
761
786
  },
762
787
 
763
788
  renderResult(result, _options, theme, context) {
@@ -798,13 +823,9 @@ export default function (pi: ExtensionAPI) {
798
823
  const jobs = (result.details as { jobs?: InspectJob[] } | undefined)?.jobs;
799
824
  if (!jobs?.length || context.isError) return resultFallback(resultText(result), theme, context.isError);
800
825
  const now = Date.now();
826
+ const rows = jobs.map((job) => jobRow(theme, job, now)).join("\n");
801
827
  return new Text(
802
- `\n${statusText(theme, "done")} ${theme.fg("muted", `${jobs.length} delegates`)}\n${jobs
803
- .map(
804
- (job) =>
805
- `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, elapsedMs(job, now)))}`,
806
- )
807
- .join("\n")}`,
828
+ `\n${statusText(theme, "done")} ${theme.fg("muted", `${jobs.length} delegates`)}\n${rows}`,
808
829
  0,
809
830
  0,
810
831
  );
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
  );
@@ -154,7 +164,6 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
154
164
  return [
155
165
  title,
156
166
  theme.fg("muted", "No delegates in this session."),
157
- // Fixed rows: title, top rule, bottom rule, footer.
158
167
  ...Array(Math.max(0, tui.terminal.rows - 4)).fill(""),
159
168
  footer,
160
169
  ].slice(0, tui.terminal.rows);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.38",
3
+ "version": "0.0.40",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/store.ts CHANGED
@@ -21,13 +21,6 @@ export type InspectJob = {
21
21
  cloneClosed?: boolean;
22
22
  };
23
23
 
24
- /** The job's latest tool call and its result, once the result arrives. */
25
- export function lastToolCall(job: InspectJob): { tool?: ChildActivity; result?: ChildActivity } {
26
- const at = job.activity.findLastIndex((entry) => entry.kind === "tool");
27
- if (at < 0) return {};
28
- return { tool: job.activity[at], result: job.activity.slice(at + 1).find((entry) => entry.kind === "result") };
29
- }
30
-
31
24
  export type DelegateJob = InspectJob & {
32
25
  controller: AbortController;
33
26
  steer?: (message: string) => Promise<void>;
@@ -164,3 +157,10 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
164
157
  }
165
158
 
166
159
  export type JobStore = ReturnType<typeof createJobStore>;
160
+
161
+ /** The job's latest tool call and its result, once the result arrives. */
162
+ export function lastToolCall(job: InspectJob): { tool?: ChildActivity; result?: ChildActivity } {
163
+ const at = job.activity.findLastIndex((entry) => entry.kind === "tool");
164
+ if (at < 0) return {};
165
+ return { tool: job.activity[at], result: job.activity.slice(at + 1).find((entry) => entry.kind === "result") };
166
+ }