@deathbeam/pi-delegate 0.0.4 → 0.0.6

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.
Files changed (3) hide show
  1. package/format.ts +54 -56
  2. package/index.ts +38 -42
  3. package/package.json +1 -1
package/format.ts CHANGED
@@ -1,43 +1,66 @@
1
- /** UI helpers stay Pi-import-free for the native check; Pi's analogous formatters are private. */
2
-
3
- export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
4
- export const SPINNER_INTERVAL_MS = 100;
1
+ /** Formatting helpers stay runtime Pi-import-free for the native check; Pi's analogous formatters are private. */
2
+ import type { Theme } from "@earendil-works/pi-coding-agent";
5
3
 
6
4
  export type JobStatus = "running" | "done" | "failed" | "cancelled";
5
+ export type UsageInfo = {
6
+ contextTokens?: number;
7
+ contextWindow?: number;
8
+ };
9
+ export type DelegateReport = {
10
+ id: string;
11
+ agent: string;
12
+ description: string;
13
+ model?: string;
14
+ toolCalls: number;
15
+ contextTokens?: number;
16
+ contextWindow?: number;
17
+ elapsedMs: number;
18
+ output?: string;
19
+ error?: string;
20
+ };
7
21
 
8
- /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
22
+ export const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
23
+ export const SPINNER_INTERVAL_MS = 100;
9
24
  export const STATUS_ICONS = {
10
25
  done: "✓",
11
26
  failed: "✗",
12
27
  cancelled: "✗",
13
28
  } 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
29
  export const STATUS_COLORS = {
22
30
  running: "warning",
23
31
  done: "success",
24
32
  failed: "error",
25
33
  cancelled: "muted",
26
34
  } as const satisfies Record<JobStatus, string>;
27
- /** pi slices extension widgets at ten lines and appends its own truncation note. */
35
+ /** Pi slices extension widgets at ten lines and appends its own truncation note. */
28
36
  export const WIDGET_MAX_LINES = 10;
29
37
  /** Only a few jobs still fit with their tool-call and tool-result lines: 1 tally + 3*3 lines. */
30
38
  const WIDGET_MAX_DETAIL_JOBS = 3;
31
39
  /** In bulk, one row per job: 1 tally + 8 rows + 1 "more running" footer. */
32
40
  const WIDGET_MAX_JOBS = 8;
33
- const EXPANDED_PAD = " ";
41
+ export const COLLAPSED_OUTPUT_LINES = 10;
42
+ export const MAX_OUTPUT_BYTES = 50 * 1024;
43
+ const EXPANDED_PAD = " ";
34
44
  const TASK_LABEL = "Task: ";
35
45
 
36
- export type ProgressInfo = {
37
- toolCalls?: number;
38
- contextTokens?: number;
39
- contextWindow?: number;
40
- };
46
+ /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
47
+ export function statusIcon(status: JobStatus, now = Date.now()): string {
48
+ return status === "running"
49
+ ? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
50
+ : STATUS_ICONS[status];
51
+ }
52
+
53
+ export function statusText(theme: Theme, status: JobStatus, now = Date.now()): string {
54
+ return theme.fg(STATUS_COLORS[status], statusIcon(status, now));
55
+ }
56
+
57
+ export function jobIdentity(theme: Theme, job: { id: string; agent: string }): string {
58
+ return `${theme.fg("muted", job.id)} ${theme.fg("toolTitle", theme.bold(job.agent))}`;
59
+ }
60
+
61
+ export function formatTools(tools: string[]): string {
62
+ return tools.join(", ") || "none";
63
+ }
41
64
 
