@yusukeshib/pi-babysit 0.6.33 → 0.6.34

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
@@ -248,7 +248,25 @@ A subagent's babysit log is a subset of Pi's standard RPC event stream
248
248
  which completion detection uses.
249
249
 
250
250
  `createRpcEventRestorer()` turns a log back into standard Pi events for
251
- viewers. Live `/babysit` and attach views render either profile, as well as logs
251
+ viewers.
252
+
253
+ ### Subagent transcript viewer
254
+
255
+ `view.mjs` shows a subagent the way Pi shows its own chat: it restores the log
256
+ to standard events and renders them with the installed Pi's components
257
+ (`AssistantMessageComponent`, `ToolExecutionComponent`, …), following the log
258
+ live. The widget's copy icon on a local subagent row copies this command:
259
+
260
+ ```sh
261
+ node ~/.pi/agent/npm/node_modules/@yusukeshib/pi-babysit/view.mjs <session-id | session dir | output.log>
262
+ ```
263
+
264
+ Keys: `q` / `Ctrl-C` quit, `Ctrl-O` expand or collapse tool output, `t`
265
+ toggle thinking blocks. `--print` renders the current transcript once to stdout;
266
+ `--cwd DIR` overrides the worker directory used to shorten tool paths. Pi
267
+ packages are loaded from the managed install (`~/.pi/agent/install`), the `pi`
268
+ on `PATH`, or `PI_BABYSIT_PI_PACKAGE_DIR`. Built-in tools use Pi's renderers;
269
+ extension tools fall back to generic rendering. Live `/babysit` and attach views render either profile, as well as logs
252
270
  written by older pi-babysit releases.
253
271
 
254
272
  ## Process ownership, interruption, shutdown, and reload
