@cydm/pie 4.8.0 → 4.10.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 +906 -158
  4. package/dist/builtin/extensions/im-forward/README.md +4 -2
  5. package/dist/builtin/extensions/im-forward/index.js +6875 -3972
  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 +285 -61
  9. package/dist/builtin/extensions/pie-proc/README.md +7 -7
  10. package/dist/builtin/extensions/pie-proc/index.js +493 -107
  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 +26 -24
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
  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-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
  19. package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +367 -65
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
  23. package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-5QMS6RQC.js} +353 -287
  24. package/dist/chunks/chunk-6WKBQZWM.js +19 -0
  25. package/dist/chunks/{chunk-LAJXWOKS.js → chunk-7LICWWUE.js} +11 -9
  26. package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BQWHLYYZ.js} +4 -3
  27. package/dist/chunks/{chunk-4PR34UZF.js → chunk-BTUMBUDU.js} +159 -145
  28. package/dist/chunks/{chunk-NHV2CALB.js → chunk-FC5AN5QP.js} +409 -32
  29. package/dist/chunks/{chunk-3W3SXVPB.js → chunk-G2K4GY6N.js} +993 -371
  30. package/dist/chunks/{chunk-BLDI2GRF.js → chunk-HK3FHIAH.js} +1364 -446
  31. package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
  32. package/dist/chunks/{chunk-CGSFBWOM.js → chunk-KWK7KTSZ.js} +4 -3
  33. package/dist/chunks/chunk-OU33ROFD.js +717 -0
  34. package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-XMTRKMBG.js} +104 -22
  35. package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-3TEMOQM5.js} +1 -1
  36. package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
  37. package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-QKJ3YVDS.js} +2 -2
  38. package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-N2ZZQLTZ.js} +5 -5
  39. package/dist/chunks/{src-EGXFJ3WA.js → src-3PSR2AAX.js} +3 -3
  40. package/dist/chunks/{src-B44QWSGM.js → src-D5GN4Q5O.js} +2 -2
  41. package/dist/chunks/{src-CLE5ILN4.js → src-F5N6O2HR.js} +20 -4
  42. package/dist/chunks/{src-Q7LU27C2.js → src-TIDKYA5F.js} +31 -1
  43. package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-JAJHK44G.js} +2 -2
  44. package/dist/cli.js +4123 -2389
  45. package/models.schema.json +271 -0
  46. package/package.json +2 -2
  47. package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
  48. package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
  49. package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
@@ -70,6 +70,7 @@ function resolveTestOnlyBackend(env = process.env) {
70
70
  }
71
71
  var init_test_backend_guard = __esm({
72
72
  "vendor/computer-use-axi/src/test-backend-guard.ts"() {
73
+ "use strict";
73
74
  }
74
75
  });
75
76
 
@@ -90,6 +91,7 @@ function toOptionalString(value) {
90
91
  }
91
92
  var init_coerce = __esm({
92
93
  "vendor/computer-use-axi/src/platform/coerce.ts"() {
94
+ "use strict";
93
95
  }
94
96
  });
95
97
 