42
65
  export function formatTokens(count: number): string {
43
66
  if (count < 1000) return String(count);
@@ -55,18 +78,13 @@ export function formatDuration(ms: number): string {
55
78
  return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
56
79
  }
57
80
 
58
- export function progressStats(progress: ProgressInfo, elapsedMs: number): string {
59
- const parts: string[] = [];
60
- if (progress.toolCalls) parts.push(`${progress.toolCalls} tool ${progress.toolCalls === 1 ? "call" : "calls"}`);
61
- if (progress.contextTokens) {
62
- parts.push(
63
- progress.contextWindow
64
- ? `${formatTokens(progress.contextTokens)}/${formatTokens(progress.contextWindow)}`
65
- : formatTokens(progress.contextTokens),
66
- );
67
- }
68
- parts.push(formatDuration(elapsedMs));
69
- return parts.join(" · ");
81
+ export function usageStats(usage: UsageInfo, elapsedMs: number): string {
82
+ const tokens = usage.contextTokens
83
+ ? usage.contextWindow
84
+ ? `${formatTokens(usage.contextTokens)}/${formatTokens(usage.contextWindow)}`
85
+ : formatTokens(usage.contextTokens)
86
+ : "";
87
+ return [tokens, formatDuration(elapsedMs)].filter(Boolean).join(" · ");
70
88
  }
71
89
 
72
90
  export function toolCallDetail(toolName: string, args: unknown): string {
@@ -96,7 +114,7 @@ export function toolCallDetail(toolName: string, args: unknown): string {
96
114
  export function launchDetails(info: { task?: string; model?: string; tools: string[] }): string[] {
97
115
  const lines = [
98
116
  `${EXPANDED_PAD}Model: ${info.model ?? "default"}`,
99
- `${EXPANDED_PAD}Tools: ${info.tools.join(", ") || "all"}`,
117
+ `${EXPANDED_PAD}Tools: ${formatTools(info.tools)}`,
100
118
  ];
101
119
  const task = (info.task ?? "").trim();
102
120
  if (task) {
@@ -109,8 +127,6 @@ export function launchDetails(info: { task?: string; model?: string; tools: stri
109
127
  return lines;
110
128
  }
111
129
 
112
- export const COLLAPSED_OUTPUT_LINES = 10;
113
-
114
130
  /** Close dangling Markdown fences so collapsed previews render correctly. */
115
131
  export function outputPreview(text: string, maxLines = COLLAPSED_OUTPUT_LINES): { shown: string[]; hidden: number } {
116
132
  const lines = text.trim().split("\n");
@@ -120,8 +136,6 @@ export function outputPreview(text: string, maxLines = COLLAPSED_OUTPUT_LINES):
120
136
  return { shown, hidden: lines.length - maxLines };
121
137
  }
122
138
 
123
- export const MAX_OUTPUT_BYTES = 50 * 1024;
124
-
125
139
  /** Cap child output without splitting UTF-8 characters. */
126
140
  export function limitOutput(text: string, maxBytes = MAX_OUTPUT_BYTES): string {
127
141
  const buffer = Buffer.from(text, "utf8");
@@ -148,30 +162,14 @@ export function resultPreview(result: unknown, maxChars = 120): string | undefin
148
162
  return line.length > maxChars ? `${line.slice(0, maxChars - 1)}…` : line;
149
163
  }
150
164
 
151
- export type DelegateReport = {
152
- id: string;
153
- agent: string;
154
- description: string;
155
- model?: string;
156
- toolCalls: number;
157
- contextTokens?: number;
158
- contextWindow?: number;
159
- elapsedMs: number;
160
- output?: string;
161
- error?: string;
162
- };
163
-
164
165
  export function reportText(report: DelegateReport): string {
165
- const calls = report.toolCalls
166
- ? ` after ${report.toolCalls} tool ${report.toolCalls === 1 ? "call" : "calls"}`
167
- : "";
168
- if (report.error) return `Delegated agent "${report.agent}" (job ${report.id}) failed${calls}: ${report.error}`;
166
+ if (report.error) return `Delegated agent "${report.agent}" (job ${report.id}) failed: ${report.error}`;
169
167
  const output = (report.output ?? "").trim();
170
- return `Delegated agent "${report.agent}" (job ${report.id}) finished${calls}.${output ? `\n\n${output}` : ""}`;
168
+ return `Delegated agent "${report.agent}" (job ${report.id}) finished.${output ? `\n\n${output}` : ""}`;
171
169
  }
172
170
 
173
- export function jobLine(info: { description?: string } & ProgressInfo, elapsedMs: number): string {
174
- return [info.description?.trim(), progressStats(info, elapsedMs)].filter(Boolean).join(" · ");
171
+ export function jobLine(info: { description?: string } & UsageInfo, elapsedMs: number): string {
172
+ return [info.description?.trim(), usageStats(info, elapsedMs)].filter(Boolean).join(" · ");
175
173
  }
176
174
 
177
175
  /** Omit detail rows in bulk so Pi's ten-line widget cap cannot split jobs. */
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, Theme } from "@earendil-works/pi-coding-agent";
7
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
8
  import {
9
9
  CONFIG_DIR_NAME,
10
10
  getAgentDir,
@@ -25,15 +25,17 @@ import { Type } from "typebox";
25
25
  import {
26
26
  COLLAPSED_OUTPUT_LINES,
27
27
  type DelegateReport,
28
+ formatTools,
29
+ jobIdentity,
28
30
  jobLine,
29
31
  type JobStatus,
30
32
  launchDetails,
31
33
  outputPreview,
32
- progressStats,
33
34
  reportText,
34
- statusIcon,
35
35
  SPINNER_INTERVAL_MS,
36
36
  STATUS_COLORS,
37
+ statusText,
38
+ usageStats,
37
39
  widgetJobs,
38
40
  } from "./format.ts";
39
41
  import { type ChildActivity, runChild } from "./child.ts";
@@ -48,7 +50,6 @@ type AgentFile = {
48
50
  };
49
51
 
50
52
  type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "description" | "task" | "model" | "tools"> & {
51
- /** True when the child keeps running after the tool returns and reports back as a follow-up message. */
52
53
  background: boolean;
53
54
  };
54
55
 
@@ -66,21 +67,21 @@ type InspectJob = {
66
67
  description: string;
67
68
  task: string;
68
69
  model: string;
70
+ tools: string[];
71
+ toolCalls: number;
72
+ contextTokens?: number;
73
+ contextWindow?: number;
74
+ startedAt: number;
75
+ endedAt?: number;
69
76
  status: JobStatus;
70
77
  activity: ChildActivity[];
71
78
  };
72
79
 
73
80
  type DelegateJob = InspectJob & {
74
- tools: string[];
75
- toolCalls: number;
76
81
  lastTool?: string;
77
82
  lastDetail?: string;
78
83
  lastResult?: string;
79
- contextTokens?: number;
80
- contextWindow?: number;
81
- startedAt: number;
82
84
  controller: AbortController;
83
- /** Set once the child is running; rejects when the child exits or rejects the command. */
84
85
  steer?: (message: string) => Promise<void>;
85
86
  };
86
87
 
@@ -91,16 +92,11 @@ type DelegateConfig = {
91
92
 
92
93
  const DEFAULT_AGENT_DIR = "~/.agents/agents";
93
94
  const BUNDLED_AGENT_DIR = fileURLToPath(new URL("./agents", import.meta.url));
94
- /** Exclude our own tools from children to prevent recursive delegation. */
95
95
  const DELEGATION_TOOLS = new Set(["delegate", "delegate_list", "delegate_steer", "delegate_cancel"]);
96
96
  const MODEL_TIERS = new Set(["cheap", "balanced", "strong"]);
97
97
  const WIDGET_KEY = "delegate";
98
98
  const RESULT_MESSAGE = "delegate-result";
99
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
-
104
100
  function expandPath(value: string, cwd: string): string {
105
101
  return resolve(cwd, value.replace(/^~(?=\/|$)/, homedir()));
106
102
  }
@@ -183,7 +179,6 @@ function resolveModel(
183
179
  function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {
184
180
  const separator = model?.indexOf("/") ?? -1;
185
181
  if (!model || separator < 0) return undefined;
186
- // Model ids may contain "/" themselves, so only the first one separates provider from id.
187
182
  return ctx.modelRegistry.find(model.slice(0, separator), model.slice(separator + 1))?.contextWindow;
188
183
  }
189
184
 
@@ -191,7 +186,6 @@ export default function (pi: ExtensionAPI) {
191
186
  const running = new Map<string, DelegateJob>();
192
187
  const recent: InspectJob[] = [];
193
188
  let viewing: (() => void) | undefined;
194
- let finished = 0;
195
189
  let ticker: ReturnType<typeof setInterval> | undefined;
196
190
 
197
191
  const addActivity = (job: DelegateJob, activity: ChildActivity) => {
@@ -212,12 +206,13 @@ export default function (pi: ExtensionAPI) {
212
206
  const remember = (job: DelegateJob, status: JobStatus, detail?: string) => {
213
207
  job.status = status;
214
208
  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 });
209
+ const { controller, steer, lastTool, lastDetail, lastResult, ...snapshot } = job;
210
+ recent.unshift({ ...snapshot, endedAt: Date.now() });
217
211
  };
218
212
 
219
213
  const refreshWidget = (ctx: ExtensionContext) => {
220
214
  if (!ctx.hasUI) return;
215
+ viewing?.();
221
216
  if (running.size === 0) {
222
217
  ctx.ui.setWidget(WIDGET_KEY, undefined);
223
218
  return;
@@ -226,13 +221,11 @@ export default function (pi: ExtensionAPI) {
226
221
  const now = Date.now();
227
222
  const { shown, hidden, detail } = widgetJobs([...running.values()]);
228
223
  const lines: string[] = [];
229
- if (running.size > 1 || finished > 0) {
230
- const counts = `${running.size} running${finished ? ` · ${finished} done` : ""}`;
231
- lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
232
- }
224
+ const counts = `${running.size} running · ${running.size + recent.length} total`;
225
+ lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
233
226
  for (const job of shown) {
234
227
  lines.push(
235
- `${statusText(theme, "running", now)} ${theme.fg("toolTitle", theme.bold(job.agent))} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`,
228
+ `${statusText(theme, "running", now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`,
236
229
  );
237
230
  if (!detail) continue;
238
231
  if (job.lastTool)
@@ -255,7 +248,6 @@ export default function (pi: ExtensionAPI) {
255
248
  if (job.controller.signal.aborted) return;
256
249
  running.delete(job.id);
257
250
  remember(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined);
258
- finished += 1;
259
251
  if (running.size === 0) stopTicker();
260
252
  refreshWidget(ctx);
261
253
  const report: DelegateReport = {
@@ -284,7 +276,6 @@ export default function (pi: ExtensionAPI) {
284
276
  running.clear();
285
277
  recent.length = 0;
286
278
  viewing = undefined;
287
- finished = 0;
288
279
  });
289
280
 
290
281
  pi.on("before_agent_start", (event, ctx) => {
@@ -304,7 +295,7 @@ export default function (pi: ExtensionAPI) {
304
295
  const container = new Container();
305
296
  container.addChild(
306
297
  new Text(
307
- `${icon} ${theme.fg("toolTitle", theme.bold(report.agent))} ${theme.fg("muted", report.description)} ${theme.fg("dim", report.id)} ${theme.fg("muted", progressStats(report, report.elapsedMs))}`,
298
+ `${icon} ${jobIdentity(theme, report)} ${theme.fg("muted", report.description)} ${theme.fg("muted", usageStats(report, report.elapsedMs))}`,
308
299
  0,
309
300
  0,
310
301
  ),
@@ -349,13 +340,17 @@ export default function (pi: ExtensionAPI) {
349
340
  // The list pane already draws a border, and the muted model line sets the task apart.
350
341
  const taskLines = (job: InspectJob, width: number) =>
351
342
  wrapTextWithAnsi(job.task.trim(), Math.max(1, width)).map((line) => theme.fg("text", line));
343
+ const toolsLines = (job: InspectJob, width: number) =>
344
+ wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
345
+ theme.fg("dim", line),
346
+ );
352
347
  const historyHeight = (job: InspectJob, width: number) =>
353
- Math.max(0, bodyHeight() - 6 - taskLines(job, width).length);
348
+ Math.max(0, bodyHeight() - 6 - taskLines(job, width).length - toolsLines(job, width).length);
354
349
  // ScrollView needs fullscreen layout; window the history in regular TUI too.
355
350
  const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
356
351
  const row = (text: string) =>
357
352
  truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
358
- const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 2));
353
+ const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
359
354
  const start = Math.max(
360
355
  0,
361
356
  Math.min(selectedIndex - Math.floor(visible / 2), items.length - visible),
@@ -363,13 +358,16 @@ export default function (pi: ExtensionAPI) {
363
358
  const lines = items
364
359
  .slice(start, start + visible)
365
360
  .flatMap((item, index) => [
361
+ row(
362
+ `${theme.fg(start + index === selectedIndex && focus === "list" ? "accent" : "text", start + index === selectedIndex ? "›" : " ")} ${statusText(theme, item.status)} ${jobIdentity(theme, item)}`,
363
+ ),
364
+ row(theme.fg("muted", ` ${item.description}`)),
366
365
  row(
367
366
  theme.fg(
368
- start + index === selectedIndex && focus === "list" ? "accent" : "text",
369
- `${start + index === selectedIndex ? "›" : " "} ${statusText(theme, item.status)} ${item.agent} ${item.id}`,
367
+ "dim",
368
+ ` ${usageStats(item, (item.endedAt ?? Date.now()) - item.startedAt)}`,
370
369
  ),
371
370
  ),
372
- row(theme.fg("muted", ` ${item.description}`)),
373
371
  ]);
374
372
  return [
375
373
  ...lines,
@@ -402,7 +400,8 @@ export default function (pi: ExtensionAPI) {
402
400
  const renderHistory = (width: number, job: InspectJob): string[] => {
403
401
  historyWidth = width;
404
402
  const task = taskLines(job, width);
405
- const height = Math.max(0, bodyHeight() - 6 - task.length);
403
+ const tools = toolsLines(job, width);
404
+ const height = historyHeight(job, width);
406
405
  const history = job.activity.flatMap((entry) => renderEntry(entry, width));
407
406
  const maxTop = Math.max(0, history.length - height);
408
407
  const start = Math.min(top ?? maxTop, maxTop);
@@ -413,14 +412,11 @@ export default function (pi: ExtensionAPI) {
413
412
  ? [theme.fg("muted", "Waiting for activity…")]
414
413
  : [];
415
414
  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),
415
+ truncateToWidth(`${statusText(theme, job.status)} ${jobIdentity(theme, job)}`, width),
422
416
  truncateToWidth(theme.fg("dim", job.model), width),
423
- "",
417
+ ...tools,
418
+ theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
419
+ truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
424
420
  ...task,
425
421
  theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
426
422
  ...shown,
@@ -667,7 +663,7 @@ export default function (pi: ExtensionAPI) {
667
663
  const container = new Container();
668
664
  container.addChild(
669
665
  new Text(
670
- `${icon} ${theme.fg("toolTitle", theme.bold(details.agent))} ${theme.fg("muted", details.description)} ${theme.fg("dim", details.id)} ${theme.fg("dim", status)}`,
666
+ `${icon} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("dim", status)}`,
671
667
  0,
672
668
  0,
673
669
  ),
@@ -743,7 +739,7 @@ export default function (pi: ExtensionAPI) {
743
739
  const container = new Container();
744
740
  container.addChild(
745
741
  new Text(
746
- `${icon} ${theme.fg("toolTitle", theme.bold(details.agent))} ${theme.fg("muted", details.description)} ${theme.fg("dim", details.id)} ${theme.fg("muted", progressStats(details, details.elapsedMs))}`,
742
+ `${icon} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
747
743
  0,
748
744
  0,
749
745
  ),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
4
4
  "description": "Run focused Pi subagents as background tasks",
5
5
  "type": "module",
6
6
  "license": "MIT",