@maheidem/pi-delegate 0.2.0 → 0.2.1
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 +12 -0
- package/commands.ts +9 -2
- package/index.ts +103 -6
- package/package.json +3 -2
- package/rpc-jsonl.ts +10 -2
- package/runner.ts +101 -3
- package/transcript-feed.ts +234 -0
- package/types.ts +5 -0
- package/ui/peek-view.ts +108 -0
- package/ui/running-view.ts +90 -28
package/README.md
CHANGED
|
@@ -118,6 +118,18 @@ 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
|
+
### Watching a child work: the live feed and `/delegate peek`
|
|
122
|
+
|
|
123
|
+
- **Foreground `/delegate run` (TUI)** opens a live feed panel: identity
|
|
124
|
+
(`role · model · elapsed · turn N · ↑in ↓out`), an elapsed-vs-hard-cap
|
|
125
|
+
progress bar, in-flight tools, and a scrolling one-line-per-event feed of
|
|
126
|
+
the child's activity — `▶ bash npm test` → `✓ … (38s)`, `✎` assistant
|
|
127
|
+
lines, `⚠` provider errors, `▣` handoff submissions. Escape twice cancels.
|
|
128
|
+
- **`/delegate peek [run-id]`** opens the same feed decoded from the run's
|
|
129
|
+
captured transcript — live-following (`● live`) while the run is active,
|
|
130
|
+
scrollable (`j`/`k`, `f` re-follow, `q` close), and equally useful
|
|
131
|
+
post-mortem on any finished run. Headless/print mode prints the tail.
|
|
132
|
+
|
|
121
133
|
### The mandatory structured handoff (protocol, not prompt)
|
|
122
134
|
|
|
123
135
|
Anything the harness NEEDS from the child is a validated protocol step —
|
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/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";
|
|
@@ -498,7 +501,20 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
498
501
|
role: request.role,
|
|
499
502
|
phase: "starting",
|
|
500
503
|
elapsedMs: 0,
|
|
501
|
-
|
|
504
|
+
feedLines: [],
|
|
505
|
+
};
|
|
506
|
+
// Live feed: every child event lands in the ring; the panel renders
|
|
507
|
+
// the bounded tail on each host refresh (1 s + event-driven).
|
|
508
|
+
const feed = new FeedRing(120);
|
|
509
|
+
let feedStartMs = 0;
|
|
510
|
+
let hardMs: number | undefined;
|
|
511
|
+
const feedLines = (): string[] => {
|
|
512
|
+
if (feed.all().length === 0) return [];
|
|
513
|
+
return renderFeedEvents([...feed.all()], {
|
|
514
|
+
startMs: feedStartMs || Date.now(),
|
|
515
|
+
maxChars: 150,
|
|
516
|
+
maxEvents: 14,
|
|
517
|
+
});
|
|
502
518
|
};
|
|
503
519
|
const runPromise = app.run(request, {
|
|
504
520
|
...hooks,
|
|
@@ -508,18 +524,44 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
508
524
|
viewState.role = u.role;
|
|
509
525
|
viewState.phase = u.phase;
|
|
510
526
|
viewState.elapsedMs = u.elapsedMs;
|
|
511
|
-
viewState.
|
|
527
|
+
viewState.model = u.model;
|
|
528
|
+
viewState.openTools = u.openTools;
|
|
529
|
+
viewState.turns = u.usage?.turns;
|
|
530
|
+
viewState.tokens = { input: u.usage?.input, output: u.usage?.output };
|
|
531
|
+
if (!feedStartMs) feedStartMs = Date.now() - u.elapsedMs;
|
|
532
|
+
},
|
|
533
|
+
onEvent: (event) => {
|
|
534
|
+
feed.push(event);
|
|
512
535
|
},
|
|
513
536
|
});
|
|
537
|
+
// Effective hard cap for the progress bar: per-run > project > user.
|
|
538
|
+
try {
|
|
539
|
+
const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
|
|
540
|
+
hardMs = request.timeoutMs ?? s.timeouts.hardMs;
|
|
541
|
+
} catch {
|
|
542
|
+
hardMs = undefined;
|
|
543
|
+
}
|
|
544
|
+
viewState.hardMs = hardMs;
|
|
545
|
+
let refreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
514
546
|
const outcome = await ctx.ui.custom<{ cancelled?: boolean } | undefined>(
|
|
515
|
-
(tui, theme, keybindings, done) =>
|
|
516
|
-
|
|
547
|
+
(tui, theme, keybindings, done) => {
|
|
548
|
+
refreshTimer = setInterval(() => {
|
|
549
|
+
viewState.elapsedMs = feedStartMs ? Date.now() - feedStartMs : viewState.elapsedMs;
|
|
550
|
+
viewState.feedLines = feedLines();
|
|
551
|
+
tui.requestRender();
|
|
552
|
+
}, 1000);
|
|
553
|
+
return new RunningView({
|
|
517
554
|
theme,
|
|
518
555
|
keybindings,
|
|
519
|
-
state: () =>
|
|
556
|
+
state: () => {
|
|
557
|
+
viewState.feedLines = feedLines();
|
|
558
|
+
return viewState;
|
|
559
|
+
},
|
|
520
560
|
done,
|
|
521
|
-
})
|
|
561
|
+
});
|
|
562
|
+
},
|
|
522
563
|
);
|
|
564
|
+
if (refreshTimer) clearInterval(refreshTimer);
|
|
523
565
|
if (outcome?.cancelled) {
|
|
524
566
|
await app.cancel();
|
|
525
567
|
say(ctx, `[delegate] cancellation requested; the run finalizes with its terminal receipt.`);
|
|
@@ -680,6 +722,61 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
680
722
|
}
|
|
681
723
|
await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
|
|
682
724
|
return;
|
|
725
|
+
case "peek": {
|
|
726
|
+
const id = intent.runId?.trim() || app.mostRecentRunId();
|
|
727
|
+
if (!id) {
|
|
728
|
+
say(ctx, "[delegate] no runs to peek at.", "warning");
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
let meta;
|
|
732
|
+
try {
|
|
733
|
+
meta = app.inspect(id).metadata;
|
|
734
|
+
} catch {
|
|
735
|
+
say(ctx, `[delegate] unknown run '${id}'.`, "error");
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
if (!fsSync.existsSync(meta.transcriptPath)) {
|
|
739
|
+
say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
if (ctx.mode === "tui") {
|
|
743
|
+
await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
|
|
744
|
+
const state = () => {
|
|
745
|
+
let live = false;
|
|
746
|
+
try {
|
|
747
|
+
live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
|
|
748
|
+
} catch {
|
|
749
|
+
live = false;
|
|
750
|
+
}
|
|
751
|
+
const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
|
|
752
|
+
return {
|
|
753
|
+
title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${meta.model}` : ""} · ${meta.state}`,
|
|
754
|
+
summary: meta.transcriptPath,
|
|
755
|
+
lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
|
|
756
|
+
live,
|
|
757
|
+
};
|
|
758
|
+
};
|
|
759
|
+
// Live-follow refresh timer; cleared the moment the
|
|
760
|
+
// overlay closes (done wrapper) — never leaks.
|
|
761
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
762
|
+
const wrappedDone = (result: { closed?: boolean }) => {
|
|
763
|
+
if (timer) clearInterval(timer);
|
|
764
|
+
done(result);
|
|
765
|
+
};
|
|
766
|
+
const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
|
|
767
|
+
timer = setInterval(() => tui.requestRender(), 1000);
|
|
768
|
+
return view;
|
|
769
|
+
});
|
|
770
|
+
} else {
|
|
771
|
+
const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
|
|
772
|
+
const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
|
|
773
|
+
say(
|
|
774
|
+
ctx,
|
|
775
|
+
`[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`,
|
|
776
|
+
);
|
|
777
|
+
}
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
683
780
|
case "resume": {
|
|
684
781
|
const runId = intent.runId?.trim();
|
|
685
782
|
if (!runId || !intent.task) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maheidem/pi-delegate",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
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
|
-
|
|
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")
|
|
509
|
-
|
|
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)
|
|
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
|
|
package/ui/peek-view.ts
ADDED
|
@@ -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
|
+
}
|
package/ui/running-view.ts
CHANGED
|
@@ -1,21 +1,32 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* delegate —
|
|
2
|
+
* delegate — live child feed panel for command-driven foreground runs.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
|
|
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
|
-
//
|
|
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
|
-
|
|
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
|
|
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) =>
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
|
|
83
|
-
|
|
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
|
}
|