@deathbeam/pi-delegate 0.0.41 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/child.ts CHANGED
@@ -1,20 +1,18 @@
1
1
  import type { ChildProcessWithoutNullStreams } from "node:child_process";
2
- import { readdirSync, readFileSync } from "node:fs";
2
+ import { readdirSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { limitOutput, resultPreview, textParts, toolCallDetail } from "./format.ts";
4
+ import { SessionManager, type MessageEndEvent } from "@earendil-works/pi-coding-agent";
5
+ import { limitOutput, textParts } from "./format.ts";
5
6
 
6
7
  type Child = ChildProcessWithoutNullStreams;
7
8
 
8
- export type ChildActivity = {
9
- kind: "tool" | "result" | "assistant" | "user" | "status";
10
- text: string;
11
- detail?: string;
12
- isError?: boolean;
13
- };
9
+ /** A child message in the shape pi's chat components render. */
10
+ export type ChildMessage = MessageEndEvent["message"];
14
11
  export type ChildUpdate = {
15
12
  toolCalls?: number;
16
13
  contextTokens?: number;
17
- activity?: ChildActivity;
14
+ /** A message the child finished; the store appends it to the job's transcript. */
15
+ message?: ChildMessage;
18
16
  };
19
17
  type ChildUpdateHandler = (update: ChildUpdate) => void;
20
18
 
@@ -127,46 +125,23 @@ export function runChild(
127
125
  switch (event.type) {
128
126
  case "tool_execution_start": {
129
127
  toolCalls += 1;
130
- const detail = toolCallDetail(event.toolName, event.args);
131
- onUpdate?.({
132
- toolCalls,
133
- activity: { kind: "tool", text: event.toolName, detail },
134
- });
135
- return;
136
- }
137
- case "tool_execution_end": {
138
- const preview = resultPreview(event.result);
139
- onUpdate?.({
140
- activity: {
141
- kind: "result",
142
- text: preview ?? "",
143
- ...(event.isError ? { isError: true } : {}),
144
- },
145
- });
128
+ onUpdate?.({ toolCalls });
146
129
  return;
147
130
  }
148
131
  case "message_update": {
149
- const delta =
150
- event.assistantMessageEvent?.type === "text_delta"
151
- ? (event.assistantMessageEvent.delta ?? "")
152
- : "";
153
- if (delta) liveText += delta;
154
132
  onUpdate?.({ contextTokens: usageTokens(event.usage) });
155
133
  return;
156
134
  }
157
135
  case "message_end": {
158
- const role = event.message?.role;
159
- if (role !== "assistant" && role !== "user") return;
160
- const text = textParts(event.message.content).join("");
161
- if (role === "assistant") {
162
- childError = event.message.errorMessage;
136
+ const message = event.message as ChildMessage;
137
+ let contextTokens: number | undefined;
138
+ if (message.role === "assistant") {
139
+ childError = message.errorMessage;
140
+ const text = textParts(message.content).join("");
163
141
  if (text) liveText = text;
142
+ contextTokens = usageTokens(message.usage);
164
143
  }
165
- if (text)
166
- onUpdate?.({
167
- contextTokens: usageTokens(event.message.usage),
168
- activity: { kind: role, text },
169
- });
144
+ onUpdate?.({ contextTokens, message });
170
145
  return;
171
146
  }
172
147
  case "agent_settled":
@@ -263,7 +238,7 @@ export function runChild(
263
238
  });
264
239
  };
265
240
  if (revive) {
266
- // An empty transcript means the pinned session was recreated (e.g. a different cwd) and the task is gone; fail rather than prompt into a blank session.
241
+ // An empty transcript means the pinned session was recreated (e.g. a different cwd); prompting would lose the task.
267
242
  void send({ type: "get_state" })
268
243
  .then((data) => {
269
244
  if (!settled && !aborted && !data?.messageCount) {
@@ -299,11 +274,10 @@ export function runChild(
299
274
  }
300
275
 
301
276
  /**
302
- * Replays the child's persisted transcript as the activity a revived job continues from, so the
303
- * inspector keeps the old history. A missing or unreadable transcript seeds nothing: the revive
304
- * itself still works.
277
+ * The child's persisted transcript, for a job whose messages are not in memory. A missing or
278
+ * unreadable session seeds nothing: the job still renders, just without history.
305
279
  */
306
- export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
280
+ export function sessionMessages(sessionDir: string, id: string): ChildMessage[] {
307
281
  let sessionFile: string | undefined;
308
282
  try {
309
283
  // Sessions are <timestamp>_<sessionId>.jsonl; a recreated pinned session is the newest one.
@@ -315,54 +289,9 @@ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
315
289
  return [];
316
290
  }
317
291
  if (!sessionFile) return [];
318
- let lines: string[];
319
292
  try {
320
- lines = readFileSync(join(sessionDir, sessionFile), "utf8").split("\n");
293
+ return SessionManager.open(join(sessionDir, sessionFile)).buildSessionContext().messages;
321
294
  } catch {
322
295
  return [];
323
296
  }
324
- const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
325
- const activity: ChildActivity[] = [];
326
- for (const line of lines) {
327
- if (!line.trim()) continue;
328
- let entry: { type?: string; message?: unknown };
329
- try {
330
- entry = JSON.parse(line);
331
- } catch {
332
- continue; // Same tolerance pi's session reader has for malformed lines.
333
- }
334
- const message =
335
- entry?.type === "message"
336
- ? (entry.message as {
337
- role?: "assistant" | "user" | "toolResult";
338
- content?: unknown;
339
- isError?: boolean;
340
- })
341
- : undefined;
342
- if (!message?.role) continue;
343
- if (message.role === "toolResult") {
344
- const preview = resultPreview({ content: message.content });
345
- activity.push({
346
- kind: "result",
347
- text: normalize(preview ?? ""),
348
- ...(message.isError ? { isError: true } : {}),
349
- });
350
- continue;
351
- }
352
- // Assistant text lands before its tool calls, matching the live event order.
353
- const text = textParts(message.content).join("");
354
- if (text) activity.push({ kind: message.role, text });
355
- if (message.role !== "assistant") continue;
356
- for (const part of Array.isArray(message.content) ? message.content : []) {
357
- const call =
358
- part && typeof part === "object" ? (part as { type?: string; name?: string; arguments?: unknown }) : {};
359
- if (call.type !== "toolCall" || !call.name) continue;
360
- activity.push({
361
- kind: "tool",
362
- text: normalize(call.name),
363
- detail: normalize(toolCallDetail(call.name, call.arguments)) || undefined,
364
- });
365
- }
366
- }
367
- return activity;
368
297
  }
package/format.ts CHANGED
@@ -20,16 +20,13 @@ export type DelegateReport = {
20
20
  id: string;
21
21
  agent: string;
22
22
  description: string;
23
- model?: string;
24
23
  toolCalls: number;
25
24
  contextTokens?: number;
26
25
  contextWindow?: number;
27
26
  elapsedMs: number;
28
27
  output?: string;
29
28
  error?: string;
30
- status: JobStatus;
31
29
  isolation?: IsolationState;
32
- cloneClosed?: boolean;
33
30
  };
34
31
 
35
32
  /** The isolation state to show for a job: pending means its clone still holds unapplied work. */
@@ -37,14 +34,12 @@ export type IsolationMark = "isolated" | "pending";
37
34
 
38
35
  type IsolationStateFields = {
39
36
  isolation?: unknown;
40
- cloneClosed?: boolean;
41
37
  status?: string;
42
38
  };
43
39
 
44
- export type DelegateDetails = Pick<
45
- DelegateJob,
46
- "id" | "agent" | "description" | "task" | "model" | "tools" | "status" | "isolation" | "cloneClosed"
47
- > & { background: boolean };
40
+ export type DelegateDetails = Pick<DelegateJob, "id" | "agent" | "model" | "tools" | "isolation"> & {
41
+ background: boolean;
42
+ };
48
43
 
49
44
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
50
45
  export const SPINNER_INTERVAL_MS = 100;
@@ -80,7 +75,7 @@ export function statusText(theme: Theme, status: JobStatus, now = Date.now()): s
80
75
  /** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
81
76
  export function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
82
77
  if (!job.isolation) return undefined;
83
- return job.cloneClosed || job.status === "running" ? "isolated" : "pending";
78
+ return job.status === "running" ? "isolated" : "pending";
84
79
  }
85
80
 
86
81
  /** `⎇`, warning-colored while the clone's work is still unapplied. */
@@ -134,6 +129,12 @@ export function tally(running: number, all: { startedAt: number; endedAt?: numbe
134
129
  return `${running} running · ${all.length} total · ${formatDuration(total)}`;
135
130
  }
136
131
 
132
+ /** A tool call's call row and, once it arrives, its result preview row; shared by the widget and the inspector. */
133
+ export function toolLines(theme: Theme, name: string, detail: string, result?: string, isError?: boolean): string[] {
134
+ const call = `${theme.fg("toolTitle", theme.bold(name))}${detail ? ` ${theme.fg("accent", detail)}` : ""}`;
135
+ return result ? [call, `${theme.fg("muted", "↳")} ${theme.fg(isError ? "error" : "toolOutput", result)}`] : [call];
136
+ }
137
+
137
138
  export function toolCallDetail(toolName: string, args: unknown): string {
138
139
  const input = (args ?? {}) as Record<string, unknown>;
139
140
  const value = (key: string) => (typeof input[key] === "string" ? (input[key] as string).trim() : "");
@@ -187,7 +188,6 @@ export function capDiff(text: string): { diff: string; note?: string } {
187
188
  return { diff: capped.slice(0, at), note: capped.slice(at + 2) };
188
189
  }
189
190
 
190
- /** The text parts of a message or tool result's content, in order. */
191
191
  export function textParts(content: unknown): string[] {
192
192
  if (typeof content === "string") return [content];
193
193
  if (!Array.isArray(content)) return [];
@@ -212,12 +212,7 @@ export function reviveHint(id: string): string {
212
212
  return `To continue this job, call delegate_steer with id ${id} and a message.`;
213
213
  }
214
214
 
215
- /**
216
- * Converts a git unified diff into pi's own diff format (`+12 content` / `-12 content` / ` 12 content`,
217
- * prefix, padded line number, space, content), which is what pi's renderDiff colors; a raw unified
218
- * diff renders as flat context. Line numbers come from the @@ headers (- uses the old side, + and
219
- * context the new side); the file path heads each file and `...` separates its hunks.
220
- */
215
+ /** Converts a git unified diff into pi's `+12 content` format, which renderDiff colors; a raw unified diff renders flat. */
221
216
  export function piDiff(unified: string): string {
222
217
  const out: string[] = [];
223
218
  let path = "";
@@ -280,10 +275,9 @@ export function reportText(report: DelegateReport): string {
280
275
  if (report.error) return `${head} failed: ${report.error}\n${reviveHint(report.id)}`;
281
276
  const output = (report.output ?? "").trim();
282
277
  // The apply hint is for the model only: the transcript renders `output`, so users never see it.
283
- const hint =
284
- report.isolation && !report.cloneClosed
285
- ? `\n\nCall delegate_apply with job ${report.id} to land its changes, or delegate_discard to drop them. Call one, not both: a successful apply removes the clone.`
286
- : "";
278
+ const hint = report.isolation
279
+ ? `\n\nCall delegate_apply with job ${report.id} to land its changes, or delegate_discard to drop them. Call one, not both: a successful apply removes the clone.`
280
+ : "";
287
281
  return `${head} finished.${output ? `\n\n${output}` : ""}${hint}`;
288
282
  }
289
283
 
package/index.ts CHANGED
@@ -29,9 +29,10 @@ import {
29
29
  tally,
30
30
  textParts,
31
31
  toolLayout,
32
+ toolLines,
32
33
  widgetJobs,
33
34
  } from "./format.ts";
34
- import { priorActivity, runChild } from "./child.ts";
35
+ import { runChild, sessionMessages } from "./child.ts";
35
36
  import { createJobStore, type DelegateJob, lastToolCall, type InspectJob } from "./store.ts";
36
37
  import {
37
38
  applyClone,
@@ -156,7 +157,6 @@ export default function (pi: ExtensionAPI) {
156
157
  /** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
157
158
  const jobsInClone = (clone: string) => store.all().filter((job) => job.isolation?.clone === clone);
158
159
 
159
- /** A job that still has a clone; throws explaining why it has none. */
160
160
  const clonedJob = (id: string) => {
161
161
  const job = store.findOrThrow(id);
162
162
  const isolation = job.isolation;
@@ -188,7 +188,6 @@ export default function (pi: ExtensionAPI) {
188
188
 
189
189
  const refreshWidget = (ctx: ExtensionContext) => {
190
190
  if (!ctx.hasUI) return;
191
- store.notify();
192
191
  const jobs = store.live();
193
192
  if (jobs.length === 0) {
194
193
  ctx.ui.setWidget(WIDGET_KEY, undefined);
@@ -204,11 +203,9 @@ export default function (pi: ExtensionAPI) {
204
203
  const { tool, result } = lastToolCall(job);
205
204
  if (tool)
206
205
  lines.push(
207
- ` ${theme.fg("toolTitle", theme.bold(tool.text))}${tool.detail ? ` ${theme.fg("accent", tool.detail)}` : ""}`,
208
- );
209
- if (result?.text)
210
- lines.push(
211
- ` ${theme.fg("muted", "↳")} ${theme.fg(result.isError ? "error" : "toolOutput", result.text)}`,
206
+ ...toolLines(theme, tool.name, tool.detail, result?.text, result?.isError).map(
207
+ (line) => ` ${line}`,
208
+ ),
212
209
  );
213
210
  }
214
211
  if (hidden) lines.push(` ${theme.fg("muted", `… ${hidden} more running · /delegate to view all`)}`);
@@ -237,16 +234,13 @@ export default function (pi: ExtensionAPI) {
237
234
  id: job.id,
238
235
  agent: job.agent,
239
236
  description: job.description,
240
- model: job.model,
241
237
  toolCalls: job.toolCalls,
242
238
  contextTokens: job.contextTokens,
243
239
  contextWindow: job.contextWindow,
244
240
  elapsedMs: elapsedMs(job),
245
241
  output: withIsolation(output ?? "", job.isolation),
246
242
  error,
247
- status: job.status,
248
243
  isolation: job.isolation,
249
- cloneClosed: job.cloneClosed,
250
244
  };
251
245
  // Idle: this starts a new turn. Streaming: steer the report in at the next turn boundary;
252
246
  // a follow-up waits for a run end that a parent stuck polling may never reach.
@@ -286,7 +280,7 @@ export default function (pi: ExtensionAPI) {
286
280
  task,
287
281
  model: displayModel,
288
282
  status: "running",
289
- activity: prior ? priorActivity(DELEGATE_SESSION_DIR, prior.id) : [],
283
+ messages: prior ? sessionMessages(DELEGATE_SESSION_DIR, prior.id) : [],
290
284
  tools,
291
285
  toolCalls: 0,
292
286
  startedAt: Date.now(),
@@ -297,14 +291,10 @@ export default function (pi: ExtensionAPI) {
297
291
  const details: DelegateDetails = {
298
292
  id: job.id,
299
293
  agent: job.agent,
300
- description: job.description,
301
- task: job.task,
302
294
  model: displayModel,
303
295
  tools,
304
296
  background: ctx.hasUI,
305
- status: job.status,
306
297
  isolation: job.isolation,
307
- cloneClosed: job.cloneClosed,
308
298
  };
309
299
  const args = [
310
300
  "--session-id",
@@ -404,7 +394,7 @@ export default function (pi: ExtensionAPI) {
404
394
  store.clear();
405
395
  });
406
396
 
407
- // Rebuilt from the active branch, like pi's todo example; abandoned branches are alternative histories.
397
+ // Rebuilt from the active branch: abandoned branches are alternative histories.
408
398
  const restoreSession = (ctx: ExtensionContext) => {
409
399
  const interrupted = store.restore(ctx.sessionManager.getBranch());
410
400
  // Custom entries never reach the model, so announce the interrupted jobs as a steered message.
@@ -470,7 +460,7 @@ export default function (pi: ExtensionAPI) {
470
460
  return container;
471
461
  });
472
462
 
473
- registerInspector(pi, store);
463
+ registerInspector(pi, store, DELEGATE_SESSION_DIR);
474
464
 
475
465
  const agentList = agentsFor(process.cwd()).map((agent) => {
476
466
  const qualifiers = [agent.model, agent.isolated ? "isolated" : undefined].filter(Boolean).join(", ");
@@ -799,7 +789,7 @@ export default function (pi: ExtensionAPI) {
799
789
  const running = jobs.filter((job) => job.status === "running").length;
800
790
  const lastActivity = (job: InspectJob) => {
801
791
  const { tool } = lastToolCall(job);
802
- return job.status === "running" && tool ? ` · ${tool.text}${tool.detail ? ` ${tool.detail}` : ""}` : "";
792
+ return job.status === "running" && tool ? ` · ${tool.name}${tool.detail ? ` ${tool.detail}` : ""}` : "";
803
793
  };
804
794
  const lines = jobs.map((job) => {
805
795
  const tag = isolationWords(job);
@@ -809,8 +799,7 @@ export default function (pi: ExtensionAPI) {
809
799
  content: [
810
800
  { type: "text", text: `${jobs.length} delegates (${running} running):\n${lines.join("\n")}` },
811
801
  ],
812
- // Rows render from the fields; the activity history stays in the store, not in every list result.
813
- details: { jobs: jobs.map(store.summary) },
802
+ details: { jobs: jobs.map(store.snapshot) },
814
803
  };
815
804
  },
816
805
  renderResult(result, _options, theme, context) {
package/inspector.ts CHANGED
@@ -1,18 +1,181 @@
1
- import { type ExtensionAPI, getMarkdownTheme, rawKeyHint } from "@earendil-works/pi-coding-agent";
2
1
  import {
3
- HStack,
2
+ AssistantMessageComponent,
3
+ type ExtensionAPI,
4
+ rawKeyHint,
5
+ type Theme,
6
+ UserMessageComponent,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import {
9
+ Box,
10
+ type Component,
4
11
  type Keybinding,
5
- Markdown,
6
12
  matchesKey,
13
+ Spacer,
14
+ Text,
7
15
  truncateToWidth,
8
16
  wrapTextWithAnsi,
9
17
  } from "@earendil-works/pi-tui";
10
- import type { ChildActivity } from "./child.ts";
11
- import { elapsedMs, formatTools, jobIdentity, STATUS_COLORS, statusText, tally, usageStats } from "./format.ts";
18
+ import { type ChildMessage, sessionMessages } from "./child.ts";
19
+ import {
20
+ elapsedMs,
21
+ formatTools,
22
+ jobIdentity,
23
+ resultPreview,
24
+ STATUS_COLORS,
25
+ statusText,
26
+ tally,
27
+ textParts,
28
+ toolCallDetail,
29
+ toolLines,
30
+ usageStats,
31
+ } from "./format.ts";
12
32
  import type { InspectJob, JobStore } from "./store.ts";
13
33
 
34
+ type Entry = { component: Component; lines?: string[] };
35
+
36
+ // pi's chat components prefix lines with OSC 133 prompt markers; past the sidebar the terminal would read one as a new prompt.
37
+ const OSC133 = /^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;
38
+
39
+ /** Rendered transcript rows, cached per width so a frame only renders rows it has never seen. */
40
+ export class History {
41
+ private readonly entries: Entry[] = [];
42
+ private width = 0;
43
+
44
+ add(component: Component): Entry {
45
+ const entry: Entry = { component };
46
+ this.entries.push(entry);
47
+ return entry;
48
+ }
49
+
50
+ invalidate() {
51
+ for (const entry of this.entries) {
52
+ entry.component.invalidate?.();
53
+ entry.lines = undefined;
54
+ }
55
+ }
56
+
57
+ window(width: number, top: number | undefined, height: number) {
58
+ if (this.width !== width) {
59
+ this.width = width;
60
+ for (const entry of this.entries) entry.lines = undefined;
61
+ }
62
+ const all = this.entries.flatMap(
63
+ (entry) => (entry.lines ??= entry.component.render(width).map((line) => line.replace(OSC133, ""))),
64
+ );
65
+ const start = Math.min(top ?? Infinity, Math.max(0, all.length - height));
66
+ return { lines: all.slice(start, start + height), start, total: all.length };
67
+ }
68
+ }
69
+
70
+ /** One tool call as a compact pi-style box: the call row plus the result's first line. */
71
+ class ToolRow implements Component {
72
+ private readonly theme: Theme;
73
+ private readonly name: string;
74
+ private readonly detail: string;
75
+ private result?: string;
76
+ private done = false;
77
+ private error = false;
78
+
79
+ constructor(theme: Theme, name: string, detail: string) {
80
+ this.theme = theme;
81
+ this.name = name;
82
+ this.detail = detail;
83
+ }
84
+
85
+ invalidate() {}
86
+
87
+ setResult(message: Extract<ChildMessage, { role: "toolResult" }>) {
88
+ this.result = resultPreview(message);
89
+ this.done = true;
90
+ this.error = message.isError === true;
91
+ }
92
+
93
+ render(width: number) {
94
+ const theme = this.theme;
95
+ // The box's own horizontal padding leaves width - 2 for each truncated row.
96
+ const inner = Math.max(1, width - 2);
97
+ const text = toolLines(theme, this.name, this.detail, this.result, this.error)
98
+ .map((line) => truncateToWidth(line, inner))
99
+ .join("\n");
100
+ const bg = this.error ? "toolErrorBg" : this.done ? "toolSuccessBg" : "toolPendingBg";
101
+ // pi's own tool box and spacing; only the content is compact.
102
+ const box = new Box(1, 1, (line) => theme.bg(bg, line));
103
+ box.addChild(new Text(text, 0, 0));
104
+ return ["", ...box.render(width)];
105
+ }
106
+ }
107
+
108
+ /** One job's transcript, built from pi's chat components and kept in sync as messages arrive. */
109
+ export class Transcript {
110
+ private history = new History();
111
+ private messages?: ChildMessage[];
112
+ private count = 0;
113
+ private readonly pending = new Map<string, Entry>();
114
+ private readonly theme: Theme;
115
+
116
+ constructor(theme: Theme) {
117
+ this.theme = theme;
118
+ }
119
+
120
+ sync(messages: ChildMessage[]) {
121
+ // The store swaps a finished job's live array for the session file's, so a different array is a new transcript.
122
+ if (messages !== this.messages) {
123
+ this.messages = messages;
124
+ this.history = new History();
125
+ this.count = 0;
126
+ this.pending.clear();
127
+ }
128
+ while (this.count < messages.length) this.add(messages[this.count++]!);
129
+ }
130
+
131
+ window(width: number, top: number | undefined, height: number) {
132
+ return this.history.window(width, top, height);
133
+ }
134
+
135
+ invalidate() {
136
+ this.history.invalidate();
137
+ }
138
+
139
+ private add(message: ChildMessage) {
140
+ if (message.role === "user") {
141
+ const text = textParts(message.content).join("");
142
+ if (!text) return;
143
+ // pi's chat spaces user messages itself; the component carries no margin.
144
+ this.history.add(new Spacer(1));
145
+ this.history.add(new UserMessageComponent(text));
146
+ return;
147
+ }
148
+ if (message.role === "assistant") {
149
+ // Thinking blocks are the child's scratchpad; the inspector shows what it said and did.
150
+ this.history.add(new AssistantMessageComponent(message, true, undefined, ""));
151
+ for (const part of message.content) {
152
+ if (part.type !== "toolCall") continue;
153
+ const row = new ToolRow(this.theme, part.name, toolCallDetail(part.name, part.arguments));
154
+ this.pending.set(part.id, this.history.add(row));
155
+ }
156
+ return;
157
+ }
158
+ if (message.role === "toolResult") {
159
+ const entry = this.pending.get(message.toolCallId);
160
+ if (!entry) return;
161
+ (entry.component as ToolRow).setResult(message);
162
+ entry.lines = undefined;
163
+ return;
164
+ }
165
+ // display: false marks model-only context (e.g. pi-archive's recent sessions); pi's chat hides it too.
166
+ if ((message as { display?: boolean }).display === false) return;
167
+ const text =
168
+ message.role === "compactionSummary"
169
+ ? message.summary
170
+ : textParts((message as { content?: unknown }).content).join("");
171
+ if (!text) return;
172
+ this.history.add(new Spacer(1));
173
+ this.history.add(new Text(text, 1, 0));
174
+ }
175
+ }
176
+
14
177
  /** The /delegate command: a full-screen inspector over the job store. */
15
- export function registerInspector(pi: ExtensionAPI, store: JobStore) {
178
+ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir: string) {
16
179
  pi.registerCommand("delegate", {
17
180
  description: "Inspect live and recent delegate activity",
18
181
  handler: async (_args, ctx) => {
@@ -31,8 +194,9 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
31
194
  let selectedId = store.all()[0]!.id;
32
195
  let focus: "list" | "history" = "list";
33
196
  let top: number | undefined;
34
- let historyWidth = 1;
35
- let markdown = new WeakMap<ChildActivity, Markdown>();
197
+ let lastWindow = { height: 0, total: 0 };
198
+ const transcripts = new Map<string, Transcript>();
199
+ const loaded = new Set<string>();
36
200
  const jobs = () => store.all();
37
201
  // Format hints from the injected manager; an imported copy would not see the user's keybindings.
38
202
  const hint = (id: Keybinding, description: string) =>
@@ -43,10 +207,22 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
43
207
  wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
44
208
  theme.fg("dim", line),
45
209
  );
46
- // Fixed rows: header, model, description, rule, counter.
47
- const historyHeight = (job: InspectJob, width: number) =>
48
- Math.max(0, bodyHeight() - 5 - toolsLines(job, width).length);
49
- // ScrollView needs fullscreen layout; window the history in regular TUI too.
210
+ const transcript = (job: InspectJob) => {
211
+ let value = transcripts.get(job.id);
212
+ if (!value) {
213
+ value = new Transcript(theme);
214
+ transcripts.set(job.id, value);
215
+ }
216
+ return value;
217
+ };
218
+ // Restored jobs carry no messages: the child's session file is their history.
219
+ const messagesOf = (job: InspectJob) => {
220
+ if (!job.messages.length && job.status !== "running" && !loaded.has(job.id)) {
221
+ loaded.add(job.id);
222
+ job.messages = sessionMessages(sessionDir, job.id);
223
+ }
224
+ return job.messages;
225
+ };
50
226
  const renderJobs = (width: number, items: InspectJob[], selectedIndex: number): string[] => {
51
227
  const row = (text: string) =>
52
228
  truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│");
@@ -70,44 +246,16 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
70
246
  row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
71
247
  ].slice(0, bodyHeight());
72
248
  };
73
- const renderEntry = (entry: ChildActivity, width: number): string[] => {
74
- if (entry.kind === "assistant" || entry.kind === "user") {
75
- let md = markdown.get(entry);
76
- if (!md) {
77
- md = new Markdown(entry.text, 0, 0, getMarkdownTheme());
78
- markdown.set(entry, md);
79
- }
80
- return [theme.fg("accent", entry.kind), ...md.render(width), ""];
81
- }
82
- if (entry.kind === "tool")
83
- return [
84
- truncateToWidth(
85
- theme.fg("toolTitle", theme.bold(entry.text)) +
86
- (entry.detail ? ` ${theme.fg("accent", entry.detail)}` : ""),
87
- width,
88
- ),
89
- ];
90
- if (entry.kind === "result")
91
- return [
92
- truncateToWidth(
93
- ` ${theme.fg("muted", "↳")} ${theme.fg(entry.isError ? "error" : "toolOutput", entry.text || "(no text output)")}`,
94
- width,
95
- ),
96
- ];
97
- // Only failure detail still says anything; the header icon carries the status.
98
- if (!entry.text) return [];
99
- return [truncateToWidth(theme.fg(STATUS_COLORS.failed, entry.text), width)];
100
- };
101
249
  const renderHistory = (width: number, job: InspectJob): string[] => {
102
- historyWidth = width;
103
250
  const tools = toolsLines(job, width);
104
- const height = historyHeight(job, width);
105
- const history = job.activity.flatMap((entry) => renderEntry(entry, width));
106
- const maxTop = Math.max(0, history.length - height);
107
- const start = Math.min(top ?? maxTop, maxTop);
108
- const visible = history.slice(start, start + height);
109
- const shown = visible.length
110
- ? visible
251
+ // Fixed rows: header, model, description, rule, counter, plus the failure detail.
252
+ const height = Math.max(0, bodyHeight() - 5 - tools.length - (job.detail ? 1 : 0));
253
+ const view = transcript(job);
254
+ view.sync(messagesOf(job));
255
+ const window = view.window(width, top, height);
256
+ lastWindow = { height, total: window.total };
257
+ const shown = window.lines.length
258
+ ? window.lines
111
259
  : height
112
260
  ? [
113
261
  theme.fg(
@@ -118,25 +266,30 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
118
266
  ),
119
267
  ]
120
268
  : [];
121
- return [
122
- truncateToWidth(
123
- `${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", usageStats(job, elapsedMs(job)))}`,
124
- width,
125
- ),
126
- truncateToWidth(theme.fg("dim", job.model), width),
127
- ...tools,
128
- truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
129
- theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
130
- ...shown,
131
- ...Array(Math.max(0, height - shown.length)).fill(""),
132
- truncateToWidth(
133
- theme.fg(
134
- "dim",
135
- `${visible.length ? `${start + 1}–${start + visible.length}` : "0"}/${history.length}`,
269
+ const counter = window.lines.length
270
+ ? `${window.start + 1}–${window.start + window.lines.length}`
271
+ : "0";
272
+ return (
273
+ [
274
+ truncateToWidth(
275
+ `${statusText(theme, job.status)} ${jobIdentity(theme, job)} ${theme.fg("muted", usageStats(job, elapsedMs(job)))}`,
276
+ width,
136
277
  ),
137
- width,
138
- ),
139
- ].slice(0, bodyHeight());
278
+ truncateToWidth(theme.fg("dim", job.model), width),
279
+ ...tools,
280
+ truncateToWidth(theme.fg("text", theme.bold(job.description)), width),
281
+ theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
282
+ ...shown,
283
+ ...Array(Math.max(0, height - shown.length)).fill(""),
284
+ ...(job.detail
285
+ ? [truncateToWidth(theme.fg(STATUS_COLORS.failed, job.detail), width)]
286
+ : []),
287
+ truncateToWidth(theme.fg("dim", `${counter}/${window.total}`), width),
288
+ ]
289
+ .slice(0, bodyHeight())
290
+ // Pad every row so the pane's right edge holds still while the transcript scrolls.
291
+ .map((line) => truncateToWidth(line, width, "…", true))
292
+ );
140
293
  };
141
294
  stopRedraw = store.subscribe(() => tui.requestRender());
142
295
  return {
@@ -152,6 +305,8 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
152
305
  `${theme.fg(focus === "history" ? "accent" : "muted", focus === "history" ? "[Activity]" : "Activity")}` +
153
306
  theme.fg("dim", ` · ${tally(store.live().length, items)}`),
154
307
  width,
308
+ "…",
309
+ true,
155
310
  );
156
311
  const footer = truncateToWidth(
157
312
  theme.fg(
@@ -159,12 +314,15 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
159
314
  `${hint("tui.select.up", "up")} · ${hint("tui.select.down", "down")} · ${rawKeyHint("←/→", "switch pane")} · ${hint("tui.select.cancel", "close")}`,
160
315
  ),
161
316
  width,
317
+ "…",
318
+ true,
162
319
  );
320
+ const rule = theme.fg("borderMuted", "─".repeat(Math.max(0, width)));
163
321
  if (!selected)
164
322
  return [
165
323
  title,
166
324
  theme.fg("muted", "No delegates in this session."),
167
- ...Array(Math.max(0, tui.terminal.rows - 4)).fill(""),
325
+ ...Array(Math.max(0, tui.terminal.rows - 4)).fill(" ".repeat(Math.max(0, width))),
168
326
  footer,
169
327
  ].slice(0, tui.terminal.rows);
170
328
  const sidebarWidth = Math.min(
@@ -172,34 +330,15 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
172
330
  Math.max(16, Math.floor(width * 0.35)),
173
331
  Math.max(1, width - 2),
174
332
  );
175
- const body = new HStack(
176
- [
177
- {
178
- component: {
179
- render: (w) => renderJobs(w, items, selectedIndex),
180
- invalidate() {},
181
- },
182
- basis: sidebarWidth,
183
- shrink: 0,
184
- },
185
- {
186
- component: { render: (w) => renderHistory(w, selected), invalidate() {} },
187
- basis: 0,
188
- grow: 1,
189
- },
190
- ],
191
- { gap: 1 },
192
- ).render(width);
193
- return [
194
- title,
195
- theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
196
- ...body,
197
- theme.fg("borderMuted", "─".repeat(Math.max(0, width))),
198
- footer,
199
- ].slice(0, tui.terminal.rows);
333
+ const historyWidth = Math.max(1, width - sidebarWidth - 1);
334
+ // HStack measures a child at the full width first, so composing the panes here keeps one render per frame.
335
+ const left = renderJobs(sidebarWidth, items, selectedIndex);
336
+ const right = renderHistory(historyWidth, selected);
337
+ const body = left.map((line, index) => `${line} ${right[index] ?? ""}`);
338
+ return [title, rule, ...body, rule, footer].slice(0, tui.terminal.rows);
200
339
  },
201
340
  invalidate() {
202
- markdown = new WeakMap();
341
+ for (const value of transcripts.values()) value.invalidate();
203
342
  },
204
343
  handleInput(data: string) {
205
344
  if (keys.matches(data, "tui.select.cancel")) done(undefined);
@@ -222,16 +361,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore) {
222
361
  selectedId;
223
362
  top = undefined;
224
363
  } else {
225
- const selected = items.find((item) => item.id === selectedId) ?? items[0];
226
- const length =
227
- selected?.activity.reduce(
228
- (sum, entry) => sum + renderEntry(entry, historyWidth).length,
229
- 0,
230
- ) ?? 0;
231
- const maxTop = Math.max(
232
- 0,
233
- length - (selected ? historyHeight(selected, historyWidth) : 0),
234
- );
364
+ const maxTop = Math.max(0, lastWindow.total - lastWindow.height);
235
365
  const position = Math.max(0, Math.min(maxTop, top ?? maxTop) + (up ? -1 : 1));
236
366
  top = position >= maxTop ? undefined : position;
237
367
  }
package/isolation.ts CHANGED
@@ -46,11 +46,7 @@ function rootOf(iso: IsolationState): string {
46
46
  return resolve(iso.clone, "..", "..", "..");
47
47
  }
48
48
 
49
- /**
50
- * Commits the main tree's current content (committed, uncommitted, and untracked files, honoring
51
- * .gitignore) with the recorded base as parent, through a scratch index so the clone's own checkout
52
- * and index stay untouched. Updates and returns the `main-snapshot` branch.
53
- */
49
+ /** Commits the main tree's current content through a scratch index, so the clone's own checkout and index stay untouched. */
54
50
  function snapshotMainTree(iso: IsolationState, root: string): string {
55
51
  const gitDir = join(iso.clone, ".git");
56
52
  const indexFile = join(gitDir, "pi-delegate-snapshot-index");
@@ -136,9 +132,8 @@ export function removeClone(iso: IsolationState): void {
136
132
  }
137
133
 
138
134
  /**
139
- * Merges the delegate's clone into the main working tree. Base rule: `base` always tracks the newest
140
- * `main-snapshot`, so a repeat apply is correct whether or not the delegate rebased onto it yet.
141
- * The main repository's .git is never written to; only its working tree receives the final patch.
135
+ * Merges the clone into the main working tree. Base rule: `base` tracks the newest `main-snapshot`, so a
136
+ * repeat apply is correct whether or not the delegate rebased onto it yet. Only the main tree is written.
142
137
  */
143
138
  export function applyClone(iso: IsolationState): ApplyResult {
144
139
  const root = rootOf(iso);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deathbeam/pi-delegate",
3
- "version": "0.0.41",
3
+ "version": "0.0.42",
4
4
  "description": "Minimal extension for delegating tasks to subagents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/store.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { ChildActivity, ChildUpdate } from "./child.ts";
1
+ import type { ChildMessage, ChildUpdate } from "./child.ts";
2
+ import { resultPreview, toolCallDetail } from "./format.ts";
2
3
  import type { IsolationState } from "./isolation.ts";
3
4
 
4
5
  export type JobStatus = "running" | "done" | "failed" | "cancelled" | "interrupted";
@@ -15,7 +16,10 @@ export type InspectJob = {
15
16
  startedAt: number;
16
17
  endedAt?: number;
17
18
  status: JobStatus;
18
- activity: ChildActivity[];
19
+ /** The child's transcript, kept in memory only: its session file is the source of truth. */
20
+ messages: ChildMessage[];
21
+ /** The failure detail shown under a finished job's transcript. */
22
+ detail?: string;
19
23
  isolation?: IsolationState;
20
24
  /** Set once an isolated job's clone was applied or discarded, so a steer revive refuses instead of rerunning in the main tree. */
21
25
  cloneClosed?: boolean;
@@ -68,25 +72,11 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
68
72
  const { controller, steer, swapModel, ...rest } = job as InspectJob & Partial<DelegateJob>;
69
73
  return rest;
70
74
  };
71
- /** The serializable form of a job: runtime handles stay out. */
72
- const snapshot = (job: InspectJob): InspectJob => {
73
- const rest = plain(job);
74
- // Copy activity: the live job keeps appending to its own array after the launch snapshot.
75
- return { ...rest, activity: [...rest.activity] };
76
- };
77
- const addActivity = (job: DelegateJob, activity: ChildActivity) => {
78
- const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
79
- job.activity.push(
80
- activity.kind === "assistant" || activity.kind === "user"
81
- ? activity
82
- : {
83
- ...activity,
84
- text: normalize(activity.text),
85
- detail: activity.detail && normalize(activity.detail),
86
- },
87
- );
88
- notify();
89
- };
75
+ /** The serializable form of a job: runtime handles and the transcript stay out. */
76
+ const snapshot = (job: InspectJob): InspectJob => ({
77
+ ...plain(job),
78
+ messages: [],
79
+ });
90
80
 
91
81
  return {
92
82
  /** Every job a view can show: live first, then history. */
@@ -94,8 +84,6 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
94
84
  live: (): DelegateJob[] => [...running.values()],
95
85
  find,
96
86
  snapshot,
97
- /** A row for delegate_list: the snapshot without the activity history a list result never renders. */
98
- summary: (job: InspectJob): InspectJob => ({ ...plain(job), activity: [] }),
99
87
  /** A job by id; the common "unknown delegate job" failure lives here so every tool phrases it alike. */
100
88
  findOrThrow: (id: string): InspectJob => {
101
89
  const job = find(id);
@@ -111,9 +99,20 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
111
99
  },
112
100
  record: (job: DelegateJob, update: ChildUpdate) => {
113
101
  if (job.status !== "running") return;
114
- if (update.toolCalls !== undefined) job.toolCalls = update.toolCalls;
115
- if (update.contextTokens !== undefined) job.contextTokens = update.contextTokens;
116
- if (update.activity) addActivity(job, update.activity);
102
+ let changed = false;
103
+ if (update.toolCalls !== undefined && update.toolCalls !== job.toolCalls) {
104
+ job.toolCalls = update.toolCalls;
105
+ changed = true;
106
+ }
107
+ if (update.contextTokens !== undefined && update.contextTokens !== job.contextTokens) {
108
+ job.contextTokens = update.contextTokens;
109
+ changed = true;
110
+ }
111
+ if (update.message) {
112
+ job.messages.push(update.message);
113
+ changed = true;
114
+ }
115
+ if (changed) notify();
117
116
  },
118
117
  /** Leaves the live set and writes the completion entry; false when the job was cancelled. */
119
118
  finish: (job: DelegateJob, status: JobStatus, detail?: string): boolean => {
@@ -121,8 +120,8 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
121
120
  if (job.controller.signal.aborted) return false;
122
121
  running.delete(job.id);
123
122
  job.status = status;
124
- if (detail) addActivity(job, { kind: "status", text: detail });
125
- commit({ ...snapshot(job), endedAt: Date.now() });
123
+ if (detail) job.detail = detail;
124
+ commit({ ...plain(job), messages: [], endedAt: Date.now() });
126
125
  return true;
127
126
  },
128
127
  /** Appends a corrected entry for a finished job changed after completion (isolation applied, discarded, or re-based). */
@@ -133,7 +132,11 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
133
132
  // Skip live jobs' launch entries (the live set renders them); copy so session entries stay append-only.
134
133
  const restored = restoredJobs(branch)
135
134
  .filter((job) => !running.has(job.id))
136
- .map((job) => ({ ...job }));
135
+ .map((job) => {
136
+ // Drop the legacy activity field: the child's session file owns the transcript.
137
+ const { activity: _legacy, ...rest } = job as InspectJob & { activity?: unknown };
138
+ return { ...rest, messages: [] };
139
+ });
137
140
  // A restored running job no live job owns means the parent crashed; the child exits on its own when
138
141
  // the parent's stdin pipe closes, so only the job state needs fixing.
139
142
  const interrupted = restored.filter((job) => job.status === "running");
@@ -145,7 +148,6 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
145
148
  history.push(...restored);
146
149
  return interrupted;
147
150
  },
148
- /** Drops all jobs and view subscriptions; called on session shutdown. */
149
151
  clear: () => {
150
152
  running.clear();
151
153
  history.length = 0;
@@ -162,8 +164,25 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
162
164
  export type JobStore = ReturnType<typeof createJobStore>;
163
165
 
164
166
  /** The job's latest tool call and its result, once the result arrives. */
165
- export function lastToolCall(job: InspectJob): { tool?: ChildActivity; result?: ChildActivity } {
166
- const at = job.activity.findLastIndex((entry) => entry.kind === "tool");
167
- if (at < 0) return {};
168
- return { tool: job.activity[at], result: job.activity.slice(at + 1).find((entry) => entry.kind === "result") };
167
+ export function lastToolCall(job: InspectJob): {
168
+ tool?: { name: string; detail: string };
169
+ result?: { text?: string; isError?: boolean };
170
+ } {
171
+ for (let i = job.messages.length - 1; i >= 0; i--) {
172
+ const message = job.messages[i]!;
173
+ if (message.role !== "assistant") continue;
174
+ for (let j = message.content.length - 1; j >= 0; j--) {
175
+ const part = message.content[j]!;
176
+ if (part.type !== "toolCall") continue;
177
+ const result = job.messages.find(
178
+ (m): m is Extract<ChildMessage, { role: "toolResult" }> =>
179
+ m.role === "toolResult" && m.toolCallId === part.id,
180
+ );
181
+ return {
182
+ tool: { name: part.name, detail: toolCallDetail(part.name, part.arguments) },
183
+ result: result ? { text: resultPreview(result), isError: result.isError } : undefined,
184
+ };
185
+ }
186
+ }
187
+ return {};
169
188
  }