@yusukeshib/pi-babysit 0.6.33 → 0.6.35

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
@@ -86,7 +86,7 @@ Descriptions are display metadata, not shell code, stdin, or instructions sent
86
86
  to the subagent.
87
87
 
88
88
  ```text
89
- babysit_run { description: "Run regression tests", command: "bun test", foreground: true }
89
+ babysit_run { description: "Run regression tests", command: "bun test", foreground: true, timeout: "10m" }
90
90
  babysit_run { description: "Review the authentication changes", profile: "subagent", task: "Review the authentication diff for security regressions", maxTurns: 5 }
91
91
  babysit_check { description: "Inspect build errors", id: "build", pattern: "ERROR" }
92
92
  babysit_wait { description: "Wait for the build to finish", id: "build" }
@@ -112,8 +112,8 @@ SSH aliases, keys, known hosts, and ProxyJump are handled by babysit/SSH;
112
112
  pi-babysit does not install remote software or copy credentials.
113
113
 
114
114
  ```text
115
- babysit_run { description: "Run tests on Linux", host: "yusuke-t4", cwd: "/home/yusuke/project", command: "bun test", foreground: true, returnLines: 30 }
116
- babysit_run { description: "Open a remote Python REPL", host: "user@server", command: "python3 -i", name: "remote-repl", continueAfterStart: true }
115
+ babysit_run { description: "Run tests on Linux", host: "yusuke-t4", cwd: "/home/yusuke/project", command: "bun test", foreground: true, timeout: "10m", returnLines: 30 }
116
+ babysit_run { description: "Open a remote Python REPL", host: "user@server", command: "python3 -i", name: "remote-repl", timeout: "none", continueAfterStart: true }
117
117
  babysit_check { description: "Read the remote REPL screen", id: "remote-repl", screen: true }
118
118
  babysit_send { description: "Evaluate a value in the remote REPL", id: "remote-repl", text: "print(42)" }
119
119
  babysit_kill { description: "Close the remote REPL", id: "remote-repl" }
@@ -248,9 +248,53 @@ 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
 
272
+ ## Execution timeouts
273
+
274
+ Commands default to an absolute **60s execution timeout**, in both foreground
275
+ and background mode, locally and over SSH. Subagents retain their **15m**
276
+ default. The babysit supervisor terminates the process when its deadline is
277
+ reached; a foreground call then returns the terminal result to the agent rather
278
+ than waiting forever. This is an execution limit, not an output-inactivity
279
+ limit or the quick-command background grace period.
280
+
281
+ Set a longer positive duration explicitly for slow work. Only an explicit
282
+ `timeout: "none"` disables the deadline, and only for background runs in
283
+ interactive/RPC mode. It is rejected with `foreground: true` or in non-interactive
284
+ mode, which always waits inline. Empty strings, zero durations, `off`, and
285
+ `never` are rejected rather than forwarded as babysit's infinite-timeout aliases.
286
+
287
+ ```text
288
+ babysit_run { description: "Run a long test suite", command: "bun test", foreground: true, timeout: "10m" }
289
+ babysit_run { description: "Start the development server", command: "bun run dev", name: "dev-server", timeout: "none", continueAfterStart: true }
290
+ ```
291
+
292
+ `idleTimeout` remains disabled by default: a silent command is not necessarily
293
+ stuck. `babysit_wait.timeout` limits only that wait, not the underlying process,
294
+ and its default remains unlimited; the process's execution timeout still applies.
295
+ To wait for readiness of an intentionally unbounded server, set a finite wait
296
+ such as `babysit_wait { description: "Wait for server readiness", id: "dev-server", expect: "listening", timeout: "15s" }`.
297
+
254
298
  ## Process ownership, interruption, shutdown, and reload
255
299
 
