@deathbeam/pi-delegate 0.0.27 → 0.0.29

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
@@ -28,11 +28,6 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
28
28
  }
29
29
  ```
30
30
 
31
- Relative `agentDirs` resolve against the project cwd, later same-name definitions win. Project `models` override global
32
- tiers (`cheap`, `balanced`, `strong`); a tier is a `provider/model` string with an optional `:<thinking>` suffix, as in
33
- pi's `--model`. An unset tier makes the child use the current session model. Thinking resolves from the agent's
34
- `model` suffix first, then the tier suffix, then the session level.
35
-
36
31
  Agents are Markdown files with frontmatter, the body becomes the child's system prompt:
37
32
 
38
33
  ```markdown
@@ -41,17 +36,17 @@ name: scout
41
36
  description: Explore the codebase
42
37
  tools: read, grep
43
38
  model: cheap
39
+ isolated: false
44
40
  ---
45
41
 
46
42
  Explore the codebase and report relevant paths.
47
43
  ```
48
44
 
49
- Omit `tools` to inherit active tools. `model` can also be an explicit `provider/model[:thinking]`. The model sees the agent list from
50
- when the extension loaded, so run `/reload` after adding agents or changing their descriptions.
51
-
52
- The main session is prompted to act as an orchestrator. When it makes 5, 10, 20, … direct exploration calls (`read`,
53
- `grep`, `find`, `ls`, shell, web tools) without delegating, a hidden reminder nudges it to delegate the rest. The count
54
- resets on each prompt and each `delegate` call.
45
+ - `name` is required and must be unique
46
+ - `descripion` is required
47
+ - `tools` is optional, a comma-separated list of tool names. Defaults to the session tools.
48
+ - `model` is optional, a tier name or `provider/model[:thinking]`. Defaults to the session model.
49
+ - `isolated` is optional, defaults to `false`. See [Isolation](#isolation).
55
50
 
56
51
  ## Isolation
57
52
 
@@ -59,8 +54,7 @@ resets on each prompt and each `delegate` call.
59
54
  `.pi/worktrees/<id>`, starting from your current working tree including uncommitted changes. Add `.pi/worktrees/` to
60
55
  `.gitignore`.
61
56
 
62
- `delegate_apply` merges the result into your working tree as uncommitted changes. On conflict the clone is kept so you
63
- can steer the delegate to resolve it. `discard: true` drops the clone instead.
57
+ `delegate_apply` merges the result into your working tree as uncommitted changes.
64
58
 
65
59
  ## Development
66
60
 
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. */
@@ -241,3 +290,94 @@ export function widgetJobs<T>(jobs: T[]): { shown: T[]; hidden: number; detail:
241
290
  const shown = detail ? jobs : jobs.slice(-WIDGET_MAX_JOBS);
242
291
  return { shown, hidden: jobs.length - shown.length, detail };
243
292
  }
293
+
294
+ export type DelegateDetails = Pick<
295
+ DelegateJob,
296
+ "id" | "agent" | "description" | "task" | "model" | "tools" | "status" | "isolation" | "cloneClosed"
297
+ > & { background: boolean };
298
+
299
+ export function resultFallback(body: string, theme: Theme, isError: boolean): Text {
300
+ const mark = statusText(theme, isError ? "failed" : "done");
301
+ return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
302
+ }
303
+
304
+ export function moreLines(theme: Theme, hidden: number): string {
305
+ return theme.fg("muted", `… ${hidden} more lines, `) + keyHint("app.tools.expand", "to expand");
306
+ }
307
+
308
+ export function appendOutput(container: Container, body: string, expanded: boolean, theme: Theme): void {
309
+ const { shown, hidden } = outputPreview(body, expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
310
+ container.addChild(new Markdown(shown.join("\n"), 0, 0, getMarkdownTheme()));
311
+ if (hidden > 0) container.addChild(new Text(moreLines(theme, hidden), 0, 0));
312
+ }
313
+
314
+ export function toolLayout(
315
+ toolName: string,
316
+ identity: string,
317
+ payload: string,
318
+ theme: Theme,
319
+ expanded: boolean,
320
+ ): Component {
321
+ const container = new Container();
322
+ if (toolName)
323
+ container.addChild(
324
+ new TruncatedText(`${theme.fg("toolTitle", theme.bold(toolName))}${identity ? ` ${identity}` : ""}`),
325
+ );
326
+ if (!payload.trim()) return container;
327
+ const body = new Text(
328
+ payload
329
+ .split("\n")
330
+ .map((line) => theme.fg("toolOutput", line))
331
+ .join("\n"),
332
+ 0,
333
+ 0,
334
+ );
335
+ if (toolName) container.addChild(new Spacer(1));
336
+ container.addChild({
337
+ render: (width) => {
338
+ // Wrapping turns one long line into many, so the cap counts rendered rows, not source lines.
339
+ const { shown, hidden } = capLines(body.render(width), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
340
+ return hidden ? [...shown, truncateToWidth(moreLines(theme, hidden), width)] : shown;
341
+ },
342
+ invalidate: () => body.invalidate(),
343
+ });
344
+ return container;
345
+ }
346
+
347
+ export function resultHeader(
348
+ theme: Theme,
349
+ job: { id: string; agent: string },
350
+ tail: string,
351
+ outcome: JobStatus = "done",
352
+ ): string {
353
+ return `${statusText(theme, outcome)} ${jobIdentity(theme, job)} ${theme.fg("muted", tail)}`;
354
+ }
355
+
356
+ export function jobSummary(job: {
357
+ description: string;
358
+ contextTokens?: number;
359
+ contextWindow?: number;
360
+ elapsedMs: number;
361
+ }): string {
362
+ return `${job.description} ${usageStats(job, job.elapsedMs)}`;
363
+ }
364
+
365
+ export function launchResult(
366
+ details: DelegateDetails,
367
+ body: string,
368
+ status: string,
369
+ expanded: boolean,
370
+ theme: Theme,
371
+ ): Component {
372
+ const container = new Container();
373
+ // The mark is the call's outcome (launch succeeded); job progress stays in the widget and report.
374
+ container.addChild(new Text(`\n${resultHeader(theme, details, status)}`, 0, 0));
375
+ // The call body already carries the task; only the launch metadata is new here.
376
+ if (expanded)
377
+ container.addChild(
378
+ new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
379
+ );
380
+ // Background results arrive as their own message; headless runs still show the output here.
381
+ if (!details.background && body) appendOutput(container, body, expanded, theme);
382
+ return container;
383
+ }
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,14 +358,9 @@ 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
366
  else if (report.output) appendOutput(container, report.output, expanded, theme);
@@ -452,7 +370,7 @@ export default function (pi: ExtensionAPI) {
452
370
  registerInspector(pi, store);
453
371
 
454
372
  const cwd = process.cwd();
455
- const agentList = discoverAgents(cwd, configFor(cwd).agentDirs).map((agent) => {
373
+ const agentList = agentsFor(cwd).map((agent) => {
456
374
  const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
457
375
  return `- ${agent.name}${qualifiers ? ` (${qualifiers})` : ""}: ${agent.description}`;
458
376
  });
@@ -502,12 +420,7 @@ export default function (pi: ExtensionAPI) {
502
420
  const params = dropNulls(rawParams);
503
421
  const { agent: agentName, description, task, model, isolated } = params;
504
422
  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
- }
423
+ const agent = agentByName(ctx.cwd, agentName);
511
424
  const effective = isolated ?? agent.isolated;
512
425
  return runDelegate(ctx, agent, undefined, { description, model, isolated: effective }, task, signal);
513
426
  },
@@ -567,7 +480,7 @@ export default function (pi: ExtensionAPI) {
567
480
  async execute(_toolCallId, rawParams, signal, _onUpdate, ctx) {
568
481
  const params = dropNulls(rawParams);
569
482
  const id = jobId(params.id);
570
- const running = store.live().find((candidate) => candidate.id === id);
483
+ const running = store.liveJob(id);
571
484
  if (running) {
572
485
  // A live job without steer would fall into the revive path and double-spawn its pinned session.
573
486
  if (!running.steer) throw new Error(`No steerable delegate job "${id}".`);
@@ -576,7 +489,7 @@ export default function (pi: ExtensionAPI) {
576
489
  await running.steer(params.message);
577
490
  } catch (error) {
578
491
  // 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))
492
+ if (!store.liveJob(id))
580
493
  throw new Error(
581
494
  `Delegate job "${id}" just finished; call delegate_steer again to continue it.`,
582
495
  );
@@ -590,7 +503,7 @@ export default function (pi: ExtensionAPI) {
590
503
  toolCalls: running.toolCalls,
591
504
  contextTokens: running.contextTokens,
592
505
  contextWindow: running.contextWindow,
593
- elapsedMs: Date.now() - running.startedAt,
506
+ elapsedMs: elapsedMs(running),
594
507
  };
595
508
  return {
596
509
  content: [
@@ -602,19 +515,13 @@ export default function (pi: ExtensionAPI) {
602
515
  details,
603
516
  };
604
517
  }
605
- const prior = store.find(id);
606
- if (!id || !prior) throw new Error(`Unknown delegate job "${id}".`);
518
+ const prior = store.findOrThrow(id);
607
519
  // An applied or discarded clone cannot be continued; a revive would run in the main tree.
608
520
  if (prior.cloneClosed)
609
521
  throw new Error(
610
522
  `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
