@deathbeam/pi-delegate 0.0.2 → 0.0.4

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
@@ -1,6 +1,7 @@
1
1
  # [@deathbeam/pi-delegate](https://www.npmjs.com/package/@deathbeam/pi-delegate)
2
2
 
3
3
  Run focused subagents with `delegate`, `delegate_list`, `delegate_steer`, and `delegate_cancel`.
4
+ Use `/delegate` command to view and manage jobs in a full-screen TUI.
4
5
 
5
6
  ## Installation
6
7
 
package/child.ts CHANGED
@@ -9,12 +9,14 @@ function usageTokens(usage: any): number | undefined {
9
9
  return tokens > 0 ? tokens : undefined;
10
10
  }
11
11
 
12
+ export type ChildActivity = { kind: "tool" | "result" | "assistant" | "status"; text: string; detail?: string };
12
13
  export type ChildUpdate = {
13
14
  toolCalls?: number;
14
15
  lastTool?: string;
15
16
  lastDetail?: string;
16
17
  lastResult?: string;
17
18
  contextTokens?: number;
19
+ activity?: ChildActivity;
18
20
  };
19
21
  export type ChildUpdateHandler = (update: ChildUpdate) => void;
20
22
 
@@ -112,18 +114,29 @@ export function runChild(
112
114
  return;
113
115
  }