package/index.ts CHANGED
@@ -639,6 +639,8 @@ interface Meta {
639
639
  // subagent
640
640
  task?: string;
641
641
  launchCommand?: string;
642
+ /** Worker working directory; the transcript viewer resolves tool paths against it. */
643
+ cwd?: string;
642
644
  reapAfter?: string;
643
645
  promptOffset?: number;
644
646
  model?: string;
@@ -2504,6 +2506,7 @@ async function spawnSubagent(
2504
2506
  messageTempDirs: delivery.tempDir
2505
2507
  ? [{ dir: delivery.tempDir, afterAgentEnd: 1 }]
2506
2508
  : undefined,
2509
+ cwd: path.resolve(opts.cwd),
2507
2510
  depth: opts.depth,
2508
2511
  maxDepth: opts.maxDepth,
2509
2512
  budget: opts.budget,
@@ -2683,6 +2686,18 @@ function sessionCliCommand(id: string, command: "log" | "attach"): string {
2683
2686
  return `BABYSIT_DIR=${shq(ROOT)} ${shq(BABYSIT_BIN)} ${command} -s ${shq(id)}`;
2684
2687
  }
2685
2688
 
2689
+ /**
2690
+ * Command copied by the widget icon: local subagents open the transcript
2691
+ * viewer (rendered with Pi's components); everything else gets its log.
2692
+ */
2693
+ export function widgetCopyCommand(id: string): string {
2694
+ const meta = readMeta(id);
2695
+ if (meta?.kind === "subagent" && !meta.host) {
2696
+ return `${shq(process.execPath)} ${shq(path.join(EXT_DIR, "view.mjs"))} ${shq(logPath(id))}`;
2697
+ }
2698
+ return sessionCliCommand(id, "log");
2699
+ }
2700
+
2686
2701
  function attachCmd(id: string): string {
2687
2702
  return sessionCliCommand(id, "attach");
2688
2703
  }
@@ -3619,7 +3634,7 @@ export default function (pi: ExtensionAPI) {
3619
3634
  if (!sessionWidget) {
3620
3635
  ctx.ui.setWidget("pi-babysit", (tui) => {
3621
3636
  sessionWidget = createWidgetComponent(summaryLines, displays,
3622
- (id) => copyToClipboard(sessionCliCommand(id, "log")),
3637
+ (id) => copyToClipboard(widgetCopyCommand(id)),
3623
3638
  () => tui.requestRender());
3624
3639
  return sessionWidget;
3625
3640
  }, { placement: "belowEditor" });
@@ -4884,6 +4899,7 @@ export default function (pi: ExtensionAPI) {
4884
4899
  launchCommand: meta?.launchCommand,
4885
4900
  reapAfter: meta?.reapAfter,
4886
4901
  startedAt: meta?.startedAt,
4902
+ cwd: meta?.cwd,
4887
4903
  task: params.text,
4888
4904
  // Start after the prompt-acceptance response. This excludes a
4889
4905
  // preceding run that settled between `send` and RPC acceptance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-babysit",
3
- "version": "0.6.33",
3
+ "version": "0.6.34",
4
4
  "description": "Run any shell command and pi subagents under babysit, with context-safe captured output.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -25,6 +25,9 @@
25
25
  "format-stream.mjs",
26
26
  "rpc-stream-proxy.mjs",
27
27
  "rpc-stream-format.mjs",
28
+ "transcript-view.mjs",
29
+ "pi-runtime.mjs",
30
+ "view.mjs",
28
31
  "search-log.mjs",
29
32
  "gc.mjs",
30
33
  "gc.d.mts",
package/pi-runtime.mjs ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Resolve the Pi packages of the INSTALLED pi, so a standalone viewer renders
3
+ * with the same components as the pi that produced the log (not a copy that
4
+ * happens to sit in pi-babysit's own node_modules).
5
+ */
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { execFileSync } from "node:child_process";
10
+ import { pathToFileURL } from "node:url";
11
+
12
+ const AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
13
+
14
+ function packageName(dir) {
15
+ try {
16
+ return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).name;
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+
22
+ function managedInstallDir() {
23
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), ".pi", "agent");
24
+ try {
25
+ const version = fs.readFileSync(path.join(agentDir, "install", "current-version"), "utf8").trim();
26
+ if (!version) return undefined;
27
+ return path.join(agentDir, "install", "releases", version, "node_modules", AGENT_PACKAGE);
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ function packageDirFromBinary() {
34
+ try {
35
+ const bin = execFileSync("sh", ["-c", "command -v pi"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
36
+ if (!bin) return undefined;
37
+ let dir = path.dirname(fs.realpathSync(bin));
38
+ for (;;) {
39
+ if (packageName(dir) === AGENT_PACKAGE) return dir;
40
+ const parent = path.dirname(dir);
41
+ if (parent === dir) return undefined;
42
+ dir = parent;
43
+ }
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ /** Directory of the installed pi-coding-agent package, or undefined. */
50
+ export function findPiPackageDir() {
51
+ const candidates = [process.env.PI_BABYSIT_PI_PACKAGE_DIR, managedInstallDir(), packageDirFromBinary()];
52
+ return candidates.find((dir) => dir && packageName(dir) === AGENT_PACKAGE);
53
+ }
54
+
55
+ function siblingPackageEntry(agentDir, name) {
56
+ for (const dir of [
57
+ path.join(path.dirname(agentDir), name),
58
+ path.join(agentDir, "node_modules", "@earendil-works", name),
59
+ ]) {
60
+ if (packageName(dir) === `@earendil-works/${name}`) {
61
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
62
+ const entry = pkg.exports?.["."]?.import ?? pkg.exports?.["."]?.default ?? pkg.module ?? pkg.main ?? "index.js";
63
+ return pathToFileURL(path.join(dir, entry)).href;
64
+ }
65
+ }
66
+ return undefined;
67
+ }
68
+
69
+ /**
70
+ * Load { agent, tui, withBuiltInRenderers, packageDir, version }.
71
+ * withBuiltInRenderers is optional (an internal module of pi-coding-agent).
72
+ */
73
+ export async function loadPiRuntime() {
74
+ const packageDir = findPiPackageDir();
75
+ let agent;
76
+ let tui;
77
+ let withBuiltInRenderers;
78
+ let version;
79
+ if (packageDir) {
80
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
81
+ version = pkg.version;
82
+ agent = await import(pathToFileURL(path.join(packageDir, pkg.exports?.["."]?.import ?? "dist/index.js")).href);
83
+ const tuiEntry = siblingPackageEntry(packageDir, "pi-tui");
84
+ tui = await import(tuiEntry ?? "@earendil-works/pi-tui");
85
+ try {
86
+ const renderers = await import(
87
+ pathToFileURL(path.join(packageDir, "dist", "core", "tools", "renderers", "index.js")).href
88
+ );
89
+ withBuiltInRenderers = renderers.withBuiltInRenderers;
90
+ } catch {
91
+ /* generic tool rendering */
92
+ }
93
+ } else {
94
+ agent = await import(AGENT_PACKAGE);
95
+ tui = await import("@earendil-works/pi-tui");
96
+ }
97
+ return { agent, tui, withBuiltInRenderers, packageDir, version };
98
+ }
@@ -0,0 +1,279 @@
1
+ /**
2
+ * transcript-view.mjs — render standard Pi RPC events with Pi's own TUI
3
+ * components, mirroring interactive mode's event handling.
4
+ *
5
+ * RPC `message_update` events are delta-only, so the streaming assistant
6
+ * message is rebuilt from content-block deltas (see Pi docs/json.md).
7
+ */
8
+
9
+ const RED = "\x1b[31m";
10
+ const DIM = "\x1b[2m";
11
+ const RESET = "\x1b[0m";
12
+
13
+ function userText(message) {
14
+ if (typeof message.content === "string") return message.content;
15
+ if (!Array.isArray(message.content)) return "";
16
+ return message.content
17
+ .filter((block) => block?.type === "text" && typeof block.text === "string")
18
+ .map((block) => block.text)
19
+ .join("");
20
+ }
21
+
22
+ /** Apply one delta-only assistantMessageEvent to a mutable assistant message. */
23
+ export function applyAssistantDelta(message, update) {
24
+ if (!update || typeof update !== "object") return;
25
+ const content = Array.isArray(message.content) ? message.content : (message.content = []);
26
+ const index = update.contentIndex;
27
+ switch (update.type) {
28
+ case "text_start":
29
+ content[index] = { type: "text", text: "" };
30
+ break;
31
+ case "text_delta":
32
+ if (content[index]?.type !== "text") content[index] = { type: "text", text: "" };
33
+ content[index].text += update.delta ?? "";
34
+ break;
35
+ case "text_end":
36
+ content[index] = { ...content[index], type: "text", text: String(update.content ?? content[index]?.text ?? "") };
37
+ break;
38
+ case "thinking_start":
39
+ content[index] = { type: "thinking", thinking: "" };
40
+ break;
41
+ case "thinking_delta":
42
+ if (content[index]?.type !== "thinking") content[index] = { type: "thinking", thinking: "" };
43
+ content[index].thinking += update.delta ?? "";
44
+ break;
45
+ case "thinking_end":
46
+ content[index] = {
47
+ ...content[index],
48
+ type: "thinking",
49
+ thinking: String(update.content ?? content[index]?.thinking ?? ""),
50
+ };
51
+ break;
52
+ case "toolcall_start":
53
+ content[index] = { type: "toolCall", id: update.id, name: update.toolName, arguments: {} };
54
+ break;
55
+ case "toolcall_end":
56
+ if (update.toolCall) content[index] = update.toolCall;
57
+ break;
58
+ default:
59
+ break;
60
+ }
61
+ }
62
+
63
+ export function createTranscriptView({ runtime, tui, cwd = process.cwd(), hideThinkingBlock = false }) {
64
+ const {
65
+ AssistantMessageComponent,
66
+ ToolExecutionComponent,
67
+ UserMessageComponent,
68
+ CustomMessageComponent,
69
+ CompactionSummaryMessageComponent,
70
+ BranchSummaryMessageComponent,
71
+ getMarkdownTheme,
72
+ } = runtime.agent;
73
+ const { Container, Spacer, Text } = runtime.tui;
74
+
75
+ const container = new Container();
76
+ const pendingTools = new Map();
77
+ const expandables = [];
78
+ const assistants = [];
79
+ let expanded = false;
80
+ let hideThinking = hideThinkingBlock;
81
+ let streaming;
82
+
83
+ const markdownTheme = () => getMarkdownTheme();
84
+ const toolDefinition = (name) => runtime.withBuiltInRenderers?.(name, undefined);
85
+ const add = (component) => {
86
+ container.addChild(component);
87
+ return component;
88
+ };
89
+ const addExpandable = (component) => {
90
+ component.setExpanded?.(expanded);
91
+ expandables.push(component);
92
+ return add(component);
93
+ };
94
+ const note = (text, color = DIM) => {
95
+ add(new Spacer(1));
96
+ add(new Text(`${color}${text}${RESET}`, 1, 0));
97
+ };
98
+
99
+ function toolComponent(name, id, args) {
100
+ let component = pendingTools.get(id);
101
+ if (component) return component;
102
+ component = new ToolExecutionComponent(name, id, args ?? {}, { showImages: false }, toolDefinition(name), tui, cwd);
103
+ addExpandable(component);
104
+ pendingTools.set(id, component);
105
+ return component;
106
+ }
107
+
108
+ function syncToolCalls(message) {
109
+ for (const block of message.content ?? []) {
110
+ if (block?.type !== "toolCall" || !block.id) continue;
111
+ const existing = pendingTools.get(block.id);
112
+ if (existing) existing.updateArgs(block.arguments ?? {});
113
+ else toolComponent(block.name, block.id, block.arguments);
114
+ }
115
+ }
116
+
117
+ function newAssistant(message) {
118
+ const component = new AssistantMessageComponent(undefined, hideThinking, markdownTheme());
119
+ assistants.push(component);
120
+ add(component);
121
+ component.updateContent(message, true);
122
+ return component;
123
+ }
124
+
125
+ function finishAssistant(component, message) {
126
+ component.updateContent(message, false);
127
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
128
+ const errorMessage =
129
+ message.errorMessage || (message.stopReason === "aborted" ? "Operation aborted" : "Error");
130
+ for (const tool of pendingTools.values()) {
131
+ tool.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
132
+ }
133
+ pendingTools.clear();
134
+ } else {
135
+ for (const tool of pendingTools.values()) tool.setArgsComplete();
136
+ }
137
+ }
138
+
139
+ function addMessage(message) {
140
+ switch (message.role) {
141
+ case "user": {
142
+ const text = userText(message);
143
+ if (!text) return;
144
+ if (container.children.length > 0) add(new Spacer(1));
145
+ add(new UserMessageComponent(text, markdownTheme()));
146
+ return;
147
+ }
148
+ case "custom":
149
+ if (message.display) addExpandable(new CustomMessageComponent(message, undefined, markdownTheme()));
150
+ return;
151
+ case "compactionSummary":
152
+ add(new Spacer(1));
153
+ addExpandable(new CompactionSummaryMessageComponent(message, markdownTheme()));
154
+ return;
155
+ case "branchSummary":
156
+ add(new Spacer(1));
157
+ addExpandable(new BranchSummaryMessageComponent(message, markdownTheme()));
158
+ return;
159
+ default:
160
+ return;
161
+ }
162
+ }
163
+
164
+ function apply(event) {
165
+ switch (event?.type) {
166
+ case "agent_start":
167
+ pendingTools.clear();
168
+ return;
169
+ case "message_start": {
170
+ const message = event.message;
171
+ if (!message) return;
172
+ if (message.role === "assistant") {
173
+ const copy = { ...message, content: [...(Array.isArray(message.content) ? message.content : [])] };
174
+ streaming = { message: copy, component: newAssistant(copy) };
175
+ } else {
176
+ addMessage(message);
177
+ }
178
+ return;
179
+ }
180
+ case "message_update": {
181
+ if (!streaming) return;
182
+ if (event.message?.role === "assistant") {
183
+ // Cumulative snapshot from old Pi releases.
184
+ streaming.message = { ...event.message, content: [...(event.message.content ?? [])] };
185
+ } else {
186
+ applyAssistantDelta(streaming.message, event.assistantMessageEvent);
187
+ }
188
+ if (event.usage) streaming.message.usage = event.usage;
189
+ streaming.component.updateContent(streaming.message, true);
190
+ syncToolCalls(streaming.message);
191
+ return;
192
+ }
193
+ case "message_end": {
194
+ const message = event.message;
195
+ if (message?.role !== "assistant") return;
196
+ const component = streaming?.component ?? newAssistant(message);
197
+ syncToolCalls(message);
198
+ finishAssistant(component, message);
199
+ streaming = undefined;
200
+ return;
201
+ }
202
+ case "tool_execution_start": {
203
+ if (event.parentToolCallId) return;
204
+ const component = toolComponent(event.toolName, event.toolCallId, event.args);
205
+ component.markExecutionStarted?.();
206
+ return;
207
+ }
208
+ case "tool_execution_update":
209
+ pendingTools.get(event.toolCallId)?.updateResult({ ...event.partialResult, isError: false }, true);
210
+ return;
211
+ case "tool_execution_end": {
212
+ const component = pendingTools.get(event.toolCallId);
213
+ if (!component) return;
214
+ component.updateResult({ ...event.result, isError: event.isError, durationMs: event.durationMs });
215
+ pendingTools.delete(event.toolCallId);
216
+ return;
217
+ }
218
+ case "agent_end":
219
+ if (streaming) {
220
+ container.removeChild(streaming.component);
221
+ streaming = undefined;
222
+ }
223
+ pendingTools.clear();
224
+ return;
225
+ case "entry_appended": {
226
+ const entry = event.entry;
227
+ if (entry?.type === "custom_message" && entry.display) {
228
+ addMessage({
229
+ role: "custom",
230
+ customType: entry.customType,
231
+ content: entry.content,
232
+ display: entry.display,
233
+ details: entry.details,
234
+ timestamp: entry.timestamp,
235
+ });
236
+ }
237
+ return;
238
+ }
239
+ case "compaction_end":
240
+ if (event.result?.summary) {
241
+ addMessage({
242
+ role: "compactionSummary",
243
+ summary: event.result.summary,
244
+ tokensBefore: event.result.tokensBefore,
245
+ timestamp: Date.now(),
246
+ });
247
+ }
248
+ return;
249
+ case "extension_error":
250
+ note(`Extension error${event.extensionPath ? ` (${event.extensionPath})` : ""}: ${event.error ?? ""}`, RED);
251
+ return;
252
+ case "error":
253
+ note(`Error: ${event.message ?? event.error ?? JSON.stringify(event)}`, RED);
254
+ return;
255
+ case "response":
256
+ if (event.success === false) note(`RPC ${event.command ?? "command"} failed: ${event.error ?? ""}`, RED);
257
+ return;
258
+ default:
259
+ return;
260
+ }
261
+ }
262
+
263
+ return {
264
+ container,
265
+ apply,
266
+ get expanded() {
267
+ return expanded;
268
+ },
269
+ setToolsExpanded(value) {
270
+ expanded = value;
271
+ for (const component of expandables) component.setExpanded?.(value);
272
+ },
273
+ toggleThinking() {
274
+ hideThinking = !hideThinking;
275
+ for (const component of assistants) component.setHideThinkingBlock(hideThinking);
276
+ return hideThinking;
277
+ },
278
+ };
279
+ }
package/view.mjs ADDED
@@ -0,0 +1,219 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * view.mjs — live, read-only view of a pi-babysit subagent rendered with Pi's
4
+ * own TUI components.
5
+ *
6
+ * node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]
7
+ *
8
+ * The subagent log (rpc-stream-format.mjs) is restored to standard Pi RPC
9
+ * events and replayed into transcript-view.mjs. Follow mode tails the log until
10
+ * you quit (q / Ctrl-C). --print renders the current transcript once to stdout.
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { pathToFileURL } from "node:url";
16
+ import { loadPiRuntime } from "./pi-runtime.mjs";
17
+ import { createRpcEventRestorer } from "./rpc-stream-format.mjs";
18
+ import { createTranscriptView } from "./transcript-view.mjs";
19
+
20
+ const USAGE = "Usage: node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]";
21
+
22
+ export function parseArgs(argv) {
23
+ const options = { print: false, cwd: undefined, target: undefined };
24
+ for (let index = 0; index < argv.length; index++) {
25
+ const arg = argv[index];
26
+ if (arg === "--print") options.print = true;
27
+ else if (arg === "--cwd") options.cwd = argv[++index];
28
+ else if (arg === "-h" || arg === "--help") options.help = true;
29
+ else if (!options.target) options.target = arg;
30
+ else throw new Error(`Unexpected argument: ${arg}`);
31
+ }
32
+ return options;
33
+ }
34
+
35
+ /** Resolve a session id, session directory, or log path to the log file. */
36
+ export function resolveLogPath(target, rootBase = process.env.PI_BABYSIT_DIR ?? path.join(os.homedir(), ".pi-babysit")) {
37
+ if (fs.existsSync(target)) {
38
+ const stat = fs.statSync(target);
39
+ return stat.isDirectory() ? path.join(target, "output.log") : target;
40
+ }
41
+ let best;
42
+ for (const root of fs.existsSync(rootBase) ? fs.readdirSync(rootBase) : []) {
43
+ const log = path.join(rootBase, root, "sessions", target, "output.log");
44
+ try {
45
+ const mtime = fs.statSync(log).mtimeMs;
46
+ if (!best || mtime > best.mtime) best = { log, mtime };
47
+ } catch {
48
+ /* not in this root */
49
+ }
50
+ }
51
+ if (!best) throw new Error(`No babysit session log found for ${target} under ${rootBase}`);
52
+ return best.log;
53
+ }
54
+
55
+ function readJson(file) {
56
+ try {
57
+ return JSON.parse(fs.readFileSync(file, "utf8"));
58
+ } catch {
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ /** pi-babysit's own metadata for a session log (<root>/meta/<id>.json). */
64
+ function sessionInfo(logPath) {
65
+ const sessionDir = path.dirname(logPath);
66
+ const id = path.basename(sessionDir);
67
+ const root = path.dirname(path.dirname(sessionDir));
68
+ return {
69
+ id,
70
+ meta: readJson(path.join(root, "meta", `${id}.json`)),
71
+ statusFile: path.join(sessionDir, "status.json"),
72
+ };
73
+ }
74
+
75
+ function piSettings() {
76
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? path.join(os.homedir(), ".pi", "agent");
77
+ return readJson(path.join(agentDir, "settings.json")) ?? {};
78
+ }
79
+
80
+ /** Incremental JSONL reader: feed bytes, get complete event objects. */
81
+ export function createLogReader(onEvent) {
82
+ const restorer = createRpcEventRestorer();
83
+ let pending = "";
84
+ const line = (raw) => {
85
+ const text = raw.replace(/\r$/, "").trim();
86
+ if (!text.startsWith("{")) return;
87
+ let event;
88
+ try {
89
+ event = JSON.parse(text);
90
+ } catch {
91
+ return;
92
+ }
93
+ for (const restored of restorer.push(event)) onEvent(restored);
94
+ };
95
+ return {
96
+ push(chunk) {
97
+ pending += chunk;
98
+ let newline;
99
+ while ((newline = pending.indexOf("\n")) >= 0) {
100
+ line(pending.slice(0, newline));
101
+ pending = pending.slice(newline + 1);
102
+ }
103
+ },
104
+ end() {
105
+ if (pending) line(pending);
106
+ pending = "";
107
+ for (const restored of restorer.end()) onEvent(restored);
108
+ },
109
+ };
110
+ }
111
+
112
+ function readFrom(file, offset) {
113
+ const size = fs.statSync(file).size;
114
+ if (size <= offset) return { text: "", offset: size < offset ? 0 : offset, truncated: size < offset };
115
+ const buffer = Buffer.alloc(size - offset);
116
+ const fd = fs.openSync(file, "r");
117
+ try {
118
+ fs.readSync(fd, buffer, 0, buffer.length, offset);
119
+ } finally {
120
+ fs.closeSync(fd);
121
+ }
122
+ return { text: buffer, offset: size, truncated: false };
123
+ }
124
+
125
+ export async function main(argv = process.argv.slice(2)) {
126
+ const options = parseArgs(argv);
127
+ if (options.help || !options.target) {
128
+ console.log(USAGE);
129
+ return options.help ? 0 : 2;
130
+ }
131
+ const logPath = resolveLogPath(options.target);
132
+ const info = sessionInfo(logPath);
133
+ const cwd = options.cwd ?? info.meta?.cwd ?? process.cwd();
134
+ const runtime = await loadPiRuntime();
135
+ const settings = piSettings();
136
+ runtime.agent.initTheme(settings.theme, false);
137
+
138
+ const decoder = new TextDecoder();
139
+ if (options.print) {
140
+ const stub = { requestRender() {} };
141
+ const view = createTranscriptView({ runtime, tui: stub, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
142
+ const reader = createLogReader((event) => view.apply(event));
143
+ reader.push(decoder.decode(fs.readFileSync(logPath)));
144
+ reader.end();
145
+ const width = process.stdout.columns || 120;
146
+ process.stdout.write(`${view.container.render(width).join("\n")}\n`);
147
+ return 0;
148
+ }
149
+
150
+ const { ProcessTerminal, Text } = runtime.tui;
151
+ // Pi >= 1.5 renders regular (scrollback) mode with TuiMainScreen; older
152
+ // pi-tui releases export the TUI class itself.
153
+ const Screen = runtime.tui.TuiMainScreen ?? runtime.tui.TUI;
154
+ if (typeof Screen !== "function") throw new Error("Unsupported pi-tui: no TuiMainScreen or TUI export");
155
+ const ui = new Screen(new ProcessTerminal());
156
+ let view = createTranscriptView({ runtime, tui: ui, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
157
+ let reader = createLogReader((event) => view.apply(event));
158
+ const status = new Text("", 1, 0);
159
+ const statusLine = () => {
160
+ const state = readJson(info.statusFile)?.state ?? "unknown";
161
+ const label = info.meta?.name && info.meta.name !== info.id ? `${info.id} (${info.meta.name})` : info.id;
162
+ status.setText(
163
+ `\x1b[2m${label} · ${state} · q quit · ctrl+o ${view.expanded ? "collapse" : "expand"} tools · t thinking\x1b[0m`,
164
+ );
165
+ };
166
+ ui.addChild(view.container);
167
+ ui.addChild(status);
168
+
169
+ let offset = 0;
170
+ const poll = () => {
171
+ const chunk = readFrom(logPath, offset);
172
+ if (chunk.truncated) {
173
+ // The log was replaced; start over.
174
+ ui.removeChild(view.container);
175
+ view = createTranscriptView({ runtime, tui: ui, cwd, hideThinkingBlock: settings.hideThinkingBlock === true });
176
+ reader = createLogReader((event) => view.apply(event));
177
+ ui.children.unshift(view.container);
178
+ }
179
+ offset = chunk.offset;
180
+ if (chunk.text.length) reader.push(decoder.decode(chunk.text, { stream: true }));
181
+ statusLine();
182
+ ui.requestRender();
183
+ };
184
+
185
+ const quit = () => {
186
+ clearInterval(timer);
187
+ ui.stop();
188
+ process.exit(0);
189
+ };
190
+ // pi-tui may enable the kitty keyboard protocol, so compare parsed keys.
191
+ const key = (data, name) => runtime.tui.matchesKey?.(data, name) ?? false;
192
+ ui.addInputListener((data) => {
193
+ if (key(data, "q") || key(data, "ctrl+c") || data === "q" || data === "\x03") quit();
194
+ else if (key(data, "ctrl+o") || data === "\x0f") view.setToolsExpanded(!view.expanded);
195
+ else if (key(data, "t") || data === "t") view.toggleThinking();
196
+ else return { consume: true };
197
+ statusLine();
198
+ ui.requestRender();
199
+ return { consume: true };
200
+ });
201
+
202
+ poll();
203
+ ui.start();
204
+ const timer = setInterval(poll, 200);
205
+ return undefined;
206
+ }
207
+
208
+ const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
209
+ if (entry === import.meta.url) {
210
+ main().then(
211
+ (code) => {
212
+ if (typeof code === "number") process.exitCode = code;
213
+ },
214
+ (error) => {
215
+ console.error(error instanceof Error ? error.message : String(error));
216
+ process.exitCode = 1;
217
+ },
218
+ );
219
+ }