@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
@@ -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();
@@ -4343,6 +4351,7 @@ var init_permissions2 = __esm({
4343
4351
 
4344
4352
  // vendor/computer-use-axi/src/broker-server.ts
4345
4353
  init_test_backend_guard();
4354
+ import { execFile as execFile2 } from "node:child_process";
4346
4355
  import { createHash as createHash4, randomUUID as randomUUID8 } from "node:crypto";
4347
4356
  import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync5, unlinkSync as unlinkSync4, writeFileSync as writeFileSync4 } from "node:fs";
4348
4357
  import net3 from "node:net";
@@ -4421,14 +4430,14 @@ var DEFAULT_CONFIG = {
4421
4430
  cursor_overlay: true,
4422
4431
  managed_browser: "chrome"
4423
4432
  };
4424
- 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"];
4425
4434
  function captureComputerUseEnvironment(env = process.env) {
4426
4435
  const out = {};
4427
4436
  for (const key of REQUEST_ENV_KEYS) {
4428
4437
  const value = env[key]?.trim();
4429
4438
  if (!value) continue;
4430
4439
  if (Buffer.byteLength(value) > 4096 || value.includes("\0")) throw new Error(`Invalid ${key}`);
4431
- 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)) {
4432
4441
  const parsed = parseBoolean(value);
4433
4442
  if (parsed === void 0) throw new Error(`Invalid ${key}`);
4434
4443
  out[key] = String(parsed);
@@ -4700,7 +4709,7 @@ function normalizeComputerUseOwner(value) {
4700
4709
 
4701
4710
  // vendor/computer-use-axi/src/broker-protocol.ts
4702
4711
  var BROKER_PROTOCOL_VERSION = 3;
4703
- var BROKER_ENGINE_VERSION = 4;
4712
+ var BROKER_ENGINE_VERSION = 5;
4704
4713
  var BROKER_PACKAGE_VERSION = "0.5.1-pie.1";
4705
4714
  var BROKER_RESULT_CACHE_MAX_ENTRIES = 256;
4706
4715
  var BROKER_REPLAY_LEDGER_MAX_IDS = 65536;
@@ -4770,6 +4779,10 @@ function boundedString(value, label2, maxBytes) {
4770
4779
  if (Buffer.byteLength(value, "utf8") > maxBytes) throw new BrokerProtocolError("invalid_params", `${label2} is too large.`);
4771
4780
  return value;
4772
4781
  }
4782
+ function optionalBoundedString(value, label2, maxBytes) {
4783
+ if (value === void 0) return void 0;
4784
+ return boundedString(value, label2, maxBytes);
4785
+ }
4773
4786
  function boundedNumber(value, label2, min, max) {
4774
4787
  if (typeof value !== "number" || !Number.isFinite(value)) throw new BrokerProtocolError("invalid_params", `${label2} must be a finite number.`);
4775
4788
  if (value < min || value > max) throw new BrokerProtocolError("invalid_params", `${label2} is out of range.`);
@@ -5061,11 +5074,20 @@ function validateHello(value) {
5061
5074
  throw new BrokerProtocolError("protocol_mismatch", `Protocol mismatch: broker ${BROKER_PROTOCOL_VERSION}, client ${String(value.protocolVersion)}.`);
5062
5075
  }
5063
5076
  if (value.buildIdentity !== BROKER_BUILD.identity) throw new BrokerProtocolError("build_mismatch", "Broker engine build identity differs.");
5077
+ let supervisor;
5078
+ if (value.supervisor !== void 0) {
5079
+ assertPlainRecord(value.supervisor, "hello.supervisor");
5080
+ assertKeys(value.supervisor, "hello.supervisor", ["pid", "startTime"]);
5081
+ const pid = Math.trunc(boundedNumber(value.supervisor.pid, "hello.supervisor.pid", 1, Number.MAX_SAFE_INTEGER));
5082
+ const startTime = optionalBoundedString(value.supervisor.startTime, "hello.supervisor.startTime", 256);
5083
+ supervisor = startTime ? { pid, startTime } : { pid };
5084
+ }
5064
5085
  return {
5065
5086
  type: "hello",
5066
5087
  buildIdentity: value.buildIdentity,
5067
5088
  protocolVersion: value.protocolVersion,
5068
- clientVersion: value.clientVersion === void 0 ? void 0 : boundedString(value.clientVersion, "clientVersion", 128)
5089
+ clientVersion: value.clientVersion === void 0 ? void 0 : boundedString(value.clientVersion, "clientVersion", 128),
5090
+ ...supervisor ? { supervisor } : {}
5069
5091
  };
5070
5092
  }
5071
5093
  function encodeFrame(value, maxBytes = BROKER_MAX_FRAME_BYTES) {
@@ -5370,7 +5392,7 @@ function artifactsRoot(env = process.env) {
5370
5392
  init_test_backend_guard();
5371
5393
  import { execFileSync, spawn as spawn4 } from "node:child_process";
5372
5394
  import { randomUUID as randomUUID7 } from "node:crypto";
5373
- 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";
5374
5396
  import { access as access4 } from "node:fs/promises";
5375
5397
  import net2 from "node:net";
5376
5398
  import os4 from "node:os";
@@ -5431,7 +5453,10 @@ function focusedTarget(env) {
5431
5453
  return { focus: { x: Math.floor(env.image.width / 2), y: Math.floor(env.image.height / 2) } };
5432
5454
  }
5433
5455
  function containsEditable(node) {
5434
- if (node.canSetValue || node.role.toLowerCase().includes("text")) return true;
5456
+ const role = node.role.toLowerCase();
5457
+ if (node.isTextInput || node.canSetValue || role === "edit" || role === "textbox" || role.includes("textfield") || role.includes("textarea")) {
5458
+ return true;
5459
+ }
5435
5460
  return node.children.some(containsEditable);
5436
5461
  }
5437
5462
  function wireableInputDescendants(node) {
@@ -5810,10 +5835,14 @@ function damerauLevenshtein(a, b) {
5810
5835
  }
5811
5836
  return matrix[a.length][b.length];
5812
5837
  }
5838
+ var ZERO_WIDTH_RE = /[\u200B-\u200D\u2060\uFEFF]/g;
5839
+ function stripZeroWidth(text) {
5840
+ return text.replace(ZERO_WIDTH_RE, "");
5841
+ }
5813
5842
  function rankedTextMatch(values, text) {
5814
- const query = text.toLowerCase().replace(/\s+/g, " ").trim().slice(0, 256);
5843
+ const query = stripZeroWidth(text).toLowerCase().replace(/\s+/g, " ").trim().slice(0, 256);
5815
5844
  if (!query) return void 0;
5816
- const candidates = values.map((value) => value.toLowerCase().replace(/\s+/g, " ").trim().slice(0, 512)).filter(Boolean);
5845
+ const candidates = values.map((value) => stripZeroWidth(value).toLowerCase().replace(/\s+/g, " ").trim().slice(0, 512)).filter(Boolean);
5817
5846
  if (candidates.some((value) => value === query)) return { reason: "exact", score: 1 };
5818
5847
  if (candidates.some((value) => value.startsWith(query) || value.split(/\W+/).some((token) => token.startsWith(query)))) return { reason: "prefix", score: 0.95 };
5819
5848
  if (candidates.some((value) => value.includes(query))) return { reason: "substring", score: 0.9 };
@@ -5848,13 +5877,13 @@ function searchOutlineRanked(outline, text, role, capability, limit = 12) {
5848
5877
  return { matches: sorted.slice(0, limit).map(({ order: _order, ...match }) => match), totalMatches: strong.length + (useFuzzy ? fuzzy.length : 0) };
5849
5878
  }
5850
5879
  function searchOutline(outline, text, role, action, limit = 50) {
5851
- const query = text?.trim().toLowerCase();
5880
+ const query = text ? stripZeroWidth(text).replace(/\s+/g, " ").trim().toLowerCase() : void 0;
5852
5881
  const roleQuery = role?.trim();
5853
5882
  const actionQuery = action?.trim();
5854
5883
  const matches = [];
5855
5884
  for (const node of outline.nodes) {
5856
5885
  const label2 = outlineNodeLabel(node);
5857
- const haystack = [label2, node.role, node.subrole, node.identifier, node.title, node.description, node.value, ...node.text.map((item) => item.string)].join(" ").toLowerCase();
5886
+ const haystack = stripZeroWidth([label2, node.role, node.subrole, node.identifier, node.title, node.description, node.value, ...node.text.map((item) => item.string)].join(" ")).replace(/\s+/g, " ").toLowerCase();
5858
5887
  if (query && !haystack.includes(query)) continue;
5859
5888
  if (roleQuery && node.role !== roleQuery) continue;
5860
5889
  if (actionQuery && !actionMatches(node, actionQuery)) continue;
@@ -6119,20 +6148,88 @@ var CdpTab = class _CdpTab {
6119
6148
  this.loadFired = void 0;
6120
6149
  }
6121
6150
  }
6122
- 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
+ }
6123
6178
  await this.withBackendNode(backendNodeId, "function(){ this.scrollIntoView({block:'center', inline:'center'}); this.click(); }");
6124
6179
  }
6125
6180
  async focusBackendNode(backendNodeId) {
6126
6181
  await this.withBackendNode(backendNodeId, "function(){ this.scrollIntoView({block:'center', inline:'center'}); this.focus(); }");
6127
6182
  }
6128
6183
  async typeIntoBackendNode(backendNodeId, text, replace) {
6129
- 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]);
6193
+ }
6194
+ async wheelAt(x, y, deltaX, deltaY) {
6195
+ await this.send("Input.dispatchMouseEvent", {
6196
+ type: "mouseWheel",
6197
+ x,
6198
+ y,
6199
+ deltaX,
6200
+ deltaY
6201
+ });
6130
6202
  }
6131
6203
  async scrollBy(deltaX, deltaY, backendNodeId) {
6132
6204
  if (backendNodeId) {
6205
+ try {
6206
+ const resolved = await this.send("DOM.resolveNode", { backendNodeId });
6207
+ const objectId = resolved?.object?.objectId;
6208
+ if (typeof objectId === "string") {
6209
+ const rectRes = await this.send("Runtime.callFunctionOn", {
6210
+ objectId,
6211
+ 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, w, h } : null; }",
6212
+ returnByValue: true
6213
+ });
6214
+ const pt = !rectRes?.exceptionDetails ? rectRes?.result?.value : void 0;
6215
+ if (pt && typeof pt.x === "number" && typeof pt.y === "number" && Number.isFinite(pt.x) && Number.isFinite(pt.y) && (pt.w ?? 0) > 0 && (pt.h ?? 0) > 0) {
6216
+ await this.wheelAt(pt.x, pt.y, deltaX, deltaY);
6217
+ return;
6218
+ }
6219
+ }
6220
+ } catch {
6221
+ }
6133
6222
  await this.withBackendNode(backendNodeId, "function(dx, dy){ this.scrollIntoView({block:'center', inline:'center'}); this.scrollBy(dx, dy); }", [deltaX, deltaY]);
6134
6223
  return;
6135
6224
  }
6225
+ try {
6226
+ const center = await this.evaluate("({ x: Math.round((window.innerWidth || 800) / 2), y: Math.round((window.innerHeight || 600) / 2) })");
6227
+ if (center && typeof center.x === "number" && typeof center.y === "number" && Number.isFinite(center.x) && Number.isFinite(center.y)) {
6228
+ await this.wheelAt(center.x, center.y, deltaX, deltaY);
6229
+ return;
6230
+ }
6231
+ } catch {
6232
+ }
6136
6233
  await this.send("Runtime.evaluate", { expression: `window.scrollBy(${JSON.stringify(deltaX)}, ${JSON.stringify(deltaY)})` });
6137
6234
  }
6138
6235
  async typeIntoFocused(text) {
@@ -6151,10 +6248,29 @@ var CdpTab = class _CdpTab {
6151
6248
  }
6152
6249
  async dragPath(path15) {
6153
6250
  if (path15.length < 2) throw new Error("CDP drag requires at least two points.");
6154
- await this.mouseAt(path15[0].x, path15[0].y, "mousePressed");
6155
- for (const point of path15.slice(1)) await this.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: point.x, y: point.y, button: "left", buttons: 1 });
6156
- const end = path15[path15.length - 1];
6157
- 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
+ }
6158
6274
  }