523
  );
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
- }
524
+ const agent = agentByName(ctx.cwd, prior.agent);
618
525
  return runDelegate(
619
526
  ctx,
620
527
  agent,
@@ -644,12 +551,7 @@ export default function (pi: ExtensionAPI) {
644
551
  const details = result.details as SteerDetails | DelegateDetails | undefined;
645
552
  const body = resultText(result);
646
553
  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
- );
554
+ if ("message" in details) return new Text(`\n${resultHeader(theme, details, jobSummary(details))}`, 0, 0);
653
555
  return launchResult(
654
556
  details,
655
557
  body,
@@ -670,7 +572,7 @@ export default function (pi: ExtensionAPI) {
670
572
  }),
671
573
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
672
574
  const id = jobId(params.id);
673
- const job = store.live().find((candidate) => candidate.id === id);
575
+ const job = store.liveJob(id);
674
576
  if (!job) throw new Error(`No running delegate job "${id}".`);
675
577
  store.finish(job, "cancelled");
676
578
  job.controller.abort();
@@ -692,12 +594,8 @@ export default function (pi: ExtensionAPI) {
692
594
  const details = result.details as { id: string; agent: string } | undefined;
693
595
  const body = resultText(result);
694
596
  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
- );
597
+ // The mark is the call's outcome (cancellation requested), not the job's cancelled status.
598
+ return new Text(`\n${resultHeader(theme, details, "cancellation requested")}`, 0, 0);
701
599
  },
