@yusukeshib/pi-babysit 0.8.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 (3) hide show
  1. package/README.md +12 -5
  2. package/index.ts +459 -133
  3. package/package.json +1 -1
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
@@ -303,12 +303,19 @@ because blindly rerunning an arbitrary command can duplicate side effects.
303
303
 
304
304
  ## How completion detection works
305
305
 
306
- - **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
307
307
  parent agent is idle, injects one
308
308
  `pi.sendMessage(…, { triggerTurn: true, deliverAs: "steer" })` containing every
309
309
  deliverable exit observed in that poll (deduped via `meta/<id>.json`). Waiting
310
310
  for idleness prevents an immediately-following `babysit_wait` from racing the
311
- 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
312
319
  together in one assistant message automatically share a notification group;
313
320
  an explicit `notificationGroup` overrides this. Group members wait for every
314
321
  currently running member to stop and then share one notification even when
@@ -320,8 +327,8 @@ because blindly rerunning an arbitrary command can duplicate side effects.
320
327
  notification. Kill results are reconciled with persisted terminal state, so
321
328
  a backend escalation warning that arrives after the child has already exited
322
329
  does not produce a false failure followed by a redundant notification.
323
- - **Subagent**: `foreground: true` or `babysit_wait` blocks on
324
- `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
325
332
  exits before it is collected emits one ready-to-collect reminder; the parent
326
333
  must still call `babysit_wait` so the answer and nested usage are persisted.
327
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,7 +778,6 @@ 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;
@@ -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();
@@ -2863,8 +3126,8 @@ function sumNestedUsage(values: Array<NestedUsage | undefined>): NestedUsage | u
2863
3126
 
2864
3127
  // Wait for ONE subagent's current task. Completion = agent_settled without a
2865
3128
  // parked babysit_run/process result (a parked run only means "waiting for
2866
- // process exit; pi will resume itself"). Parse appended bytes incrementally,
2867
- // 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.
2868
3131
  async function waitForTask(
2869
3132
  id: string,
2870
3133
  limitMs: number | null,
@@ -2879,7 +3142,7 @@ async function waitForTask(
2879
3142
  } catch {
2880
3143
  observed = { progress: emptyProgress(), offset: readMeta(id)?.promptOffset ?? 0 };
2881
3144
  }
2882
- const { progress: prog, offset: cur } = observed;
3145
+ const { progress: prog } = observed;
2883
3146
  const st = await statusOf(id);
2884
3147
 
2885
3148
  const stats =
@@ -2932,19 +3195,18 @@ async function waitForTask(
2932
3195
  progress: prog,
2933
3196
  });
2934
3197
 
2935
- // Still working — block until Pi declares the run fully settled. Unlike
2936
- // agent_end, this cannot fire before an automatic retry/compaction retry.
2937
- 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;
2938
3204
  if (limitMs != null) {
2939
3205
  const remaining = limitMs - (Date.now() - t0);
2940
3206
  if (remaining <= 0) return timeoutOutcome();
2941
- expectTimeout = `${Math.ceil(remaining / 1000)}s`;
3207
+ delay = Math.min(delay, remaining);
2942
3208
  }
2943
- const e = await bs(
2944
- ["expect", "-s", id, "--since", String(cur), "--timeout", expectTimeout, '"type":"agent_settled"'],
2945
- { signal },
2946
- );
2947
- if (signal?.aborted || e.code === 130) {
3209
+ if (await sleepUnlessAborted(delay, signal)) {
2948
3210
  return {
2949
3211
  id,
2950
3212
  kind: "interrupted",
@@ -2954,12 +3216,6 @@ async function waitForTask(
2954
3216
  progress: prog,
2955
3217
  };
2956
3218
  }
2957
- if (e.code === 124) return timeoutOutcome();
2958
- // e.code !== 0 (session likely exited mid-wait) falls through to the
2959
- // next loop iteration, where the exited branch reports the cause.
2960
- if (e.code !== 0) {
2961
- await new Promise((res) => setTimeout(res, 500));
2962
- }
2963
3219
  }
2964
3220
  }
2965
3221
 
@@ -3045,6 +3301,88 @@ function resumeNotify(id: string): void {
3045
3301
  }
3046
3302
  }
3047
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
+
3048
3386
  // Wait for a PROCESS session: either until a regex appears in its output
3049
3387
  // (`expect` — e.g. "server listening") or until the process exits.
3050
3388
  async function waitForExit(
@@ -3091,33 +3429,13 @@ async function waitForExit(
3091
3429
  // one concurrent wait timing out cannot re-enable notifications underneath
3092
3430
  // another wait that is still pending.
3093
3431
  updateWaitReservation(id, "reserve");
3094
- let w: Awaited<ReturnType<typeof bs>>;
3095
- let attempt = 0;
3096
- for (;;) {
3097
- w = await bs(["wait", "-s", id, "--timeout", t], { signal });
3098
- if (signal?.aborted) {
3099
- updateWaitReservation(id, "abandon");
3100
- return { id, kind: "interrupted", ok: false, text: `wait for ${id} was interrupted.` };
3101
- }
3102
- if (w.code === 0 || w.code === 124 || w.code === 130) break;
3103
-
3104
- // A freshly spawned session can be visible in `list` before the backend's
3105
- // wait endpoint is ready, especially when sibling foreground tools start
3106
- // concurrently. Retry that transient startup race instead of reporting the
3107
- // still-running child as "exited with code ?".
3108
- const retryStatus = await statusOf(id);
3109
- if (retryStatus?.state !== "running" || attempt++ >= 3) break;
3110
- await new Promise((resolve) => setTimeout(resolve, 50 * attempt));
3111
- }
3112
- if (w.code === 130) {
3113
- const interruptedStatus = await statusOf(id);
3114
- if (interruptedStatus?.state === "running") {
3115
- updateWaitReservation(id, "abandon");
3116
- return { id, kind: "interrupted", ok: false, text: `wait for ${id} was interrupted.` };
3117
- }
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.` };
3118
3436
  }
