@yusukeshib/pi-babysit 0.6.32 → 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
@@ -216,16 +216,6 @@ Subagents run in RPC mode with normal Pi session persistence enabled, using
216
216
  Pi's configured session storage (by default `~/.pi/agent/sessions/`). Each worker
217
217
  has its own Pi session, separate from the parent and from babysit's output log.
218
218
 
219
- Subagent logs compact Pi's streaming `message_update` events before they are
220
- recorded. Pi repeats the complete growing assistant message and partial snapshot
221
- on every token; pi-babysit retains only the incremental delta. Compact RPC
222
- logging is the default and also removes duplicate payloads from `message_start`,
223
- `turn_end`, successful `tool_execution_end`, and `agent_end`, while preserving
224
- authoritative `message_end`, failures, responses, and errors. Parked-process
225
- state is materialized as a small boolean so completion detection is unchanged.
226
- Set `PI_BABYSIT_RPC_LOG_MODE=standard` only when legacy lifecycle payloads are
227
- needed for debugging. Live `/babysit` and attach views render either format.
228
-
229
219
  All shell commands, including `pwd` and Git, go through `babysit_run`. Bundle
230
220
  closely related tiny observations when doing so safely reduces tool turns. For
231
221
  parallel checks, do not issue sibling `foreground: true` calls: start them with
@@ -235,6 +225,50 @@ suite at the end. Background subagents must likewise be collected before the
235
225
  parent task finishes so their answer and nested usage are not lost.
236
226
  Set `PI_BABYSIT_ALLOW_BASH=1` only as an explicit emergency escape hatch.
237
227
 
228
+ ### Subagent log format
229
+
230
+ A subagent's babysit log is a subset of Pi's standard RPC event stream
231
+ (`rpc-stream-format.mjs`):
232
+
233
+ - The first line is `{"type":"pi_babysit_stream","version":1,"profile":"compact"}`
234
+ (`"standard"` with `PI_BABYSIT_RPC_LOG_MODE=standard`).
235
+ - Standard events keep their type and field meaning. The compact profile only
236
+ omits fields whose value is exactly reproducible from other lines; it never
237
+ reshapes a field. pi-babysit's own data uses separate `pi_babysit_*` events.
238
+ - `message_update` is delta-only, as in Pi >= 1.4 (older Pi's cumulative
239
+ `message` / `partial` snapshots are stripped).
240
+ - Compact omissions: `message.content` / `message.details` of a non-assistant
241
+ `message_start` that is immediately followed by an identical `message_end`;
242
+ `result.content` / `result.details` of a non-error `tool_execution_end` (they
243
+ equal the `toolResult` `message_end` with the same `toolCallId`, otherwise a
244
+ `pi_babysit_tool_execution_result` event carries the original); and
245
+ `turn_end.message` / `turn_end.toolResults` / `agent_end.messages` when they
246
+ equal the values derived from the run's `message_end` events.
247
+ - Every `agent_end` is preceded by `{"type":"pi_babysit_agent_end","parked":bool}`,
248
+ which completion detection uses.
249
+
250
+ `createRpcEventRestorer()` turns a log back into standard Pi events for
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
270
+ written by older pi-babysit releases.
271
+
238
272
  ## Process ownership, interruption, shutdown, and reload
239
273
 