@@ -3813,6 +3815,7 @@ function resolvePieConfigDir(env, homeDir) {
3813
3815
  var HELPER_APP_NAME, SYSTEM_HELPER_APP_PATH;
3814
3816
  var init_helper_path = __esm({
3815
3817
  "vendor/computer-use-axi/src/platform/macos/helper-path.mjs"() {
3818
+ "use strict";
3816
3819
  HELPER_APP_NAME = "pie-computer-use.app";
3817
3820
  SYSTEM_HELPER_APP_PATH = path7.join("/Applications", HELPER_APP_NAME);
3818
3821
  }
@@ -3836,6 +3839,7 @@ function resolveExtensionRoot(moduleUrl) {
3836
3839
  }
3837
3840
  var init_package_root = __esm({
3838
3841
  "vendor/computer-use-axi/src/platform/package-root.ts"() {
3842
+ "use strict";
3839
3843
  }
3840
3844
  });
3841
3845
 
@@ -3926,6 +3930,7 @@ ${output}`.trim()));
3926
3930
  var COMMAND_TIMEOUT_MS2, HELPER_PROTOCOL_VERSION, HELPER_SETUP_TIMEOUT_MS, HELPER_APP_PATH, HELPER_APP_EXECUTABLE_PATH, DEFAULT_HELPER_SOCKET_PATH, HELPER_SOCKET_PATH, usingExternalHelperSocket, PACKAGE_ROOT, SETUP_HELPER_SCRIPT, HelperTransportError, HelperCommandError, MacosHelperClient, macosHelper;
3927
3931
  var init_helper = __esm({
3928
3932
  "vendor/computer-use-axi/src/platform/macos/helper.ts"() {
3933
+ "use strict";
3929
3934
  init_test_backend_guard();
3930
3935
  init_coerce();
3931
3936
  init_helper_path();
@@ -4165,6 +4170,7 @@ async function ensurePermissions(ctx, bridge, helperPath, signal) {
4165
4170
  }
4166
4171
  var init_permissions = __esm({
4167
4172
  "vendor/computer-use-axi/src/permissions.ts"() {
4173
+ "use strict";
4168
4174
  }
4169
4175
  });
4170
4176
 
@@ -4182,6 +4188,7 @@ function assertPlatformArchitecture(platform, diagnostics) {
4182
4188
  var PLATFORM_ARCHITECTURE_VERSION, REQUIRED_PLATFORM_INVARIANTS;
4183
4189
  var init_architecture = __esm({
4184
4190
  "vendor/computer-use-axi/src/platform/architecture.ts"() {
4191
+ "use strict";
4185
4192
  PLATFORM_ARCHITECTURE_VERSION = 1;
4186
4193
  REQUIRED_PLATFORM_INVARIANTS = [
4187
4194
  "state-scoped-observations",
@@ -4327,6 +4334,7 @@ Helper path: ${helperPath}`,
4327
4334
  var GRANT_INSTRUCTIONS, SIGNING_MIGRATION_WARNING, macosPermissionKinds, registeredForHelperPid, autoRestartAttempted;
4328
4335
  var init_permissions2 = __esm({
4329
4336
  "vendor/computer-use-axi/src/platform/macos/permissions.ts"() {
4337
+ "use strict";
4330
4338
  init_permissions();
4331
4339
  init_coerce();
4332
4340
  init_helper();
@@ -4422,14 +4430,14 @@ var DEFAULT_CONFIG = {
4422
4430
  cursor_overlay: true,
4423
4431
  managed_browser: "chrome"
4424
4432
  };
4425
- var REQUEST_ENV_KEYS = ["PIE_COMPUTER_USE_BROWSER_USE", "PIE_COMPUTER_USE_HEADLESS", "PIE_COMPUTER_USE_CURSOR_OVERLAY", "PIE_COMPUTER_USE_MANAGED_BROWSER", "PIE_COMPUTER_USE_HELIUM_EXECUTABLE", "PIE_COMPUTER_USE_CHROME_EXECUTABLE", "PIE_COMPUTER_USE_CDP_PORT", "PIE_COMPUTER_USE_DELIVERY_POLICY", "PIE_COMPUTER_USE_EVENT_DELIVERY"];
4433
+ var REQUEST_ENV_KEYS = ["PIE_COMPUTER_USE_BROWSER_USE", "PIE_COMPUTER_USE_HEADLESS", "PIE_COMPUTER_USE_BROWSER_HEADED", "PIE_COMPUTER_USE_CURSOR_OVERLAY", "PIE_COMPUTER_USE_MANAGED_BROWSER", "PIE_COMPUTER_USE_HELIUM_EXECUTABLE", "PIE_COMPUTER_USE_CHROME_EXECUTABLE", "PIE_COMPUTER_USE_CDP_PORT", "PIE_COMPUTER_USE_DELIVERY_POLICY", "PIE_COMPUTER_USE_EVENT_DELIVERY"];
4426
4434
  function captureComputerUseEnvironment(env = process.env) {
4427
4435
  const out = {};
4428
4436
  for (const key of REQUEST_ENV_KEYS) {
4429
4437
  const value = env[key]?.trim();
4430
4438
  if (!value) continue;
4431
4439
  if (Buffer.byteLength(value) > 4096 || value.includes("\0")) throw new Error(`Invalid ${key}`);
4432
- if (["PIE_COMPUTER_USE_BROWSER_USE", "PIE_COMPUTER_USE_HEADLESS", "PIE_COMPUTER_USE_CURSOR_OVERLAY"].includes(key)) {
4440
+ if (["PIE_COMPUTER_USE_BROWSER_USE", "PIE_COMPUTER_USE_HEADLESS", "PIE_COMPUTER_USE_BROWSER_HEADED", "PIE_COMPUTER_USE_CURSOR_OVERLAY"].includes(key)) {
4433
4441
  const parsed = parseBoolean(value);
4434
4442
  if (parsed === void 0) throw new Error(`Invalid ${key}`);
4435
4443
  out[key] = String(parsed);
@@ -5384,7 +5392,7 @@ function artifactsRoot(env = process.env) {
5384
5392
  init_test_backend_guard();
5385
5393
  import { execFileSync, spawn as spawn4 } from "node:child_process";
5386
5394
  import { randomUUID as randomUUID7 } from "node:crypto";
5387
- import { constants as fsConstants5, mkdirSync as mkdirSync6, mkdtempSync, readFileSync as readFileSync4, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
5395
+ import { constants as fsConstants5, mkdirSync as mkdirSync6, mkdtempSync, readFileSync as readFileSync4, renameSync as renameSync3, rmSync, writeFileSync as writeFileSync3 } from "node:fs";
5388
5396
  import { access as access4 } from "node:fs/promises";
5389
5397
  import net2 from "node:net";
5390
5398
  import os4 from "node:os";
@@ -6140,14 +6148,48 @@ var CdpTab = class _CdpTab {
6140
6148
  this.loadFired = void 0;
6141
6149
  }
6142
6150
  }
6143
- async clickBackendNode(backendNodeId) {
6151
+ async resolveVisibleBackendPoint(backendNodeId) {
6152
+ const resolved = await this.send("DOM.resolveNode", { backendNodeId });
6153
+ const objectId = resolved?.object?.objectId;
6154
+ if (typeof objectId !== "string") return void 0;
6155
+ const rectRes = await this.send("Runtime.callFunctionOn", {
6156
+ objectId,
6157
+ functionDeclaration: "function(){ this.scrollIntoView({block:'center', inline:'center'}); const r = this.getBoundingClientRect(); const vw = window.innerWidth || 0; const vh = window.innerHeight || 0; const left = Math.max(0, r.left); const top = Math.max(0, r.top); const right = Math.min(vw, r.right); const bottom = Math.min(vh, r.bottom); const w = right - left; const h = bottom - top; return w > 0 && h > 0 ? { x: left + w / 2, y: top + h / 2 } : null; }",
6158
+ returnByValue: true
6159
+ });
6160
+ const pt = !rectRes?.exceptionDetails ? rectRes?.result?.value : void 0;
6161
+ if (pt && typeof pt.x === "number" && typeof pt.y === "number" && Number.isFinite(pt.x) && Number.isFinite(pt.y)) {
6162
+ return { x: pt.x, y: pt.y };
6163
+ }
6164
+ return void 0;
6165
+ }
6166
+ async clickBackendNode(backendNodeId, clickCount2 = 1) {
6167
+ const count = Math.max(1, Math.min(3, Math.trunc(clickCount2)));
6168
+ if (count > 1) {
6169
+ const pt = await this.resolveVisibleBackendPoint(backendNodeId);
6170
+ if (!pt) throw new Error(`CDP could not resolve visible viewport point for backend node ${backendNodeId} multi-click.`);
6171
+ await this.mouseAt(pt.x, pt.y, "mouseMoved", "left", 0);
6172
+ for (let c = 1; c <= count; c += 1) {
6173
+ await this.mouseAt(pt.x, pt.y, "mousePressed", "left", c);
6174
+ await this.mouseAt(pt.x, pt.y, "mouseReleased", "left", c);
6175
+ }
6176
+ return;
6177
+ }
6144
6178
  await this.withBackendNode(backendNodeId, "function(){ this.scrollIntoView({block:'center', inline:'center'}); this.click(); }");
6145
6179
  }
6146
6180
  async focusBackendNode(backendNodeId) {
6147
6181
  await this.withBackendNode(backendNodeId, "function(){ this.scrollIntoView({block:'center', inline:'center'}); this.focus(); }");
6148
6182
  }
6149
6183
  async typeIntoBackendNode(backendNodeId, text, replace) {
6150
- await this.withBackendNode(backendNodeId, "function(text, replace){ this.scrollIntoView({block:'center', inline:'center'}); this.focus(); if (replace) { if ('value' in this) this.value = ''; else this.textContent = ''; } if ('value' in this) this.value += text; else this.textContent = (this.textContent || '') + text; this.dispatchEvent(new InputEvent('input', {bubbles:true, inputType:'insertText', data:text})); this.dispatchEvent(new Event('change', {bubbles:true})); }", [text, replace]);
6184
+ if (!replace) {
6185
+ await this.withBackendNode(
6186
+ backendNodeId,
6187
+ "function(){ if (this.isConnected === false) throw new Error('Target element is detached.'); const ariaDisabled = typeof this.getAttribute === 'function' && this.getAttribute('aria-disabled') === 'true'; if (this.disabled || ariaDisabled || this.readOnly) throw new Error('Target element is disabled or read-only.'); const editable = ('value' in this && !this.disabled && !this.readOnly) || this.isContentEditable === true; if (!editable) throw new Error('Target element is not editable.'); if (typeof this.scrollIntoView === 'function') this.scrollIntoView({block:'center', inline:'center'}); if (typeof this.focus === 'function') this.focus(); const root = typeof this.getRootNode === 'function' ? this.getRootNode() : this.ownerDocument; const active = root && 'activeElement' in root ? root.activeElement : (this.ownerDocument ? this.ownerDocument.activeElement : null); const focused = active === this || (this.isContentEditable === true && active != null && typeof this.contains === 'function' && this.contains(active)); if (!focused) throw new Error('Target element did not accept focus; refusing to insert text into another element.'); if (this.isContentEditable === true) { const sel = this.ownerDocument && this.ownerDocument.defaultView && typeof this.ownerDocument.defaultView.getSelection === 'function' ? this.ownerDocument.defaultView.getSelection() : null; if (sel && sel.rangeCount > 0 && sel.anchorNode && typeof this.contains === 'function' && !this.contains(sel.anchorNode)) { if (this.ownerDocument && typeof this.ownerDocument.createRange === 'function') { const range = this.ownerDocument.createRange(); range.selectNodeContents(this); range.collapse(false); sel.removeAllRanges(); sel.addRange(range); } } if (sel && sel.rangeCount > 0 && sel.anchorNode && typeof this.contains === 'function' && !this.contains(sel.anchorNode)) { throw new Error('Contenteditable target does not own selection; refusing to insert text.'); } } }"
6188
+ );
6189
+ await this.send("Input.insertText", { text });
6190
+ return;
6191
+ }
6192
+ await this.withBackendNode(backendNodeId, "function(text){ this.scrollIntoView({block:'center', inline:'center'}); this.focus(); if ('value' in this) { const proto = Object.getPrototypeOf(this); const desc = proto && Object.getOwnPropertyDescriptor(proto, 'value'); if (desc && typeof desc.set === 'function') desc.set.call(this, text); else this.value = text; } else { this.textContent = text; } this.dispatchEvent(new InputEvent('input', {bubbles:true, inputType:'insertReplacementText', data:text})); this.dispatchEvent(new Event('change', {bubbles:true})); }", [text]);
6151
6193
  }
6152
6194
  async wheelAt(x, y, deltaX, deltaY) {
6153
6195
  await this.send("Input.dispatchMouseEvent", {
@@ -6206,10 +6248,29 @@ var CdpTab = class _CdpTab {
6206
6248
  }
6207
6249
  async dragPath(path15) {
6208
6250
  if (path15.length < 2) throw new Error("CDP drag requires at least two points.");
6209
- await this.mouseAt(path15[0].x, path15[0].y, "mousePressed");
6210
- for (const point of path15.slice(1)) await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: point.x, y: point.y, button: "left", buttons: 1 });
6211
- const end = path15[path15.length - 1];
6212
- await this.mouseAt(end.x, end.y, "mouseReleased");
6251
+ let pressed = false;
6252
+ let lastPoint = path15[0];
6253
+ let primaryError;
6254
+ try {
6255
+ await this.mouseAt(path15[0].x, path15[0].y, "mousePressed");
6256
+ pressed = true;
6257
+ for (const point of path15.slice(1)) {
6258
+ await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: point.x, y: point.y, button: "left", buttons: 1 });
6259
+ lastPoint = point;
6260
+ }
6261
+ } catch (error) {
6262
+ primaryError = error;
6263
+ throw error;
6264
+ } finally {
6265
+ if (pressed) {
6266
+ if (primaryError !== void 0) {
6267
+ await this.mouseAt(lastPoint.x, lastPoint.y, "mouseReleased").catch(() => {
6268
+ });
6269
+ } else {
6270
+ await this.mouseAt(lastPoint.x, lastPoint.y, "mouseReleased");
6271
+ }
6272
+ }
6273
+ }
6213
6274
  }
6214
6275
  async withBackendNode(backendNodeId, functionDeclaration, args = []) {
6215
6276
  const resolved = await this.send("DOM.resolveNode", { backendNodeId });
@@ -6388,9 +6449,9 @@ async function listCdpPageContexts(port = getComputerUseEnvironmentValue("PIE_CO
6388
6449
  url: page.url ?? ""
6389
6450
  }));
6390
6451
  }
6391
- async function cdpClickForContext(contextId, backendNodeId) {
6452
+ async function cdpClickForContext(contextId, backendNodeId, clickCount2 = 1) {
6392
6453
  return await withCdpContextTab(contextId, async (tab) => {
6393
- await tab.clickBackendNode(backendNodeId);
6454
+ await tab.clickBackendNode(backendNodeId, clickCount2);
6394
6455
  return true;
6395
6456
  }) === true;
6396
6457
  }
@@ -8254,8 +8315,33 @@ function escapeEre(value) {
8254
8315
  return value.replace(/[\\^$.|?*+()[{]/g, (ch) => `\\${ch}`);
8255
8316
  }
8256
8317
  async function scanProfileHolders(profile) {
8257
- if (process.platform === "win32") return { kind: "ok", pids: [] };
8258
- const pattern = `user-data-dir=${escapeEre(profile)}([^a-zA-Z0-9_-]|$)`;
8318
+ if (process.platform === "win32") {
8319
+ return await new Promise((resolve2) => {
8320
+ execFile(
8321
+ "powershell.exe",
8322
+ [
8323
+ "-NoProfile",
8324
+ "-NonInteractive",
8325
+ "-Command",
8326
+ "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -and $_.CommandLine.Contains($env:PIE_TARGET_PROFILE) } | Select-Object -ExpandProperty ProcessId"
8327
+ ],
8328
+ {
8329
+ timeout: 3e3,
8330
+ windowsHide: true,
8331
+ env: { ...process.env, PIE_TARGET_PROFILE: profile }
8332
+ },
8333
+ (error, stdout) => {
8334
+ if (error) {
8335
+ resolve2({ kind: "unknown" });
8336
+ return;
8337
+ }
8338
+ const pids = String(stdout ?? "").split(/\s+/).map(Number).filter((n) => Number.isInteger(n) && n > 0 && n !== process.pid);
8339
+ resolve2(pids.length > 0 ? { kind: "ok", pids } : { kind: "none" });
8340
+ }
8341
+ );
8342
+ });
8343
+ }
8344
+ const pattern = `user-data-dir=${escapeEre(profile)}([[:space:]"']|$)`;
8259
8345
  return await new Promise((resolve2) => {
8260
8346
  execFile("pgrep", ["-f", pattern], { timeout: 1500 }, (error, stdout) => {
8261
8347
  if (!error) {
@@ -8272,57 +8358,225 @@ async function scanProfileHolders(profile) {
8272
8358
  });
8273
8359
  });
8274
8360
  }
8275
- async function verifyProfileHolder(pid, profile) {
8361
+ function pidStillAlive(pid) {
8362
+ try {
8363
+ process.kill(pid, 0);
8364
+ return true;
8365
+ } catch (error) {
8366
+ return error.code === "EPERM";
8367
+ }
8368
+ }
8369
+ async function verifyProfileHolderDetailed(pid, profile) {
8370
+ if (process.platform === "win32") {
8371
+ return await new Promise((resolve2) => {
8372
+ execFile(
8373
+ "powershell.exe",
8374
+ [
8375
+ "-NoProfile",
8376
+ "-NonInteractive",
8377
+ "-Command",
8378
+ `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object -ExpandProperty CommandLine`
8379
+ ],
8380
+ { timeout: 2500, windowsHide: true },
8381
+ (error, stdout) => {
8382
+ if (error) {
8383
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8384
+ return;
8385
+ }
8386
+ const command = String(stdout ?? "").trim();
8387
+ if (!command) {
8388
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8389
+ return;
8390
+ }
8391
+ resolve2(commandIncludesExactUserDataDir(command, profile) ? "match" : "no_match");
8392
+ }
8393
+ );
8394
+ });
8395
+ }
8276
8396
  if (process.platform === "darwin") {
8277
8397
  return await new Promise((resolve2) => {
8278
- execFile("ps", ["-o", "command=", "-p", String(pid)], { timeout: 1500 }, (error, stdout) => {
8398
+ execFile("ps", ["-ww", "-o", "command=", "-p", String(pid)], { timeout: 1500 }, (error, stdout) => {
8279
8399
  if (error) {
8280
- resolve2(false);
8400
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8281
8401
  return;
8282
8402
  }
8283
8403
  const command = String(stdout ?? "").trim();
8284
8404
  if (!command) {
8285
- resolve2(false);
8405
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8286
8406
  return;
8287
8407
  }
8288
- resolve2(commandIncludesExactUserDataDir(command, profile));
8408
+ resolve2(evaluateMacOsPsCommand(command, profile));
8289
8409
  });
8290
8410
  });
8291
8411
  }
8292
8412
  return await new Promise((resolve2) => {
8293
8413
  execFile("cat", [`/proc/${pid}/cmdline`], { timeout: 1500 }, (error, stdout) => {
8294
8414
  if (error) {
8295
- resolve2(false);
8415
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8296
8416
  return;
8297
8417
  }
8298
8418
  const argv = String(stdout ?? "").split("\0").filter(Boolean);
8299
- resolve2(argv.some((arg, i) => arg === `--user-data-dir=${profile}` || arg === "--user-data-dir" && argv[i + 1] === profile));
8419
+ if (argv.length === 0) {
8420
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8421
+ return;
8422
+ }
8423
+ resolve2(argv.some((arg, i) => arg === `--user-data-dir=${profile}` || arg === "--user-data-dir" && argv[i + 1] === profile) ? "match" : "no_match");
8300
8424
  });
8301
8425
  });
8302
8426
  }
8427
+ async function verifyProfileHolder(pid, profile) {
8428
+ return await verifyProfileHolderDetailed(pid, profile) === "match";
8429
+ }
8430
+ function tokenizeCommandLine(command) {
8431
+ const tokens = [];
8432
+ let current = "";
8433
+ let inToken = false;
8434
+ let quote = null;
8435
+ for (let i = 0; i < command.length; i++) {
8436
+ const ch = command[i];
8437
+ if (quote !== null) {
8438
+ if (ch === quote) {
8439
+ quote = null;
8440
+ } else {
8441
+ current += ch;
8442
+ }
8443
+ continue;
8444
+ }
8445
+ if (ch === '"' || ch === "'") {
8446
+ quote = ch;
8447
+ inToken = true;
8448
+ continue;
8449
+ }
8450
+ if (/\s|\0/.test(ch)) {
8451
+ if (inToken) {
8452
+ tokens.push(current);
8453
+ current = "";
8454
+ inToken = false;
8455
+ }
8456
+ continue;
8457
+ }
8458
+ current += ch;
8459
+ inToken = true;
8460
+ }
8461
+ if (quote !== null) return void 0;
8462
+ if (inToken) tokens.push(current);
8463
+ return tokens;
8464
+ }
8303
8465
  function commandIncludesExactUserDataDir(command, profile) {
8304
- const marker = "--user-data-dir=";
8305
- let index = command.indexOf(marker);
8306
- while (index !== -1) {
8307
- const start = index + marker.length;
8308
- if (command.startsWith(profile, start)) {
8309
- const after = start + profile.length;
8310
- if (after === command.length || /[^a-zA-Z0-9_-]/.test(command[after])) return true;
8466
+ const tokens = tokenizeCommandLine(command);
8467
+ if (!tokens) return false;
8468
+ const exactFlag = `--user-data-dir=${profile}`;
8469
+ return tokens.some((arg, i) => arg === exactFlag || arg === "--user-data-dir" && tokens[i + 1] === profile);
8470
+ }
8471
+ function evaluateMacOsPsCommand(command, profile) {
8472
+ const hasAmbiguousProfileChars = /[\s'"]/.test(profile);
8473
+ if (!hasAmbiguousProfileChars && commandIncludesExactUserDataDir(command, profile)) {
8474
+ return "match";
8475
+ }
8476
+ if (hasAmbiguousProfileChars && command.includes(profile)) {
8477
+ return "unknown";
8478
+ }
8479
+ if (tokenizeCommandLine(command) === void 0) {
8480
+ return "unknown";
8481
+ }
8482
+ return "no_match";
8483
+ }
8484
+ async function readProcessStartSignature(pid) {
8485
+ if (process.platform === "win32") {
8486
+ return await new Promise((resolve2) => {
8487
+ execFile(
8488
+ "powershell.exe",
8489
+ [
8490
+ "-NoProfile",
8491
+ "-NonInteractive",
8492
+ "-Command",
8493
+ `Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" | Select-Object -ExpandProperty CreationDate`
8494
+ ],
8495
+ { timeout: 2500, windowsHide: true },
8496
+ (error, stdout) => {
8497
+ if (error) {
8498
+ resolve2(null);
8499
+ return;
8500
+ }
8501
+ const sig = String(stdout ?? "").trim();
8502
+ resolve2(sig || null);
8503
+ }
8504
+ );
8505
+ });
8506
+ }
8507
+ return await new Promise((resolve2) => {
8508
+ execFile("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 1500 }, (error, stdout) => {
8509
+ if (error) {
8510
+ resolve2(null);
8511
+ return;
8512
+ }
8513
+ const sig = String(stdout ?? "").trim();
8514
+ resolve2(sig || null);
8515
+ });
8516
+ });
8517
+ }
8518
+ async function terminateVerifiedPid(pid, guard) {
8519
+ const verifyHolder = guard?.verifyHolder ?? verifyProfileHolderDetailed;
8520
+ const readStartSig = guard?.readStartSignature ?? readProcessStartSignature;
8521
+ const sendKill = guard?.kill ?? ((targetPid, signal) => {
8522
+ process.kill(targetPid, signal);
8523
+ });
8524
+ const sleep4 = guard?.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
8525
+ const stillOwned = async () => {
8526
+ if (!guard) return true;
8527
+ if (await verifyHolder(pid, guard.profile) !== "match") return false;
8528
+ if (guard.expectedStartSignature) {
8529
+ const currentSig = await readStartSig(pid);
8530
+ if (!currentSig || currentSig !== guard.expectedStartSignature) return false;
8311
8531
  }
8312
- index = command.indexOf(marker, index + 1);
8532
+ return true;
8533
+ };
8534
+ if (!await stillOwned()) return false;
8535
+ if (process.platform === "win32" && !guard?.kill) {
8536
+ await new Promise((resolve2) => {
8537
+ execFile("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => resolve2());
8538
+ });
8539
+ return true;
8313
8540
  }
8314
- return false;
8541
+ try {
8542
+ sendKill(pid, "SIGTERM");
8543
+ } catch {
8544
+ }
8545
+ await sleep4(400);
8546
+ let alive = false;
8547
+ try {
8548
+ sendKill(pid, 0);
8549
+ alive = true;
8550
+ } catch (error) {
8551
+ alive = error.code === "EPERM";
8552
+ }
8553
+ if (alive) {
8554
+ if (!await stillOwned()) return false;
8555
+ try {
8556
+ sendKill(pid, "SIGKILL");
8557
+ } catch {
8558
+ }
8559
+ await sleep4(300);
8560
+ }
8561
+ return true;
8315
8562
  }
8316
8563
  async function signalTreeOfProfile(profile, signal) {
8317
8564
  const scan = await scanProfileHolders(profile);
8318
8565
  if (scan.kind !== "ok") return scan.kind === "none" ? 0 : -1;
8319
8566
  let signalled = 0;
8320
8567
  for (const pid of scan.pids) {
8321
- if (!await verifyProfileHolder(pid, profile)) continue;
8322
- try {
8323
- process.kill(pid, signal);
8568
+ if (await verifyProfileHolderDetailed(pid, profile) !== "match") continue;
8569
+ if (process.platform === "win32") {
8570
+ await new Promise((resolve2) => {
8571
+ execFile("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 2e3 }, () => resolve2());
8572
+ });
8324
8573
  signalled++;
8325
- } catch {
8574
+ } else {
8575
+ try {
8576
+ process.kill(pid, signal);
8577
+ signalled++;
8578
+ } catch {
8579
+ }
8326
8580
  }
8327
8581
  }
8328
8582
  if (signalled > 0) await new Promise((resolve2) => setTimeout(resolve2, 150));
@@ -8334,7 +8588,9 @@ async function countProfileHolders(profile) {
8334
8588
  if (scan.kind === "unknown") return -1;
8335
8589
  let count = 0;
8336
8590
  for (const pid of scan.pids) {
8337
- if (await verifyProfileHolder(pid, profile)) count++;
8591
+ const verdict = await verifyProfileHolderDetailed(pid, profile);
8592
+ if (verdict === "unknown") return -1;
8593
+ if (verdict === "match") count++;
8338
8594
  }
8339
8595
  return count;
8340
8596
  }
@@ -8364,7 +8620,7 @@ async function releaseOwnedBrowser(child, port, profile) {
8364
8620
  }
8365
8621
  }
8366
8622
  }
8367
- if (profile && process.platform !== "win32") {
8623
+ if (profile) {
8368
8624
  await signalTreeOfProfile(profile, "SIGTERM");
8369
8625
  let holders = await countProfileHolders(profile);
8370
8626
  if (holders > 0) {
@@ -8372,7 +8628,7 @@ async function releaseOwnedBrowser(child, port, profile) {
8372
8628
  holders = await countProfileHolders(profile);
8373
8629
  }
8374
8630
  if (holders > 0) {
8375
- throw new Error(`Owned browser helpers survived SIGKILL (${holders} pids hold ${profile}); refusing to remove the profile while processes may still write it.`);
8631
+ throw new Error(`Owned browser helpers survived termination (${holders} pids hold ${profile}); refusing to remove the profile while processes may still write it.`);
8376
8632
  }
8377
8633
  if (holders < 0) {
8378
8634
  throw new Error(`Cannot verify that no process holds ${profile} (process scan unavailable); refusing to remove the profile.`);
@@ -8700,15 +8956,26 @@ function persistRuntimeBridgeState() {
8700
8956
  function managedBrowserManifestPath() {
8701
8957
  return path13.join(stateRootDir(process.env), "managed-browser.json");
8702
8958
  }
8703
- function writeManagedBrowserManifest(entry) {
8959
+ function writeManagedBrowserManifest(entry, opts = {}) {
8960
+ const target = managedBrowserManifestPath();
8961
+ let tmp;
8704
8962
  try {
8705
8963
  if (!entry) {
8706
- rmSync(managedBrowserManifestPath(), { force: true });
8964
+ rmSync(target, { force: true });
8707
8965
  return;
8708
8966
  }
8709
8967
  mkdirSync6(stateRootDir(process.env), { recursive: true });
8710
- writeFileSync3(managedBrowserManifestPath(), JSON.stringify({ ...entry, startedAt: Date.now() }), { encoding: "utf8" });
8711
- } catch {
8968
+ tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
8969
+ writeFileSync3(tmp, JSON.stringify({ ...entry, startedAt: Date.now() }), { encoding: "utf8" });
8970
+ renameSync3(tmp, target);
8971
+ } catch (error) {
8972
+ if (tmp) {
8973
+ try {
8974
+ rmSync(tmp, { force: true });
8975
+ } catch {
8976
+ }
8977
+ }
8978
+ if (opts.strict) throw error;
8712
8979
  }
8713
8980
  }
8714
8981
  function clearManagedBrowserManifest() {
@@ -8726,7 +8993,7 @@ function killManagedBrowserFast() {
8726
8993
  const profile = runtimeState.managedBrowserProfileDir;
8727
8994
  if (profile) {
8728
8995
  try {
8729
- const out = execFileSync("pgrep", ["-f", `user-data-dir=${escapeEre(profile)}([^a-zA-Z0-9_-]|$)`], { timeout: 1500, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] });
8996
+ const out = execFileSync("pgrep", ["-f", `user-data-dir=${escapeEre(profile)}([[:space:]"']|$)`], { timeout: 1500, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] });
8730
8997
  for (const pidText of String(out).split(/\s+/)) {
8731
8998
  const pid2 = Number(pidText);
8732
8999
  if (Number.isInteger(pid2) && pid2 > 0 && pid2 !== process.pid) {
@@ -8755,11 +9022,23 @@ async function manifestPidIsOurBrowser(pid, profileDir) {
8755
9022
  return await verifyProfileHolder(pid, profileDir);
8756
9023
  }
8757
9024
  async function sweepOrphanedManagedBrowser() {
9025
+ const manifestPath = managedBrowserManifestPath();
9026
+ let raw;
9027
+ try {
9028
+ raw = readFileSync4(manifestPath, "utf8");
9029
+ } catch (error) {
9030
+ if (error.code === "ENOENT") return;
9031
+ throw error;
9032
+ }
8758
9033
  let manifest;
8759
9034
  try {
8760
- manifest = JSON.parse(readFileSync4(managedBrowserManifestPath(), "utf8"));
9035
+ manifest = JSON.parse(raw);
8761
9036
  } catch {
8762
- clearManagedBrowserManifest();
9037
+ try {
9038
+ renameSync3(manifestPath, `${manifestPath}.corrupt-${Date.now()}`);
9039
+ } catch {
9040
+ clearManagedBrowserManifest();
9041
+ }
8763
9042
  return;
8764
9043
  }
8765
9044
  const profileDir = typeof manifest.profileDir === "string" ? manifest.profileDir : void 0;
@@ -8775,20 +9054,13 @@ async function sweepOrphanedManagedBrowser() {
8775
9054
  clearManagedBrowserManifest();
8776
9055
  return;
8777
9056
  }
8778
- if (port) await requestBrowserClose(port).catch(() => void 0);
8779
- if (pid !== void 0 && await manifestPidIsOurBrowser(pid, resolved)) {
8780
- try {
8781
- process.kill(pid, "SIGTERM");
8782
- } catch {
8783
- }
8784
- await new Promise((resolve2) => setTimeout(resolve2, 400));
8785
- if (processAlive(pid)) {
8786
- try {
8787
- process.kill(pid, "SIGKILL");
8788
- } catch {
8789
- }
8790
- await new Promise((resolve2) => setTimeout(resolve2, 300));
8791
- }
9057
+ const pidVerified = pid !== void 0 && await manifestPidIsOurBrowser(pid, resolved);
9058
+ const pidStartSignature = pidVerified && pid !== void 0 ? await readProcessStartSignature(pid) : null;
9059
+ if (port && pidVerified) {
9060
+ await requestBrowserClose(port).catch(() => void 0);
9061
+ }
9062
+ if (pidVerified && pid !== void 0) {
9063
+ await terminateVerifiedPid(pid, { profile: resolved, expectedStartSignature: pidStartSignature });
8792
9064
  }
8793
9065
  await releaseOwnedBrowser(void 0, void 0, resolved);
8794
9066
  clearManagedBrowserManifest();
@@ -9565,16 +9837,25 @@ async function helperAct(target, action, headless, signal) {
9565
9837
  };
9566
9838
  const textTimeout = "text" in action.params ? action.params.text.length * 25 + 4e3 : COMMAND_TIMEOUT_MS5;
9567
9839
  const timeoutMs = Math.max(COMMAND_TIMEOUT_MS5, textTimeout);
9568
- if ((action.usesCurrentFocus || action.needsForeground) && !headless) {
9840
+ const configuredPolicy = currentDeliveryPolicy();
9841
+ const forbidForeground = headless || configuredPolicy === "background" || configuredPolicy === "ax_only";
9842
+ if ((action.usesCurrentFocus || action.needsForeground) && !forbidForeground) {
9569
9843
  const foreground = checked(await currentPlatformBackend.act(helperActRequest(target, action, "foreground"), { signal, timeoutMs }));
9570
9844
  const trace = executionTraceFromAct(foreground, "foreground");
9571
9845
  trace.backgroundFirst = false;
9572
9846
  return trace;
9573
9847
  }
9848
+ if ((action.usesCurrentFocus || action.needsForeground) && forbidForeground) {
9849
+ const err = new Error(
9850
+ `Action '${action.action}' requires foreground focus/HID input, which is blocked under '${headless ? "headless" : configuredPolicy}' background-only policy. Use a semantic ref/CDP action or explicitly opt into PIE_COMPUTER_USE_DELIVERY_POLICY=foreground.`
9851
+ );
9852
+ err.code = "foreground_required";
9853
+ throw err;
9854
+ }
9574
9855
  try {
9575
- const initialPolicy = headless ? "ax_only" : "background";
9856
+ const initialPolicy = headless || configuredPolicy === "ax_only" ? "ax_only" : "background";
9576
9857
  const result = checked(await currentPlatformBackend.act(helperActRequest(target, action, initialPolicy), { signal, timeoutMs }));
9577
- if (canRetryInForeground(action, result.outcome, headless)) {
9858
+ if (!forbidForeground && canRetryInForeground(action, result.outcome, headless)) {
9578
9859
  const foreground = checked(await currentPlatformBackend.act(helperActRequest(target, action, "foreground"), { signal, timeoutMs }));
9579
9860
  const trace2 = executionTraceFromAct(foreground, "foreground");
9580
9861
  trace2.backgroundFirst = true;
@@ -9588,7 +9869,7 @@ async function helperAct(target, action, headless, signal) {
9588
9869
  return trace;
9589
9870
  } catch (error) {
9590
9871
  const code = error?.code;
9591
- if (code !== "foreground_required" || headless) throw error;
9872
+ if (code !== "foreground_required" || forbidForeground) throw error;
9592
9873
  const foreground = checked(await currentPlatformBackend.act(helperActRequest(target, action, "foreground"), { signal, timeoutMs }));
9593
9874
  const trace = executionTraceFromAct(foreground, "foreground");
9594
9875
  trace.backgroundFirst = true;
@@ -10368,8 +10649,7 @@ async function performBrowserTransaction(params, actions, signal) {
10368
10649
  for (const { action, target } of prepared) {
10369
10650
  let worked = false;
10370
10651
  if (action.action === "press" || action.action === "click" && action.ref) {
10371
- worked = true;
10372
- for (let count = 0; count < (action.clickCount ?? 1); count += 1) worked = await cdpClickForContext(contextId, target.backendNodeId) && worked;
10652
+ worked = await cdpClickForContext(contextId, target.backendNodeId, action.clickCount ?? 1);
10373
10653
  } else if (action.action === "click") {
10374
10654
  worked = await cdpMouseForContext(contextId, action.x, action.y, "mousePressed", action.button ?? "left", action.clickCount ?? 1) && await cdpMouseForContext(contextId, action.x, action.y, "mouseReleased", action.button ?? "left", action.clickCount ?? 1);
10375
10655
  } else if (action.action === "setText") worked = await cdpTypeForContext(contextId, target.backendNodeId, action.text ?? "", true);
@@ -10501,21 +10781,43 @@ async function performLaunchBrowser(params, signal) {
10501
10781
  const url = requestedUrl ?? "about:blank";
10502
10782
  await disconnectCdp();
10503
10783
  await releaseOwnedBrowserState(runtimeState);
10784
+ await sweepOrphanedManagedBrowser();
10504
10785
  const profileDir = mkdtempSync(path13.join(os4.tmpdir(), `pie-${browser}-cdp-`));
10786
+ try {
10787
+ writeManagedBrowserManifest({ port: String(port), profileDir }, { strict: true });
10788
+ } catch (error) {
10789
+ try {
10790
+ rmSync(profileDir, { recursive: true, force: true });
10791
+ } catch {
10792
+ }
10793
+ throw error;
10794
+ }
10795
+ const browserHeaded = getComputerUseEnvironmentValue("PIE_COMPUTER_USE_BROWSER_HEADED") === "true";
10505
10796
  const args = [
10506
10797
  `--remote-debugging-port=${port}`,
10507
10798
  `--user-data-dir=${profileDir}`,
10508
10799
  "--no-first-run",
10509
10800
  "--no-default-browser-check",
10801
+ ...!browserHeaded ? ["--headless=new", "--window-size=1440,900"] : [],
10510
10802
  url
10511
10803
  ];
10512
- const managedBrowser = spawn4(executable, args, { stdio: "ignore", detached: true });
10804
+ let managedBrowser;
10805
+ try {
10806
+ managedBrowser = spawn4(executable, args, { stdio: "ignore", detached: true, windowsHide: !browserHeaded });
10807
+ } catch (error) {
10808
+ clearManagedBrowserManifest();
10809
+ try {
10810
+ rmSync(profileDir, { recursive: true, force: true });
10811
+ } catch {
10812
+ }
10813
+ throw error;
10814
+ }
10513
10815
  managedBrowser.unref();
10514
10816
  runtimeState.managedBrowser = managedBrowser;
10515
10817
  runtimeState.managedBrowserCdpPort = String(port);
10516
10818
  runtimeState.managedBrowserPid = managedBrowser.pid;
10517
10819
  runtimeState.managedBrowserProfileDir = profileDir;
10518
- writeManagedBrowserManifest({ pid: managedBrowser.pid, port: String(port), profileDir });
10820
+ writeManagedBrowserManifest({ ...managedBrowser.pid !== void 0 ? { pid: managedBrowser.pid } : {}, port: String(port), profileDir });
10519
10821
  persistRuntimeBridgeState();
10520
10822
  setManagedCdpPort(String(port));
10521
10823
  try {