@maheidem/pi-delegate 0.1.0 → 0.1.2

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/application.ts CHANGED
@@ -29,8 +29,10 @@ import type {
29
29
  RunInspection,
30
30
  RunMetadataV1,
31
31
  RunnerOutcome,
32
+ TranscriptRecordV1,
32
33
  SessionEntryLike,
33
34
  } from "./types.ts";
35
+ import { decodeTranscriptRecord } from "./types.ts";
34
36
  import { normalizeConfig, saveConfig, type DelegateConfigV1 } from "./config.ts";
35
37
  import { EMPTY_USAGE } from "./types.ts";
36
38
  import { isRoleName, resolveRole, rolePromptExists, DELEGATE_ROLES } from "./roles.ts";
@@ -295,7 +297,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
295
297
  if (!metadata) throw Object.assign(new Error(`Unknown run id '${id}'.`), { code: "E_RUN_NOT_FOUND" });
296
298
  const inspection: RunInspection = { metadata };
297
299
  if (includeTranscript) {
298
- inspection.transcriptPreview = boundedPreview(metadata.transcriptPath, 12000);
300
+ inspection.transcriptPreview = transcriptPreview(metadata.transcriptPath, 12000);
299
301
  inspection.stderrPreview = boundedPreview(metadata.stderrPath, 4000);
300
302
  }
301
303
  return inspection;
