@yusukeshib/pi-babysit 0.7.0 → 0.8.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.
Files changed (4) hide show
  1. package/README.md +21 -22
  2. package/index.ts +463 -139
  3. package/package.json +1 -5
  4. package/view.mjs +0 -79
package/README.md CHANGED
@@ -147,7 +147,7 @@ After reconnecting, check or kill tracked workers to establish terminal status
147
147
  before local retention can collect their metadata.
148
148
 
149
149
  The background poller only contacts hosts that still have unsettled tracked
150
- sessions. When a host keeps failing (SSH error, or none of its tracked
150
+ sessions, and queries each host at most once every 2.5s. When a host keeps failing (SSH error, or none of its tracked
151
151
  sessions can be found), the poller retries it with backoff (free for two
152
152
  consecutive failures, then 5s doubling up to 60s) and sleeps while such sessions
153
153
  are the only pending work. Their status stays "unknown"; it is never
@@ -167,7 +167,9 @@ including reusable idle agents. Summary counts use `RUNNING` / `IDLE`; rows show
167
167
  and unknown-status indicators when applicable, and a colored one-line description.
168
168
  Older sessions fall back to their command or task. Rows truncate to terminal width
169
169
  with `…`. In fullscreen mode, click the single `⧉` icon at the right edge of a row
170
- to copy that session's shell-quoted `babysit log` command. It includes the local
170
+ to copy that session's shell-quoted `babysit log` command (for a local subagent,
171
+ its log file path; see [Viewing a subagent transcript](#viewing-a-subagent-transcript)).
172
+ The command includes the local
171
173
  `BABYSIT_DIR` or remote host/worker ID, without executing the command or changing
172
174
  the input buffer. The icon changes in place: `…` while copying, `✓` on success,
173
175
  or `!` on failure. The result stays visible for two seconds before returning to
@@ -232,27 +234,17 @@ RPC event stream (JSONL), recorded through the worker's PTY, so lines end in
232
234
  `\r\n`. pi-babysit adds no records and removes no fields. Parked-turn
233
235
  detection reads `agent_end.messages`.
234
236
 
235
- ### Subagent transcript viewer
237
+ ### Viewing a subagent transcript
236
238
 
237
- `view.mjs` shows a subagent the way Pi shows its own chat. It is a thin wrapper
238
- around [`@yusukeshib/pi-tail`](https://github.com/yusukeshib/pi-tail), which
239
- renders a Pi event log with the installed Pi's components
240
- (`AssistantMessageComponent`, `ToolExecutionComponent`, …) and follows it live.
241
- The wrapper resolves a session id, uses the worker's directory, and shows the
242
- session state. The widget's copy icon on a local subagent row copies this
243
- command:
239
+ The widget's copy icon on a local subagent row copies the subagent's log file
240
+ path. The log is Pi's standard RPC event stream, so any Pi event viewer can
241
+ read it, for example [pi-tail](https://github.com/yusukeshib/pi-tail), which
242
+ renders it with Pi's own components:
244
243
 
245
244
  ```sh
246
- node ~/.pi/agent/npm/node_modules/@yusukeshib/pi-babysit/view.mjs <session-id | session dir | output.log>
245
+ pi-tail -f <copied output.log path>
247
246
  ```
248
247
 
249
- Keys: `q` / `Ctrl-C` quit, `Ctrl-O` expand or collapse tool output, `t`
250
- toggle thinking blocks. `--print` renders the current transcript once to stdout;
251
- `--cwd DIR` overrides the worker directory. Because the log is a plain Pi RPC
252
- stream, `pi-tail <output.log>` works on it too. See the pi-tail README for how
253
- Pi packages, settings, themes and extension renderers are loaded
254
- (`PI_TAIL_PI_PACKAGE_DIR` overrides the Pi package directory).
255
-
256
248
  ## Execution timeouts
257
249
 
258
250
  Commands default to an absolute **60s execution timeout**, in both foreground
@@ -311,12 +303,19 @@ because blindly rerunning an arbitrary command can duplicate side effects.
311
303
 
312
304
  ## How completion detection works
313
305
 
314
- - **Process**: a 2.5s poller watches for running→exited transitions and, once the
306
+ - **Process**: a 250ms poller watches for running→exited transitions and, once the
315
307
  parent agent is idle, injects one
316
308
  `pi.sendMessage(…, { triggerTurn: true, deliverAs: "steer" })` containing every
317
309
  deliverable exit observed in that poll (deduped via `meta/<id>.json`). Waiting
318
310
  for idleness prevents an immediately-following `babysit_wait` from racing the
319
- poller and receiving a duplicate completion. Background process calls emitted
311
+ poller and receiving a duplicate completion; exits that happened during a run
312
+ are delivered as soon as the agent settles. Local status is read directly from
313
+ babysit's on-disk registry (`sessions/<id>/{meta.json,status.json,note}`) and
314
+ local logs are read from `output.log` with `babysit log`'s terminal-control
315
+ stripping, so local polling, waits, and output collection spawn no `babysit`
316
+ process. Before reading a just-finished session's output, the poller waits
317
+ (up to 1s) for the babysit supervisor to exit, because babysit records the exit
318
+ before it flushes the final PTY output. Background process calls emitted
320
319
  together in one assistant message automatically share a notification group;
321
320
  an explicit `notificationGroup` overrides this. Group members wait for every
322
321
  currently running member to stop and then share one notification even when
@@ -328,8 +327,8 @@ because blindly rerunning an arbitrary command can duplicate side effects.
328
327
  notification. Kill results are reconciled with persisted terminal state, so
329
328
  a backend escalation warning that arrives after the child has already exited
330
329
  does not produce a false failure followed by a redundant notification.
331
- - **Subagent**: `foreground: true` or `babysit_wait` blocks on
332
- `babysit expect '"type":"agent_settled"'`. A background task that settles or
330
+ - **Subagent**: `foreground: true` or `babysit_wait` re-checks the worker's RPC
331
+ log for `agent_settled` every 100ms. A background task that settles or
333
332
  exits before it is collected emits one ready-to-collect reminder; the parent
334
333
  must still call `babysit_wait` so the answer and nested usage are persisted.
335
334
  Unlike `agent_end`, `agent_settled` cannot precede an automatic retry,
package/index.ts CHANGED
@@ -196,9 +196,11 @@ export function subagentGuidance(
196
196
  "your controller reads it from the event stream.",
197
197
  ].join(" ");
198
198
  }
199
+ /** Remote status cadence per host (each query is an SSH round trip). */
199
200
  const POLL_MS = 2500;
200
- const QUICK_COMMAND_GRACE = process.env.PI_BABYSIT_QUICK_GRACE ?? "2s";
201
- const KILL_CONFIRM_TIMEOUT = "4s";
201
+ /** Background poller tick; local status is a few small file reads. */
202
+ const LOCAL_POLL_MS = 250;
203
+ const KILL_CONFIRM_TIMEOUT_MS = 4_000;
202
204
 
203
205
  interface BsSession {
204
206
  id: string;
@@ -210,6 +212,8 @@ interface BsSession {
210
212
  screen_seq?: number | null;
211
213
  host?: string;
212
214
  transportError?: string;
215
+ /** Local only: whether the babysit supervisor process still exists. */
216
+ supervisorAlive?: boolean;
213
217
  }
214
218
 
215
219
  // A worker whose PTY process is gone (alive:false) can still report state
@@ -217,11 +221,16 @@ interface BsSession {
217
221
  // died in the first few ms). Treat that as finished so it never shows or counts
218
222
  // as running. This normalizes at the source so every downstream
219
223
  // `state === "running"` check is correct.
220
- function normalizeSession(s: BsSession): BsSession {
221
- if (s.alive === false && s.state === "running") {
224
+ //
225
+ // babysit also reports a brief "starting" state before the PTY child exists.
226
+ // It is live work, so report it as running (or dead when its owner is gone)
227
+ // instead of letting `state !== "running"` checks mistake it for an exit.
228
+ export function normalizeSession(s: BsSession): BsSession {
229
+ if (s.state !== "running" && s.state !== "starting") return s;
230
+ if (s.alive === false) {
222
231
  return { ...s, state: s.exit_code != null ? "exited" : "dead" };
223
232
  }
224
- return s;
233
+ return s.state === "starting" ? { ...s, state: "running" } : s;
225
234
  }
226
235
 
227
236
  // ---------------------------------------------------------------------------
@@ -380,10 +389,128 @@ async function requireBabysit(): Promise<void> {
380
389
  if (!(await babysitAvailable())) throw new Error(babysitPreflightError ?? INSTALL_HINT);
381
390
  }
382
391
 
392
+ // ---------------------------------------------------------------------------
393
+ // local registry: read babysit's on-disk session state directly
394
+ // ---------------------------------------------------------------------------
395
+
396
+ // Every `babysit` exec costs a process spawn, which is slow on hosts with
397
+ // endpoint security (hundreds of ms each). Local status is therefore read from
398
+ // babysit's documented layout `<root>/sessions/<id>/{meta.json,status.json,note}`
399
+ // with the same rules as `babysit list --json`: unreadable meta skips the
400
+ // session, a missing status means "starting", and an owner is alive while the
401
+ // state is non-terminal and its supervisor pid exists. Remote hosts still go
402
+ // through the CLI.
403
+
404
+ /** `babysit run -d` returns before its detached worker creates the session dir. */
405
+ export const LOCAL_STARTUP_GRACE_MS = 15_000;
406
+ const pendingLocalStarts = new Map<string, number>();
407
+
408
+ export function pidAlive(pid: unknown): boolean {
409
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
410
+ try {
411
+ process.kill(pid, 0);
412
+ return true;
413
+ } catch (error) {
414
+ return (error as NodeJS.ErrnoException).code === "EPERM";
415
+ }
416
+ }
417
+
418
+ type LocalSessionRecord = BsSession & { lastChange: number };
419
+
420
+ /** Read one babysit session directory; null when it is not (yet) a session. */
421
+ export function readLocalSessionDir(dir: string, id: string): LocalSessionRecord | null {
422
+ let meta: { babysit_pid?: unknown };
423
+ try {
424
+ meta = JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8"));
425
+ } catch {
426
+ return null;
427
+ }
428
+ if (!meta || typeof meta.babysit_pid !== "number") return null;
429
+ let status: { state?: unknown; exit_code?: unknown; last_change?: unknown } = {};
430
+ try {
431
+ status = JSON.parse(fs.readFileSync(path.join(dir, "status.json"), "utf8")) ?? {};
432
+ } catch {
433
+ // babysit treats a missing or torn status as "starting".
434
+ }
435
+ const state = typeof status.state === "string" ? status.state : "starting";
436
+ const supervisorAlive = pidAlive(meta.babysit_pid);
437
+ let note: string | null = null;
438
+ try {
439
+ note = fs.readFileSync(path.join(dir, "note"), "utf8").trim();
440
+ } catch {
441
+ // not flagged
442
+ }
443
+ const lastChange = typeof status.last_change === "string" ? Date.parse(status.last_change) : Number.NaN;
444
+ return {
445
+ ...normalizeSession({
446
+ id,
447
+ state,
448
+ alive: (state === "starting" || state === "running") && supervisorAlive,
449
+ exit_code: typeof status.exit_code === "number" ? status.exit_code : null,
450
+ note,
451
+ supervisorAlive,
452
+ }),
453
+ lastChange: Number.isFinite(lastChange) ? lastChange : Date.now(),
454
+ };
455
+ }
456
+
457
+ /**
458
+ * List the local registry. `skip` names terminal sessions whose state cannot
459
+ * change any more (the poller's settled set), so they are not re-read.
460
+ */
461
+ export function readLocalRegistry(
462
+ root: string,
463
+ options: { ids?: readonly string[]; skip?: ReadonlySet<string> } = {},
464
+ pending: Map<string, number> = new Map(),
465
+ now = Date.now(),
466
+ ): { sessions: BsSession[]; error?: string } {
467
+ const dir = path.join(root, "sessions");
468
+ let names: string[];
469
+ if (options.ids) {
470
+ names = [...options.ids];
471
+ } else {
472
+ try {
473
+ names = fs.readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
474
+ } catch (error) {
475
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
476
+ return { sessions: [], error: `cannot read babysit registry ${dir}: ${error instanceof Error ? error.message : String(error)}` };
477
+ }
478
+ names = [];
479
+ }
480
+ }
481
+ const sessions: LocalSessionRecord[] = [];
482
+ const found = new Set<string>();
483
+ for (const id of names) {
484
+ // Caller-supplied ids must never escape the sessions directory.
485
+ if (!id || id === "." || id === ".." || /[\\/]/.test(id)) continue;
486
+ if (options.skip?.has(id)) continue;
487
+ const session = readLocalSessionDir(path.join(dir, id), id);
488
+ if (!session) continue;
489
+ sessions.push(session);
490
+ found.add(id);
491
+ }
492
+ for (const [id, launchedAt] of pending) {
493
+ if (found.has(id) || now - launchedAt > LOCAL_STARTUP_GRACE_MS) {
494
+ // Registered (or never will be): from now on the registry is authoritative.
495
+ pending.delete(id);
496
+ continue;
497
+ }
498
+ if (options.ids && !options.ids.includes(id)) continue;
499
+ if (options.skip?.has(id)) continue;
500
+ sessions.push({ id, state: "running", alive: true, exit_code: null, note: null, lastChange: now });
501
+ }
502
+ sessions.sort((a, b) => b.lastChange - a.lastChange);
503
+ return { sessions: sessions.map(({ lastChange: _lastChange, ...session }) => session) };
504
+ }
505
+
383
506
  // Error-aware: `babysit list` failing is NOT the same as "no sessions" —
384
507
  // callers that show state to the agent must surface the error instead of
385
508
  // silently reporting an empty registry (which reads like lost sessions).
386
- async function localSessions(host?: string): Promise<{ sessions: BsSession[]; error?: string }> {
509
+ async function localSessions(
510
+ host?: string,
511
+ options: { ids?: readonly string[]; skip?: ReadonlySet<string> } = {},
512
+ ): Promise<{ sessions: BsSession[]; error?: string }> {
513
+ if (!host) return readLocalRegistry(ROOT, options, pendingLocalStarts);
387
514
  const r = await bs(["list", "--json"], { host });
388
515
  if (r.code !== 0) {
389
516
  return {
@@ -421,18 +548,27 @@ const unknownRemoteSession = (id: string, host: string, error: string): BsSessio
421
548
  note: `status unknown on ${host}: ${error}`,
422
549
  });
423
550
 
551
+ // The poller ticks quickly because local status is a few file reads, but
552
+ // remote status costs an SSH round trip. Each host is therefore queried at
553
+ // most once per POLL_MS; ticks in between reuse that host's last poll result.
554
+ const remotePollCache = new Map<string, { at: number; sessions: Map<string, BsSession> }>();
555
+
424
556
  /**
425
557
  * List local sessions plus tracked remote sessions. With `poll: true` (the
426
558
  * background poller), settled sessions are skipped, hosts with only settled
427
- * sessions are not contacted, and failing hosts are retried with backoff.
559
+ * sessions are not contacted, hosts are queried at most once per POLL_MS, and
560
+ * failing hosts are retried with backoff.
428
561
  * `ids` limits which tracked remote sessions (and therefore hosts) are queried;
429
- * `local: false` skips the local registry.
562
+ * `localIds` limits which local sessions are read; `local: false` skips the
563
+ * local registry.
430
564
  */
431
565
  async function listSessions(
432
- options: { poll?: boolean; ids?: readonly string[]; local?: boolean } = {},
566
+ options: { poll?: boolean; ids?: readonly string[]; localIds?: readonly string[]; local?: boolean } = {},
433
567
  ): Promise<{ sessions: BsSession[]; error?: string }> {
434
568
  const local: { sessions: BsSession[]; error?: string } =
435
- options.local === false ? { sessions: [] } : await localSessions();
569
+ options.local === false
570
+ ? { sessions: [] }
571
+ : await localSessions(undefined, { ids: options.localIds, skip: options.poll ? settledSessionIds : undefined });
436
572
  const known = remoteMetadata().filter(
437
573
  ({ id }) => (!options.poll || !settledSessionIds.has(id)) && (!options.ids || options.ids.includes(id)),
438
574
  );
@@ -446,22 +582,31 @@ async function listSessions(
446
582
  }
447
583
  return;
448
584
  }
585
+ const cached = options.poll ? remotePollCache.get(host) : undefined;
586
+ if (cached && Date.now() - cached.at < POLL_MS && tracked.every(({ id }) => cached.sessions.has(id))) {
587
+ for (const { id } of tracked) local.sessions.push(cached.sessions.get(id)!);
588
+ return;
589
+ }
590
+ const queriedAt = Date.now();
449
591
  const remote = await localSessions(host);
592
+ const observed = new Map<string, BsSession>();
450
593
  let foundCount = 0;
451
594
  for (const { id, meta } of tracked) {
452
595
  const found = remote.sessions.find((session) => session.id === meta.remoteId);
453
596
  if (found && !remote.error) {
454
597
  foundCount++;
455
- local.sessions.push({ ...found, id, host });
598
+ observed.set(id, { ...found, id, host });
456
599
  const terminalState = isConfirmedTerminalState(found.state) ? found.state : undefined;
457
600
  if (meta.remoteTerminalState !== terminalState) {
458
601
  writeMeta(id, { ...readMeta(id)!, remoteTerminalState: terminalState });
459
602
  }
460
603
  } else {
461
604
  // Keep unresolved references active for polling/group delivery, never fabricate exit.
462
- local.sessions.push(unknownRemoteSession(id, host, remote.error ?? "tracked remote session not found"));
605
+ observed.set(id, unknownRemoteSession(id, host, remote.error ?? "tracked remote session not found"));
463
606
  }
464
607
  }
608
+ local.sessions.push(...observed.values());
609
+ if (options.poll) remotePollCache.set(host, { at: queriedAt, sessions: observed });
465
610
  if (foundCount > 0) {
466
611
  remoteHostBackoff.delete(host);
467
612
  } else if (options.poll) {
@@ -507,7 +652,7 @@ async function lookupStatus(
507
652
  // Only contact the registry that owns this session: a local lookup must not
508
653
  // SSH to every remote host, and a remote one needs no local list.
509
654
  const remote = Boolean(readMeta(id)?.host);
510
- const listed = await listSessions({ ids: [id], local: !remote });
655
+ const listed = await listSessions({ ids: [id], localIds: [id], local: !remote });
511
656
  const session = listed.sessions.find((session) => session.id === id) ?? null;
512
657
  if (session?.transportError) return { session: null, error: `${session.host}: ${session.transportError}` };
513
658
  if (listed.error && !readMeta(id)?.host) return { session: null, error: listed.error };
@@ -557,7 +702,7 @@ async function awaitConfirmedTermination(id: string): Promise<BsSession | null>
557
702
  // New babysit versions return only after persistence, so this is normally
558
703
  // skipped. It is a bounded compatibility guard for older binaries that
559
704
  // acknowledged signal delivery before the process actually exited.
560
- await bs(["wait", "-s", id, "--timeout", KILL_CONFIRM_TIMEOUT]);
705
+ await waitForStop(id, KILL_CONFIRM_TIMEOUT_MS);
561
706
  return statusOf(id);
562
707
  }
563
708
 
@@ -633,12 +778,11 @@ interface Meta {
633
778
  // A timeout must not re-enable the poller while another wait still owns it.
634
779
  waitReservations?: number;
635
780
  waitCompletionClaimed?: boolean;
636
- completionObservedAt?: number;
637
781
  startedAt?: number;
638
782
  // subagent
639
783
  task?: string;
640
784
  launchCommand?: string;
641
- /** Worker working directory; the transcript viewer resolves tool paths against it. */
785
+ /** Worker working directory. */
642
786
  cwd?: string;
643
787
  reapAfter?: string;
644
788
  promptOffset?: number;
@@ -661,9 +805,6 @@ interface Meta {
661
805
  subagentCollectedOffset?: number;
662
806
  /** Prompt offset whose ready-to-collect reminder was sent to the parent. */
663
807
  subagentNotifiedOffset?: number;
664
- /** Current task completion first observed by the reminder poller. */
665
- subagentCompletionObservedOffset?: number;
666
- subagentCompletionObservedAt?: number;
667
808
  }
668
809
 
669
810
  const metaDir = () => path.join(ROOT, "meta");
@@ -1138,6 +1279,8 @@ function parseDurMs(s?: string): number | null {
1138
1279
  return n * (u === "ms" ? 1 : u === "s" ? 1000 : u === "m" ? 60_000 : 3_600_000);
1139
1280
  }
1140
1281
 
1282
+ const QUICK_COMMAND_GRACE_MS = parseDurMs(process.env.PI_BABYSIT_QUICK_GRACE ?? "2s") ?? 2_000;
1283
+
1141
1284
  // ---------------------------------------------------------------------------
1142
1285
  // Context-size guard — every string that flows back into the agent's context
1143
1286
  // passes through clip(). Log tails are line-capped upstream (`--tail N`), but
@@ -1281,6 +1424,122 @@ async function searchLog(
1281
1424
  });
1282
1425
  }
1283
1426
 
1427
+ /**
1428
+ * Text view of a raw PTY log, matching `babysit log` (strip-ansi-escapes on a
1429
+ * VT parser): printable characters (including DEL) and line feeds survive;
1430
+ * other C0/C1 controls, escape/CSI sequences, and OSC/DCS/SOS/PM/APC strings are removed.
1431
+ * Invalid UTF-8 becomes U+FFFD.
1432
+ */
1433
+ export function stripTerminalOutput(bytes: Uint8Array): string {
1434
+ const text = new TextDecoder("utf-8").decode(bytes);
1435
+ let out = "";
1436
+ let state: "ground" | "escape" | "intermediate" | "csi" | "osc" | "string" = "ground";
1437
+ for (const ch of text) {
1438
+ const c = ch.codePointAt(0)!;
1439
+ if (c === 0x18 || c === 0x1a) {
1440
+ state = "ground";
1441
+ continue;
1442
+ }
1443
+ if (c === 0x1b) {
1444
+ state = "escape";
1445
+ continue;
1446
+ }
1447
+ switch (state) {
1448
+ case "ground":
1449
+ // DEL is printed by the VT parser; C1 controls are executed (dropped).
1450
+ if (c === 0x0a || (c >= 0x20 && !(c >= 0x80 && c <= 0x9f))) out += ch;
1451
+ break;
1452
+ case "escape":
1453
+ case "intermediate":
1454
+ if (c < 0x20) {
1455
+ if (c === 0x0a) out += ch;
1456
+ } else if (c <= 0x2f) {
1457
+ state = "intermediate";
1458
+ } else if (c === 0x7f) {
1459
+ // ignored
1460
+ } else if (state === "escape" && c === 0x5b) {
1461
+ state = "csi";
1462
+ } else if (state === "escape" && c === 0x5d) {
1463
+ state = "osc";
1464
+ } else if (state === "escape" && (c === 0x50 || c === 0x58 || c === 0x5e || c === 0x5f)) {
1465
+ state = "string";
1466
+ } else {
1467
+ state = "ground";
1468
+ }
1469
+ break;
1470
+ case "csi":
1471
+ if (c < 0x20) {
1472
+ if (c === 0x0a) out += ch;
1473
+ } else if (c >= 0x40 && c <= 0x7e) {
1474
+ state = "ground";
1475
+ }
1476
+ break;
1477
+ case "osc":
1478
+ if (c === 0x07) state = "ground";
1479
+ break;
1480
+ case "string":
1481
+ break;
1482
+ }
1483
+ }
1484
+ return out;
1485
+ }
1486
+
1487
+ /** Last `n` lines, matching babysit's `--tail` (a trailing newline is kept). */
1488
+ export function lastLines(text: string, n: number): string {
1489
+ if (n <= 0) return "";
1490
+ const trimmed = text.endsWith("\n") ? text.slice(0, -1) : text;
1491
+ let start = trimmed.length;
1492
+ for (let seen = 0; seen < n; seen++) {
1493
+ const index = trimmed.lastIndexOf("\n", start - 1);
1494
+ if (index < 0) return text;
1495
+ start = index;
1496
+ }
1497
+ return text.slice(start + 1);
1498
+ }
1499
+
1500
+ /** Tail reads never parse more than this many trailing bytes of a local log. */
1501
+ const LOCAL_TAIL_WINDOW_BYTES = 1_048_576;
1502
+
1503
+ /**
1504
+ * `babysit log [-s id] [--tail n]` without a CLI spawn for local sessions.
1505
+ * Remote sessions still go through `babysit --host`.
1506
+ */
1507
+ async function readSessionLog(
1508
+ id: string,
1509
+ tail?: number,
1510
+ signal?: AbortSignal,
1511
+ ): Promise<{ stdout: string; stderr: string; code: number }> {
1512
+ if (readMeta(id)?.host) {
1513
+ return bs(["log", "-s", id, ...(tail != null ? ["--tail", String(tail)] : [])], { signal });
1514
+ }
1515
+ const file = localLogPath(id);
1516
+ let bytes: Buffer;
1517
+ try {
1518
+ if (tail == null) {
1519
+ bytes = fs.readFileSync(file);
1520
+ } else {
1521
+ const size = fs.statSync(file).size;
1522
+ const length = Math.min(size, LOCAL_TAIL_WINDOW_BYTES);
1523
+ bytes = readLogBytesFrom(file, size - length);
1524
+ if (length < size) {
1525
+ // The window may start mid-line or mid-sequence: drop that first line.
1526
+ const newline = bytes.indexOf(0x0a);
1527
+ bytes = newline >= 0 ? bytes.subarray(newline + 1) : Buffer.alloc(0);
1528
+ }
1529
+ }
1530
+ } catch (error) {
1531
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
1532
+ return { stdout: "", stderr: `cannot read ${file}: ${String(error)}`, code: 1 };
1533
+ }
1534
+ if (!fs.existsSync(path.dirname(file)) && !localStatusOf(id)) {
1535
+ return { stdout: "", stderr: `babysit: no such session: ${id}`, code: 1 };
1536
+ }
1537
+ bytes = Buffer.alloc(0);
1538
+ }
1539
+ const text = stripTerminalOutput(bytes);
1540
+ return { stdout: tail == null ? text : lastLines(text, tail), stderr: "", code: 0 };
1541
+ }
1542
+
1284
1543
  export function shouldInlineCompleteOutput(outputBytes: number, maxBytes: number): boolean {
1285
1544
  return maxBytes > 0 && outputBytes <= maxBytes;
1286
1545
  }
@@ -1308,7 +1567,7 @@ async function inlineOutput(
1308
1567
  const size = Number.isFinite(bytes) ? `${bytes} bytes` : "size unavailable";
1309
1568
  return `\nOutput omitted (${size}; inline limit ${maxBytes}).`;
1310
1569
  }
1311
- const result = await bs(["log", "-s", id]);
1570
+ const result = await readSessionLog(id);
1312
1571
  if (result.code !== 0) return `\nOutput unavailable: ${clip(result.stderr || result.stdout, maxBytes)}`;
1313
1572
  const output = result.stdout.trimEnd();
1314
1573
  if (Buffer.byteLength(output) > maxBytes) {
@@ -1340,7 +1599,7 @@ async function selectedProcessOutput(
1340
1599
  const body = result.text || `(no output matching /${selection.pattern}/)`;
1341
1600
  return `\n\nSelected output /${selection.pattern}/:\n${clip(body, maxBytes)}`;
1342
1601
  }
1343
- const result = await bs(["log", "-s", id, "--tail", String(lines)], { signal });
1602
+ const result = await readSessionLog(id, lines, signal);
1344
1603
  if (result.code !== 0) return `\nOutput unavailable: ${clip(result.stderr || result.stdout, maxBytes)}`;
1345
1604
  const tail = result.stdout.trimEnd();
1346
1605
  return tail ? `\n\nSelected tail (${lines} lines max):\n${clip(tail, maxBytes)}` : "";
@@ -2228,6 +2487,7 @@ async function spawnProcess(opts: ProcOpts): Promise<{ id: string } | { error: s
2228
2487
  } catch {
2229
2488
  return { error: `could not parse id from: ${r.stdout}` };
2230
2489
  }
2490
+ pendingLocalStarts.set(id, Date.now());
2231
2491
  writeMeta(id, {
2232
2492
  kind: "process",
2233
2493
  name: opts.name ?? id,
@@ -2406,6 +2666,7 @@ async function spawnSubagent(
2406
2666
  cleanupPromptTemp();
2407
2667
  return { error: `could not parse id from: ${r.stdout}` };
2408
2668
  }
2669
+ pendingLocalStarts.set(id, Date.now());
2409
2670
 
2410
2671
  // Stamp the kind IMMEDIATELY (with notified:true) so that if validation
2411
2672
  // below fails and we kill the session, the exit poller does NOT mistake it
@@ -2635,6 +2896,8 @@ export function createWidgetComponent(
2635
2896
  };
2636
2897
  return {
2637
2898
  update(summary: string[], rows: WidgetSessionDisplay[]) {
2899
+ // The poller ticks several times per second; only repaint on change.
2900
+ if (JSON.stringify([summary, rows]) === JSON.stringify([summaryLines, sessions])) return;
2638
2901
  summaryLines = summary;
2639
2902
  sessions = rows;
2640
2903
  copyTargets.clear();
@@ -2694,14 +2957,12 @@ function sessionCliCommand(id: string, command: "log" | "attach"): string {
2694
2957
  }
2695
2958
 
2696
2959
  /**
2697
- * Command copied by the widget icon: local subagents open the transcript
2698
- * viewer (rendered with Pi's components); everything else gets its log.
2960
+ * Text copied by the widget icon: a local subagent's log file path (Pi's RPC
2961
+ * event stream, e.g. for `pi-tail -f`); everything else gets its log command.
2699
2962
  */
2700
2963
  export function widgetCopyCommand(id: string): string {
2701
2964
  const meta = readMeta(id);
2702
- if (meta?.kind === "subagent" && !meta.host) {
2703
- return `${shq(process.execPath)} ${shq(path.join(EXT_DIR, "view.mjs"))} ${shq(logPath(id))}`;
2704
- }
2965
+ if (meta?.kind === "subagent" && !meta.host) return logPath(id);
2705
2966
  return sessionCliCommand(id, "log");
2706
2967
  }
2707
2968
 
@@ -2865,8 +3126,8 @@ function sumNestedUsage(values: Array<NestedUsage | undefined>): NestedUsage | u
2865
3126
 
2866
3127
  // Wait for ONE subagent's current task. Completion = agent_settled without a
2867
3128
  // parked babysit_run/process result (a parked run only means "waiting for
2868
- // process exit; pi will resume itself"). Parse appended bytes incrementally,
2869
- // then block on the next agent_settled via race-free byte offsets.
3129
+ // process exit; pi will resume itself"). Parse appended bytes incrementally
3130
+ // and re-check every SUBAGENT_WAIT_POLL_MS.
2870
3131
  async function waitForTask(
2871
3132
  id: string,
2872
3133
  limitMs: number | null,
@@ -2881,7 +3142,7 @@ async function waitForTask(
2881
3142
  } catch {
2882
3143
  observed = { progress: emptyProgress(), offset: readMeta(id)?.promptOffset ?? 0 };
2883
3144
  }
2884
- const { progress: prog, offset: cur } = observed;
3145
+ const { progress: prog } = observed;
2885
3146
  const st = await statusOf(id);
2886
3147
 
2887
3148
  const stats =
@@ -2934,19 +3195,18 @@ async function waitForTask(
2934
3195
  progress: prog,
2935
3196
  });
2936
3197
 
2937
- // Still working — block until Pi declares the run fully settled. Unlike
2938
- // agent_end, this cannot fire before an automatic retry/compaction retry.
2939
- let expectTimeout = "0"; // indefinite
3198
+ // Still working — re-check until Pi declares the run fully settled
3199
+ // (`progress.done` comes from agent_settled, which unlike agent_end cannot
3200
+ // fire before an automatic retry/compaction retry) or the worker stops.
3201
+ // Both checks are incremental file reads, so poll in-process instead of
3202
+ // paying a `babysit expect` spawn per wait.
3203
+ let delay = SUBAGENT_WAIT_POLL_MS;
2940
3204
  if (limitMs != null) {
2941
3205
  const remaining = limitMs - (Date.now() - t0);
2942
3206
  if (remaining <= 0) return timeoutOutcome();
2943
- expectTimeout = `${Math.ceil(remaining / 1000)}s`;
3207
+ delay = Math.min(delay, remaining);
2944
3208
  }
2945
- const e = await bs(
2946
- ["expect", "-s", id, "--since", String(cur), "--timeout", expectTimeout, '"type":"agent_settled"'],
2947
- { signal },
2948
- );
2949
- if (signal?.aborted || e.code === 130) {
3209
+ if (await sleepUnlessAborted(delay, signal)) {
2950
3210
  return {
2951
3211
  id,
2952
3212
  kind: "interrupted",
@@ -2956,12 +3216,6 @@ async function waitForTask(
2956
3216
  progress: prog,
2957
3217
  };
2958
3218
  }
2959
- if (e.code === 124) return timeoutOutcome();
2960
- // e.code !== 0 (session likely exited mid-wait) falls through to the
2961
- // next loop iteration, where the exited branch reports the cause.
2962
- if (e.code !== 0) {
2963
- await new Promise((res) => setTimeout(res, 500));
2964
- }
2965
3219
  }
2966
3220
  }
2967
3221
 
@@ -3047,6 +3301,88 @@ function resumeNotify(id: string): void {
3047
3301
  }
3048
3302
  }
3049
3303
 
3304
+ /** Resolve after `ms`, or early (true) when the signal aborts. */
3305
+ function sleepUnlessAborted(ms: number, signal?: AbortSignal): Promise<boolean> {
3306
+ if (signal?.aborted) return Promise.resolve(true);
3307
+ return new Promise((resolve) => {
3308
+ const onAbort = () => {
3309
+ clearTimeout(timer);
3310
+ resolve(true);
3311
+ };
3312
+ const timer = setTimeout(() => {
3313
+ signal?.removeEventListener("abort", onAbort);
3314
+ resolve(false);
3315
+ }, ms);
3316
+ signal?.addEventListener("abort", onAbort, { once: true });
3317
+ });
3318
+ }
3319
+
3320
+ const LOCAL_WAIT_POLL_MS = 50;
3321
+ const SUBAGENT_WAIT_POLL_MS = 100;
3322
+ const LOCAL_OUTPUT_SETTLE_MAX_MS = 1_000;
3323
+
3324
+ /** Current local status (including pending launches); null when unknown. */
3325
+ function localStatusOf(id: string): BsSession | null {
3326
+ return readLocalRegistry(ROOT, { ids: [id] }, pendingLocalStarts).sessions[0] ?? null;
3327
+ }
3328
+
3329
+ /**
3330
+ * Block until a session is no longer running. Local sessions are watched
3331
+ * in-process through their status file; remote ones use `babysit wait`.
3332
+ * "timeout" from a remote wait is ambiguous (the child may exit 124), so
3333
+ * callers confirm it with a status lookup.
3334
+ */
3335
+ async function waitForStop(
3336
+ id: string,
3337
+ limitMs: number | null,
3338
+ signal?: AbortSignal,
3339
+ ): Promise<"stopped" | "timeout" | "interrupted"> {
3340
+ if (!readMeta(id)?.host) {
3341
+ const deadline = limitMs == null ? Number.POSITIVE_INFINITY : Date.now() + limitMs;
3342
+ for (;;) {
3343
+ if (signal?.aborted) return "interrupted";
3344
+ const status = localStatusOf(id);
3345
+ if (!status || status.state !== "running") return "stopped";
3346
+ const remaining = deadline - Date.now();
3347
+ if (remaining <= 0) return "timeout";
3348
+ if (await sleepUnlessAborted(Math.min(LOCAL_WAIT_POLL_MS, remaining), signal)) return "interrupted";
3349
+ }
3350
+ }
3351
+
3352
+ const t = limitMs != null ? `${Math.ceil(limitMs / 1000)}s` : "0";
3353
+ let w: Awaited<ReturnType<typeof bs>>;
3354
+ let attempt = 0;
3355
+ for (;;) {
3356
+ w = await bs(["wait", "-s", id, "--timeout", t], { signal });
3357
+ if (signal?.aborted) return "interrupted";
3358
+ if (w.code === 0 || w.code === 124 || w.code === 130) break;
3359
+
3360
+ // A freshly spawned session can be visible in `list` before the backend's
3361
+ // wait endpoint is ready. Retry that transient startup race instead of
3362
+ // reporting the still-running child as "exited with code ?".
3363
+ const retryStatus = await statusOf(id);
3364
+ if (retryStatus?.state !== "running" || attempt++ >= 3) break;
3365
+ await new Promise((resolve) => setTimeout(resolve, 50 * attempt));
3366
+ }
3367
+ if (w.code === 130 && (await statusOf(id))?.state === "running") return "interrupted";
3368
+ return w.code === 124 ? "timeout" : "stopped";
3369
+ }
3370
+
3371
+ /**
3372
+ * babysit records a local exit before draining the PTY's final bytes into
3373
+ * output.log, then the supervisor exits. Wait (bounded) for that supervisor so
3374
+ * output read right after an exit is complete.
3375
+ */
3376
+ async function awaitLocalOutputSettled(id: string, signal?: AbortSignal): Promise<void> {
3377
+ if (readMeta(id)?.host) return;
3378
+ const deadline = Date.now() + LOCAL_OUTPUT_SETTLE_MAX_MS;
3379
+ while (Date.now() < deadline) {
3380
+ const status = localStatusOf(id);
3381
+ if (!status?.supervisorAlive) return;
3382
+ if (await sleepUnlessAborted(20, signal)) return;
3383
+ }
3384
+ }
3385
+
3050
3386
  // Wait for a PROCESS session: either until a regex appears in its output
3051
3387
  // (`expect` — e.g. "server listening") or until the process exits.
3052
3388
  async function waitForExit(
@@ -3093,33 +3429,13 @@ async function waitForExit(
3093
3429
  // one concurrent wait timing out cannot re-enable notifications underneath
3094
3430
  // another wait that is still pending.
3095
3431
  updateWaitReservation(id, "reserve");
3096
- let w: Awaited<ReturnType<typeof bs>>;
3097
- let attempt = 0;
3098
- for (;;) {
3099
- w = await bs(["wait", "-s", id, "--timeout", t], { signal });
3100
- if (signal?.aborted) {
3101
- updateWaitReservation(id, "abandon");
3102
- return { id, kind: "interrupted", ok: false, text: `wait for ${id} was interrupted.` };
3103
- }
3104
- if (w.code === 0 || w.code === 124 || w.code === 130) break;
3105
-
3106
- // A freshly spawned session can be visible in `list` before the backend's
3107
- // wait endpoint is ready, especially when sibling foreground tools start
3108
- // concurrently. Retry that transient startup race instead of reporting the
3109
- // still-running child as "exited with code ?".
3110
- const retryStatus = await statusOf(id);
3111
- if (retryStatus?.state !== "running" || attempt++ >= 3) break;
3112
- await new Promise((resolve) => setTimeout(resolve, 50 * attempt));
3113
- }
3114
- if (w.code === 130) {
3115
- const interruptedStatus = await statusOf(id);
3116
- if (interruptedStatus?.state === "running") {
3117
- updateWaitReservation(id, "abandon");
3118
- return { id, kind: "interrupted", ok: false, text: `wait for ${id} was interrupted.` };
3119
- }
3432
+ const waited = await waitForStop(id, limitMs, signal);
3433
+ if (waited === "interrupted") {
3434
+ updateWaitReservation(id, "abandon");
3435
+ return { id, kind: "interrupted", ok: false, text: `wait for ${id} was interrupted.` };
3120
3436
  }
3121
- if (w.code === 124) {
3122
- // 124 is ambiguous (timeout vs child exiting 124) — disambiguate.
3437
+ if (waited === "timeout") {
3438
+ // A remote 124 is ambiguous (timeout vs child exiting 124) — disambiguate.
3123
3439
  const st0 = await statusOf(id);
3124
3440
  if (st0?.state === "running") {
3125
3441
  updateWaitReservation(id, "abandon");
@@ -3168,6 +3484,7 @@ async function waitForExit(
3168
3484
  const meta = readMeta(id);
3169
3485
  const workerDead = st.state === "dead" && st.exit_code == null;
3170
3486
  const ok = st.exit_code === 0;
3487
+ await awaitLocalOutputSettled(id, signal);
3171
3488
  const output = await selectedProcessOutput(id, st, outputSelection, signal);
3172
3489
  return {
3173
3490
  id,
@@ -3296,7 +3613,7 @@ export default function (pi: ExtensionAPI) {
3296
3613
  let pollTimer: ReturnType<typeof setInterval> | undefined;
3297
3614
  let pollNeeded = true;
3298
3615
  // Earliest time the poller should run again when every pending session is a
3299
- // remote one whose host is in backoff (0 = poll every POLL_MS).
3616
+ // remote one whose host is in backoff (0 = poll every tick).
3300
3617
  let pollDeferredUntilMs = 0;
3301
3618
  // Bumped by every re-arm so a tick that started before a new session was
3302
3619
  // created cannot switch polling off based on its stale snapshot.
@@ -3467,15 +3784,9 @@ export default function (pi: ExtensionAPI) {
3467
3784
  // A notification group is delivered only after all currently known
3468
3785
  // members have stopped, even when their exit times span many polls.
3469
3786
  if (!isNotificationGroupReady(meta, sessions, readMeta)) continue;
3470
- // Delay delivery by one poll interval. This gives an agent that chose
3471
- // babysit_wait immediately after babysit_run enough time to claim the
3472
- // completion and suppress the otherwise duplicate automatic message.
3473
- if (!meta.completionObservedAt) {
3474
- meta.completionObservedAt = Date.now();
3475
- writeMeta(session.id, meta);
3476
- continue;
3477
- }
3478
- if (Date.now() - meta.completionObservedAt < POLL_MS) continue;
3787
+ // No extra debounce: an agent that calls babysit_wait right after
3788
+ // babysit_run does so inside an active run, where delivery is already
3789
+ // deferred above, and the wait's reservation suppresses this message.
3479
3790
  ready.push({ session, meta });
3480
3791
  }
3481
3792
 
@@ -3487,10 +3798,9 @@ export default function (pi: ExtensionAPI) {
3487
3798
  : session.state === "dead" || session.exit_code == null
3488
3799
  ? "terminated"
3489
3800
  : "failed";
3801
+ await awaitLocalOutputSettled(session.id);
3490
3802
  const output = await inlineOutput(session.id, session, NOTIFY_OUTPUT_MAX_BYTES);
3491
- const runtime = meta.startedAt
3492
- ? `${Math.round(((meta.completionObservedAt ?? Date.now()) - meta.startedAt) / 1000)}s`
3493
- : "?";
3803
+ const runtime = meta.startedAt ? `${Math.round((Date.now() - meta.startedAt) / 1000)}s` : "?";
3494
3804
  const summary = ok
3495
3805
  ? `Process "${session.id}" completed successfully after ${runtime}.`
3496
3806
  : session.state === "dead" || session.exit_code == null
@@ -3563,13 +3873,6 @@ export default function (pi: ExtensionAPI) {
3563
3873
  if (session.state === "running" && !progress.done) continue;
3564
3874
 
3565
3875
  const offset = meta.promptOffset ?? 0;
3566
- if (meta.subagentCompletionObservedOffset !== offset) {
3567
- meta.subagentCompletionObservedOffset = offset;
3568
- meta.subagentCompletionObservedAt = Date.now();
3569
- writeMeta(session.id, meta);
3570
- continue;
3571
- }
3572
- if (Date.now() - (meta.subagentCompletionObservedAt ?? 0) < POLL_MS) continue;
3573
3876
  const summary = progress.done
3574
3877
  ? `task settled; ${progress.turns} turns, ${progress.toolCallCount} tools, $${progress.cost.toFixed(4)}`
3575
3878
  : `worker ${session.state} with exit code ${session.exit_code ?? "?"}; partial usage $${progress.cost.toFixed(4)}`;
@@ -3767,6 +4070,8 @@ export default function (pi: ExtensionAPI) {
3767
4070
  searchLogCache.clear();
3768
4071
  settledSessionIds.clear();
3769
4072
  remoteHostBackoff.clear();
4073
+ remotePollCache.clear();
4074
+ pendingLocalStarts.clear();
3770
4075
  armPolling();
3771
4076
  const retentionDays = Number(process.env.PI_BABYSIT_RETENTION_DAYS ?? "3");
3772
4077
  if (
@@ -3802,59 +4107,78 @@ export default function (pi: ExtensionAPI) {
3802
4107
  if (ctx.hasUI && !(await babysitAvailable())) {
3803
4108
  ctx.ui.notify(babysitPreflightError ?? INSTALL_HINT, "warning");
3804
4109
  }
4110
+ pollCtx = ctx;
3805
4111
  if (pollTimer) clearInterval(pollTimer);
3806
- pollTimer = setInterval(() => {
3807
- // Once a namespace has no live workers or pending notifications, avoid
3808
- // spawning `babysit list` forever while the UI is idle. A successful
3809
- // babysit_run re-arms polling below.
3810
- if (polling || !pollNeeded || Date.now() < pollDeferredUntilMs) return;
3811
- polling = true;
3812
- const generation = pollGeneration;
3813
- void (async () => {
3814
- const listed = await listSessions({ poll: true });
3815
- if (listed.error) {
3816
- if (generation === pollGeneration) pollNeeded = shouldKeepPollingAfterList(listed, readMeta);
3817
- throw new Error(listed.error);
3818
- }
3819
- // Finished sessions with nothing left to deliver never need another look.
3820
- const snapshot = listed.sessions.filter(
3821
- (session) =>
3822
- session.state === "running" || session.transportError || !settledSessionIds.has(session.id),
3823
- );
3824
- await enforceSubagentBudgets(snapshot);
3825
- await Promise.all([
3826
- notifyEndedProcesses(ctx, snapshot),
3827
- notifySettledSubagents(ctx, snapshot),
3828
- refreshWidget(ctx, snapshot),
3829
- ]);
3830
- const pendingTerminal = new Set<string>();
3831
- for (const session of snapshot) {
3832
- if (session.state === "running" || session.transportError) continue;
3833
- if (isSettledSession(readMeta(session.id))) settledSessionIds.add(session.id);
3834
- else pendingTerminal.add(session.id);
3835
- }
3836
- // Keep parsed progress for finished subagents whose result is still
3837
- // pending; otherwise each tick would re-parse their whole log.
3838
- pruneTerminalSessionCache(taskProgressCache, snapshot, pendingTerminal);
3839
- if (generation !== pollGeneration) return;
3840
- pollNeeded = shouldKeepPolling(snapshot, readMeta);
3841
- pollDeferredUntilMs = pollNeeded ? pollDeferredUntil(snapshot, readMeta, remoteBackoffUntil) : 0;
3842
- })()
3843
- .catch(() => {
3844
- // Keep polling armed after a transient CLI/filesystem error.
3845
- armPolling();
3846
- })
3847
- .finally(() => {
3848
- polling = false;
3849
- });
3850
- }, POLL_MS);
4112
+ pollTimer = setInterval(() => runPollTick(), LOCAL_POLL_MS);
4113
+ });
4114
+
4115
+ // Deliver anything that became ready while the agent was busy as soon as it
4116
+ // goes idle, instead of waiting for the next tick.
4117
+ pi.on("agent_settled", () => {
4118
+ runPollTick();
3851
4119
  });
3852
4120
 
4121
+ let pollCtx: ExtensionContext | undefined;
4122
+ let pollAgain = false;
4123
+ function runPollTick(): void {
4124
+ const ctx = pollCtx;
4125
+ if (!ctx) return;
4126
+ if (polling) {
4127
+ pollAgain = true;
4128
+ return;
4129
+ }
4130
+ // Once a namespace has no live workers or pending notifications, stop
4131
+ // scanning while the UI is idle. A successful babysit_run re-arms polling.
4132
+ if (!pollNeeded || Date.now() < pollDeferredUntilMs) return;
4133
+ polling = true;
4134
+ pollAgain = false;
4135
+ const generation = pollGeneration;
4136
+ void (async () => {
4137
+ const listed = await listSessions({ poll: true });
4138
+ if (listed.error) {
4139
+ if (generation === pollGeneration) pollNeeded = shouldKeepPollingAfterList(listed, readMeta);
4140
+ throw new Error(listed.error);
4141
+ }
4142
+ // Finished sessions with nothing left to deliver never need another look.
4143
+ const snapshot = listed.sessions.filter(
4144
+ (session) =>
4145
+ session.state === "running" || session.transportError || !settledSessionIds.has(session.id),
4146
+ );
4147
+ await enforceSubagentBudgets(snapshot);
4148
+ await Promise.all([
4149
+ notifyEndedProcesses(ctx, snapshot),
4150
+ notifySettledSubagents(ctx, snapshot),
4151
+ refreshWidget(ctx, snapshot),
4152
+ ]);
4153
+ const pendingTerminal = new Set<string>();
4154
+ for (const session of snapshot) {
4155
+ if (session.state === "running" || session.transportError) continue;
4156
+ if (isSettledSession(readMeta(session.id))) settledSessionIds.add(session.id);
4157
+ else pendingTerminal.add(session.id);
4158
+ }
4159
+ // Keep parsed progress for finished subagents whose result is still
4160
+ // pending; otherwise each tick would re-parse their whole log.
4161
+ pruneTerminalSessionCache(taskProgressCache, snapshot, pendingTerminal);
4162
+ if (generation !== pollGeneration) return;
4163
+ pollNeeded = shouldKeepPolling(snapshot, readMeta);
4164
+ pollDeferredUntilMs = pollNeeded ? pollDeferredUntil(snapshot, readMeta, remoteBackoffUntil) : 0;
4165
+ })()
4166
+ .catch(() => {
4167
+ // Keep polling armed after a transient CLI/filesystem error.
4168
+ armPolling();
4169
+ })
4170
+ .finally(() => {
4171
+ polling = false;
4172
+ if (pollAgain && pollCtx === ctx) runPollTick();
4173
+ });
4174
+ }
4175
+
3853
4176
  pi.on("session_shutdown", async (event) => {
3854
4177
  sessionWidget?.dispose();
3855
4178
  sessionWidget = undefined;
3856
4179
  if (pollTimer) clearInterval(pollTimer);
3857
4180
  pollTimer = undefined;
4181
+ pollCtx = undefined;
3858
4182
  // Pi also emits session_shutdown while hot-reloading and switching sessions.
3859
4183
  // Preserve detached work for those lifecycle transitions; only a real Pi
3860
4184
  // quit owns and terminates every worker in the current session namespace.
@@ -4231,7 +4555,7 @@ export default function (pi: ExtensionAPI) {
4231
4555
  // period; if it exits, return lifecycle metadata + log path immediately.
4232
4556
  // A process still running after the grace follows the parked-turn /
4233
4557
  // automatic-notification contract below.
4234
- await bs(["wait", "-s", res.id, "--timeout", QUICK_COMMAND_GRACE], { signal: _signal });
4558
+ await waitForStop(res.id, QUICK_COMMAND_GRACE_MS, _signal);
4235
4559
  let quickStatus = await statusOf(res.id);
4236
4560
  let retried = false;
4237
4561
  if (params.retryOnWorkerDeath && quickStatus?.state === "dead" && quickStatus.exit_code == null) {
@@ -4242,7 +4566,7 @@ export default function (pi: ExtensionAPI) {
4242
4566
  if (!("error" in retry)) {
4243
4567
  res = retry;
4244
4568
  retried = true;
4245
- await bs(["wait", "-s", res.id, "--timeout", QUICK_COMMAND_GRACE], { signal: _signal });
4569
+ await waitForStop(res.id, QUICK_COMMAND_GRACE_MS, _signal);
4246
4570
  quickStatus = await statusOf(res.id);
4247
4571
  }
4248
4572
  }
@@ -4636,7 +4960,7 @@ export default function (pi: ExtensionAPI) {
4636
4960
  if (sc.code !== 0) throw new Error(sc.stderr || sc.stdout || "Screenshot unavailable");
4637
4961
  parts.push(`--- screen ---\n${clip(sc.stdout.trimEnd(), checkMaxBytes) || "(blank screen)"}`);
4638
4962
  } else {
4639
- const result = await bs(["log", "-s", params.id, "--tail", String(nLines)]);
4963
+ const result = await readSessionLog(params.id, nLines);
4640
4964
  if (result.code !== 0) throw new Error(result.stderr || result.stdout || "Log unavailable");
4641
4965
  const tail = clip(
4642
4966
  result.stdout.trimEnd(),
@@ -5297,7 +5621,7 @@ export default function (pi: ExtensionAPI) {
5297
5621
  // the recorded tail is enough.
5298
5622
  const screenResult = running ? await bs(["screenshot", "-s", picked.id, "--trim"]) : undefined;
5299
5623
  const screen = screenResult ? screenResult.code === 0 ? screenResult.stdout.trimEnd() : `Screen unavailable: ${screenResult.stderr || screenResult.stdout}` : "";
5300
- const tailResult = await bs(["log", "-s", picked.id, "--tail", "30"]);
5624
+ const tailResult = await readSessionLog(picked.id, 30);
5301
5625
  const tail = tailResult.code === 0 ? tailResult.stdout.trimEnd() : `Output unavailable: ${tailResult.stderr || tailResult.stdout}`;
5302
5626
  const title =
5303
5627
  `${picked.id}${meta?.host ? ` @${meta.host}` : ""} ${picked.transportError ? "unknown" : picked.state}${elapsedSuffix}` +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yusukeshib/pi-babysit",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Run any shell command and pi subagents under babysit, with context-safe captured output.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -23,7 +23,6 @@
23
23
  "agents.ts",
24
24
  "self-reap.ts",
25
25
  "format-stream.mjs",
26
- "view.mjs",
27
26
  "search-log.mjs",
28
27
  "gc.mjs",
29
28
  "gc.d.mts",
@@ -39,9 +38,6 @@
39
38
  "./index.ts"
40
39
  ]
41
40
  },
42
- "dependencies": {
43
- "@yusukeshib/pi-tail": "^0.1.0"
44
- },
45
41
  "peerDependencies": {
46
42
  "@earendil-works/pi-ai": "*",
47
43
  "@earendil-works/pi-coding-agent": ">=1.0.0",
package/view.mjs DELETED
@@ -1,79 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * view.mjs — live, read-only view of a pi-babysit subagent, rendered by
4
- * @yusukeshib/pi-tail with Pi's own TUI components.
5
- *
6
- * node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]
7
- *
8
- * A subagent log is Pi's `pi --mode rpc` event stream. This wrapper resolves
9
- * the session, uses the worker's directory, and shows the session state.
10
- */
11
- import fs from "node:fs";
12
- import os from "node:os";
13
- import path from "node:path";
14
- import { pathToFileURL } from "node:url";
15
- import { parseArgs, runCli, runViewer } from "@yusukeshib/pi-tail";
16
-
17
- export { parseArgs };
18
-
19
- const USAGE = "Usage: node view.mjs <session-id | session dir | output.log> [--print] [--cwd DIR]";
20
-
21
- /** Resolve a session id, session directory, or log path to the log file. */
22
- export function resolveLogPath(target, rootBase = process.env.PI_BABYSIT_DIR ?? path.join(os.homedir(), ".pi-babysit")) {
23
- if (fs.existsSync(target)) {
24
- const stat = fs.statSync(target);
25
- return stat.isDirectory() ? path.join(target, "output.log") : target;
26
- }
27
- let best;
28
- for (const root of fs.existsSync(rootBase) ? fs.readdirSync(rootBase) : []) {
29
- const log = path.join(rootBase, root, "sessions", target, "output.log");
30
- try {
31
- const mtime = fs.statSync(log).mtimeMs;
32
- if (!best || mtime > best.mtime) best = { log, mtime };
33
- } catch {
34
- /* not in this root */
35
- }
36
- }
37
- if (!best) throw new Error(`No babysit session log found for ${target} under ${rootBase}`);
38
- return best.log;
39
- }
40
-
41
- function readJson(file) {
42
- try {
43
- return JSON.parse(fs.readFileSync(file, "utf8"));
44
- } catch {
45
- return undefined;
46
- }
47
- }
48
-
49
- /** pi-babysit's own metadata for a session log (<root>/meta/<id>.json). */
50
- function sessionInfo(logPath) {
51
- const sessionDir = path.dirname(logPath);
52
- const id = path.basename(sessionDir);
53
- const root = path.dirname(path.dirname(sessionDir));
54
- return {
55
- id,
56
- meta: readJson(path.join(root, "meta", `${id}.json`)),
57
- statusFile: path.join(sessionDir, "status.json"),
58
- };
59
- }
60
-
61
- export async function main(argv = process.argv.slice(2)) {
62
- const options = parseArgs(argv);
63
- if (options.help || !options.target) {
64
- console.log(USAGE);
65
- return options.help ? 0 : 2;
66
- }
67
- const file = resolveLogPath(options.target);
68
- const info = sessionInfo(file);
69
- const label = info.meta?.name && info.meta.name !== info.id ? `${info.id} (${info.meta.name})` : info.id;
70
- return runViewer({
71
- file,
72
- cwd: options.cwd ?? info.meta?.cwd ?? process.cwd(),
73
- print: options.print,
74
- status: () => `${label} · ${readJson(info.statusFile)?.state ?? "unknown"}`,
75
- });
76
- }
77
-
78
- const entry = process.argv[1] ? pathToFileURL(fs.realpathSync(process.argv[1])).href : undefined;
79
- if (entry === import.meta.url) runCli(main);