@cydm/pie 4.7.0 → 4.9.0

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 (49) hide show
  1. package/README.md +51 -27
  2. package/dist/builtin/extensions/ask-user/index.js +4 -4
  3. package/dist/builtin/extensions/cron/index.js +916 -162
  4. package/dist/builtin/extensions/im-forward/README.md +24 -7
  5. package/dist/builtin/extensions/im-forward/index.js +6823 -3683
  6. package/dist/builtin/extensions/memory/index.js +76 -28
  7. package/dist/builtin/extensions/pie-ipc/README.md +2 -2
  8. package/dist/builtin/extensions/pie-ipc/index.js +421 -27
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +453 -97
  11. package/dist/builtin/extensions/plan-mode/index.js +5 -5
  12. package/dist/builtin/extensions/subagent/index.js +8 -8
  13. package/dist/builtin/extensions/todo/index.js +4 -4
  14. package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +35 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +391 -123
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
  18. package/dist/builtin/skills/chrome-devtools-axi/{cli-NLPMVDGG.js → cli-K7ESY3XD.js} +1437 -231
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +26 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +465 -83
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +75 -22
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
  26. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
  27. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
  28. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  29. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
  30. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  31. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
  32. package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
  33. package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
  34. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
  35. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  36. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
  37. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
  38. package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
  40. package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
  41. package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
  42. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
  43. package/dist/cli.js +1918 -1489
  44. package/models.schema.json +271 -0
  45. package/package.json +2 -2
  46. package/dist/builtin/skills/chrome-devtools-axi/chunk-WOGAQ4P5.js +0 -399
  47. package/dist/chunks/chunk-7UAUDXZW.js +0 -1425
  48. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -7072,29 +7072,193 @@ function resolveExecutable(file, cwd = process.cwd(), env = process.env) {
7072
7072
 
7073
7073
  // vendor/tui-use/src/session.ts
7074
7074
  var import_node_child_process = require("node:child_process");
7075
- async function listDescendants(rootPid) {
7076
- if (process.platform === "win32") return [];
7075
+ function normalizeTty(raw) {
7076
+ const trimmed = (raw ?? "").trim();
7077
+ if (!trimmed || trimmed === "?" || trimmed === "??") return null;
7078
+ return trimmed;
7079
+ }
7080
+ function parseLeaderIdentityOutput(out) {
7081
+ const m = /^(\S+)\s+(.+)$/.exec(out.trim());
7082
+ if (!m) return { startTime: null, tty: null };
7083
+ return { tty: normalizeTty(m[1]), startTime: m[2].trim() || null };
7084
+ }
7085
+ function readLeaderIdentitySync(pid) {
7086
+ if (process.platform === "win32" || !Number.isInteger(pid) || pid <= 0) {
7087
+ return { startTime: null, tty: null };
7088
+ }
7089
+ try {
7090
+ const out = (0, import_node_child_process.execFileSync)(
7091
+ "ps",
7092
+ ["-p", String(pid), "-o", "tty=,lstart="],
7093
+ { encoding: "utf8", timeout: 1500, env: { ...process.env, LC_ALL: "C" } }
7094
+ );
7095
+ return parseLeaderIdentityOutput(out);
7096
+ } catch {
7097
+ return { startTime: null, tty: null };
7098
+ }
7099
+ }
7100
+ function readLeaderIdentity(pid) {
7101
+ if (process.platform === "win32" || !Number.isInteger(pid) || pid <= 0) {
7102
+ return Promise.resolve({ startTime: null, tty: null });
7103
+ }
7104
+ return new Promise((resolve) => {
7105
+ (0, import_node_child_process.execFile)(
7106
+ "ps",
7107
+ ["-p", String(pid), "-o", "tty=,lstart="],
7108
+ { timeout: 1500, env: { ...process.env, LC_ALL: "C" } },
7109
+ (error, stdout) => {
7110
+ if (error) {
7111
+ resolve({ startTime: null, tty: null });
7112
+ return;
7113
+ }
7114
+ resolve(parseLeaderIdentityOutput(String(stdout ?? "")));
7115
+ }
7116
+ );
7117
+ });
7118
+ }
7119
+ function readProcessStartTime(pid) {
7120
+ if (process.platform === "win32") return Promise.resolve(null);
7121
+ return new Promise((resolve) => {
7122
+ (0, import_node_child_process.execFile)(
7123
+ "ps",
7124
+ ["-p", String(pid), "-o", "lstart="],
7125
+ { timeout: 1500, env: { ...process.env, LC_ALL: "C" } },
7126
+ (error, stdout) => {
7127
+ if (error) {
7128
+ resolve(null);
7129
+ return;
7130
+ }
7131
+ const text = String(stdout ?? "").trim();
7132
+ resolve(text.length > 0 ? text : null);
7133
+ }
7134
+ );
7135
+ });
7136
+ }
7137
+ function parseStartTimeMs(startTime) {
7138
+ const parsed = Date.parse(startTime);
7139
+ return Number.isFinite(parsed) ? parsed : null;
7140
+ }
7141
+ function selectOwnedTreeFromRows(rows, leaderPid, expectedLeaderStartTime, opts = {}) {
7142
+ const hasSeeds = Boolean(opts.seededOwned && opts.seededOwned.length > 0);
7143
+ const leaderValidInput = !opts.seededOnly && Number.isInteger(leaderPid) && leaderPid > 0 && Boolean(expectedLeaderStartTime);
7144
+ if (!leaderValidInput && !hasSeeds) return [];
7145
+ const leaderRow = leaderValidInput ? rows.find((r) => r.pid === leaderPid) : void 0;
7146
+ const leaderIdentityValid = leaderValidInput ? leaderRow ? leaderRow.startTime === expectedLeaderStartTime : Boolean(opts.allowExitedLeader) : false;
7147
+ if (!leaderIdentityValid && !hasSeeds) {
7148
+ return [];
7149
+ }
7150
+ const byPid = /* @__PURE__ */ new Map();
7151
+ const byParent = /* @__PURE__ */ new Map();
7152
+ for (const row of rows) {
7153
+ byPid.set(row.pid, row);
7154
+ const list = byParent.get(row.ppid);
7155
+ if (list) list.push(row);
7156
+ else byParent.set(row.ppid, [row]);
7157
+ }
7158
+ const seen = new Set(leaderValidInput ? [leaderPid] : []);
7159
+ const frontier = [];
7077
7160
  const out = [];
7078
- const frontier = [rootPid];
7079
- const seen = /* @__PURE__ */ new Set([rootPid]);
7161
+ if (leaderIdentityValid) {
7162
+ if (leaderRow) {
7163
+ frontier.push(leaderPid);
7164
+ }
7165
+ const expectedTty = normalizeTty(opts.expectedTty ?? leaderRow?.tty);
7166
+ const minBirthMs = opts.sessionStartMs !== void 0 ? opts.sessionStartMs - 2e3 : void 0;
7167
+ const maxBirthMs = opts.captureWindowEndMs;
7168
+ for (const row of rows) {
7169
+ if (seen.has(row.pid)) continue;
7170
+ const rowTty = normalizeTty(row.tty);
7171
+ const matchesGroup = row.pgid === leaderPid;
7172
+ const matchesSession = row.sid !== void 0 && row.sid === leaderPid;
7173
+ const matchesTty = expectedTty !== null && rowTty === expectedTty;
7174
+ if (!matchesGroup && !matchesSession && !matchesTty) continue;
7175
+ if (!leaderRow && (minBirthMs !== void 0 || maxBirthMs !== void 0)) {
7176
+ const birth = parseStartTimeMs(row.startTime);
7177
+ if (birth === null) continue;
7178
+ if (minBirthMs !== void 0 && birth < minBirthMs) continue;
7179
+ if (maxBirthMs !== void 0 && birth > maxBirthMs) continue;
7180
+ }
7181
+ seen.add(row.pid);
7182
+ out.push({ pid: row.pid, startTime: row.startTime });
7183
+ frontier.push(row.pid);
7184
+ }
7185
+ }
7186
+ if (opts.seededOwned && opts.seededOwned.length > 0) {
7187
+ for (const seed of opts.seededOwned) {
7188
+ if (seen.has(seed.pid)) continue;
7189
+ const row = byPid.get(seed.pid);
7190
+ if (!row || row.startTime !== seed.startTime) continue;
7191
+ seen.add(row.pid);
7192
+ out.push({ pid: row.pid, startTime: row.startTime });
7193
+ frontier.push(row.pid);
7194
+ }
7195
+ }
7080
7196
  while (frontier.length > 0) {
7081
7197
  const parent = frontier.shift();
7082
- const children = await new Promise((resolve) => {
7083
- (0, import_node_child_process.execFile)("pgrep", ["-P", String(parent)], { timeout: 2e3 }, (error, stdout) => {
7084
- resolve(error ? [] : stdout.split("\n").map((l) => parseInt(l, 10)).filter((n) => Number.isInteger(n) && n > 0));
7085
- });
7086
- });
7198
+ const children = byParent.get(parent);
7199
+ if (!children) continue;
7087
7200
  for (const child of children) {
7088
- if (!seen.has(child)) {
7089
- seen.add(child);
7090
- out.push(child);
7091
- frontier.push(child);
7201
+ if (!seen.has(child.pid)) {
7202
+ seen.add(child.pid);
7203
+ out.push({ pid: child.pid, startTime: child.startTime });
7204
+ frontier.push(child.pid);
7092
7205
  }
7093
7206
  }
7094
7207
  }
7095
7208
  return out;
7096
7209
  }
7097
- async function sweepDescendants(pids) {
7210
+ async function listOwnedTree(leaderPid, expectedLeaderStartTime, opts = {}) {
7211
+ if (process.platform === "win32") return [];
7212
+ const hasSeeds = Boolean(opts.seededOwned && opts.seededOwned.length > 0);
7213
+ if (opts.seededOnly) {
7214
+ if (!hasSeeds) return [];
7215
+ } else if (!Number.isInteger(leaderPid) || leaderPid <= 0 || !expectedLeaderStartTime) {
7216
+ return [];
7217
+ }
7218
+ const includeSid = process.platform === "linux";
7219
+ const columns = includeSid ? "pid=,ppid=,pgid=,sid=,tty=,lstart=" : "pid=,ppid=,pgid=,tty=,lstart=";
7220
+ const rows = await new Promise((resolve) => {
7221
+ (0, import_node_child_process.execFile)(
7222
+ "ps",
7223
+ ["-eo", columns],
7224
+ { timeout: 2500, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } },
7225
+ (error, stdout) => {
7226
+ if (error) {
7227
+ resolve([]);
7228
+ return;
7229
+ }
7230
+ const parsed = [];
7231
+ for (const rawLine of String(stdout ?? "").split("\n")) {
7232
+ if (includeSid) {
7233
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(rawLine);
7234
+ if (!m) continue;
7235
+ const pid = Number(m[1]);
7236
+ const ppid = Number(m[2]);
7237
+ const pgid = Number(m[3]);
7238
+ const sid = Number(m[4]);
7239
+ const tty = normalizeTty(m[5]);
7240
+ if (pid > 0 && pid !== process.pid) {
7241
+ parsed.push({ pid, ppid, pgid, sid, ...tty ? { tty } : {}, startTime: m[6] });
7242
+ }
7243
+ } else {
7244
+ const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(rawLine);
7245
+ if (!m) continue;
7246
+ const pid = Number(m[1]);
7247
+ const ppid = Number(m[2]);
7248
+ const pgid = Number(m[3]);
7249
+ const tty = normalizeTty(m[4]);
7250
+ if (pid > 0 && pid !== process.pid) {
7251
+ parsed.push({ pid, ppid, pgid, ...tty ? { tty } : {}, startTime: m[5] });
7252
+ }
7253
+ }
7254
+ }
7255
+ resolve(parsed);
7256
+ }
7257
+ );
7258
+ });
7259
+ return selectOwnedTreeFromRows(rows, leaderPid, expectedLeaderStartTime, opts);
7260
+ }
7261
+ async function sweepOwnedTree(entries) {
7098
7262
  const alive = (pid) => {
7099
7263
  try {
7100
7264
  process.kill(pid, 0);
@@ -7103,16 +7267,25 @@ async function sweepDescendants(pids) {
7103
7267
  return false;
7104
7268
  }
7105
7269
  };
7106
- for (const pid of pids) {
7107
- if (alive(pid)) {
7108
- try {
7109
- process.kill(pid, "SIGKILL");
7110
- } catch {
7111
- }
7270
+ const verifiedChecks = await Promise.all(
7271
+ entries.map(async (entry) => {
7272
+ if (!alive(entry.pid)) return null;
7273
+ const currentStart = await readProcessStartTime(entry.pid);
7274
+ if (!currentStart || currentStart !== entry.startTime) return null;
7275
+ return entry.pid;
7276
+ })
7277
+ );
7278
+ const verifiedPids = [];
7279
+ for (const pid of verifiedChecks) {
7280
+ if (pid === null) continue;
7281
+ verifiedPids.push(pid);
7282
+ try {
7283
+ process.kill(pid, "SIGKILL");
7284
+ } catch {
7112
7285
  }
7113
7286
  }
7114
7287
  const deadline = Date.now() + 2e3;
7115
- while (Date.now() < deadline && pids.some(alive)) {
7288
+ while (Date.now() < deadline && verifiedPids.some(alive)) {
7116
7289
  await new Promise((resolve) => setTimeout(resolve, 25));
7117
7290
  }
7118
7291
  }
@@ -7283,6 +7456,18 @@ var Session = class {
7283
7456
  _title = "";
7284
7457
  _isFullscreen;
7285
7458
  pendingWrites = 0;
7459
+ pendingWriteBytes = 0;
7460
+ ptyPaused = false;
7461
+ leaderPid;
7462
+ leaderStartTime;
7463
+ leaderTty;
7464
+ observedDescendants = /* @__PURE__ */ new Map();
7465
+ activeDescendantScan = null;
7466
+ descendantScanTimer = null;
7467
+ descendantThrottleTimer = null;
7468
+ lastDescendantScanAt = 0;
7469
+ identityRetryTimers = [];
7470
+ postExitTreePromise;
7286
7471
  killPromise;
7287
7472
  // Listeners notified on any PTY data or exit
7288
7473
  changeListeners = [];
@@ -7319,24 +7504,168 @@ var Session = class {
7319
7504
  this.terminal.dispose();
7320
7505
  throw error;
7321
7506
  }
7507
+ this.leaderPid = this.ptyProcess.pid;
7508
+ const identity = readLeaderIdentitySync(this.leaderPid);
7509
+ this.leaderStartTime = identity.startTime;
7510
+ this.leaderTty = identity.tty;
7511
+ this.startLiveTrackers();
7322
7512
  this.terminal.onData((data) => {
7323
7513
  if (this._status === "running") this.ptyProcess.write(data);
7324
7514
  });
7515
+ const MAX_PENDING_WRITE_BYTES = 2 * 1024 * 1024;
7516
+ const RESUME_WRITE_BYTES = 512 * 1024;
7325
7517
  this.ptyProcess.onData((data) => {
7518
+ const bytes = Buffer.byteLength(data, "utf8");
7326
7519
  this.pendingWrites++;
7520
+ this.pendingWriteBytes += bytes;
7521
+ if (!this.ptyPaused && this.pendingWriteBytes >= MAX_PENDING_WRITE_BYTES) {
7522
+ this.ptyPaused = true;
7523
+ try {
7524
+ this.ptyProcess.pause?.();
7525
+ } catch {
7526
+ }
7527
+ }
7528
+ this.scheduleDescendantScan();
7327
7529
  this.notifyListeners();
7328
7530
  this.terminal.write(data, () => {
7329
- this.pendingWrites--;
7531
+ this.pendingWrites = Math.max(0, this.pendingWrites - 1);
7532
+ this.pendingWriteBytes = Math.max(0, this.pendingWriteBytes - bytes);
7533
+ if (this.ptyPaused && this.pendingWriteBytes <= RESUME_WRITE_BYTES) {
7534
+ this.ptyPaused = false;
7535
+ try {
7536
+ if (this._status === "running") this.ptyProcess.resume?.();
7537
+ } catch {
7538
+ }
7539
+ }
7330
7540
  this.notifyListeners();
7331
7541
  });
7332
7542
  });
7333
7543
  this.ptyProcess.onExit(({ exitCode }) => {
7334
7544
  this._status = "exited";
7335
7545
  this._exitCode = exitCode ?? null;
7546
+ this.stopLiveTrackers();
7547
+ const exitNow = Date.now();
7548
+ const inFlightScan = this.activeDescendantScan;
7549
+ this.postExitTreePromise = (async () => {
7550
+ if (inFlightScan) {
7551
+ try {
7552
+ await inFlightScan;
7553
+ } catch {
7554
+ }
7555
+ }
7556
+ return listOwnedTree(this.leaderPid, this.leaderStartTime, {
7557
+ allowExitedLeader: true,
7558
+ expectedTty: this.leaderTty,
7559
+ sessionStartMs: this.startTime,
7560
+ captureWindowEndMs: exitNow + 1e3,
7561
+ seededOwned: [...this.observedDescendants.values()]
7562
+ });
7563
+ })().catch(() => []);
7336
7564
  if (this.pendingWrites === 0) this.notifyListeners();
7337
7565
  options.onExit?.();
7338
7566
  });
7339
7567
  }
7568
+ startLiveTrackers() {
7569
+ if (process.platform === "win32") return;
7570
+ for (const delayMs of [35, 110, 200]) {
7571
+ const timer = setTimeout(() => {
7572
+ void this.refreshLeaderIdentityAsync().finally(() => {
7573
+ this.scheduleDescendantScan();
7574
+ });
7575
+ }, delayMs);
7576
+ timer.unref?.();
7577
+ this.identityRetryTimers.push(timer);
7578
+ }
7579
+ this.scheduleDescendantScan();
7580
+ this.descendantScanTimer = setInterval(() => {
7581
+ this.scheduleDescendantScan();
7582
+ }, 250);
7583
+ this.descendantScanTimer.unref?.();
7584
+ }
7585
+ stopLiveTrackers() {
7586
+ if (this.identityRetryTimers) {
7587
+ for (const timer of this.identityRetryTimers) clearTimeout(timer);
7588
+ this.identityRetryTimers = [];
7589
+ }
7590
+ if (this.descendantScanTimer) {
7591
+ clearInterval(this.descendantScanTimer);
7592
+ this.descendantScanTimer = null;
7593
+ }
7594
+ if (this.descendantThrottleTimer) {
7595
+ clearTimeout(this.descendantThrottleTimer);
7596
+ this.descendantThrottleTimer = null;
7597
+ }
7598
+ }
7599
+ async refreshLeaderIdentityAsync() {
7600
+ if (this._status !== "running" || this.leaderStartTime && this.leaderTty) return;
7601
+ const identity = await readLeaderIdentity(this.leaderPid);
7602
+ if (this._status !== "running") return;
7603
+ let recovered = false;
7604
+ if (!this.leaderStartTime && identity.startTime) {
7605
+ const birth = parseStartTimeMs(identity.startTime);
7606
+ if (birth !== null && birth >= this.startTime - 2e3 && birth <= this.startTime + 5e3) {
7607
+ this.leaderStartTime = identity.startTime;
7608
+ recovered = true;
7609
+ }
7610
+ }
7611
+ if (!this.leaderTty && identity.tty && this.leaderStartTime && identity.startTime === this.leaderStartTime) {
7612
+ this.leaderTty = identity.tty;
7613
+ recovered = true;
7614
+ }
7615
+ if (recovered) {
7616
+ this.scheduleDescendantScan();
7617
+ }
7618
+ }
7619
+ scheduleDescendantScan() {
7620
+ if (process.platform === "win32" || this._status !== "running") return;
7621
+ const MIN_INTERVAL_MS = 60;
7622
+ const now = Date.now();
7623
+ const elapsed = now - this.lastDescendantScanAt;
7624
+ if (this.activeDescendantScan || elapsed < MIN_INTERVAL_MS) {
7625
+ if (!this.descendantThrottleTimer) {
7626
+ const waitMs = Math.max(25, MIN_INTERVAL_MS - elapsed);
7627
+ this.descendantThrottleTimer = setTimeout(() => {
7628
+ this.descendantThrottleTimer = null;
7629
+ this.scheduleDescendantScan();
7630
+ }, waitMs);
7631
+ this.descendantThrottleTimer.unref?.();
7632
+ }
7633
+ return;
7634
+ }
7635
+ this.lastDescendantScanAt = now;
7636
+ const scan = (async () => {
7637
+ if (!this.leaderStartTime || !this.leaderTty) {
7638
+ await this.refreshLeaderIdentityAsync();
7639
+ }
7640
+ if (!this.leaderStartTime) return;
7641
+ const liveEntries = await listOwnedTree(this.leaderPid, this.leaderStartTime, {
7642
+ allowExitedLeader: false,
7643
+ expectedTty: this.leaderTty,
7644
+ seededOwned: [...this.observedDescendants.values()]
7645
+ });
7646
+ if (this._status === "running") {
7647
+ const liveByPid = /* @__PURE__ */ new Map();
7648
+ for (const entry of liveEntries) liveByPid.set(entry.pid, entry);
7649
+ for (const entry of liveEntries) {
7650
+ this.observedDescendants.set(entry.pid, entry);
7651
+ }
7652
+ if (this.observedDescendants.size > 128) {
7653
+ for (const pid of this.observedDescendants.keys()) {
7654
+ if (!liveByPid.has(pid)) this.observedDescendants.delete(pid);
7655
+ }
7656
+ }
7657
+ } else {
7658
+ for (const entry of liveEntries) {
7659
+ if (!this.observedDescendants.has(entry.pid)) {
7660
+ this.observedDescendants.set(entry.pid, entry);
7661
+ }
7662
+ }
7663
+ }
7664
+ })().catch(() => void 0).finally(() => {
7665
+ if (this.activeDescendantScan === scan) this.activeDescendantScan = null;
7666
+ });
7667
+ this.activeDescendantScan = scan;
7668
+ }
7340
7669
  get status() {
7341
7670
  return this._status;
7342
7671
  }
@@ -7419,6 +7748,18 @@ Supported keys: ${supported}`
7419
7748
  is_fullscreen: this._isFullscreen
7420
7749
  };
7421
7750
  }
7751
+ /** Read the live bottom rows of the active terminal buffer (`buf.baseY`),
7752
+ * independent of `buf.viewportY` scroll position, so `wait --text` still
7753
+ * observes new output even when the caller previously scrolled up. */
7754
+ readLiveTailLines() {
7755
+ const buf = this.terminal.buffer.active;
7756
+ const startY = buf.baseY;
7757
+ const out = [];
7758
+ for (let i = 0; i < this.terminal.rows; i++) {
7759
+ out.push((buf.getLine(startY + i)?.translateToString(true) ?? "").trimEnd());
7760
+ }
7761
+ return out;
7762
+ }
7422
7763
  screenIdentity() {
7423
7764
  const screen = this.readScreen({ color: true });
7424
7765
  return JSON.stringify({ ...screen, cols: this.cols, rows: this.rows, status: this.status, exit_code: this.exitCode });
@@ -7431,20 +7772,29 @@ Supported keys: ${supported}`
7431
7772
  let satisfied = false;
7432
7773
  let timedOut = false;
7433
7774
  const controller = new AbortController();
7434
- const matches = async (screen) => text === void 0 || (await matchLines([screen], text, options?.regex, controller.signal))[0] !== null;
7775
+ const matches = async (screenText) => text === void 0 || (await matchLines([screenText], text, options?.regex, controller.signal))[0] !== null;
7776
+ const readWaitTargetText = () => {
7777
+ const liveTail = this.readLiveTailLines();
7778
+ const buf = this.terminal.buffer.active;
7779
+ if (buf.viewportY === buf.baseY) return liveTail.join("\n");
7780
+ return `${liveTail.join("\n")}
7781
+ ${this.readScreen().lines.join("\n")}`;
7782
+ };
7435
7783
  if (this._status === "exited" && this.pendingWrites === 0) {
7436
7784
  const snapshot = this.snapshot(options);
7437
- return { ...snapshot, wait_satisfied: await matches(this.readScreen().lines.join("\n")), timed_out: false };
7785
+ return { ...snapshot, wait_satisfied: await matches(readWaitTargetText()), timed_out: false };
7438
7786
  }
7439
7787
  await new Promise((resolve, reject) => {
7440
7788
  let resolved = false;
7441
7789
  let idleTimer2 = null;
7790
+ let streamingCheckTimer = null;
7442
7791
  let checking = false;
7443
7792
  let recheck = false;
7444
7793
  const done = (error) => {
7445
7794
  if (!resolved) {
7446
7795
  resolved = true;
7447
7796
  if (idleTimer2) clearTimeout(idleTimer2);
7797
+ if (streamingCheckTimer) clearTimeout(streamingCheckTimer);
7448
7798
  clearTimeout(deadlineTimer);
7449
7799
  const index = this.changeListeners.indexOf(check);
7450
7800
  if (index >= 0) this.changeListeners.splice(index, 1);
@@ -7459,28 +7809,23 @@ Supported keys: ${supported}`
7459
7809
  done();
7460
7810
  }, timeoutMs);
7461
7811
  const aborted = () => done(new Error("Wait cancelled because its client disconnected."));
7462
- const check = () => {
7812
+ const runCheck = () => {
7463
7813
  if (resolved) return;
7464
- if (this.pendingWrites > 0) {
7465
- if (idleTimer2) clearTimeout(idleTimer2);
7466
- return;
7467
- }
7468
7814
  if (checking) {
7469
7815
  recheck = true;
7470
7816
  return;
7471
7817
  }
7472
7818
  checking = true;
7473
7819
  void (async () => {
7474
- const screen = this.readScreen();
7475
7820
  if (text !== void 0) {
7476
- const matched = await matches(screen.lines.join("\n"));
7821
+ const matched = await matches(readWaitTargetText());
7477
7822
  if (resolved) return;
7478
7823
  if (matched && (!options?.exit || this._status === "exited")) {
7479
7824
  satisfied = true;
7480
7825
  done();
7481
7826
  return;
7482
7827
  }
7483
- } else if (!options?.exit) {
7828
+ } else if (!options?.exit && this.pendingWrites === 0) {
7484
7829
  if (idleTimer2) clearTimeout(idleTimer2);
7485
7830
  idleTimer2 = setTimeout(() => {
7486
7831
  satisfied = true;
@@ -7499,6 +7844,24 @@ Supported keys: ${supported}`
7499
7844
  }
7500
7845
  });
7501
7846
  };
7847
+ const check = () => {
7848
+ if (resolved) return;
7849
+ if (this.pendingWrites > 0) {
7850
+ if (idleTimer2) clearTimeout(idleTimer2);
7851
+ if (text !== void 0 && !streamingCheckTimer) {
7852
+ streamingCheckTimer = setTimeout(() => {
7853
+ streamingCheckTimer = null;
7854
+ runCheck();
7855
+ }, 50);
7856
+ }
7857
+ return;
7858
+ }
7859
+ if (streamingCheckTimer) {
7860
+ clearTimeout(streamingCheckTimer);
7861
+ streamingCheckTimer = null;
7862
+ }
7863
+ runCheck();
7864
+ };
7502
7865
  this.changeListeners.push(check);
7503
7866
  options?.signal?.addEventListener("abort", aborted, { once: true });
7504
7867
  if (options?.signal?.aborted) {
@@ -7519,8 +7882,23 @@ Supported keys: ${supported}`
7519
7882
  return promise;
7520
7883
  }
7521
7884
  async killProcess() {
7885
+ this.stopLiveTrackers();
7522
7886
  if (this._status === "running") {
7523
- const descendants = await listDescendants(this.ptyProcess.pid);
7887
+ if (this.activeDescendantScan) {
7888
+ try {
7889
+ await this.activeDescendantScan;
7890
+ } catch {
7891
+ }
7892
+ }
7893
+ if (!this.leaderStartTime || !this.leaderTty) {
7894
+ await this.refreshLeaderIdentityAsync();
7895
+ }
7896
+ const observed = this.observedDescendants ? [...this.observedDescendants.values()] : [];
7897
+ const ownedTree = await listOwnedTree(this.leaderPid, this.leaderStartTime, {
7898
+ allowExitedLeader: false,
7899
+ expectedTty: this.leaderTty,
7900
+ seededOwned: observed
7901
+ });
7524
7902
  this.ptyProcess.kill();
7525
7903
  let deadline = Date.now() + 1e3;
7526
7904
  while (this._status === "running" && Date.now() < deadline) {
@@ -7539,12 +7917,39 @@ Supported keys: ${supported}`
7539
7917
  if (this._status === "running") {
7540
7918
  throw new Error(`Session ${this.id} did not exit after kill.`);
7541
7919
  }
7542
- if (process.platform !== "win32" && descendants.length > 0) {
7543
- await sweepDescendants(descendants);
7920
+ const postExit2 = this.postExitTreePromise ? await this.postExitTreePromise : [];
7921
+ const merged = /* @__PURE__ */ new Map();
7922
+ const observedAfter = this.observedDescendants ? [...this.observedDescendants.values()] : [];
7923
+ for (const entry of [...ownedTree, ...observedAfter, ...postExit2]) {
7924
+ if (!merged.has(entry.pid)) merged.set(entry.pid, entry);
7925
+ }
7926
+ if (process.platform !== "win32" && merged.size > 0) {
7927
+ const expanded = await listOwnedTree(0, null, {
7928
+ seededOnly: true,
7929
+ seededOwned: [...merged.values()]
7930
+ });
7931
+ for (const entry of expanded) {
7932
+ if (!merged.has(entry.pid)) merged.set(entry.pid, entry);
7933
+ }
7934
+ await sweepOwnedTree([...merged.values()]);
7935
+ }
7936
+ return;
7937
+ }
7938
+ const postExit = this.postExitTreePromise ? await this.postExitTreePromise : [];
7939
+ if (process.platform !== "win32" && postExit.length > 0) {
7940
+ const expanded = await listOwnedTree(0, null, {
7941
+ seededOnly: true,
7942
+ seededOwned: postExit
7943
+ });
7944
+ const merged = /* @__PURE__ */ new Map();
7945
+ for (const entry of [...postExit, ...expanded]) {
7946
+ if (!merged.has(entry.pid)) merged.set(entry.pid, entry);
7544
7947
  }
7948
+ await sweepOwnedTree([...merged.values()]);
7545
7949
  }
7546
7950
  }
7547
7951
  dispose() {
7952
+ this.stopLiveTrackers();
7548
7953
  this.terminal.dispose();
7549
7954
  }
7550
7955
  resize(cols, rows) {
@@ -7748,8 +8153,8 @@ function readStartTime(pid) {
7748
8153
  if (!Number.isInteger(pid) || pid <= 0) return void 0;
7749
8154
  if (process.platform === "win32") {
7750
8155
  try {
7751
- const { execFileSync } = require("node:child_process");
7752
- return execFileSync(
8156
+ const { execFileSync: execFileSync2 } = require("node:child_process");
8157
+ return execFileSync2(
7753
8158
  "powershell",
7754
8159
  [
7755
8160
  "-NoProfile",
@@ -7764,8 +8169,8 @@ function readStartTime(pid) {
7764
8169
  }
7765
8170
  }
7766
8171
  try {
7767
- const { execFileSync } = require("node:child_process");
7768
- return execFileSync("ps", ["-p", String(pid), "-o", "lstart="], {
8172
+ const { execFileSync: execFileSync2 } = require("node:child_process");
8173
+ return execFileSync2("ps", ["-p", String(pid), "-o", "lstart="], {
7769
8174
  timeout: 5e3,
7770
8175
  env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC0" },
7771
8176
  encoding: "utf8"
@@ -7806,7 +8211,11 @@ function pruneExited() {
7806
8211
  for (const id of exitedAt.keys()) {
7807
8212
  if (busy.get(id) || !sessions.get(id)?.canDispose) continue;
7808
8213
  if (Date.now() - exitedAt.get(id) < 3e5 && exitedAt.size <= 16) continue;
7809
- sessions.get(id)?.dispose();
8214
+ const session = sessions.get(id);
8215
+ if (session) {
8216
+ void session.kill().catch(() => {
8217
+ }).finally(() => session.dispose());
8218
+ }
7810
8219
  sessions.delete(id);
7811
8220
  exitedAt.delete(id);
7812
8221
  sessionAnchors.delete(id);
@@ -7822,7 +8231,7 @@ function reapOrphanedSessions() {
7822
8231
  for (const [id, anchor] of sessionAnchors) {
7823
8232
  if (!anchor || busy.get(id)) continue;
7824
8233
  const session = sessions.get(id);
7825
- if (!session || session.status !== "running") continue;
8234
+ if (!session) continue;
7826
8235
  if (!isSupervisorGone(anchor)) continue;
7827
8236
  try {
7828
8237
  import_node_fs2.default.appendFileSync(LOG_PATH, `[reap] session ${id} creator pid ${anchor.pid} is gone; killing PTY tree
@@ -7830,7 +8239,7 @@ function reapOrphanedSessions() {
7830
8239
  } catch {
7831
8240
  }
7832
8241
  void session.kill().then(() => {
7833
- exitedAt.set(id, Date.now());
8242
+ if (!exitedAt.has(id)) exitedAt.set(id, Date.now());
7834
8243
  sessionAnchors.delete(id);
7835
8244
  pruneExited();
7836
8245
  updateIdleTimer();
@@ -7902,7 +8311,6 @@ async function handleRequest(req, signal) {
7902
8311
  ...req,
7903
8312
  onExit: () => {
7904
8313
  exitedAt.set(id2, Date.now());
7905
- sessionAnchors.delete(id2);
7906
8314
  pruneExited();
7907
8315
  updateIdleTimer();
7908
8316
  }