@@ -460,6 +462,42 @@ function isTerminal(state: string): boolean {
460
462
  return ["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(state);
461
463
  }
462
464
 
465
+ /**
466
+ * Read a transcript envelope back as readable text: decode each record
467
+ * (UTF-8 `raw`, or base64 fallback for non-UTF-8 evidence), bounded.
468
+ */
469
+ function transcriptPreview(filePath: string, maxChars: number): string {
470
+ try {
471
+ const buf = fs.readFileSync(filePath);
472
+ if (buf.length > 200_000) {
473
+ // Bound the work on huge transcripts: decode the newest records.
474
+ const lines = buf.toString("utf8").split("\n");
475
+ const tail = lines.slice(-Math.max(1, Math.floor(200_000 / 200))).filter((l) => l.trim());
476
+ return decodeTranscriptLines(tail, maxChars, tail.length < lines.filter((l) => l.trim()).length);
477
+ }
478
+ const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
479
+ return decodeTranscriptLines(lines, maxChars, false);
480
+ } catch {
481
+ return "";
482
+ }
483
+ }
484
+
485
+ function decodeTranscriptLines(lines: string[], maxChars: number, hadMore: boolean): string {
486
+ const decoded = lines
487
+ .map((line) => {
488
+ try {
489
+ const rec = JSON.parse(line) as TranscriptRecordV1;
490
+ return decodeTranscriptRecord(rec);
491
+ } catch {
492
+ return line; // non-envelope line kept verbatim
493
+ }
494
+ })
495
+ .filter((t) => t.length > 0);
496
+ let text = decoded.join("\n");
497
+ if (text.length > maxChars) text = `${text.slice(0, maxChars)}\n… [truncated]`;
498
+ return hadMore ? `… [earlier records omitted]\n${text}` : text;
499
+ }
500
+
463
501
  function boundedPreview(filePath: string, maxBytes: number): string {
464
502
  try {
465
503
  const buf = fs.readFileSync(filePath);
package/index.ts CHANGED
@@ -41,6 +41,78 @@ import { RunningView, type RunningViewState } from "./ui/running-view.ts";
41
41
  /** Stable command-driven handoff custom message type (§6.4). */
42
42
  const HANDOFF_CUSTOM_TYPE = "delegate-handoff";
43
43
 
44
+ /**
45
+ * Compact expanded view of a finished run for the TUI: Outcome section,
46
+ * first lines of Changes/Verification/Risks, and the child's last actions.
47
+ * Pure string → string so it is unit-testable without a Pi session.
48
+ */
49
+ export function formatRunSummary(
50
+ res: DelegateRunResult,
51
+ options?: { maxLines?: number },
52
+ ): string {
53
+ const maxLines = options?.maxLines ?? 14;
54
+ const d = res.details;
55
+ const lines: string[] = [];
56
+
57
+ if (!res.ok) {
58
+ const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
59
+ lines.push(`error: ${err}`);
60
+ } else {
61
+ const handoffLines = res.handoff.split("\n");
62
+ const sections: Array<{ name: string; lines: string[] }> = [];
63
+ for (const line of handoffLines) {
64
+ const h = /^##\s+(.*)$/.exec(line);
65
+ if (h) {
66
+ sections.push({ name: h[1].trim(), lines: [] });
67
+ } else if (sections.length > 0) {
68
+ sections[sections.length - 1].lines.push(line);
69
+ }
70
+ }
71
+ if (sections.length === 0) {
72
+ // No structured headings — show the first few non-empty lines.
73
+ let shown = 0;
74
+ for (const line of handoffLines) {
75
+ if (!line.trim()) continue;
76
+ lines.push(line);
77
+ if (++shown >= 6) break;
78
+ }
79
+ } else {
80
+ for (const s of sections) {
81
+ lines.push(`## ${s.name}`);
82
+ if (s.name === "Outcome") {
83
+ lines.push(...s.lines);
84
+ } else {
85
+ let kept = 0;
86
+ for (const line of s.lines) {
87
+ if (!line.trim()) continue;
88
+ lines.push(line);
89
+ if (++kept >= 2) break;
90
+ }
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ const actions = (d.displayItems ?? [])
97
+ .map((i) => (i.type === "text" ? i.text : `tool ${i.name}`))
98
+ .filter(Boolean);
99
+ if (actions.length > 0) {
100
+ lines.push("", "last actions:");
101
+ for (const action of actions.slice(-5)) lines.push(` · ${action}`);
102
+ }
103
+
104
+ if (d.outputTruncated || d.stderrPath) {
105
+ lines.push("", `[Full transcript: ${d.transcriptPath}]`);
106
+ }
107
+
108
+ const out = lines.join("\n").split("\n");
109
+ if (out.length > maxLines) {
110
+ const head = out.slice(0, Math.max(1, maxLines - 1));
111
+ return [...head, `… (${out.length - head.length} more lines — see transcript)`].join("\n");
112
+ }
113
+ return out.join("\n");
114
+ }
115
+
44
116
  export default function delegateExtension(pi: ExtensionAPI) {
45
117
  // 1. The child never reactivates this extension (POL: no recursion).
46
118
  if (process.env.PI_DELEGATE_CHILD === "1") return;
@@ -239,20 +311,29 @@ export default function delegateExtension(pi: ExtensionAPI) {
239
311
  return new Text(theme?.fg ? theme.fg("accent", text) : text, 0, 0);
240
312
  },
241
313
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
242
- renderResult(result: any, _options: any, theme: any) {
243
- const d = result.details as { runId?: string; role?: string; state?: string; usage?: { input?: number; output?: number; cost?: number }; outputTruncated?: boolean; transcriptPath?: string } | undefined;
314
+ renderResult(result: any, options: any, theme: any) {
315
+ const d = result.details as DelegateDetails | undefined;
244
316
  if (!d?.runId) {
245
317
  const text = (result.content ?? []).map((c: { text?: string }) => c.text ?? "").filter(Boolean).join("\n");
246
318
  return new Text(text || "(no output)", 0, 0);
247
319
  }
320
+ const fg = (kind: string, s: string) => (theme?.fg ? theme.fg(kind, s) : s);
248
321
  const u = d.usage ?? {};
249
322
  const bits: string[] = [`${d.role ?? "?"} · ${d.state ?? "?"}`];
250
323
  if (u.input) bits.push(`↑${u.input}`);
251
324
  if (u.output) bits.push(`↓${u.output}`);
252
325
  if (u.cost) bits.push(`$${u.cost.toFixed(4)}`);
253
326
  const header = `→ ${d.runId}`;
254
- const body = bits.join(" ") + (d.outputTruncated && d.transcriptPath ? `\ntranscript: ${d.transcriptPath}` : "");
255
- return new Text(theme?.fg ? `${theme.fg("accent", header)}\n${body}` : `${header}\n${body}`, 0, 0);
327
+ if (!options?.expanded) {
328
+ const body = bits.join(" ") + (d.outputTruncated && d.transcriptPath ? `\ntranscript: ${d.transcriptPath}` : "");
329
+ return new Text(`${fg("accent", header)}\n${body}`, 0, 0);
330
+ }
331
+ // Expanded: compact summary — Outcome + key lines + last actions.
332
+ const res = result as unknown as DelegateRunResult;
333
+ const summary = formatRunSummary(res);
334
+ const stateColor = d.state === "succeeded" ? "success" : d.state === "cancelled" ? "muted" : "warning";
335
+ const body = bits.join(" ") + (summary ? `\n${summary}` : "");
336
+ return new Text(`${fg("accent", header)}\n${fg(stateColor, body)}`, 0, 0);
256
337
  },
257
338
  });
258
339
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/rpc-jsonl.ts CHANGED
@@ -23,7 +23,7 @@ export interface RpcRecord {
23
23
  export type RpcRecordClassification =
24
24
  | { kind: "prompt_response"; ok: boolean; id: string }
25
25
  | { kind: "message_end"; stopReason?: string }
26
- | { kind: "tool_event"; phase: "start" | "update" | "end"; toolName?: string }
26
+ | { kind: "tool_event"; phase: "start" | "update" | "end"; toolName?: string; args?: Record<string, unknown> }
27
27
  | { kind: "agent_settled" }
28
28
  | { kind: "agent_end" }
29
29
  | { kind: "extension_ui_request"; id: string }
@@ -39,6 +39,10 @@ export interface RpcParserOptions {
39
39
  }
40
40
 
41
41
  export const DEFAULT_MAX_RECORD_BYTES = 8 * 1024 * 1024; // 8 MiB
42
+
43
+ function isArgsObject(value: unknown): value is Record<string, unknown> {
44
+ return !!value && typeof value === "object" && !Array.isArray(value);
45
+ }
42
46
  export const DEFAULT_MALFORMED_THRESHOLD = 10;
43
47
 
44
48
  export class RpcJsonlParser {
@@ -145,6 +149,7 @@ export function classifyRpcRecord(record: RpcRecord): RpcRecordClassification {
145
149
  kind: "tool_event",
146
150
  phase: "start",
147
151
  toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
152
+ args: isArgsObject(obj.args) ? (obj.args as Record<string, unknown>) : undefined,
148
153
  };
149
154
  case "tool_execution_update":
150
155
  return {
package/run-store.ts CHANGED
@@ -128,13 +128,26 @@ export function appendTranscriptRecord(
128
128
  receivedAt: string,
129
129
  rawBytes: Buffer,
130
130
  ): void {
131
- const record: TranscriptRecordV1 = {
132
- schemaVersion: 1,
133
- sequence,
134
- receivedAt,
135
- stream: "stdout",
136
- rawBase64: rawBytes.toString("base64"),
137
- };
131
+ let record: TranscriptRecordV1;
132
+ try {
133
+ // Normal case: the child emits valid UTF-8 JSON — keep it readable.
134
+ record = {
135
+ schemaVersion: 1,
136
+ sequence,
137
+ receivedAt,
138
+ stream: "stdout",
139
+ raw: new TextDecoder("utf-8", { fatal: true }).decode(rawBytes),
140
+ };
141
+ } catch {
142
+ // Non-UTF-8 evidence is preserved verbatim, never dropped.
143
+ record = {
144
+ schemaVersion: 1,
145
+ sequence,
146
+ receivedAt,
147
+ stream: "stdout",
148
+ rawBase64: rawBytes.toString("base64"),
149
+ };
150
+ }
138
151
  const line = JSON.stringify(record) + "\n";
139
152
  const fd = (stdoutStream as unknown as { fd: number | null }).fd;
140
153
  if (typeof fd === "number") {
package/runner.ts CHANGED
@@ -408,7 +408,7 @@ export class DelegateRunner {
408
408
  }
409
409
  case "tool_event":
410
410
  if (cls.phase === "start" && cls.toolName) {
411
- this.pushAction(`tool ${cls.toolName}`);
411
+ this.pushAction(describeToolAction(cls.toolName, cls.args));
412
412
  this.pushUpdate(`tool:${cls.toolName}`);
413
413
  }
414
414
  break;
@@ -769,3 +769,38 @@ export class DelegateRunner {
769
769
  }
770
770
  }
771
771
  }
772
+
773
+
774
+ /**
775
+ * Display-safe one-liner for a child tool call (never fed to the model).
776
+ * Keeps at most ~100 visible chars; args are user-visible command/path
777
+ * values from the child's own session.
778
+ */
779
+ export function describeToolAction(toolName: string, args?: Record<string, unknown>): string {
780
+ const a = (key: string): string => {
781
+ const v = args?.[key];
782
+ return typeof v === "string" ? v : "";
783
+ };
784
+ let detail = "";
785
+ switch (toolName) {
786
+ case "bash":
787
+ detail = a("command");
788
+ break;
789
+ case "read":
790
+ case "write":
791
+ case "edit":
792
+ detail = a("path");
793
+ break;
794
+ case "grep":
795
+ case "find":
796
+ detail = [a("pattern"), a("path")].filter(Boolean).join(" ");
797
+ break;
798
+ case "ls":
799
+ detail = a("path") || a("command");
800
+ break;
801
+ default:
802
+ detail = "";
803
+ }
804
+ const text = detail ? `${toolName} ${detail}` : toolName;
805
+ return text.length > 100 ? `${text.slice(0, 97)}…` : text;
806
+ }
package/types.ts CHANGED
@@ -195,7 +195,17 @@ export interface TranscriptRecordV1 {
195
195
  sequence: number;
196
196
  receivedAt: string;
197
197
  stream: "stdout";
198
- rawBase64: string;
198
+ /** UTF-8 text of the raw record (the normal case — readable). */
199
+ raw?: string;
200
+ /** Base64 fallback when the bytes are not valid UTF-8. */
201
+ rawBase64?: string;
202
+ }
203
+
204
+ /** Decode a captured transcript record back to its original text. */
205
+ export function decodeTranscriptRecord(record: TranscriptRecordV1): string {
206
+ if (typeof record.raw === "string") return record.raw;
207
+ if (typeof record.rawBase64 === "string") return Buffer.from(record.rawBase64, "base64").toString("utf8");
208
+ return "";
199
209
  }
200
210
 
201
211
  export interface DelegatePaths {