240
274
  An inline process wait (`foreground: true`, or process execution in a non-UI
@@ -330,7 +364,7 @@ session totals.
330
364
  | `PI_BABYSIT_QUICK_GRACE` | `2s` | interactive process grace before a still-running command is returned as background work; use `foreground: true` to wait explicitly |
331
365
  | `PI_BABYSIT_REAP_AFTER` | `120s` | idle grace before a finished subagent self-exits (`off`/`none`/`0` disables) |
332
366
  | `PI_BABYSIT_BUDGET_GRACE` | `90s` | grace after a subagent budget is exceeded before verified termination |
333
- | `PI_BABYSIT_RPC_LOG_MODE` | `compact` | `compact` removes duplicate RPC lifecycle payloads; `standard` opts into legacy payloads |
367
+ | `PI_BABYSIT_RPC_LOG_MODE` | `compact` | `compact` omits reproducible duplicate RPC payloads; `standard` records Pi's events unchanged (see Subagent log format) |
334
368
  | `PI_BABYSIT_RETENTION_DAYS` | `3` | at most once per day, remove safe terminal roots older than this (in a background child process, so session start never waits); set `0` to disable automatic retention |
335
369
  | `PI_BABYSIT_TAIL_MAX_BYTES` | `4000` | default cap for explicit log tails/screens returned by `babysit_check`; override per call with `maxBytes` |
336
370
  | `PI_BABYSIT_INLINE_OUTPUT_MAX_BYTES` | `8000` | cap for complete process output and aggregate multi-wait results |
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;
@@ -1958,12 +1960,20 @@ function parseEventLine(progress: Progress, raw: string): void {
1958
1960
  case "agent_start":
1959
1961
  progress.agentStarts++;
1960
1962
  break;
1963
+ // The compact log precedes every agent_end with this marker and may omit
1964
+ // agent_end.messages (see rpc-stream-format.mjs).
1965
+ case "pi_babysit_agent_end":
1966
+ if (typeof event.parked === "boolean") progress.lastEndWasProcessWait = event.parked;
1967
+ break;
1961
1968
  case "agent_end": {
1962
1969
  progress.agentEnds++;
1963
- progress.lastEndWasProcessWait =
1964
- typeof event.piBabysitParked === "boolean"
1965
- ? event.piBabysitParked
1966
- : isParkedMessages(event.messages as ParkedMessage[] | undefined);
1970
+ if (typeof event.piBabysitParked === "boolean") {
1971
+ // Logs written by pi-babysit <= 0.6.32.
1972
+ progress.lastEndWasProcessWait = event.piBabysitParked;
1973
+ } else if (Array.isArray(event.messages)) {
1974
+ progress.lastEndWasProcessWait = isParkedMessages(event.messages as ParkedMessage[]);
1975
+ }
1976
+ // Otherwise keep the value from the preceding pi_babysit_agent_end marker.
1967
1977
  break;
1968
1978
  }
1969
1979
  case "agent_settled":
@@ -2346,9 +2356,9 @@ async function spawnSubagent(
2346
2356
  "--timeout",
2347
2357
  opts.timeout,
2348
2358
  ];
2349
- // Pretty-print the compact JSONL stream for humans who `attach`. The RPC
2350
- // proxy retains authoritative message_end/response/error events and reduces
2351
- // redundant lifecycle/tool payloads; parseEvents accepts both log formats.
2359
+ // Pretty-print the JSONL stream for humans who `attach`. The RPC proxy
2360
+ // writes a standard-event subset that omits only reproducible duplicate
2361
+ // payloads (rpc-stream-format.mjs); parseEvents accepts every log format.
2352
2362
  if (VIEW_CMD.trim()) bsArgs.push("--view-cmd", VIEW_CMD);
2353
2363
  if (opts.idleTimeout && opts.idleTimeout !== "none") {
2354
2364
  bsArgs.push("--idle-timeout", opts.idleTimeout);
@@ -2496,6 +2506,7 @@ async function spawnSubagent(
2496
2506
  messageTempDirs: delivery.tempDir
2497
2507
  ? [{ dir: delivery.tempDir, afterAgentEnd: 1 }]
2498
2508
  : undefined,
2509
+ cwd: path.resolve(opts.cwd),
2499
2510
  depth: opts.depth,
2500
2511
  maxDepth: opts.maxDepth,
2501
2512
  budget: opts.budget,
@@ -2675,6 +2686,18 @@ function sessionCliCommand(id: string, command: "log" | "attach"): string {
2675
2686
  return `BABYSIT_DIR=${shq(ROOT)} ${shq(BABYSIT_BIN)} ${command} -s ${shq(id)}`;
2676
2687
  }
2677
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
+
2678
2701
  function attachCmd(id: string): string {
2679
2702
  return sessionCliCommand(id, "attach");
2680
2703
  }
@@ -3611,7 +3634,7 @@ export default function (pi: ExtensionAPI) {
3611
3634
  if (!sessionWidget) {
3612
3635
  ctx.ui.setWidget("pi-babysit", (tui) => {
3613
3636
  sessionWidget = createWidgetComponent(summaryLines, displays,
3614
- (id) => copyToClipboard(sessionCliCommand(id, "log")),
3637
+ (id) => copyToClipboard(widgetCopyCommand(id)),
3615
3638
  () => tui.requestRender());
3616
3639
  return sessionWidget;
3617
3640
  }, { placement: "belowEditor" });
@@ -4876,6 +4899,7 @@ export default function (pi: ExtensionAPI) {
4876
4899
  launchCommand: meta?.launchCommand,
4877
4900
  reapAfter: meta?.reapAfter,
4878
4901
  startedAt: meta?.startedAt,
4902
+ cwd: meta?.cwd,
4879
4903
  task: params.text,
4880
4904
  // Start after the prompt-acceptance response. This excludes a
4881
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.32",
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",
@@ -24,6 +24,10 @@
24
24
  "self-reap.ts",
25
25
  "format-stream.mjs",
26
26
  "rpc-stream-proxy.mjs",
27
+ "rpc-stream-format.mjs",
28
+ "transcript-view.mjs",
29
+ "pi-runtime.mjs",
30
+ "view.mjs",
27
31
  "search-log.mjs",
28
32
  "gc.mjs",
29
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
+ }