@deathbeam/pi-delegate 0.0.28 → 0.0.30

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/agents.ts CHANGED
@@ -91,6 +91,20 @@ export function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[
91
91
  return [...agents.values()];
92
92
  }
93
93
 
94
+ export function agentsFor(cwd: string): AgentFile[] {
95
+ return discoverAgents(cwd, configFor(cwd).agentDirs);
96
+ }
97
+
98
+ export function agentByName(cwd: string, name: string): AgentFile {
99
+ const agents = agentsFor(cwd);
100
+ const agent = agents.find((candidate) => candidate.name === name);
101
+ if (!agent) {
102
+ const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
103
+ throw new Error(`Unknown agent "${name}". Available agents: ${names}.`);
104
+ }
105
+ return agent;
106
+ }
107
+
94
108
  // Same `:<thinking>` suffix pi's --model takes; only known levels split, so ids like `llama3:8b` stay whole.
95
109
  function splitThinking(value: string): { model: string; thinking?: string } {
96
110
  const match = /^(.*):(off|minimal|low|medium|high|xhigh|max)$/.exec(value);
package/format.ts CHANGED
@@ -1,6 +1,15 @@
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";
3
- import type { JobStatus } from "./store.ts";
1
+ import { getMarkdownTheme, keyHint, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ type Component,
4
+ Container,
5
+ Markdown,
6
+ Spacer,
7
+ Text,
8
+ TruncatedText,
9
+ truncateToWidth,
10
+ } from "@earendil-works/pi-tui";
11
+ import type { IsolationState } from "./isolation.ts";
12
+ import type { DelegateJob, JobStatus } from "./store.ts";
4
13
 
5
14
  type UsageInfo = {
6
15
  contextTokens?: number;
@@ -18,6 +27,9 @@ export type DelegateReport = {
18
27
  elapsedMs: number;
19
28
  output?: string;
20
29
  error?: string;
30
+ status: JobStatus;
31
+ isolation?: IsolationState;
32
+ cloneClosed?: boolean;
21
33
  };
22
34
 
23
35
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
@@ -56,8 +68,32 @@ export function statusText(theme: Theme, status: JobStatus, now = Date.now()): s
56
68
  return theme.fg(STATUS_COLORS[status], statusIcon(status, now));
57
69
  }
58
70
 
59
- export function jobIdentity(theme: Theme, job: { id: string; agent: string }): string {
60
- return `${theme.fg("muted", job.id)} ${theme.fg("toolTitle", theme.bold(job.agent))}`;
71
+ /** The isolation state to show for a job: pending means its clone still holds unapplied work. */
72
+ export type IsolationMark = "isolated" | "pending";
73
+
74
+ type IsolationStateFields = {
75
+ isolation?: unknown;
76
+ cloneClosed?: boolean;
77
+ status?: string;
78
+ };
79
+
80
+ /** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
81
+ export function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
82
+ if (!job.isolation) return undefined;
83
+ return job.cloneClosed || job.status === "running" ? "isolated" : "pending";
84
+ }
85
+
86
+ /** `⎇`, warning-colored while the clone's work is still unapplied. */
87
+ export function jobIdentity(theme: Theme, job: { id: string; agent: string } & IsolationStateFields): string {
88
+ // Details snapshot the job's state, so a transcript line keeps the mark it had when captured.
89
+ const mark = isolationMarkOf(job);
90
+ const branch = mark ? ` ${theme.fg(mark === "pending" ? "warning" : "muted", "⎇")}` : "";
91
+ return `${theme.fg("muted", job.id)} ${theme.fg("toolTitle", theme.bold(job.agent))}${branch}`;
92
+ }
93
+
94
+ export function isolationWords(job: IsolationStateFields): string {
95
+ const mark = isolationMarkOf(job);
96
+ return mark === "pending" ? "isolated, pending delegate_apply" : mark === "isolated" ? "isolated" : "";
61
97
  }
62
98
 
63
99
  export function formatTools(tools: string[]): string {
@@ -88,9 +124,18 @@ export function usageStats(usage: UsageInfo, elapsedMs: number): string {
88
124
  : "";
89
125
  return [tokens, formatDuration(elapsedMs)].filter(Boolean).join(" · ");
90
126
  }
127
+
128
+ export function elapsedMs(job: { startedAt: number; endedAt?: number }, now = Date.now()): number {
129
+ return (job.endedAt ?? now) - job.startedAt;
130
+ }
131
+
91
132
  /** Summed wall-clock across jobs; running jobs tick from `now`. Parallel jobs each count their full span. */
92
133
  export function totalElapsedMs(jobs: { startedAt: number; endedAt?: number }[], now = Date.now()): number {
93
- return jobs.reduce((sum, job) => sum + (job.endedAt ?? now) - job.startedAt, 0);
134
+ return jobs.reduce((sum, job) => sum + elapsedMs(job, now), 0);
135
+ }
136
+
137
+ export function tally(running: number, all: { startedAt: number; endedAt?: number }[], now = Date.now()): string {
138
+ return `${running} running · ${all.length} total · ${formatDuration(totalElapsedMs(all, now))}`;
94
139
  }
95
140
 
96
141
  export function toolCallDetail(toolName: string, args: unknown): string {
@@ -121,13 +166,17 @@ export function launchDetails(info: { model?: string; tools: string[] }): string
121
166
  return [`${EXPANDED_PAD}Model: ${info.model ?? "default"}`, `${EXPANDED_PAD}Tools: ${formatTools(info.tools)}`];
122
167
  }
123
168
 
169
+ /** Caps a preview at `maxLines`; callers report the hidden count their own way. */
170
+ export function capLines<T>(lines: T[], maxLines: number): { shown: T[]; hidden: number } {
171
+ if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
172
+ return { shown: lines.slice(0, maxLines), hidden: lines.length - maxLines };
173
+ }
174
+
124
175
  /** Close dangling Markdown fences so collapsed previews render correctly. */
125
176
  export function outputPreview(text: string, maxLines = COLLAPSED_OUTPUT_LINES): { shown: string[]; hidden: number } {
126
- const lines = text.trim().split("\n");
127
- if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
128
- const shown = lines.slice(0, maxLines);
129
- if (shown.filter((line) => line.trimStart().startsWith("```")).length % 2 === 1) shown.push("```");
130
- return { shown, hidden: lines.length - maxLines };
177
+ const { shown, hidden } = capLines(text.trim().split("\n"), maxLines);
178
+ if (hidden && shown.filter((line) => line.trimStart().startsWith("```")).length % 2 === 1) shown.push("```");
179
+ return { shown, hidden };
131
180
  }
132
181
 
133
182
  /** Cap child output without splitting UTF-8 characters. */
@@ -228,7 +277,12 @@ export function reportText(report: DelegateReport): string {
228
277
  const head = `Delegate "${report.agent}" (job ${report.id}, ${usageStats(report, report.elapsedMs)})`;
229
278
  if (report.error) return `${head} failed: ${report.error}\n${reviveHint(report.id)}`;
230
279
  const output = (report.output ?? "").trim();
231
- return `${head} finished.${output ? `\n\n${output}` : ""}`;
280
+ // The apply hint is for the model only: the transcript renders `output`, so users never see it.
281
+ const hint =
282
+ report.isolation && !report.cloneClosed
283
+ ? `\n\nCall delegate_apply with job ${report.id} to land its changes.`
284
+ : "";
285
+ return `${head} finished.${output ? `\n\n${output}` : ""}${hint}`;
232
286
  }
233
287
 
234
288
  export function jobLine(info: { description?: string } & UsageInfo, elapsedMs: number): string {
@@ -241,3 +295,94 @@ export function widgetJobs<T>(jobs: T[]): { shown: T[]; hidden: number; detail:
241
295
  const shown = detail ? jobs : jobs.slice(-WIDGET_MAX_JOBS);
242
296
  return { shown, hidden: jobs.length - shown.length, detail };
243
297
  }
298
+
299
+ export type DelegateDetails = Pick<
300
+ DelegateJob,
301
+ "id" | "agent" | "description" | "task" | "model" | "tools" | "status" | "isolation" | "cloneClosed"
302
+ > & { background: boolean };
303
+
304
+ export function resultFallback(body: string, theme: Theme, isError: boolean): Text {
305
+ const mark = statusText(theme, isError ? "failed" : "done");
306
+ return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
307
+ }
308
+
309
+ export function moreLines(theme: Theme, hidden: number): string {
310
+ return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
311
+ }
312
+
313
+ export function appendOutput(container: Container, body: string, expanded: boolean, theme: Theme): void {
314
+ const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
315
+ container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
316
+ if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
317
+ }
318
+
319
+ export function toolLayout(
320
+ toolName: string,
321
+ identity: string,
322
+ payload: string,
323
+ theme: Theme,
324
+ expanded: boolean,
325
+ ): Component {
326
+ const container = new Container();
327
+ if (toolName)
328
+ container.addChild(
329
+ new TruncatedText(`${theme.fg("toolTitle", theme.bold(toolName))}${identity ? ` ${identity}` : ""}`),
330
+ );
331
+ if (!payload.trim()) return container;
332
+ const body = new Text(
333
+ payload
334
+ .split("\n")
335
+ .map((line) => theme.fg("toolOutput", line))
336
+ .join("\n"),
337
+ 0,
338
+ 0,
339
+ );
340
+ if (toolName) container.addChild(new Spacer(1));
341
+ container.addChild({
342
+ render: (width) => {
343
+ // Wrapping turns one long line into many, so the cap counts rendered rows, not source lines.
344
+ const { shown, hidden } = capLines(body.render(width), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
345
+ return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden), width)] : shown;
346
+ },
347
+ invalidate: () => body.invalidate(),
348
+ });
349
+ return container;
350
+ }
351
+
352
+ export function resultHeader(
353
+ theme: Theme,
354
+ job: { id: string; agent: string },
355
+ tail: string,
356
+ outcome: JobStatus = "done",
357
+ ): string {
358
+ return `${statusText(theme, outcome)} ${jobIdentity(theme, job)} ${theme.fg("muted", tail)}`;
359
+ }
360
+
361
+ export function jobSummary(job: {
362
+ description: string;
363
+ contextTokens?: number;
364
+ contextWindow?: number;
365
+ elapsedMs: number;
366
+ }): string {
367
+ return `${job.description} ${usageStats(job, job.elapsedMs)}`;
368
+ }
369
+
370
+ export function launchResult(
371
+ details: DelegateDetails,
372
+ body: string,
373
+ status: string,
374
+ expanded: boolean,
375
+ theme: Theme,
376
+ ): Component {
377
+ const container = new Container();
378
+ // The mark is the call's outcome (launch succeeded); job progress stays in the widget and report.
379
+ container.addChild(new Text(`\n${resultHeader(theme, details, status)}`, 0, 0));
380
+ // The call body already carries the task; only the launch metadata is new here.
381
+ if (expanded)
382
+ container.addChild(
383
+ new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
384
+ );
385
+ // Background results arrive as their own message; headless runs still show the output here.
386
+ if (!details.background && body) appendOutput(container, body, expanded, theme);
387
+ return container;
388
+ }
package/index.ts CHANGED
@@ -3,31 +3,30 @@ import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { Type } from "typebox";
5
5
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
6
- import { getAgentDir, getMarkdownTheme, keyHint, renderDiff } from "@earendil-works/pi-coding-agent";
7
- import {
8
- type Component,
9
- Container,
10
- Markdown,
11
- Spacer,
12
- Text,
13
- TruncatedText,
14
- truncateToWidth,
15
- } from "@earendil-works/pi-tui";
6
+ import { getAgentDir, renderDiff } from "@earendil-works/pi-coding-agent";
7
+ import { Container, Spacer, Text } from "@earendil-works/pi-tui";
16
8
  import {
9
+ appendOutput,
10
+ capLines,
17
11
  COLLAPSED_OUTPUT_LINES,
12
+ type DelegateDetails,
18
13
  type DelegateReport,
14
+ elapsedMs,
15
+ isolationWords,
19
16
  jobIdentity,
20
17
  jobLine,
21
- launchDetails,
22
- outputPreview,
18
+ jobSummary,
19
+ launchResult,
20
+ moreLines,
23
21
  piDiff,
24
22
  reportText,
23
+ resultFallback,
24
+ resultHeader,
25
25
  reviveHint,
26
26
  SPINNER_INTERVAL_MS,
27
- formatDuration,
28
27
  statusText,
29
- totalElapsedMs,
30
- usageStats,
28
+ tally,
29
+ toolLayout,
31
30
  widgetJobs,
32
31
  } from "./format.ts";
33
32
  import { priorActivity, runChild } from "./child.ts";
@@ -41,11 +40,7 @@ import {
41
40
  type IsolationState,
42
41
  } from "./isolation.ts";
43
42
  import { registerInspector } from "./inspector.ts";
44
- import { configFor, contextWindowFor, discoverAgents, resolveModel, type AgentFile } from "./agents.ts";
45
-
46
- type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "description" | "task" | "model" | "tools"> & {
47
- background: boolean;
48
- };
43
+ import { agentByName, agentsFor, configFor, contextWindowFor, resolveModel, type AgentFile } from "./agents.ts";
49
44
 
50
45
  type SteerDetails = Pick<
51
46
  DelegateJob,
@@ -82,23 +77,6 @@ function resultText(result: { content: readonly { type: string; text?: string }[
82
77
  return result.content.flatMap((part) => (part.type === "text" ? [part.text ?? ""] : [])).join("\n");
83
78
  }
84
79
 
85
- function resultFallback(body: string, theme: Theme, isError: boolean): Text {
86
- const mark = statusText(theme, isError ? "failed" : "done");
87
- return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
88
- }
89
-
90
- /** Shared foreground output preview: delegate results, steer revives, and follow-up reports. */
91
- function appendOutput(container: Container, body: string, expanded: boolean, theme: Theme): void {
92
- const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
93
- container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
94
- if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
95
- }
96
-
97
- /** Shared collapsed-output note so all three preview sites phrase it identically. */
98
- function moreLines(theme: Theme, hidden: number): string {
99
- return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
100
- }
101
-
102
80
  /** One resolution path for launches and swaps; the error names the requested model. */
103
81
  function mustResolveModel(request: string | undefined, ctx: ExtensionContext, fallback?: string) {
104
82
  const { model, thinking } = resolveModel(request ?? fallback, configFor(ctx.cwd).models ?? {}, ctx);
@@ -111,61 +89,6 @@ function withIsolation(output: string, isolation: IsolationState | undefined): s
111
89
  return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
112
90
  }
113
91
 
114
- /** Shared tool layout: an optional identity header, then a width-aware payload preview. */
115
- function toolLayout(toolName: string, identity: string, payload: string, theme: Theme, expanded: boolean): Component {
116
- const container = new Container();
117
- if (toolName)
118
- container.addChild(
119
- new TruncatedText(`${theme.fg("toolTitle", theme.bold(toolName))}${identity ? ` ${identity}` : ""}`),
120
- );
121
- if (!payload.trim()) return container;
122
- const body = new Text(
123
- payload
124
- .split("\n")
125
- .map((line) => theme.fg("toolOutput", line))
126
- .join("\n"),
127
- 0,
128
- 0,
129
- );
130
- if (toolName) container.addChild(new Spacer(1));
131
- container.addChild({
132
- render: (width) => {
133
- // Wrapping turns one long line into many, so the cap counts rendered rows, not source lines.
134
- const lines = body.render(width);
135
- if (expanded || lines.length <= COLLAPSED_OUTPUT_LINES) return lines;
136
- return [
137
- ...lines.slice(0, COLLAPSED_OUTPUT_LINES),
138
- truncateToWidth(moreLines(theme, lines.length - COLLAPSED_OUTPUT_LINES), width),
139
- ];
140
- },
141
- invalidate: () => body.invalidate(),
142
- });
143
- return container;
144
- }
145
-
146
- /** Shared launch-result card: delegate launches and steer revives render identically. */
147
- function launchResult(
148
- details: DelegateDetails,
149
- body: string,
150
- status: string,
151
- expanded: boolean,
152
- theme: Theme,
153
- ): Component {
154
- const container = new Container();
155
- // The mark is the call's outcome (launch succeeded); job progress stays in the widget and report.
156
- container.addChild(
157
- new Text(`\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`, 0, 0),
158
- );
159
- // The call body already carries the task; only the launch metadata is new here.
160
- if (expanded)
161
- container.addChild(
162
- new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
163
- );
164
- // Background results arrive as their own message; headless runs still show the output here.
165
- if (!details.background && body) appendOutput(container, body, expanded, theme);
166
- return container;
167
- }
168
-
169
92
  export default function (pi: ExtensionAPI) {
170
93
  const store = createJobStore(pi.appendEntry);
171
94
  let ticker: ReturnType<typeof setInterval> | undefined;
@@ -173,17 +96,6 @@ export default function (pi: ExtensionAPI) {
173
96
  let directCalls = 0;
174
97
  let nextReminder = FIRST_REMINDER_AT;
175
98
 
176
- const jobSnapshot = (job: InspectJob) => ({
177
- id: job.id,
178
- agent: job.agent,
179
- description: job.description,
180
- contextTokens: job.contextTokens,
181
- contextWindow: job.contextWindow,
182
- startedAt: job.startedAt,
183
- status: job.status,
184
- endedAt: job.endedAt,
185
- });
186
-
187
99
  const jobTarget = (rawId: unknown, theme: Theme): string => {
188
100
  const id = jobId(rawId);
189
101
  const job = store.find(id);
@@ -203,11 +115,11 @@ export default function (pi: ExtensionAPI) {
203
115
  const { shown, hidden, detail } = widgetJobs(jobs);
204
116
  const lines: string[] = [];
205
117
  const all = store.all();
206
- const counts = `${jobs.length} running · ${all.length} total · ${formatDuration(totalElapsedMs(all, now))}`;
118
+ const counts = tally(jobs.length, all, now);
207
119
  lines.push(`${statusText(theme, "running", now)} ${theme.fg("muted", counts)}`);
208
120
  for (const job of shown) {
209
121
  lines.push(
210
- `${statusText(theme, "running", now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, now - job.startedAt))}`,
122
+ `${statusText(theme, "running", now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, elapsedMs(job, now)))}`,
211
123
  );
212
124
  if (!detail) continue;
213
125
  if (job.lastTool)
@@ -241,9 +153,12 @@ export default function (pi: ExtensionAPI) {
241
153
  toolCalls: job.toolCalls,
242
154
  contextTokens: job.contextTokens,
243
155
  contextWindow: job.contextWindow,
244
- elapsedMs: Date.now() - job.startedAt,
156
+ elapsedMs: elapsedMs(job),
245
157
  output: withIsolation(output ?? "", job.isolation),
246
158
  error,
159
+ status: job.status,
160
+ isolation: job.isolation,
161
+ cloneClosed: job.cloneClosed,
247
162
  };
248
163
  // Idle: this starts a new turn. Streaming: steer the report in at the next turn boundary;
249
164
  // a follow-up waits for a run end that a parent stuck polling may never reach.
@@ -295,6 +210,9 @@ export default function (pi: ExtensionAPI) {
295
210
  model: displayModel,
296
211
  tools,
297
212
  background: ctx.hasUI,
213
+ status: job.status,
214
+ isolation: job.isolation,
215
+ cloneClosed: job.cloneClosed,
298
216
  };
299
217
  const args = [
300
218
  "--session-id",
@@ -395,7 +313,12 @@ export default function (pi: ExtensionAPI) {
395
313
  pi.sendMessage(
396
314
  {
397
315
  customType: INTERRUPTED_MESSAGE,
398
- content: `<system-reminder>These delegate jobs were interrupted by a restart or crash; their transcripts survive. Continue each with delegate_steer (job id plus your guidance):\n${interrupted.map((job) => `- ${job.id} ${job.agent}: ${job.description}`).join("\n")}</system-reminder>`,
316
+ content: `<system-reminder>These delegate jobs were interrupted by a restart or crash; their transcripts survive. Continue each with delegate_steer (job id plus your guidance):\n${interrupted
317
+ .map((job) => {
318
+ const isolation = isolationWords(job);
319
+ return `- ${job.id} ${job.agent}: ${job.description}${isolation ? ` (${isolation})` : ""}`;
320
+ })
321
+ .join("\n")}</system-reminder>`,
399
322
  display: false,
400
323
  },
401
324
  { deliverAs: "steer" },
@@ -435,24 +358,22 @@ export default function (pi: ExtensionAPI) {
435
358
  pi.registerMessageRenderer(RESULT_MESSAGE, (message, { expanded }, theme) => {
436
359
  const report = message.details as DelegateReport | undefined;
437
360
  if (!report?.agent) return undefined;
438
- const icon = statusText(theme, report.error ? "failed" : "done");
439
361
  const container = new Container();
440
362
  container.addChild(
441
- new Text(
442
- `${icon} ${jobIdentity(theme, report)} ${theme.fg("muted", report.description)} ${theme.fg("muted", usageStats(report, report.elapsedMs))}`,
443
- 0,
444
- 0,
445
- ),
363
+ new Text(resultHeader(theme, report, jobSummary(report), report.error ? "failed" : "done"), 0, 0),
446
364
  );
447
365
  if (report.error) container.addChild(new Text(theme.fg("error", report.error), 0, 0));
448
- else if (report.output) appendOutput(container, report.output, expanded, theme);
366
+ else if (report.output) {
367
+ container.addChild(new Spacer(1));
368
+ appendOutput(container, report.output, expanded, theme);
369
+ }
449
370
  return container;
450
371
  });
451
372
 
452
373
  registerInspector(pi, store);
453
374
 
454
375
  const cwd = process.cwd();
455
- const agentList = discoverAgents(cwd, configFor(cwd).agentDirs).map((agent) => {
376
+ const agentList = agentsFor(cwd).map((agent) => {
456
377
  const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
457
378
  return `- ${agent.name}${qualifiers ? ` (${qualifiers})` : ""}: ${agent.description}`;
458
379
  });
@@ -502,12 +423,7 @@ export default function (pi: ExtensionAPI) {
502
423
  const params = dropNulls(rawParams);
503
424
  const { agent: agentName, description, task, model, isolated } = params;
504
425
  if (!agentName || !description || !task) throw new Error("agent, description and task are required.");
505
- const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
506
- const agent = agents.find((candidate) => candidate.name === agentName);
507
- if (!agent) {
508
- const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
509
- throw new Error(`Unknown agent "${agentName}". Available agents: ${names}.`);
510
- }
426
+ const agent = agentByName(ctx.cwd, agentName);
511
427
  const effective = isolated ?? agent.isolated;
512
428
  return runDelegate(ctx, agent, undefined, { description, model, isolated: effective }, task, signal);
513
429
  },
@@ -567,7 +483,7 @@ export default function (pi: ExtensionAPI) {
567
483
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
568
484
  const params = dropNulls(rawParams);
569
485
  const id = jobId(params.id);
570
- const running = store.live().find((candidate) => candidate.id === id);
486
+ const running = store.liveJob(id);
571
487
  if (running) {
572
488
  // A live job without steer would fall into the revive path and double-spawn its pinned session.
573
489
  if (!running.steer) throw new Error(`No steerable delegate job "${id}".`);
@@ -576,7 +492,7 @@ export default function (pi: ExtensionAPI) {
576
492
  await running.steer(params.message);
577
493
  } catch (error) {
578
494
  // The swap or steer await can outlast the job (a model ack waits up to 30s); raw child errors are cryptic.
579
- if (!store.live().some((candidate) => candidate.id === id))
495
+ if (!store.liveJob(id))
580
496
  throw new Error(
581
497
  `Delegate job "${id}" just finished; call delegate_steer again to continue it.`,
582
498
  );
@@ -590,7 +506,7 @@ export default function (pi: ExtensionAPI) {
590
506
  toolCalls: running.toolCalls,
591
507
  contextTokens: running.contextTokens,
592
508
  contextWindow: running.contextWindow,
593
- elapsedMs: Date.now() - running.startedAt,
509
+ elapsedMs: elapsedMs(running),
594
510
  };
595
511
  return {
596
512
  content: [
@@ -602,19 +518,13 @@ export default function (pi: ExtensionAPI) {
602
518
  details,
603
519
  };
604
520
  }
605
- const prior = store.find(id);
606
- if (!id || !prior) throw new Error(`Unknown delegate job "${id}".`);
521
+ const prior = store.findOrThrow(id);
607
522
  // An applied or discarded clone cannot be continued; a revive would run in the main tree.
608
523
  if (prior.cloneClosed)
609
524
  throw new Error(
610
525
  `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.`,
611
526
  );
612
- const agents = discoverAgents(ctx.cwd, configFor(ctx.cwd).agentDirs);
613
- const agent = agents.find((candidate) => candidate.name === prior.agent);
614
- if (!agent) {
615
- const names = agents.map((candidate) => candidate.name).join(", ") || "(none)";
616
- throw new Error(`Unknown agent "${prior.agent}". Available agents: ${names}.`);
617
- }
527
+ const agent = agentByName(ctx.cwd, prior.agent);
618
528
  return runDelegate(
619
529
  ctx,
620
530
  agent,
@@ -644,12 +554,7 @@ export default function (pi: ExtensionAPI) {
644
554
  const details = result.details as SteerDetails | DelegateDetails | undefined;
645
555
  const body = resultText(result);
646
556
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
647
- if ("message" in details)
648
- return new Text(
649
- `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", details.description)} ${theme.fg("muted", usageStats(details, details.elapsedMs))}`,
650
- 0,
651
- 0,
652
- );
557
+ if ("message" in details) return new Text(`\n${resultHeader(theme, details, jobSummary(details))}`, 0, 0);
653
558
  return launchResult(
654
559
  details,
655
560
  body,
@@ -670,7 +575,7 @@ export default function (pi: ExtensionAPI) {
670
575
  }),
671
576
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
672
577
  const id = jobId(params.id);
673
- const job = store.live().find((candidate) => candidate.id === id);
578
+ const job = store.liveJob(id);
674
579
  if (!job) throw new Error(`No running delegate job "${id}".`);
675
580
  store.finish(job, "cancelled");
676
581
  job.controller.abort();
@@ -692,12 +597,8 @@ export default function (pi: ExtensionAPI) {
692
597
  const details = result.details as { id: string; agent: string } | undefined;
693
598
  const body = resultText(result);
694
599
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
695
- return new Text(
696
- // The mark is the call's outcome (cancellation requested), not the job's cancelled status.
697
- `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", "cancellation requested")}`,
698
- 0,
699
- 0,
700
- );
600
+ // The mark is the call's outcome (cancellation requested), not the job's cancelled status.
601
+ return new Text(`\n${resultHeader(theme, details, "cancellation requested")}`, 0, 0);
701
602
  },
702
603
  });
703
604
 
@@ -716,17 +617,21 @@ export default function (pi: ExtensionAPI) {
716
617
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
717
618
  const params = dropNulls(rawParams);
718
619
  const id = jobId(params.id);
719
- const job = store.find(id);
720
- if (!id || !job) throw new Error(`Unknown delegate job "${id}".`);
620
+ const job = store.findOrThrow(id);
721
621
  if (job.status === "running")
722
622
  throw new Error(`Delegate job "${id}" is still running; steer it or cancel it first.`);
723
623
  if (!job.isolation)
724
624
  throw new Error(`Delegate job "${id}" is not isolated; its changes are already in the main tree.`);
725
- if (params.discard === true) {
726
- removeClone(job.isolation);
625
+
626
+ const isolation = job.isolation;
627
+ const closeClone = () => {
628
+ removeClone(isolation);
727
629
  job.isolation = undefined;
728
630
  job.cloneClosed = true;
729
631
  store.save(job);
632
+ };
633
+ if (params.discard === true) {
634
+ closeClone();
730
635
  return {
731
636
  content: [
732
637
  {
@@ -747,10 +652,7 @@ export default function (pi: ExtensionAPI) {
747
652
  );
748
653
  }
749
654
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
750
- removeClone(job.isolation);
751
- job.isolation = undefined;
752
- job.cloneClosed = true;
753
- store.save(job);
655
+ closeClone();
754
656
  return {
755
657
  content: [
756
658
  {
@@ -781,18 +683,12 @@ export default function (pi: ExtensionAPI) {
781
683
  const body = resultText(result);
782
684
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
783
685
  const status = details.discarded ? "clone discarded" : "changes applied";
784
- const header = `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`;
686
+ const header = `\n${resultHeader(theme, details, status)}`;
785
687
  const diff = details.diff?.trim() ? renderDiff(piDiff(details.diff)) : "";
786
688
  if (!diff) return new Text(header, 0, 0);
787
- const lines = diff.split("\n");
788
689
  // Collapsed shows the head like the other delegate previews; expanded shows the full colored diff.
789
- const shown =
790
- expanded || lines.length <= COLLAPSED_OUTPUT_LINES
791
- ? lines
792
- : [
793
- ...lines.slice(0, COLLAPSED_OUTPUT_LINES),
794
- moreLines(theme, lines.length - COLLAPSED_OUTPUT_LINES),
795
- ];
690
+ const { shown, hidden } = capLines(diff.split("\n"), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
691
+ if (hidden) shown.push(moreLines(theme, hidden));
796
692
  const container = new Container();
797
693
  container.addChild(new Text(header, 0, 0));
798
694
  container.addChild(new Spacer(1));
@@ -818,26 +714,26 @@ export default function (pi: ExtensionAPI) {
818
714
  ? ` · ${lastTool}${lastDetail ? ` ${lastDetail}` : ""}`
819
715
  : "";
820
716
  };
821
- const lines = jobs.map(
822
- (job) =>
823
- `- ${job.id} ${job.agent} · ${job.status} · ${jobLine(job, (job.endedAt ?? now) - job.startedAt)}${lastActivity(job)}`,
824
- );
717
+ const lines = jobs.map((job) => {
718
+ const tag = isolationWords(job);
719
+ return `- ${job.id} ${job.agent} · ${job.status}${tag ? ` · ${tag}` : ""} · ${jobLine(job, elapsedMs(job, now))}${lastActivity(job)}`;
720
+ });
825
721
  return {
826
722
  content: [
827
723
  { type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
828
724
  ],
829
- details: { jobs: jobs.map(jobSnapshot) },
725
+ details: { jobs: jobs.map(store.snapshot) },
830
726
  };
831
727
  },
832
728
  renderResult(result, _options, theme, context) {
833
- const jobs = (result.details as { jobs?: ReturnType<typeof jobSnapshot>[] } | undefined)?.jobs;
729
+ const jobs = (result.details as { jobs?: InspectJob[] } | undefined)?.jobs;
834
730
  if (!jobs?.length || context.isError) return resultFallback(resultText(result), theme, context.isError);
835
731
  const now = Date.now();
836
732
  return new Text(
837
733
  `\n${statusText(theme, "done")} ${theme.fg("muted", `${jobs.length} delegates`)}\n${jobs
838
734
  .map(
839
735
  (job) =>
840
- `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, (job.endedAt ?? now) - job.startedAt))}`,
736
+ `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, elapsedMs(job, now)))}`,
841
737
  )
842
738
  .join("\n")}`,
843
739
  0,
package/inspector.ts CHANGED
@@ -1,15 +1,7 @@
1
1
  import { type ExtensionAPI, getMarkdownTheme, keyHint, rawKeyHint } from "@earendil-works/pi-coding-agent";
2
2
  import { HStack, Markdown, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
3
  import type { ChildActivity } from "./child.ts";
4
- import {
5
- formatDuration,
6
- formatTools,
7
- jobIdentity,
8
- STATUS_COLORS,
9
- statusText,
10
- totalElapsedMs,
11
- usageStats,
12
- } from "./format.ts";
4
+ import { elapsedMs, formatTools, jobIdentity, STATUS_COLORS, statusText, tally, usageStats } from "./format.ts";
13
5
  import type { InspectJob, JobStore } from "./store.ts";
14
6
 
15
7
  /** The /delegate command: a full-screen inspector over the job store. */
@@ -60,12 +52,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
60
52
  `${theme.fg(start + index === selectedIndex && focus === "list" ? "accent" : "text", start + index === selectedIndex ? "›" : " ")} ${statusText(theme, item.status)} ${jobIdentity(theme, item)}`,
61
53
  ),
62
54
  row(theme.fg("muted", ` ${item.description}`)),
63
- row(
64
- theme.fg(
65
- "muted",
66
- ` ${usageStats(item, (item.endedAt ?? Date.now()) - item.startedAt)}`,
67
- ),
68
- ),
55
+ row(theme.fg("muted", ` ${usageStats(item, elapsedMs(item))}`)),
69
56
  ]);
70
57
  return [
71
58
  ...lines,
@@ -117,7 +104,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
117
104
  : [];
118
105
  return [
119
106
  truncateToWidth(
120
- `${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", usageStats(job, (job.endedAt ?? Date.now()) - job.startedAt))}`,
107
+ `${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", usageStats(job, elapsedMs(job)))}`,
121
108
  width,
122
109
  ),
123
110
  truncateToWidth(theme.fg("dim", job.model), width),
@@ -147,10 +134,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
147
134
  const title = truncateToWidth(
148
135
  `${theme.fg(focus === "list" ? "accent" : "muted", focus === "list" ? "[Jobs]" : "Jobs")} ` +
149
136
  `${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
150
- theme.fg(
151
- "dim",
152
- ` · ${store.live().length} running · ${items.length} total · ${formatDuration(totalElapsedMs(items))}`,
153
- ),
137
+ theme.fg("dim", ` · ${tally(store.live().length, items)}`),
154
138
  width,
155
139
  );
156
140
  const footer = truncateToWidth(
package/isolation.ts CHANGED
@@ -5,7 +5,7 @@ import { join, relative, resolve } from "node:path";
5
5
  /** Persisted with the job: where the clone lives and which main-tree snapshot it started from. */
6
6
  export type IsolationState = { clone: string; base: string };
7
7
 
8
- export type ApplyResult =
8
+ type ApplyResult =
9
9
  | { kind: "applied"; stat: string; diff: string }
10
10
  | { kind: "empty" }
11
11
  | { kind: "conflict"; files: string[]; snapshot: string };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.28",
3
+ "version": "0.0.30",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/store.ts CHANGED
@@ -60,10 +60,13 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
60
60
  const stale = history.findIndex((item) => item.id === id);
61
61
  if (stale >= 0) history.splice(stale, 1);
62
62
  };
63
- const entryData = (job: DelegateJob): InspectJob => {
64
- const { controller, steer, swapModel, lastTool, lastDetail, lastResult, ...snapshot } = job;
63
+ const find = (id: string) => running.get(id) ?? history.find((item) => item.id === id);
64
+ /** The serializable form of a job: runtime handles and the latest tool detail stay out. */
65
+ const snapshot = (job: InspectJob): InspectJob => {
66
+ const { controller, steer, swapModel, lastTool, lastDetail, lastResult, ...plain } = job as InspectJob &
67
+ Partial<DelegateJob>;
65
68
  // Copy activity: the live job keeps appending to its own array after the launch snapshot.
66
- return { ...snapshot, activity: [...snapshot.activity] };
69
+ return { ...plain, activity: [...plain.activity] };
67
70
  };
68
71
  const addActivity = (job: DelegateJob, activity: ChildActivity) => {
69
72
  const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
@@ -83,10 +86,18 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
83
86
  /** Every job a view can show: live first, then history. */
84
87
  all: (): InspectJob[] => [...running.values(), ...history],
85
88
  live: (): DelegateJob[] => [...running.values()],
86
- find: (id: string) => running.get(id) ?? history.find((item) => item.id === id),
89
+ find,
90
+ snapshot,
91
+ /** A job by id; the common "unknown delegate job" failure lives here so every tool phrases it alike. */
92
+ findOrThrow: (id: string): InspectJob => {
93
+ const job = find(id);
94
+ if (!job) throw new Error(`Unknown delegate job "${id}".`);
95
+ return job;
96
+ },
97
+ liveJob: (id: string) => running.get(id),
87
98
  /** Writes the launch entry a restarted parent restores from; background jobs join the live set. */
88
99
  launch: (job: DelegateJob, background: boolean) => {
89
- append(JOB_ENTRY, entryData(job));
100
+ append(JOB_ENTRY, snapshot(job));
90
101
  drop(job.id);
91
102
  if (background) running.set(job.id, job);
92
103
  },
@@ -107,7 +118,7 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
107
118
  running.delete(job.id);
108
119
  job.status = status;
109
120
  if (detail) addActivity(job, { kind: "status", text: detail });
110
- const entry: InspectJob = { ...entryData(job), endedAt: Date.now() };
121
+ const entry: InspectJob = { ...snapshot(job), endedAt: Date.now() };
111
122
  drop(entry.id);
112
123
  history.unshift(entry);
113
124
  append(JOB_ENTRY, entry);
@@ -118,7 +129,7 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
118
129
  save: (job: InspectJob) => {
119
130
  drop(job.id);
120
131
  history.unshift(job);
121
- append(JOB_ENTRY, { ...job, activity: [...job.activity] });
132
+ append(JOB_ENTRY, snapshot(job));
122
133
  notify();
123
134
  },
124
135
  /** Rebuilds history from the branch and returns the jobs it marked interrupted. */