256
300
  An inline process wait (`foreground: true`, or process execution in a non-UI
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;
@@ -2129,6 +2131,28 @@ async function reserveUniqueSessionId(name: string): Promise<string> {
2129
2131
  return id;
2130
2132
  }
2131
2133
 
2134
+ /** Resolve a bounded execution deadline before invoking the supervisor. */
2135
+ export function resolveRunTimeout(timeout: string | undefined, isSubagent: boolean, waitsInline: boolean): string {
2136
+ const value = timeout === undefined ? (isSubagent ? "15m" : "60s") : timeout.trim().toLowerCase();
2137
+ if (value === "none") {
2138
+ if (waitsInline) {
2139
+ throw new Error('timeout: "none" requires a background run; foreground and non-interactive runs need a finite timeout.');
2140
+ }
2141
+ return value;
2142
+ }
2143
+ // babysit also accepts empty/zero/off/never as infinite deadlines. Do not
2144
+ // forward those aliases: unbounded execution must be an explicit "none".
2145
+ const match = /^(\d+)\s*(ms|s|m|h|d)?$/.exec(value);
2146
+ const amount = match ? Number(match[1]) : NaN;
2147
+ const unit = match?.[2] ?? "s";
2148
+ const multipliers: Record<string, number> = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };
2149
+ const multiplier = multipliers[unit]!;
2150
+ if (!Number.isSafeInteger(amount * multiplier) || amount <= 0) {
2151
+ throw new Error('Invalid timeout: use a positive duration (e.g. "60s", "10m") or explicit "none" for a background run.');
2152
+ }
2153
+ return `${amount}${unit}`;
2154
+ }
2155
+
2132
2156
  interface ProcOpts {
2133
2157
  description: string;
2134
2158
  name?: string;
@@ -2136,7 +2160,7 @@ interface ProcOpts {
2136
2160
  cwd?: string;
2137
2161
  host?: string;
2138
2162
  env?: Record<string, string | undefined>;
2139
- timeout?: string; // default: none — dev servers may run indefinitely
2163
+ timeout: string; // resolved to 60s unless explicitly overridden
2140
2164
  idleTimeout?: string;
2141
2165
  pty: boolean;
2142
2166
  notificationGroup?: string;
@@ -2177,7 +2201,7 @@ async function spawnProcess(opts: ProcOpts): Promise<{ id: string } | { error: s
2177
2201
  const remote = !!opts.host && opts.host !== "local";
2178
2202
  const bsArgs = ["run", "-d", "--json", "--size", "120x40"];
2179
2203
  if (!opts.pty) bsArgs.push("--no-tty");
2180
- if (opts.timeout && opts.timeout !== "none") bsArgs.push("--timeout", opts.timeout);
2204
+ if (opts.timeout !== "none") bsArgs.push("--timeout", opts.timeout);
2181
2205
  if (opts.idleTimeout && opts.idleTimeout !== "none")
2182
2206
  bsArgs.push("--idle-timeout", opts.idleTimeout);
2183
2207
  const reservedId = remote ? await reserveUniqueSessionId(opts.name ?? "remote-proc") : opts.name ? await reserveUniqueSessionId(opts.name) : undefined;
@@ -2504,6 +2528,7 @@ async function spawnSubagent(
2504
2528
  messageTempDirs: delivery.tempDir
2505
2529
  ? [{ dir: delivery.tempDir, afterAgentEnd: 1 }]
2506
2530
  : undefined,
2531
+ cwd: path.resolve(opts.cwd),
2507
2532
  depth: opts.depth,
2508
2533
  maxDepth: opts.maxDepth,
2509
2534
  budget: opts.budget,
@@ -2683,6 +2708,18 @@ function sessionCliCommand(id: string, command: "log" | "attach"): string {
2683
2708
  return `BABYSIT_DIR=${shq(ROOT)} ${shq(BABYSIT_BIN)} ${command} -s ${shq(id)}`;
2684
2709
  }
2685
2710
 
2711
+ /**
2712
+ * Command copied by the widget icon: local subagents open the transcript
2713
+ * viewer (rendered with Pi's components); everything else gets its log.
2714
+ */
2715
+ export function widgetCopyCommand(id: string): string {
2716
+ const meta = readMeta(id);
2717
+ if (meta?.kind === "subagent" && !meta.host) {
2718
+ return `${shq(process.execPath)} ${shq(path.join(EXT_DIR, "view.mjs"))} ${shq(logPath(id))}`;
2719
+ }
2720
+ return sessionCliCommand(id, "log");
2721
+ }
2722
+
2686
2723
  function attachCmd(id: string): string {
2687
2724
  return sessionCliCommand(id, "attach");
2688
2725
  }
@@ -3619,7 +3656,7 @@ export default function (pi: ExtensionAPI) {
3619
3656
  if (!sessionWidget) {
3620
3657
  ctx.ui.setWidget("pi-babysit", (tui) => {
3621
3658
  sessionWidget = createWidgetComponent(summaryLines, displays,
3622
- (id) => copyToClipboard(sessionCliCommand(id, "log")),
3659
+ (id) => copyToClipboard(widgetCopyCommand(id)),
3623
3660
  () => tui.requestRender());
3624
3661
  return sessionWidget;
3625
3662
  }, { placement: "belowEditor" });
@@ -3893,6 +3930,7 @@ export default function (pi: ExtensionAPI) {
3893
3930
  promptSnippet: "Run supervised commands or bounded pi subagents with context-safe logs",
3894
3931
  promptGuidelines: [
3895
3932
  "Use babysit_run for shell commands and give meaningful sessions a stable name; bundle tiny related read-only observations into one command.",
3933
+ "babysit_run commands default to a 60s execution timeout (subagents: 15m). Set a longer timeout for long-running work; timeout: none is allowed only for explicit background runs, never foreground or non-interactive runs.",
3896
3934
  "Use babysit_run foreground mode for one process or subagent whose result is needed now; never issue sibling foreground runs in parallel. For parallel process checks, start background runs with continueAfterStart and collect them with one multi-session babysit_wait.",
3897
3935
  "Use returnPattern/returnLines for noisy commands. During edit/fix loops run targeted checks first and one full validation suite at the end instead of repeating every full gate.",
3898
3936
  "After a background process starts, stop the turn for its automatic notification; never poll or sleep. Use continueAfterStart only for specific non-polling process work.",
@@ -3976,7 +4014,7 @@ export default function (pi: ExtensionAPI) {
3976
4014
  timeout: Type.Optional(
3977
4015
  Type.String({
3978
4016
  description:
3979
- "Absolute auto-kill after this long (e.g. 30m). Default: none for processes (dev servers may run forever), 15m for subagents. 'none' disables.",
4017
+ "Absolute auto-kill after a positive duration (e.g. 60s, 10m). Default: 60s for processes, 15m for subagents. Explicit 'none' disables only for background runs; forbidden with foreground or in non-interactive mode. Zero/empty/off/never are invalid.",
3980
4018
  }),
3981
4019
  ),
3982
4020
  reapAfter: Type.Optional(
@@ -4038,8 +4076,10 @@ export default function (pi: ExtensionAPI) {
4038
4076
  }),
4039
4077
  async execute(_id, params, _signal, _onUpdate, ctx) {
4040
4078
  const description = params.description.trim();
4041
- await requireBabysit();
4042
4079
  const isSubagent = params.profile === "subagent";
4080
+ const waitsInline = !ctx.hasUI || params.foreground === true;
4081
+ const timeout = resolveRunTimeout(params.timeout, isSubagent, waitsInline);
4082
+ await requireBabysit();
4043
4083
  validateProcessHost(params.host);
4044
4084
  if (isSubagent && (params.cwd !== undefined || (params.host && params.host !== "local"))) throw new Error("host/cwd are process-only options; remote subagents are not supported.");
4045
4085
  if (params.host && params.host !== "local" && params.retryOnWorkerDeath) throw new Error("Remote automatic launch retries are unsupported; reconcile the tracked session explicitly.");
@@ -4127,7 +4167,6 @@ export default function (pi: ExtensionAPI) {
4127
4167
 
4128
4168
  // --- process mode ---
4129
4169
  if (!isSubagent) {
4130
- const waitsInline = !ctx.hasUI || params.foreground === true;
4131
4170
  const lifecycle = resolveProcessLifecycle(params.lifecycle, waitsInline);
4132
4171
  if (params.returnPattern) {
4133
4172
  try {
@@ -4150,7 +4189,7 @@ export default function (pi: ExtensionAPI) {
4150
4189
  command: params.command as string,
4151
4190
  host: params.host,
4152
4191
  cwd: params.cwd ?? (params.host && params.host !== "local" ? undefined : ctx.cwd),
4153
- timeout: params.timeout,
4192
+ timeout,
4154
4193
  idleTimeout: params.idleTimeout,
4155
4194
  pty: params.pty ?? true,
4156
4195
  env: processSessionEnvironment(ctx, pi.getThinkingLevel()),
@@ -4315,7 +4354,7 @@ export default function (pi: ExtensionAPI) {
4315
4354
  }
4316
4355
  : undefined,
4317
4356
  reapAfter: params.reapAfter,
4318
- timeout: params.timeout ?? "15m",
4357
+ timeout,
4319
4358
  idleTimeout: params.idleTimeout,
4320
4359
  });
4321
4360
 
@@ -4884,6 +4923,7 @@ export default function (pi: ExtensionAPI) {
4884
4923
  launchCommand: meta?.launchCommand,
4885
4924
  reapAfter: meta?.reapAfter,
4886
4925
  startedAt: meta?.startedAt,
4926
+ cwd: meta?.cwd,
4887
4927
  task: params.text,
4888
4928
  // Start after the prompt-acceptance response. This excludes a
4889
4929
  // 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.35",
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
+ }