6159
6275
  async withBackendNode(backendNodeId, functionDeclaration, args = []) {
6160
6276
  const resolved = await this.send("DOM.resolveNode", { backendNodeId });
@@ -6333,9 +6449,9 @@ async function listCdpPageContexts(port = getComputerUseEnvironmentValue("PIE_CO
6333
6449
  url: page.url ?? ""
6334
6450
  }));
6335
6451
  }
6336
- async function cdpClickForContext(contextId, backendNodeId) {
6452
+ async function cdpClickForContext(contextId, backendNodeId, clickCount2 = 1) {
6337
6453
  return await withCdpContextTab(contextId, async (tab) => {
6338
- await tab.clickBackendNode(backendNodeId);
6454
+ await tab.clickBackendNode(backendNodeId, clickCount2);
6339
6455
  return true;
6340
6456
  }) === true;
6341
6457
  }
@@ -8199,8 +8315,33 @@ function escapeEre(value) {
8199
8315
  return value.replace(/[\\^$.|?*+()[{]/g, (ch) => `\\${ch}`);
8200
8316
  }
8201
8317
  async function scanProfileHolders(profile) {
8202
- if (process.platform === "win32") return { kind: "ok", pids: [] };
8203
- 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:]"']|$)`;
8204
8345
  return await new Promise((resolve2) => {
8205
8346
  execFile("pgrep", ["-f", pattern], { timeout: 1500 }, (error, stdout) => {
8206
8347
  if (!error) {
@@ -8217,57 +8358,153 @@ async function scanProfileHolders(profile) {
8217
8358
  });
8218
8359
  });
8219
8360
  }
8220
- 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
+ }
8221
8396
  if (process.platform === "darwin") {
8222
8397
  return await new Promise((resolve2) => {
8223
8398
  execFile("ps", ["-o", "command=", "-p", String(pid)], { timeout: 1500 }, (error, stdout) => {
8224
8399
  if (error) {
8225
- resolve2(false);
8400
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8226
8401
  return;
8227
8402
  }
8228
8403
  const command = String(stdout ?? "").trim();
8229
8404
  if (!command) {
8230
- resolve2(false);
8405
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8231
8406
  return;
8232
8407
  }
8233
- resolve2(commandIncludesExactUserDataDir(command, profile));
8408
+ resolve2(commandIncludesExactUserDataDir(command, profile) ? "match" : "no_match");
8234
8409
  });
8235
8410
  });
8236
8411
  }
8237
8412
  return await new Promise((resolve2) => {
8238
8413
  execFile("cat", [`/proc/${pid}/cmdline`], { timeout: 1500 }, (error, stdout) => {
8239
8414
  if (error) {
8240
- resolve2(false);
8415
+ resolve2(pidStillAlive(pid) ? "unknown" : "no_match");
8241
8416
  return;
8242
8417
  }
8243
8418
  const argv = String(stdout ?? "").split("\0").filter(Boolean);
8244
- 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");
8245
8424
  });
8246
8425
  });
8247
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
+ }
8248
8465
  function commandIncludesExactUserDataDir(command, profile) {
8249
- const marker = "--user-data-dir=";
8250
- let index = command.indexOf(marker);
8251
- while (index !== -1) {
8252
- const start = index + marker.length;
8253
- if (command.startsWith(profile, start)) {
8254
- const after = start + profile.length;
8255
- 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
+ async function terminateVerifiedPid(pid) {
8472
+ if (process.platform === "win32") {
8473
+ await new Promise((resolve2) => {
8474
+ execFile("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 3e3 }, () => resolve2());
8475
+ });
8476
+ return;
8477
+ }
8478
+ try {
8479
+ process.kill(pid, "SIGTERM");
8480
+ } catch {
8481
+ }
8482
+ await new Promise((resolve2) => setTimeout(resolve2, 400));
8483
+ if (pidStillAlive(pid)) {
8484
+ try {
8485
+ process.kill(pid, "SIGKILL");
8486
+ } catch {
8256
8487
  }
8257
- index = command.indexOf(marker, index + 1);
8488
+ await new Promise((resolve2) => setTimeout(resolve2, 300));
8258
8489
  }
8259
- return false;
8260
8490
  }
8261
8491
  async function signalTreeOfProfile(profile, signal) {
8262
8492
  const scan = await scanProfileHolders(profile);
8263
8493
  if (scan.kind !== "ok") return scan.kind === "none" ? 0 : -1;
8264
8494
  let signalled = 0;
8265
8495
  for (const pid of scan.pids) {
8266
- if (!await verifyProfileHolder(pid, profile)) continue;
8267
- try {
8268
- process.kill(pid, signal);
8496
+ if (await verifyProfileHolderDetailed(pid, profile) !== "match") continue;
8497
+ if (process.platform === "win32") {
8498
+ await new Promise((resolve2) => {
8499
+ execFile("taskkill.exe", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 2e3 }, () => resolve2());
8500
+ });
8269
8501
  signalled++;
8270
- } catch {
8502
+ } else {
8503
+ try {
8504
+ process.kill(pid, signal);
8505
+ signalled++;
8506
+ } catch {
8507
+ }
8271
8508
  }
8272
8509
  }
8273
8510
  if (signalled > 0) await new Promise((resolve2) => setTimeout(resolve2, 150));
@@ -8279,7 +8516,9 @@ async function countProfileHolders(profile) {
8279
8516
  if (scan.kind === "unknown") return -1;
8280
8517
  let count = 0;
8281
8518
  for (const pid of scan.pids) {
8282
- if (await verifyProfileHolder(pid, profile)) count++;
8519
+ const verdict = await verifyProfileHolderDetailed(pid, profile);
8520
+ if (verdict === "unknown") return -1;
8521
+ if (verdict === "match") count++;
8283
8522
  }
8284
8523
  return count;
8285
8524
  }
@@ -8309,7 +8548,7 @@ async function releaseOwnedBrowser(child, port, profile) {
8309
8548
  }
8310
8549
  }
8311
8550
  }
8312
- if (profile && process.platform !== "win32") {
8551
+ if (profile) {
8313
8552
  await signalTreeOfProfile(profile, "SIGTERM");
8314
8553
  let holders = await countProfileHolders(profile);
8315
8554
  if (holders > 0) {
@@ -8317,7 +8556,7 @@ async function releaseOwnedBrowser(child, port, profile) {
8317
8556
  holders = await countProfileHolders(profile);
8318
8557
  }
8319
8558
  if (holders > 0) {
8320
- throw new Error(`Owned browser helpers survived SIGKILL (${holders} pids hold ${profile}); refusing to remove the profile while processes may still write it.`);
8559
+ throw new Error(`Owned browser helpers survived termination (${holders} pids hold ${profile}); refusing to remove the profile while processes may still write it.`);
8321
8560
  }
8322
8561
  if (holders < 0) {
8323
8562
  throw new Error(`Cannot verify that no process holds ${profile} (process scan unavailable); refusing to remove the profile.`);
@@ -8645,15 +8884,26 @@ function persistRuntimeBridgeState() {
8645
8884
  function managedBrowserManifestPath() {
8646
8885
  return path13.join(stateRootDir(process.env), "managed-browser.json");
8647
8886
  }
8648
- function writeManagedBrowserManifest(entry) {
8887
+ function writeManagedBrowserManifest(entry, opts = {}) {
8888
+ const target = managedBrowserManifestPath();
8889
+ let tmp;
8649
8890
  try {
8650
8891
  if (!entry) {
8651
- rmSync(managedBrowserManifestPath(), { force: true });
8892
+ rmSync(target, { force: true });
8652
8893
  return;
8653
8894
  }
8654
8895
  mkdirSync6(stateRootDir(process.env), { recursive: true });
8655
- writeFileSync3(managedBrowserManifestPath(), JSON.stringify({ ...entry, startedAt: Date.now() }), { encoding: "utf8" });
8656
- } catch {
8896
+ tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
8897
+ writeFileSync3(tmp, JSON.stringify({ ...entry, startedAt: Date.now() }), { encoding: "utf8" });
8898
+ renameSync3(tmp, target);
8899
+ } catch (error) {
8900
+ if (tmp) {
8901
+ try {
8902
+ rmSync(tmp, { force: true });
8903
+ } catch {
8904
+ }
8905
+ }
8906
+ if (opts.strict) throw error;
8657
8907
  }
8658
8908
  }
8659
8909
  function clearManagedBrowserManifest() {
@@ -8671,7 +8921,7 @@ function killManagedBrowserFast() {
8671
8921
  const profile = runtimeState.managedBrowserProfileDir;
8672
8922
  if (profile) {
8673
8923
  try {
8674
- const out = execFileSync("pgrep", ["-f", `user-data-dir=${escapeEre(profile)}([^a-zA-Z0-9_-]|$)`], { timeout: 1500, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] });
8924
+ const out = execFileSync("pgrep", ["-f", `user-data-dir=${escapeEre(profile)}([[:space:]"']|$)`], { timeout: 1500, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] });
8675
8925
  for (const pidText of String(out).split(/\s+/)) {
8676
8926
  const pid2 = Number(pidText);
8677
8927
  if (Number.isInteger(pid2) && pid2 > 0 && pid2 !== process.pid) {
@@ -8700,11 +8950,23 @@ async function manifestPidIsOurBrowser(pid, profileDir) {
8700
8950
  return await verifyProfileHolder(pid, profileDir);
8701
8951
  }
8702
8952
  async function sweepOrphanedManagedBrowser() {
8953
+ const manifestPath = managedBrowserManifestPath();
8954
+ let raw;
8955
+ try {
8956
+ raw = readFileSync4(manifestPath, "utf8");
8957
+ } catch (error) {
8958
+ if (error.code === "ENOENT") return;
8959
+ throw error;
8960
+ }
8703
8961
  let manifest;
8704
8962
  try {
8705
- manifest = JSON.parse(readFileSync4(managedBrowserManifestPath(), "utf8"));
8963
+ manifest = JSON.parse(raw);
8706
8964
  } catch {
8707
- clearManagedBrowserManifest();
8965
+ try {
8966
+ renameSync3(manifestPath, `${manifestPath}.corrupt-${Date.now()}`);
8967
+ } catch {
8968
+ clearManagedBrowserManifest();
8969
+ }
8708
8970
  return;
8709
8971
  }
8710
8972
  const profileDir = typeof manifest.profileDir === "string" ? manifest.profileDir : void 0;
@@ -8720,20 +8982,12 @@ async function sweepOrphanedManagedBrowser() {
8720
8982
  clearManagedBrowserManifest();
8721
8983
  return;
8722
8984
  }
8723
- if (port) await requestBrowserClose(port).catch(() => void 0);
8724
- if (pid !== void 0 && await manifestPidIsOurBrowser(pid, resolved)) {
8725
- try {
8726
- process.kill(pid, "SIGTERM");
8727
- } catch {
8728
- }
8729
- await new Promise((resolve2) => setTimeout(resolve2, 400));
8730
- if (processAlive(pid)) {
8731
- try {
8732
- process.kill(pid, "SIGKILL");
8733
- } catch {
8734
- }
8735
- await new Promise((resolve2) => setTimeout(resolve2, 300));
8736
- }
8985
+ const pidVerified = pid !== void 0 && await manifestPidIsOurBrowser(pid, resolved);
8986
+ if (port && pidVerified) {
8987
+ await requestBrowserClose(port).catch(() => void 0);
8988
+ }
8989
+ if (pidVerified && pid !== void 0) {
8990
+ await terminateVerifiedPid(pid);
8737
8991
  }
8738
8992
  await releaseOwnedBrowser(void 0, void 0, resolved);
8739
8993
  clearManagedBrowserManifest();
@@ -8865,7 +9119,7 @@ function trimOrUndefined(value) {
8865
9119
  return trimmed.length > 0 ? trimmed : void 0;
8866
9120
  }
8867
9121
  function normalizeText2(value) {
8868
- return (value ?? "").trim().toLowerCase();
9122
+ return (value ?? "").replace(/[\u200B-\u200D\u2060\uFEFF]/g, "").trim().toLowerCase();
8869
9123
  }
8870
9124
  function outlineNodeCenter(node) {
8871
9125
  if (!node.rect) {
@@ -9510,16 +9764,25 @@ async function helperAct(target, action, headless, signal) {
9510
9764
  };
9511
9765
  const textTimeout = "text" in action.params ? action.params.text.length * 25 + 4e3 : COMMAND_TIMEOUT_MS5;
9512
9766
  const timeoutMs = Math.max(COMMAND_TIMEOUT_MS5, textTimeout);
9513
- if ((action.usesCurrentFocus || action.needsForeground) && !headless) {
9767
+ const configuredPolicy = currentDeliveryPolicy();
9768
+ const forbidForeground = headless || configuredPolicy === "background" || configuredPolicy === "ax_only";
9769
+ if ((action.usesCurrentFocus || action.needsForeground) && !forbidForeground) {
9514
9770
  const foreground = checked(await currentPlatformBackend.act(helperActRequest(target, action, "foreground"), { signal, timeoutMs }));
9515
9771
  const trace = executionTraceFromAct(foreground, "foreground");
9516
9772
  trace.backgroundFirst = false;
9517
9773
  return trace;
9518
9774
  }
9775
+ if ((action.usesCurrentFocus || action.needsForeground) && forbidForeground) {
9776
+ const err = new Error(
9777
+ `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.`
9778
+ );
9779
+ err.code = "foreground_required";
9780
+ throw err;
9781
+ }
9519
9782
  try {
9520
- const initialPolicy = headless ? "ax_only" : "background";
9783
+ const initialPolicy = headless || configuredPolicy === "ax_only" ? "ax_only" : "background";
9521
9784
  const result = checked(await currentPlatformBackend.act(helperActRequest(target, action, initialPolicy), { signal, timeoutMs }));
9522
- if (canRetryInForeground(action, result.outcome, headless)) {
9785
+ if (!forbidForeground && canRetryInForeground(action, result.outcome, headless)) {
9523
9786
  const foreground = checked(await currentPlatformBackend.act(helperActRequest(target, action, "foreground"), { signal, timeoutMs }));
9524
9787
  const trace2 = executionTraceFromAct(foreground, "foreground");
9525
9788
  trace2.backgroundFirst = true;
@@ -9533,7 +9796,7 @@ async function helperAct(target, action, headless, signal) {
9533
9796
  return trace;
9534
9797
  } catch (error) {
9535
9798
  const code = error?.code;
9536
- if (code !== "foreground_required" || headless) throw error;
9799
+ if (code !== "foreground_required" || forbidForeground) throw error;
9537
9800
  const foreground = checked(await currentPlatformBackend.act(helperActRequest(target, action, "foreground"), { signal, timeoutMs }));
9538
9801
  const trace = executionTraceFromAct(foreground, "foreground");
9539
9802
  trace.backgroundFirst = true;
@@ -10313,8 +10576,7 @@ async function performBrowserTransaction(params, actions, signal) {
10313
10576
  for (const { action, target } of prepared) {
10314
10577
  let worked = false;
10315
10578
  if (action.action === "press" || action.action === "click" && action.ref) {
10316
- worked = true;
10317
- for (let count = 0; count < (action.clickCount ?? 1); count += 1) worked = await cdpClickForContext(contextId, target.backendNodeId) && worked;
10579
+ worked = await cdpClickForContext(contextId, target.backendNodeId, action.clickCount ?? 1);
10318
10580
  } else if (action.action === "click") {
10319
10581
  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);
10320
10582
  } else if (action.action === "setText") worked = await cdpTypeForContext(contextId, target.backendNodeId, action.text ?? "", true);
@@ -10446,21 +10708,43 @@ async function performLaunchBrowser(params, signal) {
10446
10708
  const url = requestedUrl ?? "about:blank";
10447
10709
  await disconnectCdp();
10448
10710
  await releaseOwnedBrowserState(runtimeState);
10711
+ await sweepOrphanedManagedBrowser();
10449
10712
  const profileDir = mkdtempSync(path13.join(os4.tmpdir(), `pie-${browser}-cdp-`));
10713
+ try {
10714
+ writeManagedBrowserManifest({ port: String(port), profileDir }, { strict: true });
10715
+ } catch (error) {
10716
+ try {
10717
+ rmSync(profileDir, { recursive: true, force: true });
10718
+ } catch {
10719
+ }
10720
+ throw error;
10721
+ }
10722
+ const browserHeaded = getComputerUseEnvironmentValue("PIE_COMPUTER_USE_BROWSER_HEADED") === "true";
10450
10723
  const args = [
10451
10724
  `--remote-debugging-port=${port}`,
10452
10725
  `--user-data-dir=${profileDir}`,
10453
10726
  "--no-first-run",
10454
10727
  "--no-default-browser-check",
10728
+ ...!browserHeaded ? ["--headless=new", "--window-size=1440,900"] : [],
10455
10729
  url
10456
10730
  ];
10457
- const managedBrowser = spawn4(executable, args, { stdio: "ignore", detached: true });
10731
+ let managedBrowser;
10732
+ try {
10733
+ managedBrowser = spawn4(executable, args, { stdio: "ignore", detached: true, windowsHide: !browserHeaded });
10734
+ } catch (error) {
10735
+ clearManagedBrowserManifest();
10736
+ try {
10737
+ rmSync(profileDir, { recursive: true, force: true });
10738
+ } catch {
10739
+ }
10740
+ throw error;
10741
+ }
10458
10742
  managedBrowser.unref();
10459
10743
  runtimeState.managedBrowser = managedBrowser;
10460
10744
  runtimeState.managedBrowserCdpPort = String(port);
10461
10745
  runtimeState.managedBrowserPid = managedBrowser.pid;
10462
10746
  runtimeState.managedBrowserProfileDir = profileDir;
10463
- writeManagedBrowserManifest({ pid: managedBrowser.pid, port: String(port), profileDir });
10747
+ writeManagedBrowserManifest({ ...managedBrowser.pid !== void 0 ? { pid: managedBrowser.pid } : {}, port: String(port), profileDir });
10464
10748
  persistRuntimeBridgeState();
10465
10749
  setManagedCdpPort(String(port));
10466
10750
  try {
@@ -10616,10 +10900,38 @@ function isAlive(pid) {
10616
10900
  try {
10617
10901
  process.kill(pid, 0);
10618
10902
  return true;
10619
- } catch {
10620
- return false;
10903
+ } catch (error) {
10904
+ return error?.code !== "ESRCH";
10621
10905
  }
10622
10906
  }
10907
+ function readProcessStartTimeAsync(pid) {
10908
+ if (!Number.isInteger(pid) || pid <= 0) return Promise.resolve(void 0);
10909
+ return new Promise((resolve2) => {
10910
+ const cmd = process.platform === "win32" ? "powershell" : "ps";
10911
+ const args = process.platform === "win32" ? [
10912
+ "-NoProfile",
10913
+ "-NonInteractive",
10914
+ "-Command",
10915
+ `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; if ($p) { $p.CreationDate.ToString('o') }`
10916
+ ] : ["-p", String(pid), "-o", "lstart="];
10917
+ const opts = process.platform === "win32" ? { timeout: 3e3, encoding: "utf8", windowsHide: true } : { timeout: 3e3, encoding: "utf8", env: { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC0" } };
10918
+ execFile2(cmd, args, opts, (error, stdout) => {
10919
+ if (error) {
10920
+ resolve2(void 0);
10921
+ return;
10922
+ }
10923
+ const trimmed = (stdout ?? "").trim();
10924
+ resolve2(trimmed || void 0);
10925
+ });
10926
+ });
10927
+ }
10928
+ async function isSupervisorGoneAsync(supervisor) {
10929
+ if (!isAlive(supervisor.pid)) return true;
10930
+ if (!supervisor.startTime) return false;
10931
+ const observed = await readProcessStartTimeAsync(supervisor.pid);
10932
+ if (!observed) return false;
10933
+ return observed !== supervisor.startTime;
10934
+ }
10623
10935
  function acquireBootstrapLock(directory) {
10624
10936
  ensurePrivateDirectory(directory);
10625
10937
  const lockPath = path14.join(directory, "broker.lock");
@@ -10745,6 +11057,32 @@ async function startBroker(options = {}) {
10745
11057
  const replayLedgerLimit = options.replayLedgerLimit ?? BROKER_REPLAY_LEDGER_MAX_IDS;
10746
11058
  const owners = /* @__PURE__ */ new Set();
10747
11059
  const knownStateIds = /* @__PURE__ */ new Set();
11060
+ const supervisors = /* @__PURE__ */ new Map();
11061
+ let hasUnsupervisedCaller = false;
11062
+ const registerSupervisor = (anchor) => {
11063
+ if (!anchor) return;
11064
+ const coarseKey = `${anchor.pid}:`;
11065
+ if (anchor.startTime) {
11066
+ supervisors.delete(coarseKey);
11067
+ supervisors.set(`${anchor.pid}:${anchor.startTime}`, anchor);
11068
+ return;
11069
+ }
11070
+ for (const existing of supervisors.values()) {
11071
+ if (existing.pid === anchor.pid && existing.startTime) return;
11072
+ }
11073
+ supervisors.set(coarseKey, anchor);
11074
+ };
11075
+ {
11076
+ const rawPid = process.env.PIE_SUPERVISOR_PID?.trim();
11077
+ if (rawPid && /^\d+$/.test(rawPid)) {
11078
+ const pid = Number(rawPid);
11079
+ if (Number.isSafeInteger(pid) && pid > 0) {
11080
+ const startTime = process.env.PIE_SUPERVISOR_START_TIME?.trim();
11081
+ registerSupervisor(startTime ? { pid, startTime } : { pid });
11082
+ }
11083
+ }
11084
+ }
11085
+ const unknownGraceMs = options.unknownGraceMs ?? BROKER_DRAIN_MAX_MS;
10748
11086
  let active = 0;
10749
11087
  let queued = 0;
10750
11088
  let lastActivity = Date.now();
@@ -10825,6 +11163,7 @@ async function startBroker(options = {}) {
10825
11163
  if (entry.finished) {
10826
11164
  if (state === "done") {
10827
11165
  entry.state = "done";
11166
+ entry.unknownSince = void 0;
10828
11167
  entry.result = result;
10829
11168
  entry.error = void 0;
10830
11169
  if (result !== void 0) collectStateIds(result, knownStateIds);
@@ -10838,6 +11177,7 @@ async function startBroker(options = {}) {
10838
11177
  }
10839
11178
  entry.finished = true;
10840
11179
  entry.state = state;
11180
+ entry.unknownSince = state === "unknown" ? Date.now() : void 0;
10841
11181
  entry.result = result;
10842
11182
  entry.error = error;
10843
11183
  if (result !== void 0) collectStateIds(result, knownStateIds);
@@ -10871,6 +11211,8 @@ async function startBroker(options = {}) {
10871
11211
  if (currentState === "unknown" || currentState === "error") return;
10872
11212
  const message = error instanceof Error ? error.message : String(error);
10873
11213
  finish(entry, "error", void 0, { code: "engine_error", message, dispatched: entry.dispatched });
11214
+ } finally {
11215
+ entry.settled = true;
10874
11216
  }
10875
11217
  };
10876
11218
  const handleEngineRequest = async (request, socket) => {
@@ -10920,6 +11262,7 @@ async function startBroker(options = {}) {
10920
11262
  state: "queued",
10921
11263
  dispatched: false,
10922
11264
  finished: false,
11265
+ settled: false,
10923
11266
  slotHeld: false,
10924
11267
  controller: new AbortController(),
10925
11268
  fingerprint,
@@ -11018,6 +11361,7 @@ async function startBroker(options = {}) {
11018
11361
  const decoder = new FrameDecoder();
11019
11362
  let helloOk = false;
11020
11363
  let helloRejected = false;
11364
+ let socketSupervisor;
11021
11365
  const drainingConnection = stopping || drainRequested;
11022
11366
  if (drainingConnection) {
11023
11367
  send(socket, {
@@ -11083,8 +11427,9 @@ async function startBroker(options = {}) {
11083
11427
  continue;
11084
11428
  }
11085
11429
  try {
11086
- validateHello(frame);
11430
+ const hello = validateHello(frame);
11087
11431
  helloOk = true;
11432
+ socketSupervisor = hello.supervisor;
11088
11433
  send(socket, {
11089
11434
  type: "hello",
11090
11435
  ok: true,
@@ -11128,7 +11473,12 @@ async function startBroker(options = {}) {
11128
11473
  });
11129
11474
  continue;
11130
11475
  }
11131
- void (request.command === "status" || request.command === "stop" || request.command === "permissions" || request.command === "debug_restart_helper" ? handleControl(request, socket) : handleEngineRequest(request, socket));
11476
+ const isControl = request.command === "status" || request.command === "stop" || request.command === "permissions" || request.command === "debug_restart_helper";
11477
+ if (!isControl) {
11478
+ if (socketSupervisor) registerSupervisor(socketSupervisor);
11479
+ else hasUnsupervisedCaller = true;
11480
+ }
11481
+ void (isControl ? handleControl(request, socket) : handleEngineRequest(request, socket));
11132
11482
  }
11133
11483
  });
11134
11484
  socket.on("close", () => {
@@ -11225,7 +11575,9 @@ async function startBroker(options = {}) {
11225
11575
  }
11226
11576
  }
11227
11577
  const deadline = Date.now() + BROKER_DRAIN_MAX_MS;
11228
- while ((permissionSetupInFlight || [...entries.values()].some((entry) => entry.state === "running" || entry.state === "unknown")) && Date.now() < deadline) {
11578
+ while ((permissionSetupInFlight || [...entries.values()].some(
11579
+ (entry) => entry.state === "running" || entry.state === "unknown" && !entry.settled
11580
+ )) && Date.now() < deadline) {
11229
11581
  await sleep3(50);
11230
11582
  }
11231
11583
  persistManifest();
@@ -11292,13 +11644,43 @@ async function startBroker(options = {}) {
11292
11644
  await shutdown("close");
11293
11645
  }
11294
11646
  };
11647
+ const checkIntervalMs = Math.min(
11648
+ options.supervisorCheckMs ?? 15e3,
11649
+ Math.min(6e4, Math.max(1e3, Math.floor(idleExitMs / 4)))
11650
+ );
11651
+ let lifecycleCheckInFlight = false;
11295
11652
  idleTimer = setInterval(() => {
11296
- if (stopping) return;
11297
- const uncertain = [...entries.values()].some((entry) => entry.state === "running" || entry.state === "unknown" || entry.state === "queued");
11298
- if (uncertain || permissionSetupInFlight) return;
11299
- if (Date.now() - lastActivity < idleExitMs) return;
11300
- void shutdown("idle");
11301
- }, Math.min(6e4, Math.max(1e3, Math.floor(idleExitMs / 4))));
11653
+ if (stopping || lifecycleCheckInFlight) return;
11654
+ lifecycleCheckInFlight = true;
11655
+ void (async () => {
11656
+ try {
11657
+ if (stopping) return;
11658
+ const now = Date.now();
11659
+ const busy = [...entries.values()].some(
11660
+ (entry) => entry.state === "running" || entry.state === "queued" || entry.state === "unknown" && !entry.settled && now - (entry.unknownSince ?? entry.startedAt) < unknownGraceMs
11661
+ );
11662
+ if (busy || permissionSetupInFlight) return;
11663
+ if (!hasUnsupervisedCaller && supervisors.size > 0) {
11664
+ const snapshot = [...supervisors.entries()];
11665
+ for (const [key, anchor] of snapshot) {
11666
+ if (stopping) return;
11667
+ if (await isSupervisorGoneAsync(anchor)) {
11668
+ if (supervisors.get(key) === anchor) supervisors.delete(key);
11669
+ }
11670
+ }
11671
+ if (stopping) return;
11672
+ if (!hasUnsupervisedCaller && supervisors.size === 0) {
11673
+ void shutdown("supervisors_gone");
11674
+ return;
11675
+ }
11676
+ }
11677
+ if (Date.now() - lastActivity < idleExitMs) return;
11678
+ void shutdown("idle");
11679
+ } finally {
11680
+ lifecycleCheckInFlight = false;
11681
+ }
11682
+ })();
11683
+ }, Math.max(50, checkIntervalMs));
11302
11684
  idleTimer.unref?.();
11303
11685
  return statusHandle;
11304
11686
  }