@maheidem/pi-delegate 0.2.0 → 0.2.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/README.md CHANGED
@@ -118,6 +118,29 @@ Consequences worth internalizing:
118
118
  than blamed on the provider, and the stderr tail is no longer presented as
119
119
  the cause.
120
120
 
121
+ ### Concurrent calls queue (fan-out just works)
122
+
123
+ Models naturally issue several `delegate` calls in one turn. Pi executes
124
+ them truly in parallel; delegate runs **one child at a time** and places
125
+ concurrent calls in a bounded FIFO queue (`queueLimit`, default 3): a 4-way
126
+ fan-out becomes 4 back-to-back children and 4 real results — no error
127
+ storm. Aborting a still-queued call removes it (resolved as `cancelled`,
128
+ never spawned). Beyond the limit the call fails fast with an instructive
129
+ `E_DELEGATE_BUSY` ("wait for the in-flight results, then re-issue").
130
+ `/delegate status` shows the queue depth.
131
+
132
+ ### Watching a child work: the live feed and `/delegate peek`
133
+
134
+ - **Foreground `/delegate run` (TUI)** opens a live feed panel: identity
135
+ (`role · model · elapsed · turn N · ↑in ↓out`), an elapsed-vs-hard-cap
136
+ progress bar, in-flight tools, and a scrolling one-line-per-event feed of
137
+ the child's activity — `▶ bash npm test` → `✓ … (38s)`, `✎` assistant
138
+ lines, `⚠` provider errors, `▣` handoff submissions. Escape twice cancels.
139
+ - **`/delegate peek [run-id]`** opens the same feed decoded from the run's
140
+ captured transcript — live-following (`● live`) while the run is active,
141
+ scrollable (`j`/`k`, `f` re-follow, `q` close), and equally useful
142
+ post-mortem on any finished run. Headless/print mode prints the tail.
143
+
121
144
  ### The mandatory structured handoff (protocol, not prompt)
122
145
 
123
146
  Anything the harness NEEDS from the child is a validated protocol step —
package/application.ts CHANGED
@@ -64,6 +64,18 @@ interface ActiveRunReservation {
64
64
  startedAt: string;
65
65
  }
66
66
 
