@cydm/pie 4.6.1 → 4.8.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.
@@ -1,19 +1,19 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
- import {
3
- readProcessCommandLine
4
- } from "../../../chunks/chunk-7RJXKN7N.js";
5
2
  import {
6
3
  liveSessionHolder
7
4
  } from "../../../chunks/chunk-CGSFBWOM.js";
8
5
  import "../../../chunks/chunk-CBDQJMUI.js";
6
+ import {
7
+ readProcessCommandLine
8
+ } from "../../../chunks/chunk-7RJXKN7N.js";
9
+ import "../../../chunks/chunk-ZPJ3BNQB.js";
9
10
  import {
10
11
  Type
11
12
  } from "../../../chunks/chunk-XXGYUYXI.js";
12
- import "../../../chunks/chunk-ZPJ3BNQB.js";
13
13
  import "../../../chunks/chunk-LZQXQOPJ.js";
14
14
 
15
15
  // builtin/extensions/pie-proc/index.ts
16
- import { spawn } from "node:child_process";
16
+ import { execFileSync, spawn } from "node:child_process";
17
17
  import { createRequire } from "node:module";
18
18
  import { fileURLToPath } from "node:url";
19
19
  import * as fs from "node:fs";
@@ -38,6 +38,7 @@ var DEFAULT_MAX_WORKERS = 50;
38
38
  var DEFAULT_CONFIG = { allowCwd: [], maxWorkers: DEFAULT_MAX_WORKERS, killGraceMs: 15e3, defaultTtlMs: 0 };
39
39
  var IM_FORWARD_ALLOWED_KEYS = /* @__PURE__ */ new Set(["enabled", "provider", "chatId", "openId", "allowUsers", "retryBackoffMs", "larkCliProfile"]);
40
40
  var ONESHOT_TASK_ENV = "PIE_PROC_ONESHOT_TASK";