3119
- if (w.code === 124) {
3120
- // 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.
3121
3439
  const st0 = await statusOf(id);
3122
3440
  if (st0?.state === "running") {
3123
3441
  updateWaitReservation(id, "abandon");
@@ -3166,6 +3484,7 @@ async function waitForExit(
3166
3484
  const meta = readMeta(id);
3167
3485
  const workerDead = st.state === "dead" && st.exit_code == null;
3168
3486
  const ok = st.exit_code === 0;
3487
+ await awaitLocalOutputSettled(id, signal);
3169
3488
  const output = await selectedProcessOutput(id, st, outputSelection, signal);
3170
3489
  return {
3171
3490
  id,
@@ -3294,7 +3613,7 @@ export default function (pi: ExtensionAPI) {
3294
3613
  let pollTimer: ReturnType<typeof setInterval> | undefined;
3295
3614
  let pollNeeded = true;
3296
3615
  // Earliest time the poller should run again when every pending session is a
3297
- // remote one whose host is in backoff (0 = poll every POLL_MS).
3616
+ // remote one whose host is in backoff (0 = poll every tick).
3298
3617
  let pollDeferredUntilMs = 0;
3299
3618
  // Bumped by every re-arm so a tick that started before a new session was
3300
3619
  // created cannot switch polling off based on its stale snapshot.
@@ -3465,15 +3784,9 @@ export default function (pi: ExtensionAPI) {
3465
3784
  // A notification group is delivered only after all currently known
3466
3785
  // members have stopped, even when their exit times span many polls.
3467
3786
  if (!isNotificationGroupReady(meta, sessions, readMeta)) continue;
3468
- // Delay delivery by one poll interval. This gives an agent that chose
3469
- // babysit_wait immediately after babysit_run enough time to claim the
3470
- // completion and suppress the otherwise duplicate automatic message.
3471
- if (!meta.completionObservedAt) {
3472
- meta.completionObservedAt = Date.now();
3473
- writeMeta(session.id, meta);
3474
- continue;
3475
- }
3476
- 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.
3477
3790
  ready.push({ session, meta });
3478
3791
  }
3479
3792
 
@@ -3485,10 +3798,9 @@ export default function (pi: ExtensionAPI) {
3485
3798
  : session.state === "dead" || session.exit_code == null
3486
3799
  ? "terminated"
3487
3800
  : "failed";
3801
+ await awaitLocalOutputSettled(session.id);
3488
3802
  const output = await inlineOutput(session.id, session, NOTIFY_OUTPUT_MAX_BYTES);
3489
- const runtime = meta.startedAt
3490
- ? `${Math.round(((meta.completionObservedAt ?? Date.now()) - meta.startedAt) / 1000)}s`
3491
- : "?";
3803
+ const runtime = meta.startedAt ? `${Math.round((Date.now() - meta.startedAt) / 1000)}s` : "?";
3492
3804
  const summary = ok
3493
3805
  ? `Process "${session.id}" completed successfully after ${runtime}.`
3494
3806
  : session.state === "dead" || session.exit_code == null
@@ -3561,13 +3873,6 @@ export default function (pi: ExtensionAPI) {
3561
3873
  if (session.state === "running" && !progress.done) continue;
3562
3874
 
3563
3875
  const offset = meta.promptOffset ?? 0;
3564
- if (meta.subagentCompletionObservedOffset !== offset) {
3565
- meta.subagentCompletionObservedOffset = offset;
3566
- meta.subagentCompletionObservedAt = Date.now();
3567
- writeMeta(session.id, meta);
3568
- continue;
3569
- }
3570
- if (Date.now() - (meta.subagentCompletionObservedAt ?? 0) < POLL_MS) continue;
3571
3876
  const summary = progress.done
3572
3877
  ? `task settled; ${progress.turns} turns, ${progress.toolCallCount} tools, $${progress.cost.toFixed(4)}`
3573
3878
  : `worker ${session.state} with exit code ${session.exit_code ?? "?"}; partial usage $${progress.cost.toFixed(4)}`;
@@ -3765,6 +4070,8 @@ export default function (pi: ExtensionAPI) {
3765
4070
  searchLogCache.clear();
3766
4071
  settledSessionIds.clear();
3767
4072
  remoteHostBackoff.clear();
4073
+ remotePollCache.clear();
4074
+ pendingLocalStarts.clear();
3768
4075
  armPolling();
3769
4076
  const retentionDays = Number(process.env.PI_BABYSIT_RETENTION_DAYS ?? "3");
3770
4077
  if (
@@ -3800,59 +4107,78 @@ export default function (pi: ExtensionAPI) {
3800
4107
  if (ctx.hasUI && !(await babysitAvailable())) {
3801
4108
  ctx.ui.notify(babysitPreflightError ?? INSTALL_HINT, "warning");
3802
4109
  }
4110
+ pollCtx = ctx;
3803
4111
  if (pollTimer) clearInterval(pollTimer);
3804
- pollTimer = setInterval(() => {
3805
- // Once a namespace has no live workers or pending notifications, avoid
3806
- // spawning `babysit list` forever while the UI is idle. A successful
3807
- // babysit_run re-arms polling below.
3808
- if (polling || !pollNeeded || Date.now() < pollDeferredUntilMs) return;
3809
- polling = true;
3810
- const generation = pollGeneration;
3811
- void (async () => {
3812
- const listed = await listSessions({ poll: true });
3813
- if (listed.error) {
3814
- if (generation === pollGeneration) pollNeeded = shouldKeepPollingAfterList(listed, readMeta);
3815
- throw new Error(listed.error);
3816
- }
3817
- // Finished sessions with nothing left to deliver never need another look.
3818
- const snapshot = listed.sessions.filter(
3819
- (session) =>
3820
- session.state === "running" || session.transportError || !settledSessionIds.has(session.id),
3821
- );
3822
- await enforceSubagentBudgets(snapshot);
3823
- await Promise.all([
3824
- notifyEndedProcesses(ctx, snapshot),
3825
- notifySettledSubagents(ctx, snapshot),
3826
- refreshWidget(ctx, snapshot),
3827
- ]);
3828
- const pendingTerminal = new Set<string>();
3829
- for (const session of snapshot) {
3830
- if (session.state === "running" || session.transportError) continue;
3831
- if (isSettledSession(readMeta(session.id))) settledSessionIds.add(session.id);
3832
- else pendingTerminal.add(session.id);
3833
- }
3834
- // Keep parsed progress for finished subagents whose result is still
3835
- // pending; otherwise each tick would re-parse their whole log.
3836
- pruneTerminalSessionCache(taskProgressCache, snapshot, pendingTerminal);
3837
- if (generation !== pollGeneration) return;
3838
- pollNeeded = shouldKeepPolling(snapshot, readMeta);
3839
- pollDeferredUntilMs = pollNeeded ? pollDeferredUntil(snapshot, readMeta, remoteBackoffUntil) : 0;
3840
- })()
3841
- .catch(() => {
3842
- // Keep polling armed after a transient CLI/filesystem error.
3843
- armPolling();
3844
- })
3845
- .finally(() => {
3846
- polling = false;
3847
- });
3848
- }, 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();
3849
4119
  });
3850
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
+
3851
4176
  pi.on("session_shutdown", async (event) => {
3852
4177
  sessionWidget?.dispose();
3853
4178
  sessionWidget = undefined;
3854
4179
  if (pollTimer) clearInterval(pollTimer);
3855
4180
  pollTimer = undefined;
4181
+ pollCtx = undefined;
3856
4182
  // Pi also emits session_shutdown while hot-reloading and switching sessions.
3857
4183
  // Preserve detached work for those lifecycle transitions; only a real Pi
3858
4184
  // quit owns and terminates every worker in the current session namespace.
@@ -4229,7 +4555,7 @@ export default function (pi: ExtensionAPI) {
4229
4555
  // period; if it exits, return lifecycle metadata + log path immediately.
4230
4556
  // A process still running after the grace follows the parked-turn /
4231
4557
  // automatic-notification contract below.
4232
- await bs(["wait", "-s", res.id, "--timeout", QUICK_COMMAND_GRACE], { signal: _signal });
4558
+ await waitForStop(res.id, QUICK_COMMAND_GRACE_MS, _signal);
4233
4559
  let quickStatus = await statusOf(res.id);
4234
4560
  let retried = false;
4235
4561
  if (params.retryOnWorkerDeath && quickStatus?.state === "dead" && quickStatus.exit_code == null) {
@@ -4240,7 +4566,7 @@ export default function (pi: ExtensionAPI) {
4240
4566
  if (!("error" in retry)) {
4241
4567
  res = retry;
4242
4568
  retried = true;
4243
- await bs(["wait", "-s", res.id, "--timeout", QUICK_COMMAND_GRACE], { signal: _signal });
4569
+ await waitForStop(res.id, QUICK_COMMAND_GRACE_MS, _signal);
4244
4570
  quickStatus = await statusOf(res.id);
4245
4571
  }
4246
4572
  }
@@ -4634,7 +4960,7 @@ export default function (pi: ExtensionAPI) {
4634
4960
  if (sc.code !== 0) throw new Error(sc.stderr || sc.stdout || "Screenshot unavailable");
4635
4961
  parts.push(`--- screen ---\n${clip(sc.stdout.trimEnd(), checkMaxBytes) || "(blank screen)"}`);
4636
4962
  } else {
4637
- const result = await bs(["log", "-s", params.id, "--tail", String(nLines)]);
4963
+ const result = await readSessionLog(params.id, nLines);
4638
4964
  if (result.code !== 0) throw new Error(result.stderr || result.stdout || "Log unavailable");
4639
4965
  const tail = clip(
4640
4966
  result.stdout.trimEnd(),
@@ -5295,7 +5621,7 @@ export default function (pi: ExtensionAPI) {
5295
5621
  // the recorded tail is enough.
5296
5622
  const screenResult = running ? await bs(["screenshot", "-s", picked.id, "--trim"]) : undefined;
5297
5623
  const screen = screenResult ? screenResult.code === 0 ? screenResult.stdout.trimEnd() : `Screen unavailable: ${screenResult.stderr || screenResult.stdout}` : "";
5298
- const tailResult = await bs(["log", "-s", picked.id, "--tail", "30"]);
5624
+ const tailResult = await readSessionLog(picked.id, 30);
5299
5625
  const tail = tailResult.code === 0 ? tailResult.stdout.trimEnd() : `Output unavailable: ${tailResult.stderr || tailResult.stdout}`;
5300
5626
  const title =
5301
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.8.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",