114
116
  switch (event.type) {
115
- case "tool_execution_start":
117
+ case "tool_execution_start": {
116
118
  toolCalls += 1;
119
+ const detail = toolCallDetail(event.toolName, event.args);
117
120
  onUpdate?.({
118
121
  toolCalls,
119
122
  lastTool: event.toolName,
120
- lastDetail: toolCallDetail(event.toolName, event.args),
123
+ lastDetail: detail,
121
124
  lastResult: "",
125
+ activity: { kind: "tool", text: event.toolName, detail },
122
126
  });
123
127
  return;
124
- case "tool_execution_end":
125
- onUpdate?.({ lastResult: resultPreview(event.result) });
128
+ }
129
+ case "tool_execution_end": {
130
+ const preview = resultPreview(event.result);
131
+ onUpdate?.({
132
+ lastResult: preview,
133
+ activity: {
134
+ kind: "result",
135
+ text: `↳ ${event.toolName}${event.isError ? " ✗" : ""}: ${preview ?? "(no text output)"}`,
136
+ },
137
+ });
126
138
  return;
139
+ }
127
140
  case "message_update": {
128
141
  const contextTokens = usageTokens(event.usage);
129
142
  const delta =
@@ -144,7 +157,10 @@ export function runChild(
144
157
  .join("") ?? "";
145
158
  if (text) {
146
159
  liveText = text;
147
- onUpdate?.({ contextTokens: usageTokens(event.message.usage) });
160
+ onUpdate?.({
161
+ contextTokens: usageTokens(event.message.usage),
162
+ activity: { kind: "assistant", text },
163
+ });
148
164
  }
149
165
  return;
150
166
  }
package/format.ts CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
4
4
  export const SPINNER_INTERVAL_MS = 100;
5
+
6
+ export type JobStatus = "running" | "done" | "failed" | "cancelled";
7
+
8
+ /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
9
+ export const STATUS_ICONS = {
10
+ done: "✓",
11
+ failed: "✗",
12
+ cancelled: "✗",
13
+ } as const satisfies Record<Exclude<JobStatus, "running">, string>;
14
+
15
+ export function statusIcon(status: JobStatus, now = Date.now()): string {
16
+ return status === "running"
17
+ ? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
18
+ : STATUS_ICONS[status];
19
+ }
20
+
21
+ export const STATUS_COLORS = {
22
+ running: "warning",
23
+ done: "success",
24
+ failed: "error",
25
+ cancelled: "muted",
26
+ } as const satisfies Record<JobStatus, string>;
5
27
  /** pi slices extension widgets at ten lines and appends its own truncation note. */
6
28
  export const WIDGET_MAX_LINES = 10;
7
29
  /** Only a few jobs still fit with their tool-call and tool-result lines: 1 tally + 3*3 lines. */
package/index.ts CHANGED
@@ -4,7 +4,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
7
+ import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
8
8
  import {
9
9
  CONFIG_DIR_NAME,
10
10
  getAgentDir,
@@ -12,21 +12,31 @@ import {
12
12
  keyHint,
13
13
  parseFrontmatter,
14
14
  } from "@earendil-works/pi-coding-agent";
15
- import { Container, Markdown, Text } from "@earendil-works/pi-tui";
15
+ import {
16
+ Container,
17
+ HStack,
18
+ Markdown,
19
+ Text,
20
+ matchesKey,
21
+ truncateToWidth,
22
+ wrapTextWithAnsi,
23
+ } from "@earendil-works/pi-tui";
16
24
  import { Type } from "typebox";
17
25
  import {
18
26
  COLLAPSED_OUTPUT_LINES,
19
27
  type DelegateReport,
20
28
  jobLine,
29
+ type JobStatus,
21
30
  launchDetails,
22
31
  outputPreview,
23
32
  progressStats,
24
33
  reportText,
25
- SPINNER_FRAMES,
34
+ statusIcon,
26
35
  SPINNER_INTERVAL_MS,
36
+ STATUS_COLORS,
27
37
  widgetJobs,
28
38
  } from "./format.ts";
29
- import { runChild } from "./child.ts";
39
+ import { type ChildActivity, runChild } from "./child.ts";
30
40
 
31
41
  type AgentFile = {
32
42
  name: string;
@@ -50,12 +60,17 @@ type SteerDetails = Pick<
50
60
  elapsedMs: number;
51
61
  };
52
62
 
53
- type DelegateJob = {
63
+ type InspectJob = {
54
64
  id: string;
55
65
  agent: string;
56
66
  description: string;
57
67
  task: string;
58
68
  model: string;
69
+ status: JobStatus;
70
+ activity: ChildActivity[];
71
+ };
72
+
73
+ type DelegateJob = InspectJob & {
59
74
  tools: string[];
60
75
  toolCalls: number;
61
76
  lastTool?: string;
@@ -82,6 +97,10 @@ const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
82
97
  const WIDGET_KEY = "delegate";
83
98
  const RESULT_MESSAGE = "delegate-result";
84
99
 
100
+ /** Glyph + color for a job status, identical in the widget, the transcript, and the observer. */
101
+ const statusText = (theme: Theme, status: JobStatus, now = Date.now()) =>
102
+ theme.fg(STATUS_COLORS[status], statusIcon(status, now));
103
+
85
104
  function expandPath(value: string, cwd: string): string {
86
105
  return resolve(cwd, value.replace(/^~(?=\/|$)/, homedir()));
87
106
  }
@@ -170,9 +189,33 @@ function contextWindowFor(ctx: ExtensionContext, model: string | undefined): num
170
189
 
171
190
  export default function (pi: ExtensionAPI) {
172
191
  const running = new Map<string, DelegateJob>();
192
+ const recent: InspectJob[] = [];
193
+ let viewing: (() => void) | undefined;
173
194
  let finished = 0;
174
195
  let ticker: ReturnType<typeof setInterval> | undefined;
175
196
 
197
+ const addActivity = (job: DelegateJob, activity: ChildActivity) => {
198
+ const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
199
+ job.activity.push(
200
+ activity.kind === "assistant"
201
+ ? activity
202
+ : {
203
+ ...activity,
204
+ text: normalize(activity.text),
205
+ detail: activity.detail && normalize(activity.detail),
206
+ },
207
+ );
208
+ viewing?.();
209
+ };
210
+
211
+ // Status words are gone; only a failure detail is worth a log line.
212
+ const remember = (job: DelegateJob, status: JobStatus, detail?: string) => {
213
+ job.status = status;
214
+ if (detail) addActivity(job, { kind: "status", text: detail });
215
+ const { id, agent, description, task, model, activity } = job;
216
+ recent.unshift({ id, agent, description, task, model, status, activity });
217
+ };
218
+
176
219
  const refreshWidget = (ctx: ExtensionContext) => {
177
220
  if (!ctx.hasUI) return;
178
221
  if (running.size === 0) {
@@ -181,16 +224,15 @@ export default function (pi: ExtensionAPI) {
181
224
  }
182
225
  const theme = ctx.ui.theme;
183
226
  const now = Date.now();
184
- const frame = SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!;
185
227
  const { shown, hidden, detail } = widgetJobs([...running.values()]);
186
228
  const lines: string[] = [];
187
229
  if (running.size > 1 || finished > 0) {
188
230
  const counts = `${running.size} running${finished ? ` · ${finished} done` : ""}`;
189
- lines.push(`${theme.fg("warning", frame)} ${theme.fg("muted", counts)}`);
231
+ lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
190
232
  }
191
233
  for (const job of shown) {
192
234
  lines.push(
193
- `${theme.fg("warning", frame)} ${theme.fg("toolTitle", theme.bold(job.agent))} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`,
235
+ `${statusText(theme, "running", now)} ${theme.fg("toolTitle", theme.bold(job.agent))} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`,
194
236
  );
195
237
  if (!detail) continue;
196
238
  if (job.lastTool)
@@ -212,6 +254,7 @@ export default function (pi: ExtensionAPI) {
212
254
  // Cancellation was already acknowledged; shutdown has no UI to report into.
213
255
  if (job.controller.signal.aborted) return;
214
256
  running.delete(job.id);
257
+ remember(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined);
215
258
  finished += 1;
216
259
  if (running.size === 0) stopTicker();
217
260
  refreshWidget(ctx);
@@ -239,6 +282,8 @@ export default function (pi: ExtensionAPI) {
239
282
  stopTicker();
240
283
  for (const job of running.values()) job.controller.abort();
241
284
  running.clear();
285
+ recent.length = 0;
286
+ viewing = undefined;
242
287
  finished = 0;
243
288
  });
244
289
 
@@ -255,7 +300,7 @@ export default function (pi: ExtensionAPI) {
255
300
  pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded }, theme) => {
256
301
  const report = message.details as DelegateReport | undefined;
257
302
  if (!report?.agent) return undefined;
258
- const icon = report.error ? theme.fg("error", "✗") : theme.fg("success", "✓");
303
+ const icon = statusText(theme, report.error ? "failed" : "done");
259
304
  const container = new Container();
260
305
  container.addChild(
261
306
  new Text(
@@ -280,6 +325,223 @@ export default function (pi: ExtensionAPI) {
280
325
  return container;
281
326
  });
282
327
 
328
+ pi.registerCommand("delegate", {
329
+ description: "Inspect live and recent delegate activity",
330
+ handler: async (_args, ctx) => {
331
+ if (ctx.mode !== "tui") return;
332
+ if (!running.size && !recent.length) {
333
+ ctx.ui.notify("No delegates in this session yet.", "info");
334
+ return;
335
+ }
336
+ const screen = {
337
+ overlay: true,
338
+ overlayOptions: { width: "100%", maxHeight: "100%", row: 0, col: 0 },
339
+ } as const;
340
+ try {
341
+ await ctx.ui.custom((tui, theme, keys, done) => {
342
+ let selectedId = running.keys().next().value ?? recent[0]!.id;
343
+ let focus: "list" | "history" = "list";
344
+ let top: number | undefined;
345
+ let historyWidth = 1;
346
+ let markdown = new WeakMap<ChildActivity, Markdown>();
347
+ const jobs = () => [...running.values(), ...recent];
348
+ const bodyHeight = () => Math.max(0, tui.terminal.rows - 3);
349
+ // The list pane already draws a border, and the muted model line sets the task apart.
350
+ const taskLines = (job: InspectJob, width: number) =>
351
+ wrapTextWithAnsi(job.task.trim(), Math.max(1, width)).map((line) => theme.fg("text", line));
352
+ const historyHeight = (job: InspectJob, width: number) =>
353
+ Math.max(0, bodyHeight() - 6 - taskLines(job, width).length);
354
+ // ScrollView needs fullscreen layout; window the history in regular TUI too.
355
+ const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
356
+ const row = (text: string) =>
357
+ truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
358
+ const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 2));
359
+ const start = Math.max(
360
+ 0,
361
+ Math.min(selectedIndex - Math.floor(visible / 2), items.length - visible),
362
+ );
363
+ const lines = items
364
+ .slice(start, start + visible)
365
+ .flatMap((item, index) => [
366
+ row(
367
+ theme.fg(
368
+ start + index === selectedIndex && focus === "list" ? "accent" : "text",
369
+ `${start + index === selectedIndex ? "›" : " "} ${statusText(theme, item.status)} ${item.agent} ${item.id}`,
370
+ ),
371
+ ),
372
+ row(theme.fg("muted", ` ${item.description}`)),
373
+ ]);
374
+ return [
375
+ ...lines,
376
+ ...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
377
+ row(theme.fg("dim", ` ${selectedIndex + 1}/${items.length}`)),
378
+ ].slice(0, bodyHeight());
379
+ };
380
+ const renderEntry = (entry: ChildActivity, width: number): string[] => {
381
+ if (entry.kind === "assistant") {
382
+ let md = markdown.get(entry);
383
+ if (!md) {
384
+ md = new Markdown(entry.text, 0, 0, getMarkdownTheme());
385
+ markdown.set(entry, md);
386
+ }
387
+ return [theme.fg("accent", "assistant"), ...md.render(width), ""];
388
+ }
389
+ if (entry.kind === "tool")
390
+ return [
391
+ truncateToWidth(
392
+ theme.fg("toolTitle", entry.text) +
393
+ (entry.detail ? ` ${theme.fg("accent", entry.detail)}` : ""),
394
+ width,
395
+ ),
396
+ ];
397
+ if (entry.kind === "result") return [truncateToWidth(theme.fg("text", entry.text), width)];
398
+ // Only failure detail still says anything; the header icon carries the status.
399
+ if (!entry.text) return [];
400
+ return [truncateToWidth(theme.fg(STATUS_COLORS.failed, entry.text), width)];
401
+ };
402
+ const renderHistory = (width: number, job: InspectJob): string[] => {
403
+ historyWidth = width;
404
+ const task = taskLines(job, width);
405
+ const height = Math.max(0, bodyHeight() - 6 - task.length);
406
+ const history = job.activity.flatMap((entry) => renderEntry(entry, width));
407
+ const maxTop = Math.max(0, history.length - height);
408
+ const start = Math.min(top ?? maxTop, maxTop);
409
+ const visible = history.slice(start, start + height);
410
+ const shown = visible.length
411
+ ? visible
412
+ : height
413
+ ? [theme.fg("muted", "Waiting for activity…")]
414
+ : [];
415
+ return [
416
+ truncateToWidth(
417
+ theme.fg(focus === "history" ? "accent" : "toolTitle", theme.bold(job.agent)) +
418
+ ` ${theme.fg("dim", job.id)} ${statusText(theme, job.status)}`,
419
+ width,
420
+ ),
421
+ truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
422
+ truncateToWidth(theme.fg("dim", job.model), width),
423
+ "",
424
+ ...task,
425
+ theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
426
+ ...shown,
427
+ ...Array(Math.max(0, height - shown.length)).fill(""),
428
+ truncateToWidth(
429
+ theme.fg(
430
+ "dim",
431
+ `${visible.length ? `${start + 1}–${start + visible.length}` : "0"}/${history.length}`,
432
+ ),
433
+ width,
434
+ ),
435
+ ].slice(0, bodyHeight());
436
+ };
437
+ viewing = () => tui.requestRender();
438
+ return {
439
+ render(width: number) {
440
+ const items = jobs();
441
+ const selectedIndex = Math.max(
442
+ 0,
443
+ items.findIndex((item) => item.id === selectedId),
444
+ );
445
+ const selected = items[selectedIndex];
446
+ const title = truncateToWidth(
447
+ `${theme.fg(focus === "list" ? "accent" : "muted", focus === "list" ? "[Jobs]" : "Jobs")} ` +
448
+ `${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
449
+ theme.fg("dim", ` · ${running.size} running · ${items.length} total`),
450
+ width,
451
+ );
452
+ const footer = truncateToWidth(
453
+ theme.fg(
454
+ "dim",
455
+ `${keyHint("tui.select.up", "previous")} · ${keyHint("tui.select.down", "next")} · Tab switch pane · ${keyHint("tui.select.cancel", "close")}`,
456
+ ),
457
+ width,
458
+ );
459
+ if (!selected)
460
+ return [
461
+ title,
462
+ theme.fg("muted", "No delegates in this session."),
463
+ ...Array(Math.max(0, tui.terminal.rows - 3)).fill(""),
464
+ footer,
465
+ ].slice(0, tui.terminal.rows);
466
+ const sidebarWidth = Math.min(
467
+ 40,
468
+ Math.max(16, Math.floor(width * 0.35)),
469
+ Math.max(1, width - 2),
470
+ );
471
+ const body = new HStack(
472
+ [
473
+ {
474
+ component: {
475
+ render: (w) => renderJobs(w, items, selectedIndex),
476
+ invalidate() {},
477
+ },
478
+ basis: sidebarWidth,
479
+ shrink: 0,
480
+ },
481
+ {
482
+ component: { render: (w) => renderHistory(w, selected), invalidate() {} },
483
+ basis: 0,
484
+ grow: 1,
485
+ },
486
+ ],
487
+ { gap: 1 },
488
+ ).render(width);
489
+ return [
490
+ title,
491
+ theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
492
+ ...body,
493
+ footer,
494
+ ].slice(0, tui.terminal.rows);
495
+ },
496
+ invalidate() {
497
+ markdown = new WeakMap();
498
+ },
499
+ handleInput(data: string) {
500
+ if (keys.matches(data, "tui.select.cancel")) done(undefined);
501
+ else if (matchesKey(data, "tab")) focus = focus === "list" ? "history" : "list";
502
+ else if (matchesKey(data, "left")) focus = "list";
503
+ else if (
504
+ matchesKey(data, "right") ||
505
+ (focus === "list" && keys.matches(data, "tui.select.confirm"))
506
+ )
507
+ focus = "history";
508
+ else if (keys.matches(data, "tui.select.up") || keys.matches(data, "tui.select.down")) {
509
+ const up = keys.matches(data, "tui.select.up");
510
+ const items = jobs();
511
+ if (focus === "list") {
512
+ const index = Math.max(
513
+ 0,
514
+ items.findIndex((item) => item.id === selectedId),
515
+ );
516
+ selectedId =
517
+ items[Math.max(0, Math.min(items.length - 1, index + (up ? -1 : 1)))]?.id ??
518
+ selectedId;
519
+ top = undefined;
520
+ } else {
521
+ const selected = items.find((item) => item.id === selectedId) ?? items[0];
522
+ const length =
523
+ selected?.activity.reduce(
524
+ (sum, entry) => sum + renderEntry(entry, historyWidth).length,
525
+ 0,
526
+ ) ?? 0;
527
+ const maxTop = Math.max(
528
+ 0,
529
+ length - (selected ? historyHeight(selected, historyWidth) : 0),
530
+ );
531
+ const position = Math.max(0, Math.min(maxTop, top ?? maxTop) + (up ? -1 : 1));
532
+ top = position >= maxTop ? undefined : position;
533
+ }
534
+ }
535
+ tui.requestRender();
536
+ },
537
+ };
538
+ }, screen);
539
+ } finally {
540
+ viewing = undefined;
541
+ }
542
+ },
543
+ });
544
+
283
545
  pi.registerTool({
284
546
  name: "delegate",
285
547
  label: "Delegate",
@@ -319,6 +581,8 @@ export default function (pi: ExtensionAPI) {
319
581
  description: params.description.trim(),
320
582
  task: params.task,
321
583
  model,
584
+ status: "running",
585
+ activity: [],
322
586
  tools,
323
587
  toolCalls: 0,
324
588
  startedAt: Date.now(),
@@ -347,9 +611,12 @@ export default function (pi: ExtensionAPI) {
347
611
  stdio: "pipe",
348
612
  });
349
613
  const run = runChild(child, params.task, details.background ? job.controller.signal : signal, (update) => {
350
- for (const [key, value] of Object.entries(update)) {
614
+ if (job.status !== "running") return;
615
+ const { activity, ...progress } = update;
616
+ for (const [key, value] of Object.entries(progress)) {
351
617
  if (value !== undefined) (job as Record<string, unknown>)[key] = value;
352
618
  }
619
+ if (activity && details.background) addActivity(job, activity);
353
620
  });
354
621
  job.steer = run.steer;
355
622
 
@@ -395,7 +662,7 @@ export default function (pi: ExtensionAPI) {
395
662
  const body = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
396
663
  if (!details?.agent) return new Text(body || "(no output)", 0, 0);
397
664
 
398
- const icon = context.isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
665
+ const icon = statusText(theme, context.isError ? "failed" : "done");
399
666
  const status = details.background ? "started in background" : "completed";
400
667
  const container = new Container();
401
668
  container.addChild(
@@ -472,7 +739,7 @@ export default function (pi: ExtensionAPI) {
472
739
  const details = result.details as SteerDetails | undefined;
473
740
  const body = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
474
741
  if (!details?.agent) return new Text(body || "(no output)", 0, 0);
475
- const icon = context.isError ? theme.fg("error", "✗") : theme.fg("success", "✓");
742
+ const icon = statusText(theme, context.isError ? "failed" : "done");
476
743
  const container = new Container();
477
744
  container.addChild(
478
745
  new Text(
@@ -500,6 +767,7 @@ export default function (pi: ExtensionAPI) {
500
767
  const job = running.get(id);
501
768
  if (!job) throw new Error(`No running delegate job "${id}".`);
502
769
  running.delete(id);
770
+ remember(job, "cancelled");
503
771
  job.controller.abort();
504
772
  if (running.size === 0) stopTicker();
505
773
  refreshWidget(ctx);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.2",
4
- "description": "Run focused Pi subagents as background or foreground tasks",
3
+ "version": "0.0.4",
4
+ "description": "Run focused Pi subagents as background tasks",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {