@deathbeam/pi-delegate 0.0.40 → 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/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");
@@ -116,13 +112,17 @@ export function cloneCwd(iso: IsolationState, cwd: string): string {
116
112
  /** Clone location plus a stat of everything the delegate changed, for the job's report. */
117
113
  export function isolationSummary(iso: IsolationState): string {
118
114
  const lines = [`Isolated clone: ${iso.clone}`];
115
+ const indexFile = join(iso.clone, ".git", "pi-delegate-summary-index");
119
116
  try {
120
- // Staging first pulls uncommitted and untracked changes into the stat.
121
- git(["add", "-A"], { cwd: iso.clone });
122
- const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone }).trimEnd();
117
+ // A scratch index stages uncommitted and untracked changes for the stat without touching the clone's own index.
118
+ git(["read-tree", "HEAD"], { cwd: iso.clone, indexFile });
119
+ git(["add", "-A"], { cwd: iso.clone, indexFile });
120
+ const stat = git(["diff", "--stat", iso.base], { cwd: iso.clone, indexFile }).trimEnd();
123
121
  if (stat) lines.push(`Changes in this clone:\n${stat}`);
124
122
  } catch {
125
123
  // The clone may already be applied or gone; the path alone still says where the work lives.
124
+ } finally {
125
+ rmSync(indexFile, { force: true });
126
126
  }
127
127
  return lines.join("\n");
128
128
  }
@@ -132,9 +132,8 @@ export function removeClone(iso: IsolationState): void {
132
132
  }
133
133
 
134
134
  /**
135
- * Merges the delegate's clone into the main working tree. Base rule: `base` always tracks the newest
136
- * `main-snapshot`, so a repeat apply is correct whether or not the delegate rebased onto it yet.
137
- * 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.
138
137
  */
139
138
  export function applyClone(iso: IsolationState): ApplyResult {
140
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.40",
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;
@@ -57,26 +61,22 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
57
61
  const stale = history.findIndex((item) => item.id === id);
58
62
  if (stale >= 0) history.splice(stale, 1);
59
63
  };
60
- const find = (id: string) => running.get(id) ?? history.find((item) => item.id === id);
61
- /** The serializable form of a job: runtime handles stay out. */
62
- const snapshot = (job: InspectJob): InspectJob => {
63
- const { controller, steer, swapModel, ...plain } = job as InspectJob & Partial<DelegateJob>;
64
- // Copy activity: the live job keeps appending to its own array after the launch snapshot.
65
- return { ...plain, activity: [...plain.activity] };
66
- };
67
- const addActivity = (job: DelegateJob, activity: ChildActivity) => {
68
- const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
69
- job.activity.push(
70
- activity.kind === "assistant" || activity.kind === "user"
71
- ? activity
72
- : {
73
- ...activity,
74
- text: normalize(activity.text),
75
- detail: activity.detail && normalize(activity.detail),
76
- },
77
- );
64
+ const commit = (entry: InspectJob) => {
65
+ drop(entry.id);
66
+ history.unshift(entry);
67
+ append(JOB_ENTRY, snapshot(entry));
78
68
  notify();
79
69
  };
70
+ const find = (id: string) => running.get(id) ?? history.find((item) => item.id === id);
71
+ const plain = (job: InspectJob) => {
72
+ const { controller, steer, swapModel, ...rest } = job as InspectJob & Partial<DelegateJob>;
73
+ return rest;
74
+ };
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
+ });
80
80
 
81
81
  return {
82
82
  /** Every job a view can show: live first, then history. */
@@ -99,9 +99,20 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
99
99
  },
100
100
  record: (job: DelegateJob, update: ChildUpdate) => {
101
101
  if (job.status !== "running") return;
102
- if (update.toolCalls !== undefined) job.toolCalls = update.toolCalls;
103
- if (update.contextTokens !== undefined) job.contextTokens = update.contextTokens;
104
- 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();
105
116
  },
106
117
  /** Leaves the live set and writes the completion entry; false when the job was cancelled. */
107
118
  finish: (job: DelegateJob, status: JobStatus, detail?: string): boolean => {
@@ -109,28 +120,23 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
109
120
  if (job.controller.signal.aborted) return false;
110
121
  running.delete(job.id);
111
122
  job.status = status;
112
- if (detail) addActivity(job, { kind: "status", text: detail });
113
- const entry: InspectJob = { ...snapshot(job), endedAt: Date.now() };
114
- drop(entry.id);
115
- history.unshift(entry);
116
- append(JOB_ENTRY, entry);
117
- notify();
123
+ if (detail) job.detail = detail;
124
+ commit({ ...plain(job), messages: [], endedAt: Date.now() });
118
125
  return true;
119
126
  },
120
127
  /** Appends a corrected entry for a finished job changed after completion (isolation applied, discarded, or re-based). */
121
- save: (job: InspectJob) => {
122
- drop(job.id);
123
- history.unshift(job);
124
- append(JOB_ENTRY, snapshot(job));
125
- notify();
126
- },
128
+ save: (job: InspectJob) => commit(job),
127
129
  /** Rebuilds history from the branch and returns the jobs it marked interrupted. */
128
130
  restore: (branch: readonly unknown[]): InspectJob[] => {
129
131
  history.length = 0;
130
132
  // Skip live jobs' launch entries (the live set renders them); copy so session entries stay append-only.
131
133
  const restored = restoredJobs(branch)
132
134
  .filter((job) => !running.has(job.id))
133
- .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
+ });
134
140
  // A restored running job no live job owns means the parent crashed; the child exits on its own when
135
141
  // the parent's stdin pipe closes, so only the job state needs fixing.
136
142
  const interrupted = restored.filter((job) => job.status === "running");
@@ -142,7 +148,6 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
142
148
  history.push(...restored);
143
149
  return interrupted;
144
150
  },
145
- /** Drops all jobs and view subscriptions; called on session shutdown. */
146
151
  clear: () => {
147
152
  running.clear();
148
153
  history.length = 0;
@@ -159,8 +164,25 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
159
164
  export type JobStore = ReturnType<typeof createJobStore>;
160
165
 
161
166
  /** The job's latest tool call and its result, once the result arrives. */
162
- export function lastToolCall(job: InspectJob): { tool?: ChildActivity; result?: ChildActivity } {
163
- const at = job.activity.findLastIndex((entry) => entry.kind === "tool");
164
- if (at < 0) return {};
165
- 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 {};
166
188
  }