67
+ /**
68
+ * A concurrent delegate call waiting for the single child slot. Pi executes
69
+ * parallel tool calls truly in parallel and models routinely fan out — the
70
+ * queue serializes those calls on the one-child policy instead of failing
71
+ * them: a 4-way fan-out becomes 4 back-to-back children and 4 real results.
72
+ */
73
+ interface QueuedRun {
74
+ request: DelegateRequest;
75
+ hooks: RunHooks;
76
+ resolve: (result: RunAttemptResult) => void;
77
+ }
78
+
67
79
  function errorResult(
68
80
  runId: string,
69
81
  role: RoleName,
@@ -98,6 +110,7 @@ function errorResult(
98
110
 
99
111
  export class DelegateApplicationImpl implements DelegateApplication {
100
112
  private activeRun: ActiveRunReservation | null = null;
113
+ private runQueue: QueuedRun[] = [];
101
114
  private readonly modeRuntime: ModeRuntime;
102
115
  private readonly ports: DelegateApplicationPorts;
103
116
  private liveConfig: DelegateConfigV1;
@@ -183,24 +196,57 @@ export class DelegateApplicationImpl implements DelegateApplication {
183
196
  }
184
197
 
185
198
  /**
186
- * Canonical run entry point shared by tool and command. Reservation is
187
- * synchronous before the first await (POL-005).
199
+ * Canonical entry point shared by tool and command. ONE child executes at
200
+ * a time (POL-005): concurrent calls queue (bounded by `queueLimit`) and
201
+ * run back-to-back — models fan out, and the queue turns that into
202
+ * serialized results instead of an error storm.
188
203
  */
189
204
  async run(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
190
- // 1. Synchronous reservation BEFORE any await.
191
205
  if (this.activeRun) {
192
- return {
193
- ok: false,
194
- busy: true,
195
- runId: this.activeRun.id,
196
- role: this.activeRun.role,
197
- message: `Delegation is busy with run ${this.activeRun.id} (${this.activeRun.role}).`,
198
- error: {
199
- code: "E_DELEGATE_BUSY",
200
- message: `Active run ${this.activeRun.id} (${this.activeRun.role}). Inspect, cancel, or wait.`,
201
- },
202
- };
206
+ if (this.runQueue.length >= this.liveConfig.queueLimit) {
207
+ return {
208
+ ok: false,
209
+ busy: true,
210
+ runId: this.activeRun.id,
211
+ role: this.activeRun.role,
212
+ message: `Delegation queue is full (${this.runQueue.length} waiting) while run ${this.activeRun.id} (${this.activeRun.role}) executes.`,
213
+ error: {
214
+ code: "E_DELEGATE_BUSY",
215
+ message: `Queue full (${this.runQueue.length} waiting; limit ${this.liveConfig.queueLimit}); active run ${this.activeRun.id} (${this.activeRun.role}). Wait for the in-flight results, then re-issue.`,
216
+ },
217
+ };
218
+ }
219
+ return await new Promise<RunAttemptResult>((resolve) => {
220
+ const entry: QueuedRun = { request, hooks, resolve };
221
+ // Aborting a STILL-QUEUED call removes it (the runner wires
222
+ // the signal only once spawned); once started, the runner
223
+ // owns cancellation through the same signal.
224
+ const onAbort = () => {
225
+ const idx = this.runQueue.indexOf(entry);
226
+ if (idx >= 0) {
227
+ this.runQueue.splice(idx, 1);
228
+ resolve(
229
+ errorResult("", request.role, "E_CANCELLED", "aborted before start (queued call cancelled)", {
230
+ state: "cancelled",
231
+ }),
232
+ );
233
+ }
234
+ };
235
+ if (hooks.abortSignal) {
236
+ if (hooks.abortSignal.aborted) {
237
+ onAbort();
238
+ return;
239
+ }
240
+ hooks.abortSignal.addEventListener("abort", onAbort, { once: true });
241
+ }
242
+ this.runQueue.push(entry);
243
+ });
203
244
  }
245
+ return await this.startRun(request, hooks);
246
+ }
247
+
248
+ /** Execute one run in the free slot (reservation stays synchronous). */
249
+ private async startRun(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
204
250
 
205
251
  const agentDir = this.ports.agentDir;
206
252
  // Config cascade: project .pi/delegate/config.json overlays the
@@ -346,9 +392,29 @@ export class DelegateApplicationImpl implements DelegateApplication {
346
392
  } catch (error) {
347
393
  this.activeRun = null;
348
394
  return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
395
+ } finally {
396
+ this.startNextQueuedRun();
349
397
  }
350
398
  }
351
399
 
400
+ /** Queued-call introspection for status views. */
401
+ queuedRunCount(): number {
402
+ return this.runQueue.length;
403
+ }
404
+
405
+ queueLimit(): number {
406
+ return this.liveConfig.queueLimit;
407
+ }
408
+
409
+ /** Pop the next queued run (if any) into the free slot, fire-and-forget. */
410
+ private startNextQueuedRun(): void {
411
+ const next = this.runQueue.shift();
412
+ if (!next) return;
413
+ void this.startRun(next.request, next.hooks).then(next.resolve, (error: unknown) => {
414
+ next.resolve(errorResult("", next.request.role, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`));
415
+ });
416
+ }
417
+
352
418
  /** Cancel the active run (default) or an exact run ID. */
353
419
  async cancel(runId?: string): Promise<CancelResult> {
354
420
  const active = this.activeRun;
package/commands.ts CHANGED
@@ -20,6 +20,7 @@ export type DelegateIntent =
20
20
  | { kind: "cancel"; runId?: string }
21
21
  | { kind: "inspect"; runId?: string }
22
22
  | { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
23
+ | { kind: "peek"; runId?: string }
23
24
  | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number }
24
25
  | { kind: "invalid"; token: string; usage: string };
25
26
 
@@ -32,6 +33,7 @@ export const DELEGATE_USAGE = [
32
33
  "/delegate doctor diagnostics (no LLM call)",
33
34
  "/delegate cancel [run-id] cancel the active (or matching) run",
34
35
  "/delegate resume <run-id> <task...> continue a prior run's child session",
36
+ "/delegate peek [run-id] live/final feed of a run's child activity",
35
37
  "/delegate inspect [run-id] show run metadata (defaults to latest)",
36
38
  "/delegate run <general|research> <task...> run with an explicit role",
37
39
  "/delegate research <task...> research-role shorthand",
@@ -51,6 +53,7 @@ const RESERVED_FIRST_TOKENS = new Set([
51
53
  "cancel",
52
54
  "inspect",
53
55
  "resume",
56
+ "peek",
54
57
  "run",
55
58
  "research",
56
59
  ]);
@@ -94,6 +97,10 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
94
97
  const rest = trimmed.slice("inspect".length).trim();
95
98
  return { kind: "inspect", runId: rest || undefined };
96
99
  }
100
+ case "peek": {
101
+ const rest = trimmed.slice("peek".length).trim();
102
+ return { kind: "peek", runId: rest || undefined };
103
+ }
97
104
  case "resume": {
98
105
  const rest = trimmed.slice("resume".length).trim();
99
106
  if (!rest) return invalid("resume");
@@ -136,7 +143,7 @@ function invalid(token: string): DelegateIntent {
136
143
  export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
137
144
  const words = (prefix ?? "").trimStart();
138
145
  const tokens = words.split(/\s+/);
139
- const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "inspect ", "resume ", "run ", "research "];
146
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "inspect ", "resume ", "peek ", "run ", "research "];
140
147
 
141
148
  const matches: string[] = [];
142
149
  if (tokens.length <= 1) {
@@ -150,7 +157,7 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
150
157
  for (const role of ROLE_NAMES) {
151
158
  if (role.startsWith(p)) matches.push(`${role} `);
152
159
  }
153
- } else if (tokens[0] === "cancel" || tokens[0] === "inspect" || tokens[0] === "resume") {
160
+ } else if (tokens[0] === "cancel" || tokens[0] === "inspect" || tokens[0] === "resume" || tokens[0] === "peek") {
154
161
  const p = tokens[1] ?? "";
155
162
  for (const id of recentRunIds) {
156
163
  if (id.startsWith(p)) matches.push(`${id} `);
package/config.ts CHANGED
@@ -20,6 +20,8 @@ export interface DelegateConfigV1 {
20
20
  handoffGraceMs: number;
21
21
  /** Bounded wait for the mandatory-handoff enforcement answer (default 60 s). */
22
22
  handoffEnforceTimeoutMs: number;
23
+ /** Concurrent calls beyond the active child wait in this FIFO queue. */
24
+ queueLimit: number;
23
25
  /** R1: watchdog budget while a tool call is in flight (default: hard). */
24
26
  stuckToolTimeoutMs?: number;
25
27
  maxRuns: number;
@@ -37,6 +39,7 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
37
39
  killGraceMs: 5_000,
38
40
  handoffGraceMs: 90_000,
39
41
  handoffEnforceTimeoutMs: 60_000,
42
+ queueLimit: 3,
40
43
  stuckToolTimeoutMs: undefined,
41
44
  maxRuns: 50,
42
45
  maxRunAgeDays: 30,
@@ -51,6 +54,7 @@ const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
51
54
  killGraceMs: 100,
52
55
  handoffGraceMs: 1_000,
53
56
  handoffEnforceTimeoutMs: 1_000,
57
+ queueLimit: 0,
54
58
  stuckToolTimeoutMs: 1_000,
55
59
  maxRuns: 1,
56
60
  maxRunAgeDays: 1,
@@ -65,6 +69,7 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
65
69
  killGraceMs: 60_000,
66
70
  handoffGraceMs: 600_000,
67
71
  handoffEnforceTimeoutMs: 600_000,
72
+ queueLimit: 20,
68
73
  stuckToolTimeoutMs: 604_800_000,
69
74
  maxRuns: 10_000,
70
75
  maxRunAgeDays: 3650,
package/index.ts CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  import { Text } from "@earendil-works/pi-tui";
23
23
 
24
24
  import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
25
+ import * as fsSync from "node:fs";
25
26
  import { delegateVersion } from "./version.ts";
26
27
  import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
27
28
  import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
@@ -39,6 +40,8 @@ import type {
39
40
  } from "./types.ts";
40
41
  import { SettingsPanel, type PanelSnapshot, type PanelActionResult } from "./ui/settings-panel.ts";
41
42
  import { RunningView, type RunningViewState } from "./ui/running-view.ts";
43
+ import { PeekView } from "./ui/peek-view.ts";
44
+ import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
42
45
 
43
46
  /** Stable command-driven handoff custom message type (§6.4). */
44
47
  const HANDOFF_CUSTOM_TYPE = "delegate-handoff";
@@ -300,6 +303,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
300
303
  if (!res.ok) {
301
304
  const parts = [head];
302
305
  const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
306
+ if (d.state === "cancelled") {
307
+ // A cancellation is user intent, not a failure — neutral line,
308
+ // plus the resume path when a durable session exists.
309
+ parts.push(`cancelled — ${res.error?.message ?? "aborted"}; no handoff.`);
310
+ if (d.sessionPath) parts.push(`resume: re-issue with resumeFrom: ${d.runId} to continue in the same child context.`);
311
+ if (res.details.partialHandoff) parts.push("", "partial handoff (captured at kill):", res.details.partialHandoff);
312
+ if (res.modelNote) parts.push(`note: ${res.modelNote}`);
313
+ parts.push(`transcript: ${d.transcriptPath}`);
314
+ return parts.join("\n");
315
+ }
303
316
  parts.push(`error: ${err}`);
304
317
  // R2: the killed child's own account of its partial work.
305
318
  if (res.details.partialHandoff) {
@@ -366,6 +379,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
366
379
  "Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
367
380
  "Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
368
381
  "Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
382
+ "Parallel delegate calls are fine: they queue and run back-to-back (one child at a time) — every call gets a real result; do not re-issue on 'queue full', wait for the in-flight results instead.",
369
383
  "A timed-out run leaves a partialHandoff, a git checkpoint and a resumable child session: pass resumeFrom: <runId> to continue in the same context instead of re-explaining, and inspect the receipt's gitDelta before repairing anything.",
370
384
  "Pin model: 'provider/model-id' when the child must not silently follow the parent's current model (e.g. after a mid-session model fallback).",
371
385
  "For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
@@ -498,7 +512,20 @@ export default function delegateExtension(pi: ExtensionAPI) {
498
512
  role: request.role,
499
513
  phase: "starting",
500
514
  elapsedMs: 0,
501
- lastActions: [],
515
+ feedLines: [],
516
+ };
517
+ // Live feed: every child event lands in the ring; the panel renders
518
+ // the bounded tail on each host refresh (1 s + event-driven).
519
+ const feed = new FeedRing(120);
520
+ let feedStartMs = 0;
521
+ let hardMs: number | undefined;
522
+ const feedLines = (): string[] => {
523
+ if (feed.all().length === 0) return [];
524
+ return renderFeedEvents([...feed.all()], {
525
+ startMs: feedStartMs || Date.now(),
526
+ maxChars: 150,
527
+ maxEvents: 14,
528
+ });
502
529
  };
503
530
  const runPromise = app.run(request, {
504
531
  ...hooks,
@@ -508,18 +535,44 @@ export default function delegateExtension(pi: ExtensionAPI) {
508
535
  viewState.role = u.role;
509
536
  viewState.phase = u.phase;
510
537
  viewState.elapsedMs = u.elapsedMs;
511
- viewState.lastActions = u.lastActions;
538
+ viewState.model = u.model;
539
+ viewState.openTools = u.openTools;
540
+ viewState.turns = u.usage?.turns;
541
+ viewState.tokens = { input: u.usage?.input, output: u.usage?.output };
542
+ if (!feedStartMs) feedStartMs = Date.now() - u.elapsedMs;
543
+ },
544
+ onEvent: (event) => {
545
+ feed.push(event);
512
546
  },
513
547
  });
548
+ // Effective hard cap for the progress bar: per-run > project > user.
549
+ try {
550
+ const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
551
+ hardMs = request.timeoutMs ?? s.timeouts.hardMs;
552
+ } catch {
553
+ hardMs = undefined;
554
+ }
555
+ viewState.hardMs = hardMs;
556
+ let refreshTimer: ReturnType<typeof setInterval> | undefined;
514
557
  const outcome = await ctx.ui.custom<{ cancelled?: boolean } | undefined>(
515
- (tui, theme, keybindings, done) =>
516
- new RunningView({
558
+ (tui, theme, keybindings, done) => {
559
+ refreshTimer = setInterval(() => {
560
+ viewState.elapsedMs = feedStartMs ? Date.now() - feedStartMs : viewState.elapsedMs;
561
+ viewState.feedLines = feedLines();
562
+ tui.requestRender();
563
+ }, 1000);
564
+ return new RunningView({
517
565
  theme,
518
566
  keybindings,
519
- state: () => viewState,
567
+ state: () => {
568
+ viewState.feedLines = feedLines();
569
+ return viewState;
570
+ },
520
571
  done,
521
- }),
572
+ });
573
+ },
522
574
  );
575
+ if (refreshTimer) clearInterval(refreshTimer);
523
576
  if (outcome?.cancelled) {
524
577
  await app.cancel();
525
578
  say(ctx, `[delegate] cancellation requested; the run finalizes with its terminal receipt.`);
@@ -560,6 +613,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
560
613
  const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
561
614
  lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
562
615
  lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
616
+ const queued = app.queuedRunCount();
617
+ lines.push(`queue: ${queued} waiting (concurrent calls serialize; limit ${app.queueLimit()})`);
563
618
  if (s.lastRun) {
564
619
  const dur = s.lastRun.durationMs != null ? `${Math.round(s.lastRun.durationMs / 1000)}s` : "";
565
620
  lines.push(`last run: ${s.lastRun.runId} ${s.lastRun.role} ${s.lastRun.state} ${dur}`.trimEnd());
@@ -680,6 +735,61 @@ export default function delegateExtension(pi: ExtensionAPI) {
680
735
  }
681
736
  await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
682
737
  return;
738
+ case "peek": {
739
+ const id = intent.runId?.trim() || app.mostRecentRunId();
740
+ if (!id) {
741
+ say(ctx, "[delegate] no runs to peek at.", "warning");
742
+ return;
743
+ }
744
+ let meta;
745
+ try {
746
+ meta = app.inspect(id).metadata;
747
+ } catch {
748
+ say(ctx, `[delegate] unknown run '${id}'.`, "error");
749
+ return;
750
+ }
751
+ if (!fsSync.existsSync(meta.transcriptPath)) {
752
+ say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
753
+ return;
754
+ }
755
+ if (ctx.mode === "tui") {
756
+ await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
757
+ const state = () => {
758
+ let live = false;
759
+ try {
760
+ live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
761
+ } catch {
762
+ live = false;
763
+ }
764
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
765
+ return {
766
+ title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${meta.model}` : ""} · ${meta.state}`,
767
+ summary: meta.transcriptPath,
768
+ lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
769
+ live,
770
+ };
771
+ };
772
+ // Live-follow refresh timer; cleared the moment the
773
+ // overlay closes (done wrapper) — never leaks.
774
+ let timer: ReturnType<typeof setInterval> | undefined;
775
+ const wrappedDone = (result: { closed?: boolean }) => {
776
+ if (timer) clearInterval(timer);
777
+ done(result);
778
+ };
779
+ const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
780
+ timer = setInterval(() => tui.requestRender(), 1000);
781
+ return view;
782
+ });
783
+ } else {
784
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
785
+ const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
786
+ say(
787
+ ctx,
788
+ `[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`,
789
+ );
790
+ }
791
+ return;
792
+ }
683
793
  case "resume": {
684
794
  const runId = intent.runId?.trim();
685
795
  if (!runId || !intent.task) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
@@ -37,7 +37,8 @@
37
37
  "run-store.ts",
38
38
  "types.ts",
39
39
  "version.ts",
40
- "handoff.ts",
40
+ "handoff.ts",
41
+ "transcript-feed.ts",
41
42
  "roles/",
42
43
  "ui/",
43
44
  "README.md",
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"; id?: string; toolName?: string; args?: Record<string, unknown>; result?: { details?: unknown; isError?: boolean } }
26
+ | { kind: "tool_event"; phase: "start" | "update" | "end"; id?: string; toolName?: string; args?: Record<string, unknown>; result?: { details?: unknown; isError?: boolean; textHead?: string } }
27
27
  | { kind: "agent_settled" }
28
28
  | { kind: "agent_end" }
29
29
  | { kind: "extension_ui_request"; id: string }
@@ -161,13 +161,21 @@ export function classifyRpcRecord(record: RpcRecord): RpcRecordClassification {
161
161
  };
162
162
  case "tool_execution_end": {
163
163
  const result = (obj.result ?? {}) as Record<string, unknown>;
164
+ const content = Array.isArray(result.content) ? (result.content as Array<Record<string, unknown>>) : [];
165
+ let textHead = "";
166
+ for (const b of content) {
167
+ if (b?.type === "text" && typeof b.text === "string" && b.text.trim()) {
168
+ textHead = b.text.trim().slice(0, 240);
169
+ break;
170
+ }
171
+ }
164
172
  return {
165
173
  kind: "tool_event",
166
174
  phase: "end",
167
175
  id: typeof obj.toolCallId === "string" ? obj.toolCallId : undefined,
168
176
  toolName: typeof obj.toolName === "string" ? obj.toolName : undefined,
169
177
  ...(result && typeof result === "object"
170
- ? { result: { details: result.details, isError: result.isError === true } }
178
+ ? { result: { details: result.details, isError: result.isError === true, ...(textHead ? { textHead } : {}) } }
171
179
  : {}),
172
180
  };
173
181
  }
package/runner.ts CHANGED
@@ -27,6 +27,7 @@ import { classifyRpcRecord, RpcJsonlParser, type RpcRecord } from "./rpc-jsonl.t
27
27
  import { appendTranscriptRecord, updateRunMetadata, type OpenedRun } from "./run-store.ts";
28
28
  import { formatDuration } from "./config.ts";
29
29
  import { renderHandoff, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
30
+ import type { FeedEvent } from "./transcript-feed.ts";
30
31
 
31
32
  export interface RunnerConfig {
32
33
  maxResultBytes: number;
@@ -242,6 +243,12 @@ export class DelegateRunner {
242
243
  private lastAssistant: AssistantFinal | null = null;
243
244
  /** R1: toolCallIds with a start but no matching end yet. */
244
245
  private openToolCalls = new Set<string>();
246
+ /** Feed: toolCallId → start ms (for end-event durations). */
247
+ private toolStartedAt = new Map<string, number>();
248
+ /** Feed: toolCallId → tool name. */
249
+ private toolNames = new Map<string, string>();
250
+ /** Feed: toolCallId → the start event's arg detail (path/command). */
251
+ private toolDetails = new Map<string, string>();
245
252
  /** R2: handoff negotiation phase after a timeout cancel. */
246
253
  private handoffPhase: "none" | "await-settle" | "await-handoff" = "none";
247
254
  /** Structured handoff captured from the child's `handoff` tool call. */
@@ -500,19 +507,70 @@ export class DelegateRunner {
500
507
  case "message_end": {
501
508
  const message = (record.parsed as { message?: unknown }).message;
502
509
  this.ingestMessage(message, cls.stopReason);
510
+ const m = message as { role?: string; stopReason?: string; errorMessage?: string; content?: Array<{ type?: string; text?: string }> } | null;
511
+ if (m?.role === "assistant") {
512
+ if (m.stopReason === "error") {
513
+ this.emitEvent({
514
+ atMs: Date.now(),
515
+ kind: "provider_error",
516
+ detail: (m.errorMessage ?? "").trim() || "provider error (no message)",
517
+ });
518
+ } else {
519
+ const text = (m.content ?? []).find((b) => b?.type === "text" && b.text?.trim())?.text ?? "";
520
+ if (text.trim()) {
521
+ this.emitEvent({
522
+ atMs: Date.now(),
523
+ kind: "assistant",
524
+ detail: text.split("\n").filter(Boolean)[0] ?? "",
525
+ });
526
+ }
527
+ }
528
+ }
503
529
  break;
504
530
  }
505
531
  case "tool_event":
506
532
  // R1: track open tool calls (start/end pairs by toolCallId).
507
533
  if (cls.id) {
508
- if (cls.phase === "start") this.openToolCalls.add(cls.id);
509
- else if (cls.phase === "end") this.openToolCalls.delete(cls.id);
534
+ if (cls.phase === "start") {
535
+ this.openToolCalls.add(cls.id);
536
+ this.toolStartedAt.set(cls.id, Date.now());
537
+ if (cls.toolName) this.toolNames.set(cls.id, cls.toolName);
538
+ this.toolDetails.set(cls.id, feedDetailFor(cls.toolName ?? "", cls.args));
539
+ } else if (cls.phase === "end") {
540
+ this.openToolCalls.delete(cls.id);
541
+ this.toolStartedAt.delete(cls.id);
542
+ this.toolNames.delete(cls.id);
543
+ this.toolDetails.delete(cls.id);
544
+ }
510
545
  // a tool event resets the watchdog to the right budget
511
546
  this.armInactivity();
512
547
  }
513
548
  if (cls.phase === "start" && cls.toolName) {
514
549
  this.pushAction(describeToolAction(cls.toolName, cls.args));
515
550
  this.pushUpdate(`tool:${cls.toolName}`);
551
+ this.emitEvent({
552
+ atMs: Date.now(),
553
+ kind: "tool_start",
554
+ tool: cls.toolName,
555
+ detail: feedDetailFor(cls.toolName, cls.args),
556
+ });
557
+ }
558
+ if (cls.phase === "end" && cls.toolName && cls.id) {
559
+ const started = this.toolStartedAt.get(cls.id);
560
+ // Echo the start's arg detail (path/command); bash keeps
561
+ // its output head — file-content heads are noise.
562
+ const argDetail = this.toolDetails.get(cls.id) ?? "";
563
+ const head = cls.result?.textHead ?? "";
564
+ const detail =
565
+ cls.toolName === "bash" && head ? head.slice(0, 70) : (argDetail || head.slice(0, 70) || "done");
566
+ this.emitEvent({
567
+ atMs: Date.now(),
568
+ kind: "tool_end",
569
+ tool: cls.toolName,
570
+ detail,
571
+ isError: cls.result?.isError === true,
572
+ ...(started ? { durationMs: Date.now() - started } : {}),
573
+ });
516
574
  }
517
575
  // Structured handoff: the child's mandatory final report rides
518
576
  // on the handoff tool result details — capture it verbatim
@@ -520,11 +578,19 @@ export class DelegateRunner {
520
578
  if (cls.phase === "end" && cls.toolName === "handoff") {
521
579
  const candidate = (cls.result?.details as { delegateHandoff?: unknown } | undefined)?.delegateHandoff;
522
580
  const validation = validateHandoffSubmission(candidate);
523
- if (validation.ok) this.structuredHandoff = validation.value ?? null;
581
+ if (validation.ok) {
582
+ this.structuredHandoff = validation.value ?? null;
583
+ this.emitEvent({
584
+ atMs: Date.now(),
585
+ kind: "handoff",
586
+ detail: `handoff submitted (${validation.value?.outcome ?? "?"})`,
587
+ });
588
+ }
524
589
  }
525
590
  break;
526
591
  case "agent_settled":
527
592
  this.settled = true;
593
+ this.emitEvent({ atMs: Date.now(), kind: "settled", detail: "agent settled" });
528
594
  this.finalizeSettled();
529
595
  break;
530
596
  case "agent_end":
@@ -1056,6 +1122,25 @@ export class DelegateRunner {
1056
1122
  if (this.lastActions.length > 10) this.lastActions.shift();
1057
1123
  }
1058
1124
 
1125
+ /** Names of tools currently in flight (for live views). */
1126
+ private openToolNames(): string[] {
1127
+ const names = new Set<string>();
1128
+ for (const id of this.openToolCalls) {
1129
+ const name = this.toolNames.get(id);
1130
+ if (name) names.add(name);
1131
+ }
1132
+ return [...names];
1133
+ }
1134
+
1135
+ /** Live feed fan-out (unthrottled; views bound what they keep). */
1136
+ private emitEvent(event: FeedEvent): void {
1137
+ try {
1138
+ this.hooks.onEvent?.(event);
1139
+ } catch {
1140
+ // feed failures never affect the run
1141
+ }
1142
+ }
1143
+
1059
1144
  private pushUpdate(phase: "starting" | "running" | `tool:${string}` | "finalizing"): void {
1060
1145
  if (!this.hooks.onUpdate) return;
1061
1146
  const now = Date.now();
@@ -1066,6 +1151,7 @@ export class DelegateRunner {
1066
1151
  role: this.req.role.name,
1067
1152
  phase,
1068
1153
  model: this.req.parentModel,
1154
+ openTools: this.openToolNames(),
1069
1155
  elapsedMs: this.startedAtMs ? now - this.startedAtMs : 0,
1070
1156
  lastActions: this.lastActions.slice(-5),
1071
1157
  usage: { ...this.usage, turns: this.turns },
@@ -1219,6 +1305,18 @@ export function gitDeltaSince(cwd: string, _since?: string): string | null {
1219
1305
  return parts.join("\n").slice(0, 4000);
1220
1306
  }
1221
1307
 
1308
+ /** Feed detail for a tool start: command/path head (display-safe). */
1309
+ function feedDetailFor(toolName: string, args?: Record<string, unknown>): string {
1310
+ const a = (key: string): string => {
1311
+ const v = args?.[key];
1312
+ return typeof v === "string" ? v : "";
1313
+ };
1314
+ const v = a("command") || a("path") || a("pattern") || a("query");
1315
+ if (v) return v.replace(/\s+/g, " ").slice(0, 90);
1316
+ if (toolName === "handoff") return "structured submission";
1317
+ return "";
1318
+ }
1319
+
1222
1320
  /**
1223
1321
  * Display-safe one-liner for a child tool call (never fed to the model).
1224
1322
  * Keeps at most ~100 visible chars; args are user-visible command/path
@@ -0,0 +1,234 @@
1
+ /**
2
+ * delegate — child-activity feed formatting (Pi-free).
3
+ *
4
+ * One formatter, two consumers: the live running panel (in-memory events
5
+ * pushed by the runner) and `/delegate peek` (events decoded from the
6
+ * captured RPC transcript on disk). Everything bounded and width-safe by
7
+ * character count; components truncate to terminal width themselves.
8
+ */
9
+
10
+ import * as fs from "node:fs";
11
+ import { decodeTranscriptRecord, type TranscriptRecordV1 } from "./types.ts";
12
+
13
+ /** One feed event, whether captured live or decoded from a transcript. */
14
+ export interface FeedEvent {
15
+ /** Epoch ms (live) or ISO string (transcript) — normalized to ms. */
16
+ atMs: number;
17
+ kind: "tool_start" | "tool_end" | "assistant" | "provider_error" | "handoff" | "settled" | "info";
18
+ tool?: string;
19
+ detail: string;
20
+ /** tool_end: failure marker. */
21
+ isError?: boolean;
22
+ /** tool_end: duration ms when known. */
23
+ durationMs?: number;
24
+ }
25
+
26
+ export interface FeedRenderOptions {
27
+ /** Feed window start (epoch ms) — events are stamped +Ns relative to it. */
28
+ startMs: number;
29
+ /** Maximum events kept/rendered. */
30
+ maxEvents?: number;
31
+ /** Maximum characters per line. */
32
+ maxChars?: number;
33
+ }
34
+
35
+ const DEFAULT_MAX_EVENTS = 200;
36
+ const DEFAULT_MAX_CHARS = 160;
37
+
38
+ function clip(text: string, max: number): string {
39
+ const s = text.replace(/\s+/g, " ").trim();
40
+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
41
+ }
42
+
43
+ /** Render feed events as bounded one-liners: `+42s ▶ bash npm test`. */
44
+ export function renderFeedEvents(events: FeedEvent[], opts: FeedRenderOptions): string[] {
45
+ const maxChars = opts.maxChars ?? DEFAULT_MAX_CHARS;
46
+ const maxEvents = opts.maxEvents ?? DEFAULT_MAX_EVENTS;
47
+ const lines: string[] = [];
48
+ for (const e of events.slice(-maxEvents)) {
49
+ const rel = Math.max(0, Math.round((e.atMs - opts.startMs) / 1000));
50
+ const ts = rel >= 60 ? `${Math.floor(rel / 60)}m${String(rel % 60).padStart(2, "0")}s` : `${rel}s`;
51
+ let mark = "·";
52
+ let text = e.detail;
53
+ switch (e.kind) {
54
+ case "tool_start":
55
+ mark = "▶";
56
+ text = e.tool ? `${e.tool} ${e.detail}` : e.detail;
57
+ break;
58
+ case "tool_end":
59
+ mark = e.isError ? "✗" : "✓";
60
+ text = e.tool ? `${e.tool} ${e.detail}` : e.detail;
61
+ if (e.durationMs !== undefined) text += ` (${Math.round(e.durationMs / 1000)}s)`;
62
+ break;
63
+ case "assistant":
64
+ mark = "✎";
65
+ break;
66
+ case "provider_error":
67
+ mark = "⚠";
68
+ break;
69
+ case "handoff":
70
+ mark = "▣";
71
+ break;
72
+ case "settled":
73
+ mark = "◉";
74
+ break;
75
+ }
76
+ lines.push(clip(`+${ts} ${mark} ${text}`, maxChars));
77
+ }
78
+ return lines;
79
+ }
80
+
81
+ /** Live feed ring: bounded append with drop-oldest. */
82
+ export class FeedRing {
83
+ private readonly events: FeedEvent[] = [];
84
+ private readonly capacity: number;
85
+ constructor(capacity = 120) {
86
+ this.capacity = capacity;
87
+ }
88
+ push(event: FeedEvent): void {
89
+ this.events.push(event);
90
+ if (this.events.length > this.capacity) this.events.shift();
91
+ }
92
+ all(): readonly FeedEvent[] {
93
+ return this.events;
94
+ }
95
+ }
96
+
97
+ interface ParsedRecord {
98
+ receivedAtMs: number;
99
+ type?: string;
100
+ toolCallId?: string;
101
+ toolName?: string;
102
+ args?: unknown;
103
+ result?: { content?: Array<{ type?: string; text?: string }>; isError?: boolean; details?: { delegateHandoff?: { outcome?: string } } };
104
+ message?: {
105
+ role?: string;
106
+ stopReason?: string;
107
+ errorMessage?: string;
108
+ content?: Array<{ type?: string; text?: string; thinking?: string }>;
109
+ };
110
+ }
111
+
112
+ function parseEnvelope(line: string): { atMs: number; rec: ParsedRecord | null } {
113
+ try {
114
+ const env = JSON.parse(line) as TranscriptRecordV1;
115
+ const atMs = Date.parse(env.receivedAt);
116
+ let rec: ParsedRecord | null = null;
117
+ try {
118
+ rec = JSON.parse(decodeTranscriptRecord(env)) as ParsedRecord;
119
+ } catch {
120
+ rec = null;
121
+ }
122
+ return { atMs: Number.isFinite(atMs) ? atMs : 0, rec };
123
+ } catch {
124
+ return { atMs: 0, rec: null };
125
+ }
126
+ }
127
+
128
+ function resultTextHead(result: ParsedRecord["result"]): string {
129
+ const blocks = result?.content ?? [];
130
+ for (const b of blocks) {
131
+ if (b?.type === "text" && typeof b.text === "string" && b.text.trim()) return b.text;
132
+ }
133
+ return "";
134
+ }
135
+
136
+ /**
137
+ * Decode the tail of a captured child transcript into feed events — the
138
+ * backing store for `/delegate peek` (live runs grow the file in real time).
139
+ */
140
+ export function feedEventsFromTranscript(
141
+ transcriptPath: string,
142
+ opts?: { maxEvents?: number; maxBytes?: number },
143
+ ): { startMs: number; events: FeedEvent[] } {
144
+ const maxEvents = opts?.maxEvents ?? 120;
145
+ const maxBytes = opts?.maxBytes ?? 1_500_000;
146
+ const events: FeedEvent[] = [];
147
+ let startMs = 0;
148
+ try {
149
+ const stat = fs.statSync(transcriptPath);
150
+ const fd = fs.openSync(transcriptPath, "r");
151
+ try {
152
+ const readFrom = Math.max(0, stat.size - maxBytes);
153
+ const buf = Buffer.alloc(stat.size - readFrom);
154
+ fs.readSync(fd, buf, 0, buf.length, readFrom);
155
+ const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
156
+ // A tail cut can start mid-line; drop a partial first line.
157
+ if (readFrom > 0 && lines.length > 0) lines.shift();
158
+ const openTools = new Map<string, { name?: string; atMs: number; detail?: string }>();
159
+ for (const line of lines) {
160
+ const { atMs, rec } = parseEnvelope(line);
161
+ if (!rec || !atMs) continue;
162
+ if (startMs === 0) startMs = atMs;
163
+ switch (rec.type) {
164
+ case "tool_execution_start": {
165
+ const name = rec.toolName ?? "tool";
166
+ const detail = describeArgs(name, rec.args);
167
+ openTools.set(rec.toolCallId ?? String(events.length), { name, atMs, detail });
168
+ events.push({ atMs, kind: "tool_start", tool: name, detail });
169
+ break;
170
+ }
171
+ case "tool_execution_end": {
172
+ const name = rec.toolName ?? "tool";
173
+ const open = openTools.get(rec.toolCallId ?? "");
174
+ openTools.delete(rec.toolCallId ?? "");
175
+ // End lines echo the start's arg detail (path/command) —
176
+ // file-content heads are noise; bash keeps its output head.
177
+ const head = resultTextHead(rec.result);
178
+ const detail =
179
+ name === "bash" && head
180
+ ? clip(head, 70)
181
+ : (open?.detail || (head ? clip(head, 70) : "done"));
182
+ events.push({
183
+ atMs,
184
+ kind: "tool_end",
185
+ tool: name,
186
+ detail,
187
+ isError: rec.result?.isError === true || /\berror\b/i.test(head.slice(0, 40)),
188
+ ...(open ? { durationMs: atMs - open.atMs } : {}),
189
+ });
190
+ break;
191
+ }
192
+ case "message_end": {
193
+ const m = rec.message ?? {};
194
+ if (m.role !== "assistant") break;
195
+ if (m.stopReason === "error") {
196
+ events.push({
197
+ atMs,
198
+ kind: "provider_error",
199
+ detail: m.errorMessage?.trim() || "provider error (no message)",
200
+ });
201
+ break;
202
+ }
203
+ const blocks = m.content ?? [];
204
+ const handoff = rec as unknown as { toolName?: string };
205
+ void handoff;
206
+ let text = "";
207
+ for (const b of blocks) if (b?.type === "text" && b.text?.trim()) text = b.text;
208
+ if (text.trim()) events.push({ atMs, kind: "assistant", detail: text.split("\n").filter(Boolean)[0] ?? text });
209
+ break;
210
+ }
211
+ case "agent_settled":
212
+ events.push({ atMs, kind: "settled", detail: "agent settled" });
213
+ break;
214
+ default:
215
+ break;
216
+ }
217
+ }
218
+ } finally {
219
+ fs.closeSync(fd);
220
+ }
221
+ } catch {
222
+ // unreadable/missing transcript → empty feed
223
+ }
224
+ return { startMs, events: events.slice(-maxEvents) };
225
+ }
226
+
227
+ function describeArgs(tool: string, args: unknown): string {
228
+ if (!args || typeof args !== "object") return "";
229
+ const a = args as Record<string, unknown>;
230
+ const v = a.command ?? a.path ?? a.pattern ?? a.query;
231
+ if (typeof v === "string") return clip(v, 90);
232
+ if (tool === "handoff") return "structured submission";
233
+ return "";
234
+ }
package/types.ts CHANGED
@@ -22,6 +22,7 @@ export interface DelegateRole {
22
22
  }
23
23
 
24
24
  import type { HandoffSubmission } from "./handoff.ts";
25
+ import type { FeedEvent } from "./transcript-feed.ts";
25
26
 
26
27
  // ── Errors ────────────────────────────────────────────────────────────────
27
28
 
@@ -375,6 +376,8 @@ export interface RunStreamUpdate {
375
376
  phase: "starting" | "running" | `tool:${string}` | "finalizing";
376
377
  /** R5: the resolved child model, echoed in live updates. */
377
378
  model?: string;
379
+ /** Live feed: tool names with a start but no end yet. */
380
+ openTools?: string[];
378
381
  elapsedMs: number;
379
382
  lastActions: string[];
380
383
  usage: DelegateUsage;
@@ -382,6 +385,8 @@ export interface RunStreamUpdate {
382
385
 
383
386
  export type RunHooks = {
384
387
  onUpdate?: (update: RunStreamUpdate) => void;
388
+ /** Live feed events for the running panel and peek views (every event, unthrottled). */
389
+ onEvent?: (event: FeedEvent) => void;
385
390
  abortSignal?: AbortSignal;
386
391
  };
387
392
 
@@ -0,0 +1,108 @@
1
+ /**
2
+ * delegate — `/delegate peek` overlay: a scrollable, live-following view of
3
+ * a child's activity, decoded from its captured RPC transcript (works for
4
+ * the active run AND post-mortem). The host owns the refresh timer (1 s
5
+ * while following) and must clear it when the overlay closes.
6
+ */
7
+
8
+ import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
9
+ import type { Theme, KeybindingsManager, ThemeColor } from "@earendil-works/pi-coding-agent";
10
+
11
+ export interface PeekViewState {
12
+ /** Header: run id + state/model. */
13
+ title: string;
14
+ /** One muted summary line (path, size, role, finished state…). */
15
+ summary: string;
16
+ /** Formatted feed lines, oldest first (newest at the bottom). */
17
+ lines: string[];
18
+ /** True while the run is still active (enables follow). */
19
+ live: boolean;
20
+ }
21
+
22
+ export interface PeekViewHost {
23
+ theme: Theme;
24
+ keybindings: KeybindingsManager;
25
+ state(): PeekViewState;
26
+ done(result: { closed?: boolean }): void;
27
+ }
28
+
29
+ export class PeekView implements Component {
30
+ private readonly host: PeekViewHost;
31
+ private offsetFromEnd = 0;
32
+ private following = true;
33
+ private lastLineCount = 0;
34
+
35
+ constructor(host: PeekViewHost) {
36
+ this.host = host;
37
+ }
38
+
39
+ handleInput(data: string): void {
40
+ const kb = this.host.keybindings;
41
+ const up = (kb?.matches?.(data, "tui.select.up") ?? false) || matchesKey(data, "j");
42
+ const down = (kb?.matches?.(data, "tui.select.down") ?? false) || matchesKey(data, "k");
43
+ const cancel =
44
+ (kb?.matches?.(data, "tui.select.cancel") ?? false) ||
45
+ matchesKey(data, "escape") ||
46
+ matchesKey(data, "q");
47
+ if (cancel) {
48
+ this.host.done({ closed: true });
49
+ } else if (up) {
50
+ this.following = false;
51
+ this.offsetFromEnd += 1;
52
+ } else if (down) {
53
+ this.offsetFromEnd = Math.max(0, this.offsetFromEnd - 1);
54
+ if (this.offsetFromEnd === 0) this.following = true;
55
+ } else if (matchesKey(data, "f")) {
56
+ this.following = true;
57
+ this.offsetFromEnd = 0;
58
+ }
59
+ }
60
+
61
+ invalidate(): void {
62
+ // Rendered from host state each frame; no cache to clear.
63
+ }
64
+
65
+ render(width: number): string[] {
66
+ const s = this.host.state();
67
+ const theme = this.host.theme;
68
+ const w = Math.max(1, Math.floor(width));
69
+ const fg = (kind: ThemeColor, text: string) => (theme?.fg ? theme.fg(kind, text) : text);
70
+ const title = ` Peek · ${s.title} `;
71
+ const top = `╭─${truncateToWidth(title, Math.max(4, w - 4))}${"─".repeat(Math.max(0, w - 3 - Math.min(title.length, Math.max(4, w - 4))))}─╮`;
72
+ const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`;
73
+ const inner = Math.max(1, w - 4);
74
+ const pad = (text: string, color?: ThemeColor) => {
75
+ const line = `│ ${truncateToWidth(text, inner)} │`;
76
+ return color && theme?.fg ? theme.fg(color, line) : line;
77
+ };
78
+
79
+ // Viewport: keep the overlay in the 20–24 line budget.
80
+ const maxFeed = Math.max(1, 20 - 4);
81
+ const total = s.lines.length;
82
+ if (total !== this.lastLineCount && this.following) this.offsetFromEnd = 0;
83
+ this.lastLineCount = total;
84
+ const end = Math.max(0, total - this.offsetFromEnd);
85
+ const start = Math.max(0, end - maxFeed);
86
+ const window = s.lines.slice(start, end);
87
+
88
+ const lines: string[] = [
89
+ truncateToWidth(top, w),
90
+ pad(s.summary, "muted"),
91
+ pad(
92
+ s.live
93
+ ? fg("success", `● live — following (j/k scroll, f re-follow, q close)`)
94
+ : `final — ${total} events (j/k scroll, q close)`,
95
+ s.live ? "success" : "dim",
96
+ ),
97
+ ];
98
+ if (total === 0) {
99
+ lines.push(pad("no activity captured", "muted"));
100
+ } else {
101
+ for (const line of window) lines.push(pad(line));
102
+ if (start > 0) lines.push(pad(`… ${start} earlier event(s) — j to scroll up`, "dim"));
103
+ if (end < total) lines.push(pad(`… ${total - end} newer event(s) — k to scroll down`, "dim"));
104
+ }
105
+ lines.push(truncateToWidth(bottom, w));
106
+ return lines.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
107
+ }
108
+ }
@@ -1,21 +1,32 @@
1
1
  /**
2
- * delegate — compact live running view for command-driven foreground runs.
2
+ * delegate — live child feed panel for command-driven foreground runs.
3
3
  *
4
- * Renders ≤ ~4 bounded lines (status, elapsed, last actions) inside a
5
- * width-safe bordered box and cancels via Escape (done({ cancel: true })).
6
- * Keyboard uses the injected KeybindingsManager where available; Escape is
7
- * the canonical cancel. Refresh cadence is owned by the host (1 s).
4
+ * A window into the running child: identity + budgets header, elapsed-vs-hard
5
+ * progress, in-flight tools, and a bounded scrolling feed of the child's
6
+ * activity (tool starts/ends, assistant lines, provider errors, handoff).
7
+ * Cancels via Escape twice (armed). Refresh cadence is owned by the host
8
+ * (1 s); feed lines arrive pre-formatted from the adapter's event ring.
8
9
  */
9
10
 
10
11
  import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
11
- import type { Theme, KeybindingsManager } from "@earendil-works/pi-coding-agent";
12
+ import type { Theme, KeybindingsManager, ThemeColor } from "@earendil-works/pi-coding-agent";
12
13
 
13
14
  export interface RunningViewState {
14
15
  runId: string;
15
16
  role: string;
17
+ /** Resolved child model ("provider/model"). */
18
+ model?: string;
16
19
  phase: string;
17
20
  elapsedMs: number;
18
- lastActions: string[];
21
+ /** Effective hard cap — drives the progress bar. */
22
+ hardMs?: number;
23
+ turns?: number;
24
+ /** Tokens observed so far. */
25
+ tokens?: { input?: number; output?: number };
26
+ /** Tools currently in flight. */
27
+ openTools?: string[];
28
+ /** Pre-formatted feed lines (newest last), already clipped. */
29
+ feedLines: string[];
19
30
  }
20
31
 
21
32
  export interface RunningViewHost {
@@ -25,9 +36,21 @@ export interface RunningViewHost {
25
36
  done(result: { cancelled?: boolean }): void;
26
37
  }
27
38
 
39
+ function fmtDuration(ms: number): string {
40
+ const s = Math.max(0, Math.round(ms / 1000));
41
+ if (s < 60) return `${s}s`;
42
+ return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
43
+ }
44
+
45
+ function fmtTokens(n?: number): string {
46
+ if (!n) return "0";
47
+ if (n < 1000) return String(n);
48
+ if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
49
+ return `${Math.round(n / 100_000) / 10}M`;
50
+ }
51
+
28
52
  export class RunningView implements Component {
29
53
  private readonly host: RunningViewHost;
30
- private cachedLines: string[] | undefined;
31
54
  private cancelArmed = false;
32
55
 
33
56
  constructor(host: RunningViewHost) {
@@ -41,7 +64,7 @@ export class RunningView implements Component {
41
64
  matchesKey(data, "escape") ||
42
65
  matchesKey(data, "q");
43
66
  if (isCancelKey) {
44
- // §12 — confirm cancellation of a running child before signalling.
67
+ // Cancel is destructive to the child — require a second press.
45
68
  if (this.cancelArmed) {
46
69
  this.host.done({ cancelled: true });
47
70
  } else {
@@ -52,34 +75,73 @@ export class RunningView implements Component {
52
75
  }
53
76
 
54
77
  invalidate(): void {
55
- this.cachedLines = undefined;
78
+ // No internal cache: state() is cheap and host-driven refresh is 1 s.
56
79
  }
57
80
 
58
81
  render(width: number): string[] {
59
82
  const s = this.host.state();
60
83
  const theme = this.host.theme;
61
84
  const w = Math.max(1, Math.floor(width));
62
- const secs = Math.round(s.elapsedMs / 1000);
63
- const title = truncateToWidth(" Delegating ", Math.max(4, w - 4));
85
+ const title = " Delegating ";
64
86
  const border = "─".repeat(Math.max(0, w - title.length - 2));
65
- const top = `╭─${title}${border}─╮`;
66
- const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`;
87
+ const top = `╭─${title}${border.slice(0, Math.max(0, border.length))}─╮`.slice(0, w);
88
+ const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`.slice(0, w);
67
89
  const inner = Math.max(1, w - 4);
68
- const pad = (text: string) => `│ ${truncateToWidth(text, inner)} │`;
69
- const lines: string[] = [top, pad(`${s.role} · ${s.phase} · ${secs}s`), pad(s.runId)];
70
- for (const action of s.lastActions.slice(-2)) {
71
- lines.push(pad(`· ${action}`));
90
+ const pad = (text: string, color?: ThemeColor) => {
91
+ const line = `│ ${truncateToWidth(text, inner)} │`;
92
+ return color && theme?.fg ? theme.fg(color, line) : line;
93
+ };
94
+
95
+ const fg = (kind: ThemeColor, text: string) => (theme?.fg ? theme.fg(kind, text) : text);
96
+ const lines: string[] = [top];
97
+
98
+ // Header: identity + elapsed + turns + tokens.
99
+ const head = [
100
+ s.role,
101
+ s.model,
102
+ fg("accent", fmtDuration(s.elapsedMs)),
103
+ ...(s.turns !== undefined ? [`turn ${s.turns}`] : []),
104
+ ...(s.tokens ? [`↑${fmtTokens(s.tokens.input)} ↓${fmtTokens(s.tokens.output)}`] : []),
105
+ ]
106
+ .filter(Boolean)
107
+ .join(" · ");
108
+ lines.push(pad(head));
109
+
110
+ // Progress: elapsed vs hard cap (never color-only — text carries %).
111
+ if (s.hardMs && s.hardMs > 0) {
112
+ const frac = Math.min(1, s.elapsedMs / s.hardMs);
113
+ const barWidth = Math.max(4, Math.min(inner - 14, 24));
114
+ const filled = Math.round(frac * barWidth);
115
+ const bar = `${"█".repeat(filled)}${"░".repeat(Math.max(0, barWidth - filled))}`;
116
+ lines.push(pad(`${bar} ${Math.round(frac * 100)}% of ${fmtDuration(s.hardMs)} hard`));
72
117
  }
73
- lines.push(pad(this.cancelArmed ? "ESC again: CONFIRM cancel" : "esc cancel"));
74
- lines.push(bottom);
75
- // Width safety: every rendered line must fit the available width.
76
- for (const line of lines) {
77
- if (visibleWidth(line) > w) {
78
- // Fallback: clip hard rather than corrupt layout.
79
- return [truncateToWidth(top, w), ...lines.map((l) => truncateToWidth(l, w))].slice(0, Math.max(1, Math.min(lines.length, 20)));
80
- }
118
+
119
+ // In-flight tools.
120
+ if (s.openTools && s.openTools.length > 0) {
121
+ lines.push(pad(fg("warning", `in flight: ${s.openTools.join(", ")}`)));
122
+ }
123
+
124
+ // Feed: newest last; take as many as fit the budget.
125
+ const feedBudget = Math.max(0, 16 - lines.length - 2);
126
+ const feed = s.feedLines.slice(-feedBudget);
127
+ if (feed.length > 0) {
128
+ for (const line of feed) lines.push(pad(line, "text"));
129
+ } else {
130
+ lines.push(pad("starting — waiting for the child's first events…", "muted"));
81
131
  }
82
- this.cachedLines = lines;
83
- return lines;
132
+
133
+ // Footer.
134
+ lines.push(
135
+ pad(
136
+ this.cancelArmed
137
+ ? fg("error", "ESC again: CONFIRM cancel")
138
+ : "esc/q cancel (press twice)",
139
+ this.cancelArmed ? "error" : "dim",
140
+ ),
141
+ );
142
+ lines.push(bottom);
143
+
144
+ // Width safety: hard-clip rather than corrupt layout.
145
+ return lines.map((l) => (visibleWidth(l) > w ? truncateToWidth(l, w) : l));
84
146
  }
85
147
  }