@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/README.md CHANGED
@@ -44,7 +44,7 @@ Explore the codebase and report relevant paths.
44
44
  ```
45
45
 
46
46
  - `name` is required and must be unique
47
- - `descripion` is required
47
+ - `description` is required
48
48
  - `tools` is optional, a comma-separated list of tool names. Defaults to the session tools.
49
49
  - `model` is optional, a tier name or `provider/model[:thinking]`. Defaults to the session model.
50
50
  - `isolated` is optional, defaults to `false`. See [Isolation](#isolation).
package/agents.ts CHANGED
@@ -80,7 +80,7 @@ function loadAgents(dir: string): AgentFile[] {
80
80
  return agents;
81
81
  }
82
82
 
83
- export function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
83
+ function discoverAgents(cwd: string, configuredDirs: unknown): AgentFile[] {
84
84
  const dirs = [BUNDLED_AGENT_DIR, DEFAULT_AGENT_DIR, ...stringList(configuredDirs)].map((dir) =>
85
85
  expandPath(dir, cwd),
86
86
  );
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, 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 = transcriptText(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) {
@@ -298,22 +273,11 @@ export function runChild(
298
273
  };
299
274
  }
300
275
 
301
- /** Text parts of a message's content, in order. */
302
- function transcriptText(content: unknown): string[] {
303
- if (typeof content === "string") return [content];
304
- if (!Array.isArray(content)) return [];
305
- return content
306
- .map((part) => (part && typeof part === "object" ? (part as { type?: string; text?: string }) : {}))
307
- .filter((part) => part.type === "text" && typeof part.text === "string")
308
- .map((part) => part.text!);
309
- }
310
-
311
276
  /**
312
- * Replays the child's persisted transcript as the activity a revived job continues from, so the
313
- * inspector keeps the old history. A missing or unreadable transcript seeds nothing: the revive
314
- * 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.
315
279
  */
316
- export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
280
+ export function sessionMessages(sessionDir: string, id: string): ChildMessage[] {
317
281
  let sessionFile: string | undefined;
318
282
  try {
319
283
  // Sessions are <timestamp>_<sessionId>.jsonl; a recreated pinned session is the newest one.
@@ -325,54 +289,9 @@ export function priorActivity(sessionDir: string, id: string): ChildActivity[] {
325
289
  return [];
326
290
  }
327
291
  if (!sessionFile) return [];
328
- let lines: string[];
329
292
  try {
330
- lines = readFileSync(join(sessionDir, sessionFile), "utf8").split("\n");
293
+ return SessionManager.open(join(sessionDir, sessionFile)).buildSessionContext().messages;
331
294
  } catch {
332
295
  return [];
333
296
  }
334
- const normalize = (text: string) => text.replace(/\s+/g, " ").trim();
335
- const activity: ChildActivity[] = [];
336
- for (const line of lines) {
337
- if (!line.trim()) continue;
338
- let entry: { type?: string; message?: unknown };
339
- try {
340
- entry = JSON.parse(line);
341
- } catch {
342
- continue; // Same tolerance pi's session reader has for malformed lines.
343
- }
344
- const message =
345
- entry?.type === "message"
346
- ? (entry.message as {
347
- role?: "assistant" | "user" | "toolResult";
348
- content?: unknown;
349
- isError?: boolean;
350
- })
351
- : undefined;
352
- if (!message?.role) continue;
353
- if (message.role === "toolResult") {
354
- const preview = resultPreview({ content: message.content });
355
- activity.push({
356
- kind: "result",
357
- text: normalize(preview ?? ""),
358
- ...(message.isError ? { isError: true } : {}),
359
- });
360
- continue;
361
- }
362
- // Assistant text lands before its tool calls, matching the live event order.
363
- const text = transcriptText(message.content).join("");
364
- if (text) activity.push({ kind: message.role, text });
365
- if (message.role !== "assistant") continue;
366
- for (const part of Array.isArray(message.content) ? message.content : []) {
367
- const call =
368
- part && typeof part === "object" ? (part as { type?: string; name?: string; arguments?: unknown }) : {};
369
- if (call.type !== "toolCall" || !call.name) continue;
370
- activity.push({
371
- kind: "tool",
372
- text: normalize(call.name),
373
- detail: normalize(toolCallDetail(call.name, call.arguments)) || undefined,
374
- });
375
- }
376
- }
377
- return activity;
378
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;
@@ -65,7 +60,6 @@ export const STATUS_COLORS = {
65
60
  const WIDGET_MAX_JOBS = 5;
66
61
  export const COLLAPSED_OUTPUT_LINES = 10;
67
62
  const MAX_OUTPUT_BYTES = 50 * 1024;
68
- const EXPANDED_PAD = " ";
69
63
 
70
64
  /** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
71
65
  function statusIcon(status: JobStatus, now = Date.now()): string {
@@ -81,7 +75,7 @@ export function statusText(theme: Theme, status: JobStatus, now = Date.now()): s
81
75
  /** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
82
76
  export function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
83
77
  if (!job.isolation) return undefined;
84
- return job.cloneClosed || job.status === "running" ? "isolated" : "pending";
78
+ return job.status === "running" ? "isolated" : "pending";
85
79
  }
86
80
 
87
81
  /** `⎇`, warning-colored while the clone's work is still unapplied. */
@@ -130,13 +124,15 @@ export function elapsedMs(job: { startedAt: number; endedAt?: number }, now = Da
130
124
  return (job.endedAt ?? now) - job.startedAt;
131
125
  }
132
126
 
133
- /** Summed wall-clock across jobs; running jobs tick from `now`. Parallel jobs each count their full span. */
134
- export function totalElapsedMs(jobs: { startedAt: number; endedAt?: number }[], now = Date.now()): number {
135
- return jobs.reduce((sum, job) => sum + elapsedMs(job, now), 0);
127
+ export function tally(running: number, all: { startedAt: number; endedAt?: number }[], now = Date.now()): string {
128
+ const total = all.reduce((sum, job) => sum + elapsedMs(job, now), 0);
129
+ return `${running} running · ${all.length} total · ${formatDuration(total)}`;
136
130
  }
137
131
 
138
- export function tally(running: number, all: { startedAt: number; endedAt?: number }[], now = Date.now()): string {
139
- return `${running} running · ${all.length} total · ${formatDuration(totalElapsedMs(all, now))}`;
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];
140
136
  }
141
137
 
142
138
  export function toolCallDetail(toolName: string, args: unknown): string {
@@ -161,12 +157,6 @@ export function toolCallDetail(toolName: string, args: unknown): string {
161
157
  return "";
162
158
  }
163
159
  }
164
-
165
- /** Expanded launch metadata; the call renderer shows the task. */
166
- export function launchDetails(info: { model?: string; tools: string[] }): string[] {
167
- return [`${EXPANDED_PAD}Model: ${info.model ?? "default"}`, `${EXPANDED_PAD}Tools: ${formatTools(info.tools)}`];
168
- }
169
-
170
160
  /** Caps a preview at `maxLines`; callers report the hidden count their own way. */
171
161
  export function capLines<T>(lines: T[], maxLines: number): { shown: T[]; hidden: number } {
172
162
  if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
@@ -190,14 +180,25 @@ export function limitOutput(text: string, maxBytes = MAX_OUTPUT_BYTES): string {
190
180
  return `${buffer.subarray(0, end).toString("utf8")}\n\n[Output truncated: ${buffer.length - end} bytes omitted.]`;
191
181
  }
192
182
 
193
- export function resultPreview(result: unknown, maxChars = 120): string | undefined {
194
- const content = (result as { content?: unknown })?.content;
195
- if (!Array.isArray(content)) return undefined;
196
- const text = content
197
- .map((part) => (part as { type?: string; text?: string }) ?? {})
183
+ /** Caps a diff for storage, keeping the truncation note out of the patch so diff renderers never parse it. */
184
+ export function capDiff(text: string): { diff: string; note?: string } {
185
+ const capped = limitOutput(text);
186
+ if (capped === text) return { diff: text };
187
+ const at = capped.lastIndexOf("\n\n[Output truncated: ");
188
+ return { diff: capped.slice(0, at), note: capped.slice(at + 2) };
189
+ }
190
+
191
+ export function textParts(content: unknown): string[] {
192
+ if (typeof content === "string") return [content];
193
+ if (!Array.isArray(content)) return [];
194
+ return content
195
+ .map((part) => (part && typeof part === "object" ? (part as { type?: string; text?: string }) : {}))
198
196
  .filter((part) => part.type === "text" && typeof part.text === "string")
199
- .map((part) => part.text as string)
200
- .join("\n");
197
+ .map((part) => part.text!);
198
+ }
199
+
200
+ export function resultPreview(result: unknown, maxChars = 120): string | undefined {
201
+ const text = textParts((result as { content?: unknown })?.content).join("\n");
201
202
  const line = text
202
203
  .split("\n")
203
204
  .find((candidate) => candidate.trim())
@@ -211,12 +212,7 @@ export function reviveHint(id: string): string {
211
212
  return `To continue this job, call delegate_steer with id ${id} and a message.`;
212
213
  }
213
214
 
214
- /**
215
- * Converts a git unified diff into pi's own diff format (`+12 content` / `-12 content` / ` 12 content`,
216
- * prefix, padded line number, space, content), which is what pi's renderDiff colors; a raw unified
217
- * diff renders as flat context. Line numbers come from the @@ headers (- uses the old side, + and
218
- * context the new side); the file path heads each file and `...` separates its hunks.
219
- */
215
+ /** Converts a git unified diff into pi's `+12 content` format, which renderDiff colors; a raw unified diff renders flat. */
220
216
  export function piDiff(unified: string): string {
221
217
  const out: string[] = [];
222
218
  let path = "";
@@ -224,7 +220,14 @@ export function piDiff(unified: string): string {
224
220
  let hunkSeen = false;
225
221
  let oldNum = 0;
226
222
  let newNum = 0;
227
- let width = 1;
223
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
224
+ // One width for the whole diff, so hunks and files line up.
225
+ const width = Math.max(
226
+ 1,
227
+ ...[...unified.matchAll(new RegExp(HUNK, "gm"))].map(
228
+ ([, os, oc, ns, nc]) => String(Math.max(+os! + (+oc! || 1), +ns! + (+nc! || 1)) - 1).length,
229
+ ),
230
+ );
228
231
  const header = () => {
229
232
  if (!pathShown) {
230
233
  out.push(path);
@@ -239,16 +242,9 @@ export function piDiff(unified: string): string {
239
242
  hunkSeen = false;
240
243
  continue;
241
244
  }
242
- const hunk = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
245
+ const hunk = HUNK.exec(line);
243
246
  if (hunk) {
244
- const [, oldStart, oldCount, newStart, newCount] = hunk;
245
- // The width comes free from the hunk header's last line number on each side.
246
- width = String(
247
- Math.max(
248
- Number(oldStart) + (Number(oldCount) || 1) - 1,
249
- Number(newStart) + (Number(newCount) || 1) - 1,
250
- ),
251
- ).length;
247
+ const [, oldStart, , newStart] = hunk;
252
248
  header();
253
249
  if (hunkSeen) out.push(` ${"".padStart(width, " ")} ...`);
254
250
  hunkSeen = true;
@@ -279,10 +275,9 @@ export function reportText(report: DelegateReport): string {
279
275
  if (report.error) return `${head} failed: ${report.error}\n${reviveHint(report.id)}`;
280
276
  const output = (report.output ?? "").trim();
281
277
  // The apply hint is for the model only: the transcript renders `output`, so users never see it.
282
- const hint =
283
- report.isolation && !report.cloneClosed
284
- ? `\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.`
285
- : "";
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
+ : "";
286
281
  return `${head} finished.${output ? `\n\n${output}` : ""}${hint}`;
287
282
  }
288
283
 
@@ -383,7 +378,11 @@ export function launchResult(
383
378
  // The call body already carries the task; only the launch metadata is new here.
384
379
  if (expanded)
385
380
  container.addChild(
386
- new Text(theme.fg("muted", launchDetails({ model: details.model, tools: details.tools }).join("\n")), 0, 0),
381
+ new Text(
382
+ theme.fg("muted", ` Model: ${details.model ?? "default"}\n Tools: ${formatTools(details.tools)}`),
383
+ 0,
384
+ 0,
385
+ ),
387
386
  );
388
387
  // Background results arrive as their own message; headless runs still show the output here.
389
388
  if (!details.background && body) appendOutput(container, body, expanded, theme, keyHint);