41
+ var LAUNCH_TOKEN_ENV = "PIE_PROC_LAUNCH_TOKEN";
41
42
  function configDirRoot() {
42
43
  const env = process.env.PIE_CODING_AGENT_DIR;
43
44
  if (!env) return path.join(os.homedir(), ".pie");
@@ -46,11 +47,19 @@ function configDirRoot() {
46
47
  function expandTilde(p) {
47
48
  return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
48
49
  }
49
- function readConfig() {
50
+ function configCandidates() {
50
51
  const candidates = [path.join(configDirRoot(), "pie-proc.json")];
51
- if (configDirRoot() !== path.join(os.homedir(), ".pie")) {
52
+ const pinnedRoot = process.env.PIE_PROC_REGISTRY_ROOT;
53
+ if (pinnedRoot) {
54
+ const pinDerived = path.join(path.dirname(path.resolve(expandTilde(pinnedRoot))), "pie-proc.json");
55
+ if (!candidates.includes(pinDerived)) candidates.push(pinDerived);
56
+ } else if (configDirRoot() !== path.join(os.homedir(), ".pie")) {
52
57
  candidates.push(path.join(os.homedir(), ".pie", "pie-proc.json"));
53
58
  }
59
+ return candidates;
60
+ }
61
+ function readConfig() {
62
+ const candidates = configCandidates();
54
63
  for (const file of candidates) {
55
64
  try {
56
65
  const raw = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -67,6 +76,8 @@ function readConfig() {
67
76
  return { ...DEFAULT_CONFIG };
68
77
  }
69
78
  function pieProcDir() {
79
+ const pinned = process.env.PIE_PROC_REGISTRY_ROOT;
80
+ if (pinned) return path.resolve(expandTilde(pinned));
70
81
  return path.join(configDirRoot(), "pie-proc");
71
82
  }
72
83
  function registryFile() {
@@ -179,17 +190,157 @@ function casRegistry(mutate) {
179
190
  function updateRegistry(mutate) {
180
191
  return casRegistry(mutate);
181
192
  }
182
- function workerLiveness(record) {
183
- if (record.pid === 0) return "dead";
193
+ function processExists(pid) {
194
+ if (!Number.isSafeInteger(pid) || pid <= 1) return false;
184
195
  try {
185
- process.kill(record.pid, 0);
196
+ process.kill(pid, 0);
197
+ return true;
198
+ } catch (error) {
199
+ return error.code === "EPERM";
200
+ }
201
+ }
202
+ function probeProcessGroup(pgid) {
203
+ if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 1) return "dead";
204
+ try {
205
+ process.kill(-pgid, 0);
206
+ return "alive";
207
+ } catch (error) {
208
+ return error.code === "EPERM" ? "eperm" : "dead";
209
+ }
210
+ }
211
+ function isZombieProcess(pid) {
212
+ if (process.platform === "win32") return false;
213
+ try {
214
+ const out = execFileSync("ps", ["-p", String(pid), "-o", "stat="], {
215
+ encoding: "utf8",
216
+ timeout: 3e3,
217
+ stdio: ["ignore", "pipe", "pipe"],
218
+ env: { ...process.env, LC_ALL: "C", LANG: "C" }
219
+ }).trim();
220
+ if (!out) return false;
221
+ return out.startsWith("Z");
186
222
  } catch {
187
- return "dead";
223
+ return "unknown";
188
224
  }
225
+ }
226
+ function readProcessGroupMembers(pgid) {
227
+ if (process.platform === "win32" || !Number.isSafeInteger(pgid) || pgid <= 1) return [];
228
+ try {
229
+ const out = execFileSync("ps", ["-e", "-o", "pid=,pgid=,uid=,stat=,lstart="], {
230
+ encoding: "utf8",
231
+ timeout: 3e3,
232
+ stdio: ["ignore", "pipe", "pipe"],
233
+ env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC" }
234
+ });
235
+ const members = [];
236
+ for (const rawLine of out.split(/\r?\n/)) {
237
+ const line = rawLine.trim();
238
+ if (!line) continue;
239
+ const match = /^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/.exec(line);
240
+ if (!match) continue;
241
+ const pid = Number(match[1]);
242
+ const memberPgid = Number(match[2]);
243
+ const uid = Number(match[3]);
244
+ const stat = match[4];
245
+ if (memberPgid !== pgid) continue;
246
+ if (stat.startsWith("Z")) continue;
247
+ const normalized = match[5].replace(/\s+/g, " ").trim();
248
+ const parsedStart = Date.parse(`${normalized} UTC`);
249
+ members.push({
250
+ pid,
251
+ uid,
252
+ stat,
253
+ startedAtMs: Number.isFinite(parsedStart) ? parsedStart : void 0
254
+ });
255
+ }
256
+ return members;
257
+ } catch {
258
+ return void 0;
259
+ }
260
+ }
261
+ function hasBoundedToken(haystack, needle) {
262
+ let idx = haystack.indexOf(needle);
263
+ while (idx !== -1) {
264
+ const beforeOk = idx === 0 || /\s/.test(haystack[idx - 1]);
265
+ const afterIdx = idx + needle.length;
266
+ const afterOk = afterIdx === haystack.length || /\s/.test(haystack[afterIdx]);
267
+ if (beforeOk && afterOk) return true;
268
+ idx = haystack.indexOf(needle, idx + 1);
269
+ }
270
+ return false;
271
+ }
272
+ function verifyProcessEnvOwnership(pid, marker, pieDir) {
273
+ if (process.platform === "linux") {
274
+ let raw2;
275
+ try {
276
+ raw2 = fs.readFileSync(`/proc/${pid}/environ`, "utf8");
277
+ } catch {
278
+ return "unverified";
279
+ }
280
+ let sawOtherToken = false;
281
+ for (const entry of raw2.split("\0")) {
282
+ if (entry === `${LAUNCH_TOKEN_ENV}=${marker}`) return "matched";
283
+ if (pieDir && entry === `PIE_CODING_AGENT_DIR=${pieDir}`) return "matched";
284
+ if (entry.startsWith(`${LAUNCH_TOKEN_ENV}=`)) sawOtherToken = true;
285
+ }
286
+ return sawOtherToken ? "foreign" : "unverified";
287
+ }
288
+ let raw;
289
+ try {
290
+ raw = execFileSync("ps", ["eww", "-p", String(pid), "-o", "command="], {
291
+ encoding: "utf8",
292
+ timeout: 3e3,
293
+ stdio: ["ignore", "pipe", "pipe"],
294
+ env: { ...process.env, LC_ALL: "C", LANG: "C" }
295
+ });
296
+ } catch {
297
+ return "unverified";
298
+ }
299
+ if (!raw) return "unverified";
300
+ if (hasBoundedToken(raw, `${LAUNCH_TOKEN_ENV}=${marker}`)) return "matched";
301
+ if (pieDir && hasBoundedToken(raw, `PIE_CODING_AGENT_DIR=${pieDir}`)) return "matched";
302
+ if (raw.includes(`${LAUNCH_TOKEN_ENV}=`)) return "foreign";
303
+ return "unverified";
304
+ }
305
+ function workerLiveness(record, opts = {}) {
306
+ if (record.pid === 0 || !Number.isSafeInteger(record.pid) || record.pid <= 1) return "dead";
189
307
  const marker = record.launchToken ?? record.sessionId;
190
- const cmd = readProcessCommandLine(record.pid);
191
- if (cmd === void 0) return "unknown";
192
- return cmd.includes(marker) ? "alive" : "dead";
308
+ if (processExists(record.pid)) {
309
+ const cmd = readProcessCommandLine(record.pid);
310
+ if (cmd === void 0) return "unknown";
311
+ if (cmd.includes(marker)) return "alive";
312
+ const zombie = isZombieProcess(record.pid);
313
+ if (zombie === "unknown") return "unknown";
314
+ if (!zombie) return "dead";
315
+ }
316
+ if (process.platform !== "win32") {
317
+ const groupProbe = probeProcessGroup(record.pid);
318
+ if (groupProbe === "dead") return "dead";
319
+ if (groupProbe === "eperm") return "unknown";
320
+ const hasSpawnedAt = typeof record.spawnedAt === "number" && Number.isFinite(record.spawnedAt);
321
+ if (!hasSpawnedAt) return "unknown";
322
+ const bootAtMs = Date.now() - os.uptime() * 1e3;
323
+ if (record.spawnedAt < bootAtMs - 5e3) return "dead";
324
+ const members = readProcessGroupMembers(record.pid);
325
+ if (members === void 0) return "unknown";
326
+ if (members.length === 0) return "dead";
327
+ if (members.some((m) => m.pid === record.pid)) return "unknown";
328
+ const selfUid = typeof process.getuid === "function" ? process.getuid() : void 0;
329
+ if (selfUid !== void 0 && members.some((m) => m.uid !== selfUid)) return "unknown";
330
+ for (const member of members) {
331
+ if (member.startedAtMs === void 0) return "unknown";
332
+ if (member.startedAtMs < record.spawnedAt - 5e3) return "dead";
333
+ }
334
+ let envMatched = false;
335
+ for (const member of members) {
336
+ const ownership = verifyProcessEnvOwnership(member.pid, marker, record.pieDir);
337
+ if (ownership === "foreign") return "dead";
338
+ if (ownership === "matched") envMatched = true;
339
+ }
340
+ if (envMatched || opts.trustVerifiedGroup) return "orphaned_group";
341
+ return "unknown";
342
+ }
343
+ return "dead";
193
344
  }
194
345
  function canonicalDir(dir) {
195
346
  const resolved = path.resolve(expandTilde(dir));
@@ -207,13 +358,20 @@ function cwdAllowedOrThrow(cwd, allow) {
207
358
  } catch {
208
359
  }
209
360
  }
210
- const file = path.join(configDirRoot(), "pie-proc.json");
361
+ const file = configCandidates()[0];
211
362
  let exists = false;
212
363
  try {
213
364
  exists = fs.existsSync(file);
214
365
  } catch {
215
366
  }
216
- throw new Error(exists ? `cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots in ${file}; edit that file \u2014 it is re-read on every spawn, so no host restart is needed` : `cwd "${cwd}" is outside the pie-proc allowCwd roots: there is no config yet at ${file}. Create it with {"allowCwd": ["${cwd}"]} \u2014 it is read on every spawn, so no host restart is needed`);
367
+ const effective = configCandidates().find((c) => {
368
+ try {
369
+ return fs.existsSync(c);
370
+ } catch {
371
+ return false;
372
+ }
373
+ }) ?? file;
374
+ throw new Error(exists || effective !== file ? `cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots in ${effective}; edit that file \u2014 it is re-read on every spawn, so no host restart is needed` : `cwd "${cwd}" is outside the pie-proc allowCwd roots: there is no config yet at ${effective}. Create it with {"allowCwd": ["${cwd}"]} \u2014 it is read on every spawn, so no host restart is needed`);
217
375
  }
218
376
  function safeName(name) {
219
377
  return /^[a-z0-9][a-z0-9-_]{0,47}$/i.test(name);
@@ -340,6 +498,38 @@ function pieProc(ctx) {
340
498
  ctx.log(`pie-proc: reservation release for gen ${generation} failed (${error instanceof Error ? error.message : String(error)}); sweep will retry`);
341
499
  }
342
500
  };
501
+ const signalWorkerProcessGroup = (pid, signal, opts = {}) => {
502
+ if (!Number.isSafeInteger(pid) || pid <= 1) return;
503
+ if (process.platform === "win32") {
504
+ try {
505
+ execFileSync("taskkill.exe", ["/F", "/T", "/PID", String(pid)], {
506
+ windowsHide: true,
507
+ stdio: "ignore",
508
+ timeout: 5e3
509
+ });
510
+ return;
511
+ } catch {
512
+ }
513
+ if (!opts.groupOnly) {
514
+ try {
515
+ process.kill(pid, signal);
516
+ } catch {
517
+ }
518
+ }
519
+ return;
520
+ }
521
+ try {
522
+ process.kill(-pid, signal);
523
+ return;
524
+ } catch {
525
+ }
526
+ if (!opts.groupOnly) {
527
+ try {
528
+ process.kill(pid, signal);
529
+ } catch {
530
+ }
531
+ }
532
+ };
343
533
  const sweep = () => {
344
534
  try {
345
535
  if (abortedGenerations.size > 0) {
@@ -393,14 +583,31 @@ function pieProc(ctx) {
393
583
  changed = true;
394
584
  continue;
395
585
  }
586
+ if (liveness === "orphaned_group") {
587
+ if (w.orphanSignaledAt === void 0) {
588
+ signalWorkerProcessGroup(w.pid, "SIGTERM", { groupOnly: true });
589
+ ctx.log(`pie-proc: orphaned process group detected for dead worker ${w.name} (pgid ${w.pid}); sent SIGTERM`);
590
+ keep.push({ ...w, orphanSignaledAt: cutoff });
591
+ changed = true;
592
+ } else if (cutoff - w.orphanSignaledAt >= currentConfig().killGraceMs) {
593
+ signalWorkerProcessGroup(w.pid, "SIGKILL", { groupOnly: true });
594
+ ctx.log(`pie-proc: orphaned process group for ${w.name} (pgid ${w.pid}) survived grace window; escalated to SIGKILL`);
595
+ if (w.orphanEscalatedAt === void 0) {
596
+ keep.push({ ...w, orphanEscalatedAt: cutoff });
597
+ changed = true;
598
+ } else {
599
+ keep.push(w);
600
+ }
601
+ } else {
602
+ keep.push(w);
603
+ }
604
+ continue;
605
+ }
396
606
  const ttl = w.kind === "resident" ? w.ttlMs ?? currentConfig().defaultTtlMs : 0;
397
607
  if (ttl > 0 && liveness === "alive" && cutoff - Math.max(w.lastActiveAt, observeActivity(w)) > ttl) {
398
- try {
399
- process.kill(w.pid, "SIGTERM");
400
- } catch {
401
- }
608
+ signalWorkerProcessGroup(w.pid, "SIGTERM");
402
609
  ctx.log(`pie-proc: idle TTL signaled worker ${w.name} (idle > ${Math.round(ttl / 1e3)}s, identity verified)`);
403
- keep.push({ ...w, ttlMs: 0 });
610
+ keep.push({ ...w, ttlMs: 0, orphanSignaledAt: cutoff });
404
611
  changed = true;
405
612
  continue;
406
613
  }
@@ -570,11 +777,14 @@ function pieProc(ctx) {
570
777
  ...resumeSessionId ? ["--resume-required", "--worker-token", launchToken] : []
571
778
  ] : [...loaderArgs(), entry, "--session-id", sessionId];
572
779
  const inheritedIpcRoot = path.resolve(expandTilde(process.env.PIE_IPC_CONFIG_DIR ?? configDirRoot()));
780
+ const inheritedRegistryRoot = path.resolve(expandTilde(process.env.PIE_PROC_REGISTRY_ROOT ?? pieProcDir()));
573
781
  const { PIE_DEFAULT_PROVIDER: _p, PIE_DEFAULT_MODEL: _m, PIE_MANAGER_BOOTSTRAP: _b, PIE_PROC_CURATED_NAME: _c, ...inheritedEnv } = process.env;
574
782
  const childEnv = {
575
783
  ...inheritedEnv,
576
784
  PIE_CODING_AGENT_DIR: pieDir,
577
785
  PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
786
+ PIE_PROC_REGISTRY_ROOT: inheritedRegistryRoot,
787
+ [LAUNCH_TOKEN_ENV]: launchToken,
578
788
  PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
579
789
  };
580
790
  if (params.kind === "oneshot") {
@@ -635,9 +845,12 @@ function pieProc(ctx) {
635
845
  };
636
846
  });
637
847
  } catch (error) {
638
- try {
639
- child.kill("SIGKILL");
640
- } catch {
848
+ if (typeof child.pid === "number") signalWorkerProcessGroup(child.pid, "SIGKILL");
849
+ else {
850
+ try {
851
+ child.kill("SIGKILL");
852
+ } catch {
853
+ }
641
854
  }
642
855
  releaseReservation(generation);
643
856
  throw error instanceof Error ? error : new Error(String(error));
@@ -671,25 +884,35 @@ function pieProc(ctx) {
671
884
  if (liveness === "unknown") {
672
885
  throw new Error(`worker "${name}" (pid ${target.pid}): identity could not be verified (probe failed); refusing to signal an unverified pid. Retry shortly, or inspect the process manually before removing the registry entry.`);
673
886
  }
674
- try {
675
- process.kill(target.pid, opts.force ? "SIGKILL" : "SIGTERM");
676
- } catch {
677
- }
678
- if (!opts.force) {
887
+ const verifiedGroupOpts = { trustVerifiedGroup: true };
888
+ signalWorkerProcessGroup(target.pid, opts.force ? "SIGKILL" : "SIGTERM", {
889
+ groupOnly: liveness === "orphaned_group"
890
+ });
891
+ if (opts.force) {
892
+ const killDeadline = Date.now() + 1500;
893
+ while (Date.now() < killDeadline) {
894
+ await new Promise((r) => setTimeout(r, 100));
895
+ if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
896
+ }
897
+ } else {
679
898
  const deadline = Date.now() + currentConfig().killGraceMs;
680
899
  while (Date.now() < deadline) {
681
- await new Promise((r) => setTimeout(r, 300));
682
- if (workerLiveness(target) === "dead") break;
900
+ await new Promise((r) => setTimeout(r, 200));
901
+ if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
683
902
  }
684
- if (workerLiveness(target) === "alive") {
685
- try {
686
- process.kill(target.pid, "SIGKILL");
687
- } catch {
903
+ const afterGrace = workerLiveness(target, verifiedGroupOpts);
904
+ if (afterGrace === "alive" || afterGrace === "orphaned_group") {
905
+ signalWorkerProcessGroup(target.pid, "SIGKILL", {
906
+ groupOnly: afterGrace === "orphaned_group"
907
+ });
908
+ const killDeadline = Date.now() + 1500;
909
+ while (Date.now() < killDeadline) {
910
+ await new Promise((r) => setTimeout(r, 100));
911
+ if (workerLiveness(target, verifiedGroupOpts) === "dead") break;
688
912
  }
689
- await new Promise((r) => setTimeout(r, 500));
690
913
  }
691
914
  }
692
- const finalState = workerLiveness(target);
915
+ const finalState = workerLiveness(target, verifiedGroupOpts);
693
916
  if (finalState === "dead") {
694
917
  updateRegistry((snap) => ({ next: snap.workers.filter((w) => w.generation !== target.generation), result: void 0 }));
695
918
  ctx.log(`pie-proc: killed worker "${name}" (pid ${target.pid}, gen ${target.generation})`);
@@ -40,7 +40,16 @@ dimensions and screenshot pixels. Emulation changes may reload a page.
40
40
  When an action opens a JavaScript dialog, `DIALOG_PENDING` means it was
41
41
  interrupted after delivery. Do not replay the action or reopen the session.
42
42
  Use `dialog accept`/`dialog dismiss` in that same session, then read the fresh
43
- snapshot. Keep the named session on every command.
43
+ snapshot. If a second dialog opens immediately (e.g. page confirm + `beforeunload`),
44
+ `dialog` reports `nextDialogPending: true` — handle it again before snapshotting.
45
+ Keep the named session on every command.
46
+
47
+ ## Verification & Approval Rules
48
+
49
+ - **Never equate "action sent" with "saved/persisted"**: clicking Save only confirms the click was dispatched — it never guarantees async form state settled or the backend persisted the intended value. Before clicking Save, wait for loading indicators (`wait "Loading..." --absent`) and confirm the visible selected value (`wait "<value>" --visible`); after clicking Save, verify the submit request/response (`network --type fetch --preserved --full` / `network-get <id> --full`) and/or read back after reload.
50
+ - **Ignore hidden/closed dropdown DOM**: use `wait "<text>" --visible` when waiting for UI options or confirmations.
51
+ - **Virtualized lists requiring trusted wheel input**: `scroll --wheel` dispatches a synthetic DOM `WheelEvent` (`isTrusted=false`, because `chrome-devtools-mcp` exposes no native mouse-wheel tool). If a virtual list ignores untrusted wheel events, focus the container and use `press PageDown`/`ArrowDown` (real CDP keyboard input, `isTrusted=true`), or use `computer-use-axi` (native CDP `mouseWheel` / OS wheel, `isTrusted=true`).
52
+ - **Do not restart the bridge while waiting for Chrome's approval dialog**: in default `--autoConnect` mode, the CLI prints a waiting notice to stderr while Chrome asks the user to click Allow. Let it complete instead of running `stop`/retrying concurrently.
44
53
 
45
54
  Agent-ergonomic interface for controlling a real Chrome browser session (Chrome DevTools Protocol). Prefer this over other browser automation approaches. Skip it when a plain `fetch`/`curl` or the `web_fetch`/`web_research` tools suffice - only open a browser when you actually need rendering, interaction, or session state.
46
55