702
600
  });
703
601
 
@@ -716,17 +614,21 @@ export default function (pi: ExtensionAPI) {
716
614
  async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
717
615
  const params = dropNulls(rawParams);
718
616
  const id = jobId(params.id);
719
- const job = store.find(id);
720
- if (!id || !job) throw new Error(`Unknown delegate job "${id}".`);
617
+ const job = store.findOrThrow(id);
721
618
  if (job.status === "running")
722
619
  throw new Error(`Delegate job "${id}" is still running; steer it or cancel it first.`);
723
620
  if (!job.isolation)
724
621
  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);
622
+
623
+ const isolation = job.isolation;
624
+ const closeClone = () => {
625
+ removeClone(isolation);
727
626
  job.isolation = undefined;
728
627
  job.cloneClosed = true;
729
628
  store.save(job);
629
+ };
630
+ if (params.discard === true) {
631
+ closeClone();
730
632
  return {
731
633
  content: [
732
634
  {
@@ -747,10 +649,7 @@ export default function (pi: ExtensionAPI) {
747
649
  );
748
650
  }
749
651
  const stat = result.kind === "applied" ? `\n${result.stat}` : "";
750
- removeClone(job.isolation);
751
- job.isolation = undefined;
752
- job.cloneClosed = true;
753
- store.save(job);
652
+ closeClone();
754
653
  return {
755
654
  content: [
756
655
  {
@@ -781,18 +680,12 @@ export default function (pi: ExtensionAPI) {
781
680
  const body = resultText(result);
782
681
  if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
783
682
  const status = details.discarded ? "clone discarded" : "changes applied";
784
- const header = `\n${statusText(theme, "done")} ${jobIdentity(theme, details)} ${theme.fg("muted", status)}`;
683
+ const header = `\n${resultHeader(theme, details, status)}`;
785
684
  const diff = details.diff?.trim() ? renderDiff(piDiff(details.diff)) : "";
786
685
  if (!diff) return new Text(header, 0, 0);
787
- const lines = diff.split("\n");
788
686
  // 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
- ];
687
+ const { shown, hidden } = capLines(diff.split("\n"), expanded ? Infinity : COLLAPSED_OUTPUT_LINES);
688
+ if (hidden) shown.push(moreLines(theme, hidden));
796
689
  const container = new Container();
797
690
  container.addChild(new Text(header, 0, 0));
798
691
  container.addChild(new Spacer(1));
@@ -818,26 +711,26 @@ export default function (pi: ExtensionAPI) {
818
711
  ? ` · ${lastTool}${lastDetail ? ` ${lastDetail}` : ""}`
819
712
  : "";
820
713
  };
821
- const lines = jobs.map(
822
- (job) =>
823
- `- ${job.id} ${job.agent} · ${job.status} · ${jobLine(job, (job.endedAt ?? now) - job.startedAt)}${lastActivity(job)}`,
824
- );
714
+ const lines = jobs.map((job) => {
715
+ const tag = isolationWords(job);
716
+ return `- ${job.id} ${job.agent} · ${job.status}${tag ? ` · ${tag}` : ""} · ${jobLine(job, elapsedMs(job, now))}${lastActivity(job)}`;
717
+ });
825
718
  return {
826
719
  content: [
827
720
  { type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
828
721
  ],
829
- details: { jobs: jobs.map(jobSnapshot) },
722
+ details: { jobs: jobs.map(store.snapshot) },
830
723
  };
831
724
  },
832
725
  renderResult(result, _options, theme, context) {
833
- const jobs = (result.details as { jobs?: ReturnType<typeof jobSnapshot>[] } | undefined)?.jobs;
726
+ const jobs = (result.details as { jobs?: InspectJob[] } | undefined)?.jobs;
834
727
  if (!jobs?.length || context.isError) return resultFallback(resultText(result), theme, context.isError);
835
728
  const now = Date.now();
836
729
  return new Text(
837
730
  `\n${statusText(theme, "done")} ${theme.fg("muted", `${jobs.length} delegates`)}\n${jobs
838
731
  .map(
839
732
  (job) =>
840
- `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, (job.endedAt ?? now) - job.startedAt))}`,
733
+ `${statusText(theme, job.status, now)} ${jobIdentity(theme, job)} ${theme.fg("muted", jobLine(job, elapsedMs(job, now)))}`,
841
734
  )
842
735
  .join("\n")}`,
843
736
  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 };
@@ -122,6 +122,7 @@ export function isolationSummary(iso: IsolationState): string {
122
122
  } catch {
123
123
  // The clone may already be applied or gone; the path alone still says where the work lives.
124
124
  }
125
+ lines.push("Apply with delegate_apply to land these changes in the main tree.");
125
126
  return lines.join("\n");
126
127
  }
127
128
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.27",
3
+ "version": "0.0.29",
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. */