@copylee/dsh-computer-use 0.12.0 → 0.13.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.
package/lib/index.js CHANGED
@@ -6,7 +6,7 @@ import { setTimeout as setTimeout$1 } from "node:timers/promises";
6
6
  import { arch, homedir, platform, release, tmpdir } from "node:os";
7
7
  import { execFile, spawn } from "node:child_process";
8
8
  import { chmod, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
9
- import { dirname, join } from "node:path";
9
+ import { basename, dirname, join } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { Worker } from "node:worker_threads";
12
12
  import * as zlib from "node:zlib";
@@ -164,17 +164,22 @@ function isTransientShell(win) {
164
164
  function isHostWindow(win) {
165
165
  return HOST_EXES.includes(win.exe.toLowerCase());
166
166
  }
167
+ /** Split a normalized name into word tokens on whitespace and common exe separators. */
168
+ function nameTokens(value) {
169
+ return value.split(/[\s._-]+/).filter(Boolean);
170
+ }
167
171
  /** Does a granted (or requested) app name refer to this window? */
168
172
  function appMatches(name, win) {
169
173
  const g = normalizeApp(name);
170
174
  const exe = exeBase(win);
171
175
  if (g === "" || exe === "") return false;
172
- const compactG = g.replace(/\s/g, "");
173
- if (exe === g || exe === compactG) return true;
176
+ const compactG = g.replace(/[\s._-]+/g, "");
177
+ const compactExe = exe.replace(/[\s._-]+/g, "");
178
+ if (exe === g || compactExe === compactG) return true;
174
179
  const aliases = ALIASES[g];
175
180
  if (aliases?.includes(exe) && exe !== "applicationframehost") return true;
176
- if (exe.length >= 3 && compactG.includes(exe)) return true;
177
- if (compactG.length >= 3 && exe.includes(compactG)) return true;
181
+ const gWords = nameTokens(g);
182
+ if (gWords.length > 1 && exe.length >= 4 && gWords.includes(exe)) return true;
178
183
  if (exe === "applicationframehost") {
179
184
  const title = win.title.toLowerCase();
180
185
  return title.includes(g) || (aliases?.some((alias) => title.includes(alias)) ?? false);
@@ -229,6 +234,20 @@ var AccessControl = class {
229
234
  this.grants.delete(session);
230
235
  }
231
236
  /**
237
+ * Why reading/observing `win` is refused, or undefined when allowed.
238
+ * Always blocks DeepSeek Harness and blocked apps (password managers, user-blocked apps).
239
+ * When `requireGrant` is true (e.g. CDP DOM inspection or clipboard read), also enforces
240
+ * per-app session grants.
241
+ */
242
+ readDenial(session, win, mode, blocked, action, requireGrant = false) {
243
+ if (!win || win.exe === "") return void 0;
244
+ const label = `${win.exe}${win.title ? ` ("${win.title.slice(0, 60)}")` : ""}`;
245
+ if (isHostWindow(win)) return `Refused to ${action} ${label}: that is the DeepSeek Harness window itself.`;
246
+ if ([...DEFAULT_BLOCKED, ...blocked].some((name) => appMatches(name, win))) return `Refused to ${action} ${label}: this app is blocked for computer use in the plugin settings.`;
247
+ if (!requireGrant || mode === "allow-all" || this.isGranted(session, win)) return void 0;
248
+ return `Refused to ${action} ${label}: the app is not granted for this session. Call request_access with this app's name first (granted so far: ${this.granted(session).join(", ") || "none"}).`;
249
+ }
250
+ /**
232
251
  * Why input may not go to `win`, or undefined when it may. `action` is a
233
252
  * short verb for the message ("click", "type into").
234
253
  */
@@ -584,6 +603,148 @@ function parseModifiers(text) {
584
603
  return parseKeys(text.replace(/\s+/g, "")).flat();
585
604
  }
586
605
  //#endregion
606
+ //#region lib/types/lease.js
607
+ /**
608
+ * Single-machine desktop control lease: prevents concurrent sessions / subagents
609
+ * from fighting over the mouse, keyboard, or shared Computer state (`lastMarks`,
610
+ * `seen`, `lastShot`). A session acquires the lease while acting and releases it
611
+ * immediately when its turn ends (or after `idleExpiryMs` of inactivity).
612
+ */
613
+ var DesktopLease = class {
614
+ idleExpiryMs;
615
+ waitTimeoutMs;
616
+ holder;
617
+ waiters = [];
618
+ tail = Promise.resolve();
619
+ constructor(idleExpiryMs = 15e3, waitTimeoutMs = 4e3) {
620
+ this.idleExpiryMs = idleExpiryMs;
621
+ this.waitTimeoutMs = waitTimeoutMs;
622
+ }
623
+ expireIfIdle(now = Date.now()) {
624
+ if (this.holder && this.holder.activeCalls === 0 && now - this.holder.lastActiveAt >= this.idleExpiryMs) {
625
+ this.holder = void 0;
626
+ this.wakeNext();
627
+ }
628
+ }
629
+ /** Current active lease holder (if not expired). */
630
+ current() {
631
+ this.expireIfIdle();
632
+ return this.holder ? { ...this.holder } : void 0;
633
+ }
634
+ /** Explicitly release the lease held by `session` (e.g. when a turn finishes). */
635
+ release(session) {
636
+ if (!this.holder || this.holder.session !== session) return;
637
+ if (this.holder.activeCalls > 0) return;
638
+ this.holder = void 0;
639
+ this.wakeNext();
640
+ }
641
+ /** Acquire the desktop lease for `session`, waiting briefly if another session is finishing up. */
642
+ async acquire(session, signal) {
643
+ if (signal?.aborted) throw new Error("Cancelled.");
644
+ const now = Date.now();
645
+ this.expireIfIdle(now);
646
+ if (!this.holder) {
647
+ this.holder = {
648
+ session,
649
+ activeCalls: 1,
650
+ acquiredAt: now,
651
+ lastActiveAt: now
652
+ };
653
+ return;
654
+ }
655
+ if (this.holder.session === session) {
656
+ this.holder.activeCalls++;
657
+ this.holder.lastActiveAt = now;
658
+ return;
659
+ }
660
+ const remainingIdle = this.holder.activeCalls === 0 ? Math.max(0, this.idleExpiryMs - (now - this.holder.lastActiveAt)) : this.waitTimeoutMs;
661
+ const waitMs = Math.min(this.waitTimeoutMs, Math.max(50, remainingIdle));
662
+ await new Promise((resolve, reject) => {
663
+ const cleanup = (w) => {
664
+ clearTimeout(w.timer);
665
+ if (w.signal && w.onAbort) w.signal.removeEventListener("abort", w.onAbort);
666
+ const idx = this.waiters.indexOf(w);
667
+ if (idx >= 0) this.waiters.splice(idx, 1);
668
+ };
669
+ const waiter = {
670
+ session,
671
+ resolve: () => {
672
+ cleanup(waiter);
673
+ resolve();
674
+ },
675
+ reject: (err) => {
676
+ cleanup(waiter);
677
+ reject(err);
678
+ },
679
+ timer: setTimeout(() => {
680
+ this.expireIfIdle();
681
+ if (!this.holder || this.holder.session === session) {
682
+ const t = Date.now();
683
+ this.holder = this.holder ? {
684
+ ...this.holder,
685
+ activeCalls: this.holder.activeCalls + 1,
686
+ lastActiveAt: t
687
+ } : {
688
+ session,
689
+ activeCalls: 1,
690
+ acquiredAt: t,
691
+ lastActiveAt: t
692
+ };
693
+ waiter.resolve();
694
+ return;
695
+ }
696
+ waiter.reject(/* @__PURE__ */ new Error(`DESKTOP_BUSY: Session "${this.holder.session}" is currently controlling the desktop. Wait for it to finish before acting.`));
697
+ }, waitMs),
698
+ ...signal ? { signal } : {}
699
+ };
700
+ if (signal) {
701
+ waiter.onAbort = () => waiter.reject(/* @__PURE__ */ new Error("Cancelled."));
702
+ signal.addEventListener("abort", waiter.onAbort, { once: true });
703
+ }
704
+ this.waiters.push(waiter);
705
+ });
706
+ }
707
+ /** Run `fn` exclusively under `session`'s desktop lease, serializing overlapping calls. */
708
+ async withLease(session, signal, fn) {
709
+ await this.acquire(session, signal);
710
+ const run = async () => {
711
+ try {
712
+ if (signal?.aborted) throw new Error("Cancelled.");
713
+ return await fn();
714
+ } finally {
715
+ if (this.holder && this.holder.session === session) {
716
+ this.holder.activeCalls = Math.max(0, this.holder.activeCalls - 1);
717
+ this.holder.lastActiveAt = Date.now();
718
+ if (this.holder.activeCalls === 0) this.expireIfIdle();
719
+ }
720
+ }
721
+ };
722
+ const prev = this.tail;
723
+ let releaseTail;
724
+ this.tail = new Promise((r) => {
725
+ releaseTail = r;
726
+ });
727
+ await prev;
728
+ try {
729
+ return await run();
730
+ } finally {
731
+ releaseTail();
732
+ }
733
+ }
734
+ wakeNext() {
735
+ if (this.holder || this.waiters.length === 0) return;
736
+ const next = this.waiters.shift();
737
+ const now = Date.now();
738
+ this.holder = {
739
+ session: next.session,
740
+ activeCalls: 1,
741
+ acquiredAt: now,
742
+ lastActiveAt: now
743
+ };
744
+ next.resolve();
745
+ }
746
+ };
747
+ //#endregion
587
748
  //#region lib/types/target.js
588
749
  /**
589
750
  * Finding a control by what it says instead of where it is. A batch can then
@@ -789,6 +950,107 @@ function typingPieces(text, size = 60) {
789
950
  return out;
790
951
  }
791
952
  //#endregion
953
+ //#region lib/types/ui-diff.js
954
+ const MAX_WINDOWS = 16;
955
+ const MAX_AGE_MS = 12e4;
956
+ function baseKey(el) {
957
+ if (el.automationId && el.automationId.trim() !== "") return `id:${el.role}:${el.automationId.trim()}`;
958
+ const bx = Math.round(el.x / 32);
959
+ const by = Math.round(el.y / 32);
960
+ return `rn:${el.role}:${el.name}:${bx}:${by}`;
961
+ }
962
+ function indexElements(elements) {
963
+ const counts = /* @__PURE__ */ new Map();
964
+ const out = /* @__PURE__ */ new Map();
965
+ for (const el of elements) {
966
+ const raw = baseKey(el);
967
+ const occ = counts.get(raw) ?? 0;
968
+ counts.set(raw, occ + 1);
969
+ out.set(occ === 0 ? raw : `${raw}#${occ}`, el);
970
+ }
971
+ return out;
972
+ }
973
+ function describeChanges(prev, next) {
974
+ const diffs = [];
975
+ if (prev.name !== next.name) diffs.push(`name: "${prev.name.slice(0, 30)}" -> "${next.name.slice(0, 30)}"`);
976
+ if (prev.value !== next.value) diffs.push(`value: "${String(prev.value ?? "").slice(0, 30)}" -> "${String(next.value ?? "").slice(0, 30)}"`);
977
+ if (prev.checked !== next.checked) diffs.push(`${prev.checked ? "checked" : "unchecked"} -> ${next.checked ? "checked" : "unchecked"}`);
978
+ if (prev.disabled !== next.disabled) diffs.push(next.disabled ? "disabled" : "enabled");
979
+ if (Math.abs(prev.x - next.x) > 8 || Math.abs(prev.y - next.y) > 8 || Math.abs(prev.width - next.width) > 8 || Math.abs(prev.height - next.height) > 8) diffs.push("moved");
980
+ return diffs;
981
+ }
982
+ var UiDiffTracker = class {
983
+ snapshots = /* @__PURE__ */ new Map();
984
+ /** Record a full snapshot as the latest baseline for `hwnd` without computing a diff. */
985
+ record(hwnd, title, elements) {
986
+ this.store(hwnd, title, indexElements(elements));
987
+ }
988
+ /** Compute the incremental delta against the last snapshot of `hwnd`, updating the stored baseline. */
989
+ diff(hwnd, title, elements) {
990
+ const now = Date.now();
991
+ const nextKeyed = indexElements(elements);
992
+ const prev = this.snapshots.get(hwnd);
993
+ if (!prev || now - prev.at > MAX_AGE_MS) {
994
+ this.store(hwnd, title, nextKeyed, now);
995
+ return {
996
+ isBaseline: true,
997
+ titleChanged: false,
998
+ added: [...elements],
999
+ changed: [],
1000
+ removed: [],
1001
+ unchangedCount: 0
1002
+ };
1003
+ }
1004
+ const added = [];
1005
+ const changed = [];
1006
+ const removed = [];
1007
+ let unchangedCount = 0;
1008
+ for (const [key, nextEl] of nextKeyed) {
1009
+ const prevEl = prev.keyed.get(key);
1010
+ if (!prevEl) {
1011
+ added.push(nextEl);
1012
+ continue;
1013
+ }
1014
+ const diffs = describeChanges(prevEl, nextEl);
1015
+ if (diffs.length > 0) changed.push({
1016
+ element: nextEl,
1017
+ changes: diffs
1018
+ });
1019
+ else unchangedCount++;
1020
+ }
1021
+ for (const [key, prevEl] of prev.keyed) if (!nextKeyed.has(key)) removed.push(prevEl);
1022
+ const titleChanged = prev.title !== title;
1023
+ const previousTitle = titleChanged ? prev.title : void 0;
1024
+ this.store(hwnd, title, nextKeyed, now);
1025
+ return {
1026
+ isBaseline: false,
1027
+ titleChanged,
1028
+ ...previousTitle !== void 0 ? { previousTitle } : {},
1029
+ added,
1030
+ changed,
1031
+ removed,
1032
+ unchangedCount
1033
+ };
1034
+ }
1035
+ clear(hwnd) {
1036
+ if (hwnd === void 0) this.snapshots.clear();
1037
+ else this.snapshots.delete(hwnd);
1038
+ }
1039
+ store(hwnd, title, keyed, now = Date.now()) {
1040
+ this.snapshots.delete(hwnd);
1041
+ this.snapshots.set(hwnd, {
1042
+ at: now,
1043
+ title,
1044
+ keyed
1045
+ });
1046
+ while (this.snapshots.size > MAX_WINDOWS) {
1047
+ const oldest = this.snapshots.keys().next().value;
1048
+ if (oldest !== void 0) this.snapshots.delete(oldest);
1049
+ else break;
1050
+ }
1051
+ }
1052
+ };
1053
+ //#endregion
792
1054
  //#region lib/types/computer.js
793
1055
  /**
794
1056
  * The computer-use engine behind the tools: one coordinate space (the latest
@@ -870,11 +1132,16 @@ var Computer = class Computer {
870
1132
  clickHistory = [];
871
1133
  /** The agent that last wrote the clipboard; when it goes idle the user's clipboard comes back. */
872
1134
  clipboardAgent;
873
- constructor(helper, access, overlay, settings) {
1135
+ /** Single-machine desktop control lease preventing concurrent sessions from colliding. */
1136
+ lease;
1137
+ /** Per-window UI Automation tree snapshot tracker for incremental `diff: true` queries. */
1138
+ uiDiff = new UiDiffTracker();
1139
+ constructor(helper, access, overlay, settings, lease = new DesktopLease()) {
874
1140
  this.helper = helper;
875
1141
  this.access = access;
876
1142
  this.overlay = overlay;
877
1143
  this.settings = settings;
1144
+ this.lease = lease;
878
1145
  overlay.onStart = () => this.noteStart();
879
1146
  }
880
1147
  async refreshDisplays() {
@@ -1009,7 +1276,7 @@ var Computer = class Computer {
1009
1276
  seen;
1010
1277
  /** Snapshot of the foreground window geometry captured during the latest screenshot/marks look. */
1011
1278
  lastShotWindow;
1012
- /** Most recent Set-of-Marks element list so `target: "#12"` resolves directly. */
1279
+ /** Most recent Set-of-Marks element list so `target: "#12"` resolves directly until the screen mutates. */
1013
1280
  lastMarks;
1014
1281
  /** The latest foreground window that was not DeepSeek Harness itself. */
1015
1282
  lastTarget;
@@ -1017,6 +1284,11 @@ var Computer = class Computer {
1017
1284
  resetLook() {
1018
1285
  this.seen = void 0;
1019
1286
  this.lastShotWindow = void 0;
1287
+ this.lastMarks = void 0;
1288
+ }
1289
+ /** Drop cached Set-of-Marks indices whenever the screen or foreground state mutates. */
1290
+ invalidateMarks() {
1291
+ this.lastMarks = void 0;
1020
1292
  }
1021
1293
  async remember() {
1022
1294
  const now = await this.foreground().catch(() => void 0);
@@ -1187,6 +1459,12 @@ var Computer = class Computer {
1187
1459
  if (!win) return "Foreground window: none (desktop).";
1188
1460
  return `Foreground window: ${win.exe} — "${win.title.slice(0, 80)}".`;
1189
1461
  }
1462
+ /** Enforce access control for read/observe surfaces (UIA, OCR, Set-of-Marks, CDP, clipboard). */
1463
+ assertReadable(call, win, verb = "read", requireGrant = false) {
1464
+ const s = this.settings();
1465
+ const reason = this.access.readDenial(call.session, win, s.accessMode, s.blockedApps, verb, requireGrant);
1466
+ if (reason) throw new Error(reason);
1467
+ }
1190
1468
  async assertAllowed(call, win, verb) {
1191
1469
  const s = this.settings();
1192
1470
  const reason = this.access.denial(call.session, win, s.accessMode, s.blockedApps, verb);
@@ -1318,12 +1596,22 @@ var Computer = class Computer {
1318
1596
  height: shot.height
1319
1597
  }
1320
1598
  };
1321
- if (typeof raw.hwnd === "number") this.lastMarks = {
1322
- hwnd: raw.hwnd,
1323
- at: Date.now(),
1324
- elements
1325
- };
1326
1599
  await this.remember();
1600
+ const winSnap = this.lastShotWindow;
1601
+ const markHwnd = typeof raw.hwnd === "number" ? raw.hwnd : winSnap?.hwnd;
1602
+ if (typeof markHwnd === "number") {
1603
+ const sameWin = winSnap && winSnap.hwnd === markHwnd;
1604
+ this.lastMarks = {
1605
+ hwnd: markHwnd,
1606
+ title: sameWin ? winSnap.title : String(raw.title ?? ""),
1607
+ x: sameWin ? winSnap.x : 0,
1608
+ y: sameWin ? winSnap.y : 0,
1609
+ width: sameWin ? winSnap.width : 0,
1610
+ height: sameWin ? winSnap.height : 0,
1611
+ at: Date.now(),
1612
+ elements
1613
+ };
1614
+ }
1327
1615
  return {
1328
1616
  window: raw,
1329
1617
  elements,
@@ -1387,17 +1675,29 @@ var Computer = class Computer {
1387
1675
  if (signal.aborted) throw new Error("Cancelled.");
1388
1676
  const window = await this.foreground();
1389
1677
  if (!window) throw new Error("No foreground window for the named target.");
1390
- if (markMatch && this.lastMarks && this.lastMarks.hwnd === window.hwnd && Date.now() - this.lastMarks.at <= 12e4) {
1678
+ if (markMatch) {
1391
1679
  const idx = Number.parseInt(markMatch[1], 10);
1392
- const marked = this.lastMarks.elements.find((el, i) => (el.mark ?? i + 1) === idx);
1393
- if (marked) return {
1394
- point: {
1395
- x: Math.round(marked.x + marked.width / 2),
1396
- y: Math.round(marked.y + marked.height / 2)
1397
- },
1398
- element: marked,
1399
- window
1400
- };
1680
+ const snap = this.lastMarks;
1681
+ if (snap) {
1682
+ const expired = Date.now() - snap.at > 45e3;
1683
+ const moved = snap.width > 0 && snap.height > 0 && (Math.abs(window.x - snap.x) > 16 || Math.abs(window.y - snap.y) > 16 || Math.abs(window.width - snap.width) > 16 || Math.abs(window.height - snap.height) > 16);
1684
+ const userIntervened = this.overlay.userTypedSince?.(snap.at) === true || this.overlay.hasUserActions?.() === true;
1685
+ if (snap.hwnd !== window.hwnd || snap.title !== window.title || moved || expired || userIntervened) {
1686
+ this.lastMarks = void 0;
1687
+ throw new Error(`STALE_MARKS: Set-of-Marks #${idx} is no longer valid because the window or screen state changed. Call ui_elements({ marks: true }) again to refresh marks.`);
1688
+ }
1689
+ const marked = snap.elements.find((el, i) => (el.mark ?? i + 1) === idx);
1690
+ if (marked) return {
1691
+ point: {
1692
+ x: Math.round(marked.x + marked.width / 2),
1693
+ y: Math.round(marked.y + marked.height / 2)
1694
+ },
1695
+ element: marked,
1696
+ window
1697
+ };
1698
+ throw new Error(`No Set-of-Marks control #${idx} in the latest marks snapshot (1..${snap.elements.length}).`);
1699
+ }
1700
+ throw new Error(`STALE_MARKS: No active Set-of-Marks snapshot for #${idx} (marks expire after any action or window change). Call ui_elements({ marks: true }) first.`);
1401
1701
  }
1402
1702
  const match = await this.find(target, window.hwnd);
1403
1703
  if (match.kind === "found") {
@@ -1617,188 +1917,208 @@ var Computer = class Computer {
1617
1917
  }
1618
1918
  if (INPUT.has(action)) this.seen = void 0;
1619
1919
  if (KEYBOARD.has(action)) await this.refocusFromHost();
1620
- switch (action) {
1621
- case "screenshot": {
1622
- const drained = s.reportUserActions ? this.overlay.drainUserActions?.() ?? [] : [];
1623
- const userNotes = await this.formatUserActions(drained);
1624
- const shot = await this.takeScreenshot({
1625
- force: input.force === true || drained.length > 0,
1626
- ...input.detail ? { detail: input.detail } : {}
1627
- });
1628
- if (shot === "unchanged") return { text: `Screenshot unchanged for display ${this.currentIndex}: the screen looks identical to your previous screenshot (pass force: true to capture anyway).${userNotes}` };
1629
- return {
1630
- text: `Screenshot ${shot.width}x${shot.height} of display ${this.currentIndex}.${userNotes}`,
1631
- image: shot
1632
- };
1633
- }
1634
- case "zoom": {
1635
- const shot = await this.zoom(input.region, {
1636
- force: input.force === true,
1637
- ...input.detail ? { detail: input.detail } : {}
1638
- });
1639
- if (shot === "unchanged") return { text: `Zoomed view of region [${(input.region ?? []).join(", ")}] is unchanged from your previous zoom of this region (pass force: true to capture anyway).` };
1640
- return {
1641
- text: `Zoomed view of region [${(input.region ?? []).join(", ")}] at ${shot.width}x${shot.height}. Pixel positions in this image are NOT screen coordinates; keep using full-screenshot coordinates for actions.`,
1642
- image: shot
1643
- };
1644
- }
1645
- case "cursor_position": {
1646
- const p = await this.toModel(await this.cursor());
1647
- return { text: `Cursor at (${p.x}, ${p.y})${p.offscreen ? " — on another display" : ""}.` };
1648
- }
1649
- case "wait": {
1650
- if (input.until) return { text: await this.waitUntil(input, call.signal) };
1651
- const seconds = Math.min(30, Math.max(0, Number(input.duration ?? 1) || 0));
1652
- const waited = await this.waitForQuiet(seconds * 1e3, call.signal);
1653
- return { text: waited < seconds * 1e3 - 200 ? `Waited ${(waited / 1e3).toFixed(1)}s (the screen settled early).` : `Waited ${seconds}s.` };
1654
- }
1655
- case "mouse_move": {
1656
- const { point: p, label } = await this.aim(input, call);
1657
- if (!p) throw new Error("mouse_move needs coordinate or target.");
1658
- await this.helper.call("move", { ...p });
1659
- return { text: `Moved the mouse${label.replace(/^ (at|on)/, " to")}.` };
1660
- }
1661
- case "left_click":
1662
- case "right_click":
1663
- case "middle_click":
1664
- case "double_click":
1665
- case "triple_click": {
1666
- const { point, label, named } = await this.aim(input, call);
1667
- let p = point;
1668
- const hitWin = !named ? await this.checkPointer(call, p, "click") : void 0;
1669
- const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
1670
- const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
1671
- const modifiers = parseModifiers(input.modifiers ?? input.text);
1672
- if (action === "left_click" && named && modifiers.length === 0) {
1673
- const semantic = named.element.role === "Edit" || named.element.editable ? "focus" : "invoke";
1674
- if (await this.semanticAction(call, named, semantic)) return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
1920
+ try {
1921
+ switch (action) {
1922
+ case "screenshot": {
1923
+ const drained = s.reportUserActions ? this.overlay.drainUserActions?.() ?? [] : [];
1924
+ const userNotes = await this.formatUserActions(drained);
1925
+ const shot = await this.takeScreenshot({
1926
+ force: input.force === true || drained.length > 0,
1927
+ ...input.detail ? { detail: input.detail } : {}
1928
+ });
1929
+ if (shot === "unchanged") return { text: `Screenshot unchanged for display ${this.currentIndex}: the screen looks identical to your previous screenshot (pass force: true to capture anyway).${userNotes}` };
1930
+ return {
1931
+ text: `Screenshot ${shot.width}x${shot.height} of display ${this.currentIndex}.${userNotes}`,
1932
+ image: shot
1933
+ };
1675
1934
  }
1676
- if (action === "left_click" && !named && p && modifiers.length === 0 && s.elementFirstClick) {
1677
- const hit = await this.helper.call("ui_point_click", {
1678
- x: p.x,
1679
- y: p.y,
1680
- ...hitWin ? { hwnd: hitWin.hwnd } : {}
1681
- }, 2e3).catch(() => null);
1682
- if (hit?.ok) {
1683
- const repeat = this.noteClick(p);
1684
- const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
1685
- return { text: `Invoked ${hit.name ? `${hit.role || "control"} "${hit.name.slice(0, 40)}"` : hit.role || "control"}${label} in background (${hit.mechanism || "uia"}).${repeatHint}` };
1686
- }
1935
+ case "zoom": {
1936
+ const shot = await this.zoom(input.region, {
1937
+ force: input.force === true,
1938
+ ...input.detail ? { detail: input.detail } : {}
1939
+ });
1940
+ if (shot === "unchanged") return { text: `Zoomed view of region [${(input.region ?? []).join(", ")}] is unchanged from your previous zoom of this region (pass force: true to capture anyway).` };
1941
+ return {
1942
+ text: `Zoomed view of region [${(input.region ?? []).join(", ")}] at ${shot.width}x${shot.height}. Pixel positions in this image are NOT screen coordinates; keep using full-screenshot coordinates for actions.`,
1943
+ image: shot
1944
+ };
1687
1945
  }
1688
- if (named) p = await this.namedClickPoint(call, input.target, named);
1689
- const labelCoord = input.coordinate ? {
1690
- labelX: Math.round(input.coordinate[0]),
1691
- labelY: Math.round(input.coordinate[1])
1692
- } : p ? await this.toModel(p).then((m) => ({
1693
- labelX: m.x,
1694
- labelY: m.y
1695
- })) : {};
1696
- const clickRes = await this.helper.call("click", {
1697
- ...p ?? {},
1698
- ...labelCoord,
1699
- button,
1700
- count,
1701
- modifiers,
1702
- ...s.restorePointer ? { restorePointer: true } : {}
1703
- });
1704
- const clickedAt = p ?? (typeof clickRes?.x === "number" && typeof clickRes?.y === "number" ? {
1705
- x: clickRes.x,
1706
- y: clickRes.y
1707
- } : void 0);
1708
- const repeat = this.noteClick(clickedAt, clickRes?.repeat);
1709
- const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
1710
- return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.${repeatHint}` };
1711
- }
1712
- case "left_click_drag": {
1713
- const from = await this.point(input.start_coordinate, "start_coordinate");
1714
- const to = await this.point(input.coordinate);
1715
- await this.checkPointer(call, from, "drag in");
1716
- if (this.settings().harnessUrl) await this.checkPointer(call, to, "drag to");
1717
- await this.helper.call("drag", {
1718
- x1: from.x,
1719
- y1: from.y,
1720
- x2: to.x,
1721
- y2: to.y,
1722
- button: "left"
1723
- });
1724
- return { text: `Dragged from (${input.start_coordinate.join(", ")}) to (${input.coordinate.join(", ")}).` };
1725
- }
1726
- case "left_mouse_down":
1727
- case "left_mouse_up": {
1728
- const p = input.coordinate ? await this.point(input.coordinate) : void 0;
1729
- if (action === "left_mouse_down") {
1730
- const window = await this.windowAt(p ?? await this.cursor());
1731
- if (window && this.overlay.isRememberedWebWindow(window)) throw new Error("Use a single drag action within the work page instead of holding the mouse button in this browser window.");
1732
- await this.assertAllowed(call, window, "press the mouse in");
1946
+ case "cursor_position": {
1947
+ const p = await this.toModel(await this.cursor());
1948
+ return { text: `Cursor at (${p.x}, ${p.y})${p.offscreen ? " — on another display" : ""}.` };
1733
1949
  }
1734
- await this.helper.call("button", {
1735
- ...p ?? {},
1736
- button: "left",
1737
- up: action === "left_mouse_up"
1738
- });
1739
- this.heldButton = action === "left_mouse_down";
1740
- return { text: `Left button ${action === "left_mouse_down" ? "down" : "up"}.` };
1741
- }
1742
- case "scroll": {
1743
- const { point: p } = await this.aim(input, call);
1744
- await this.checkPointer(call, p, "scroll");
1745
- const amount = Math.max(1, Math.min(30, Math.round(input.scroll_amount ?? 3)));
1746
- const direction = input.scroll_direction ?? "down";
1747
- const dy = direction === "down" ? amount : direction === "up" ? -amount : 0;
1748
- const dx = direction === "right" ? amount : direction === "left" ? -amount : 0;
1749
- await this.helper.call("scroll", {
1750
- ...p ?? {},
1751
- dx,
1752
- dy,
1753
- modifiers: parseModifiers(input.modifiers)
1754
- });
1755
- return { text: `Scrolled ${direction} ${amount}.` };
1756
- }
1757
- case "type": {
1758
- const text = input.text ?? "";
1759
- if (text === "") throw new Error("type needs text.");
1760
- let into = "";
1761
- if (input.target || input.coordinate) {
1950
+ case "wait": {
1951
+ if (input.until) return { text: await this.waitUntil(input, call.signal) };
1952
+ const seconds = Math.min(30, Math.max(0, Number(input.duration ?? 1) || 0));
1953
+ const waited = await this.waitForQuiet(seconds * 1e3, call.signal);
1954
+ return { text: waited < seconds * 1e3 - 200 ? `Waited ${(waited / 1e3).toFixed(1)}s (the screen settled early).` : `Waited ${seconds}s.` };
1955
+ }
1956
+ case "mouse_move": {
1957
+ const { point: p, label } = await this.aim(input, call);
1958
+ if (!p) throw new Error("mouse_move needs coordinate or target.");
1959
+ await this.helper.call("move", { ...p });
1960
+ return { text: `Moved the mouse${label.replace(/^ (at|on)/, " to")}.` };
1961
+ }
1962
+ case "left_click":
1963
+ case "right_click":
1964
+ case "middle_click":
1965
+ case "double_click":
1966
+ case "triple_click": {
1762
1967
  const { point, label, named } = await this.aim(input, call);
1763
- if (s.protectPasswords && named?.element.password) throw new Error(`Refused to type into password field "${named.element.name || "password"}". Ask the user to enter the password themselves.`);
1764
1968
  let p = point;
1765
- const focused = named && await this.semanticAction(call, named, "focus");
1766
- if (!focused) {
1767
- if (named) p = await this.namedClickPoint(call, input.target, named);
1768
- else await this.checkPointer(call, p, "click");
1769
- await this.helper.call("click", {
1770
- ...p ?? {},
1771
- button: "left",
1772
- count: 1,
1773
- modifiers: []
1774
- });
1969
+ const hitWin = !named ? await this.checkPointer(call, p, "click") : void 0;
1970
+ const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
1971
+ const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
1972
+ const modifiers = parseModifiers(input.modifiers ?? input.text);
1973
+ if (action === "left_click" && named && modifiers.length === 0) {
1974
+ const semantic = named.element.role === "Edit" || named.element.editable ? "focus" : "invoke";
1975
+ if (await this.semanticAction(call, named, semantic)) return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
1775
1976
  }
1776
- await setTimeout$1(120, void 0, { signal: call.signal });
1777
- if (named) await this.checkNamed(call, named.window);
1778
- into = ` (${focused ? "focused" : "clicked"}${label} first)`;
1977
+ if (action === "left_click" && !named && p && modifiers.length === 0 && s.elementFirstClick) {
1978
+ let hit = null;
1979
+ let uncertainReason;
1980
+ try {
1981
+ hit = await this.helper.call("ui_point_click", {
1982
+ x: p.x,
1983
+ y: p.y,
1984
+ ...hitWin ? { hwnd: hitWin.hwnd } : {}
1985
+ }, 2e3);
1986
+ } catch (error) {
1987
+ uncertainReason = error instanceof Error ? error.message : String(error);
1988
+ }
1989
+ if (hit?.ok === true) {
1990
+ this.invalidateMarks();
1991
+ const repeat = this.noteClick(p);
1992
+ const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
1993
+ return { text: `Invoked ${hit.name ? `${hit.role || "control"} "${hit.name.slice(0, 40)}"` : hit.role || "control"}${label} in background (${hit.mechanism || "uia"}).${repeatHint}` };
1994
+ }
1995
+ if (uncertainReason !== void 0 || hit?.uncertain === true || hit !== null && typeof hit === "object" && hit.ok !== false) {
1996
+ this.invalidateMarks();
1997
+ return {
1998
+ text: `Uncertain: background semantic click${label} did not confirm whether it executed (${uncertainReason ?? hit?.reason ?? "background semantic click did not confirm completion"}). Physical click was NOT performed to avoid double-triggering; inspect the new screenshot before retrying.`,
1999
+ ...call.vision ? { image: await this.screenshot() } : {},
2000
+ skipped: true
2001
+ };
2002
+ }
2003
+ }
2004
+ if (named) p = await this.namedClickPoint(call, input.target, named);
2005
+ const labelCoord = input.coordinate ? {
2006
+ labelX: Math.round(input.coordinate[0]),
2007
+ labelY: Math.round(input.coordinate[1])
2008
+ } : p ? await this.toModel(p).then((m) => ({
2009
+ labelX: m.x,
2010
+ labelY: m.y
2011
+ })) : {};
2012
+ const clickRes = await this.helper.call("click", {
2013
+ ...p ?? {},
2014
+ ...labelCoord,
2015
+ button,
2016
+ count,
2017
+ modifiers,
2018
+ ...s.restorePointer ? { restorePointer: true } : {}
2019
+ });
2020
+ const clickedAt = p ?? (typeof clickRes?.x === "number" && typeof clickRes?.y === "number" ? {
2021
+ x: clickRes.x,
2022
+ y: clickRes.y
2023
+ } : void 0);
2024
+ const repeat = this.noteClick(clickedAt, clickRes?.repeat);
2025
+ const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
2026
+ return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.${repeatHint}` };
1779
2027
  }
1780
- await this.checkKeyboard(call, "type into");
1781
- if (s.protectPasswords) {
1782
- const pwd = await this.helper.call("password_focus", {}, 1500).catch(() => null);
1783
- if (pwd?.password) throw new Error(`Refused to type into a password input${pwd.name ? ` ("${pwd.name.slice(0, 40)}")` : ""}. Ask the user to enter the password themselves.`);
2028
+ case "left_click_drag": {
2029
+ const from = await this.point(input.start_coordinate, "start_coordinate");
2030
+ const to = await this.point(input.coordinate);
2031
+ await this.checkPointer(call, from, "drag in");
2032
+ if (this.settings().harnessUrl) await this.checkPointer(call, to, "drag to");
2033
+ await this.helper.call("drag", {
2034
+ x1: from.x,
2035
+ y1: from.y,
2036
+ x2: to.x,
2037
+ y2: to.y,
2038
+ button: "left"
2039
+ });
2040
+ return { text: `Dragged from (${input.start_coordinate.join(", ")}) to (${input.coordinate.join(", ")}).` };
1784
2041
  }
1785
- if (input.replace === true) {
1786
- await this.sendKeys(call, parseKeys("ctrl+a"));
1787
- await setTimeout$1(50, void 0, { signal: call.signal });
2042
+ case "left_mouse_down":
2043
+ case "left_mouse_up": {
2044
+ const p = input.coordinate ? await this.point(input.coordinate) : void 0;
2045
+ if (action === "left_mouse_down") {
2046
+ const window = await this.windowAt(p ?? await this.cursor());
2047
+ if (window && this.overlay.isRememberedWebWindow(window)) throw new Error("Use a single drag action within the work page instead of holding the mouse button in this browser window.");
2048
+ await this.assertAllowed(call, window, "press the mouse in");
2049
+ }
2050
+ await this.helper.call("button", {
2051
+ ...p ?? {},
2052
+ button: "left",
2053
+ up: action === "left_mouse_up"
2054
+ });
2055
+ this.heldButton = action === "left_mouse_down";
2056
+ return { text: `Left button ${action === "left_mouse_down" ? "down" : "up"}.` };
1788
2057
  }
1789
- return { text: `${await this.enterText(text, call)}${input.replace === true ? " (replaced existing text)" : ""}${into}` };
1790
- }
1791
- case "key": {
1792
- const combos = parseKeys(input.text ?? "");
1793
- await this.sendKeys(call, combos);
1794
- return { text: `Pressed ${input.text}.` };
1795
- }
1796
- case "hold_key": {
1797
- const combos = parseKeys(input.text ?? "");
1798
- const seconds = Math.min(10, Math.max(.05, input.duration ?? .5));
1799
- await this.sendKeys(call, combos, Math.round(seconds * 1e3));
1800
- return { text: `Held ${input.text} for ${seconds}s.` };
2058
+ case "scroll": {
2059
+ const { point: p } = await this.aim(input, call);
2060
+ await this.checkPointer(call, p, "scroll");
2061
+ const amount = Math.max(1, Math.min(30, Math.round(input.scroll_amount ?? 3)));
2062
+ const direction = input.scroll_direction ?? "down";
2063
+ const dy = direction === "down" ? amount : direction === "up" ? -amount : 0;
2064
+ const dx = direction === "right" ? amount : direction === "left" ? -amount : 0;
2065
+ await this.helper.call("scroll", {
2066
+ ...p ?? {},
2067
+ dx,
2068
+ dy,
2069
+ modifiers: parseModifiers(input.modifiers)
2070
+ });
2071
+ return { text: `Scrolled ${direction} ${amount}.` };
2072
+ }
2073
+ case "type": {
2074
+ const text = input.text ?? "";
2075
+ if (text === "") throw new Error("type needs text.");
2076
+ let into = "";
2077
+ if (input.target || input.coordinate) {
2078
+ const { point, label, named } = await this.aim(input, call);
2079
+ if (s.protectPasswords && named?.element.password) throw new Error(`Refused to type into password field "${named.element.name || "password"}". Ask the user to enter the password themselves.`);
2080
+ let p = point;
2081
+ const focused = named && await this.semanticAction(call, named, "focus");
2082
+ if (!focused) {
2083
+ if (named) p = await this.namedClickPoint(call, input.target, named);
2084
+ else await this.checkPointer(call, p, "click");
2085
+ await this.helper.call("click", {
2086
+ ...p ?? {},
2087
+ button: "left",
2088
+ count: 1,
2089
+ modifiers: []
2090
+ });
2091
+ }
2092
+ await setTimeout$1(120, void 0, { signal: call.signal });
2093
+ if (named) await this.checkNamed(call, named.window);
2094
+ into = ` (${focused ? "focused" : "clicked"}${label} first)`;
2095
+ }
2096
+ await this.checkKeyboard(call, "type into");
2097
+ if (s.protectPasswords) {
2098
+ const pwd = await this.helper.call("password_focus", {}, 1500).catch(() => null);
2099
+ if (pwd?.password) throw new Error(`Refused to type into a password input${pwd.name ? ` ("${pwd.name.slice(0, 40)}")` : ""}. Ask the user to enter the password themselves.`);
2100
+ }
2101
+ if (input.replace === true) {
2102
+ await this.sendKeys(call, parseKeys("ctrl+a"));
2103
+ await setTimeout$1(50, void 0, { signal: call.signal });
2104
+ }
2105
+ return { text: `${await this.enterText(text, call)}${input.replace === true ? " (replaced existing text)" : ""}${into}` };
2106
+ }
2107
+ case "key": {
2108
+ const combos = parseKeys(input.text ?? "");
2109
+ await this.sendKeys(call, combos);
2110
+ return { text: `Pressed ${input.text}.` };
2111
+ }
2112
+ case "hold_key": {
2113
+ const combos = parseKeys(input.text ?? "");
2114
+ const seconds = Math.min(10, Math.max(.05, input.duration ?? .5));
2115
+ await this.sendKeys(call, combos, Math.round(seconds * 1e3));
2116
+ return { text: `Held ${input.text} for ${seconds}s.` };
2117
+ }
2118
+ default: throw new Error(`Unknown action: ${String(action)}`);
1801
2119
  }
2120
+ } finally {
2121
+ if (INPUT.has(action)) this.invalidateMarks();
1802
2122
  }
1803
2123
  }
1804
2124
  /**
@@ -1995,6 +2315,7 @@ function buildDiagnosticSnapshot(options) {
1995
2315
  restorePointer: s.restorePointer,
1996
2316
  protectPasswords: s.protectPasswords,
1997
2317
  windowChangeGuard: s.windowChangeGuard,
2318
+ cdpEnabled: s.cdpEnabled,
1998
2319
  cdpPort: s.cdpPort,
1999
2320
  blockedAppsCount: s.blockedApps.length,
2000
2321
  hasCustomHarnessUrl: Boolean(s.harnessUrl)
@@ -2023,7 +2344,7 @@ function formatDiagnosticText(snap) {
2023
2344
  //#endregion
2024
2345
  //#region lib/types/helper-client.js
2025
2346
  /**
2026
- * Builds and drives the Windows helper (helper/CuHelper.cs): compiled once
2347
+ * Builds and drives the Windows helper (helper/*.cs): compiled once
2027
2348
  * with the in-box .NET Framework csc.exe into a per-source-hash cache folder,
2028
2349
  * then kept running and spoken to as JSON lines over stdio.
2029
2350
  */
@@ -2044,7 +2365,14 @@ function helperAssetPath(name) {
2044
2365
  return candidates.find((path) => existsSync(path)) ?? candidates[0];
2045
2366
  }
2046
2367
  function helperSourcePath() {
2047
- return helperAssetPath("CuHelper.cs");
2368
+ return helperAssetPath("Program.cs");
2369
+ }
2370
+ /** All modular C# 5 source files under `helper/` compiled together into `cu-helper.exe`. */
2371
+ function helperSourceFiles() {
2372
+ const dir = dirname(helperSourcePath());
2373
+ if (!existsSync(dir)) return [helperSourcePath()];
2374
+ const files = readdirSync(dir).filter((name) => name.endsWith(".cs")).sort((a, b) => a.localeCompare(b)).map((name) => join(dir, name));
2375
+ return files.length > 0 ? files : [helperSourcePath()];
2048
2376
  }
2049
2377
  function frameworkDir() {
2050
2378
  const windir = process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows";
@@ -2058,11 +2386,13 @@ function cacheRoot() {
2058
2386
  return join(process.env.LOCALAPPDATA ?? tmpdir(), "dsh-computer-use");
2059
2387
  }
2060
2388
  let building;
2061
- /** Compile the helper if this source version has no cached exe yet; returns the exe path. */
2062
- async function ensureHelperExe(source = helperSourcePath()) {
2389
+ /** Compile the helper if this source set has no cached exe yet; returns the exe path. */
2390
+ async function ensureHelperExe(sources = helperSourceFiles()) {
2391
+ const files = Array.isArray(sources) ? [...sources] : [sources];
2063
2392
  building ??= (async () => {
2064
- const code = await readFile(source);
2065
- const hash = createHash("sha256").update(code).digest("hex").slice(0, 12);
2393
+ const hasher = createHash("sha256");
2394
+ for (const file of files) hasher.update(basename(file)).update("\0").update(await readFile(file)).update("\0");
2395
+ const hash = hasher.digest("hex").slice(0, 12);
2066
2396
  const dir = join(cacheRoot(), `helper-${hash}`);
2067
2397
  const exe = join(dir, "cu-helper.exe");
2068
2398
  if (existsSync(exe)) return exe;
@@ -2076,7 +2406,7 @@ async function ensureHelperExe(source = helperSourcePath()) {
2076
2406
  `-out:${temp}`,
2077
2407
  `-lib:${join(fw, "WPF")}`,
2078
2408
  ...REFERENCES.map((ref) => `-r:${ref}`),
2079
- source
2409
+ ...files
2080
2410
  ];
2081
2411
  await new Promise((resolve, reject) => {
2082
2412
  execFile(join(fw, "csc.exe"), args, {
@@ -3148,7 +3478,7 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
3148
3478
  - Prefer reliable keyboard shortcuts (ctrl+l for a browser address bar, ctrl+s, alt+F4, ctrl+t). Click the center of targets. When text is too small to read, zoom once on a generous region that contains everything you need (zooming step by step wastes calls).
3149
3479
  - Actions return a fresh screenshot taken once the screen stops changing (page loads included, up to a few seconds), so you rarely need wait. If something is still loading, use wait: it also returns a screenshot, so never follow it with a separate screenshot call. Explicit screenshot and zoom skip sending duplicate pixels when nothing changed (pass force: true to capture anyway); pass detail: "low" when you only need a quick visual confirmation rather than reading small text.
3150
3480
  - When the overlay is enabled, a colored pointer cursor with a subtle click ripple briefly stays visible in the next screenshot at the click position (blue = left click, purple = double click, green = right click, cyan = middle click, orange = triple click) so you can verify exactly where your click landed. If you see a repeat-click warning on the same spot, inspect the screen before clicking again.
3151
- - For windows with sparse or empty UI Automation trees (canvas UIs, games, custom-drawn apps), use ui_elements with ocr: true to read visible text and clickable center coordinates via built-in Windows OCR; target lookups and ui_elements with text: true also fall back to Windows OCR automatically when UIA finds nothing. On dense UIs with duplicate button labels, use ui_elements with marks: true to get a Set-of-Marks numbered screenshot and click or type by target "#12". For Chromium browsers with a local debug port, ui_elements with cdp: true reads visible DOM elements directly.
3481
+ - For windows with sparse or empty UI Automation trees (canvas UIs, games, custom-drawn apps), use ui_elements with ocr: true to read visible text and clickable center coordinates via built-in Windows OCR; target lookups and ui_elements with text: true also fall back to Windows OCR automatically when UIA finds nothing. On repeated inspections of the same window, pass diff: true to ui_elements to receive only added/changed/removed controls and save tokens. On dense UIs with duplicate button labels, use ui_elements with marks: true to get a Set-of-Marks numbered screenshot and click or type by target "#12" (marks expire automatically after any action or window change). When CDP is enabled in settings, ui_elements with cdp: true reads visible DOM elements of the active matched browser tab.
3152
3482
  - When replacing text in an existing field, pass replace: true to type so it selects all and replaces in one step. Password fields are protected by default: never attempt to type passwords; stop and ask the user.
3153
3483
  - When the user asks you to write something in an app, enter it there with type, even long or multi-line Markdown: the user watches it appear (long text is streamed in paragraph by paragraph, literally, without the editor's auto-formatting getting in the way). Do not write the file from a shell and reopen it instead, and do not put text on the clipboard with shell commands (Set-Clipboard, clip): that clutters the user's clipboard history.
3154
3484
  - App skills & macros: open_application returns your saved notes for the app it opens; follow them instead of rediscovering how the app behaves. After working out an unfamiliar app (or finding a note wrong), record the reusable part with app_skill rather than in general memory. For repeatable multi-step routines, save parameterized sequences via app_skill save_macro and replay them with computer_batch macro.
@@ -3393,6 +3723,7 @@ const DEFAULTS = {
3393
3723
  restorePointer: false,
3394
3724
  protectPasswords: true,
3395
3725
  windowChangeGuard: true,
3726
+ cdpEnabled: false,
3396
3727
  cdpPort: 0
3397
3728
  };
3398
3729
  /** Unwrap `.volatile()` refs (`{ get() }`) and fall back to defaults for bad values. */
@@ -3404,6 +3735,8 @@ function resolveConfig(raw) {
3404
3735
  return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : DEFAULTS[key];
3405
3736
  };
3406
3737
  const bool = (key) => typeof out[key] === "boolean" ? out[key] : DEFAULTS[key];
3738
+ const cdpPort = num("cdpPort", 0, 65535);
3739
+ const cdpEnabled = typeof out.cdpEnabled === "boolean" ? out.cdpEnabled : cdpPort > 0;
3407
3740
  const sessionMode = out.sessionMode === "off" || out.sessionMode === "on" || out.sessionMode === "always" ? out.sessionMode : out.defaultSessionEnabled === true ? "on" : DEFAULTS.sessionMode;
3408
3741
  return {
3409
3742
  harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
@@ -3430,7 +3763,8 @@ function resolveConfig(raw) {
3430
3763
  restorePointer: bool("restorePointer"),
3431
3764
  protectPasswords: bool("protectPasswords"),
3432
3765
  windowChangeGuard: bool("windowChangeGuard"),
3433
- cdpPort: num("cdpPort", 0, 65535),
3766
+ cdpEnabled,
3767
+ cdpPort,
3434
3768
  typingMode: out.typingMode === "stream" || out.typingMode === "type" || out.typingMode === "paste" ? out.typingMode : DEFAULTS.typingMode,
3435
3769
  blockedApps: Array.isArray(out.blockedApps) ? out.blockedApps.filter((item) => typeof item === "string" && item.trim() !== "") : []
3436
3770
  };
@@ -9883,12 +10217,44 @@ function toolAbortedBeforeDispatchResult(prior) {
9883
10217
  * `fetch` + `WebSocket`. Never launches a separate browser and fails quietly
9884
10218
  * back to UIA + OCR when no local debug port is open.
9885
10219
  */
9886
- const DEFAULT_PORTS = [9222, 9229];
9887
- /** Probe candidate localhost debugging ports and return the first matching visible page target. */
10220
+ const DEFAULT_PORTS = [9222];
10221
+ const BROWSER_SUFFIX_RE = /\s*(?:[-–—]\s*(?:google\s+chrome|microsoft[\u200b\s]*edge|chromium|brave|vivaldi|opera|mozilla\s+firefox|360极速浏览器|qq浏览器)(?:\s*[-–—]\s*[^-–—]+)?|\(\d+\))$/i;
10222
+ /** Strip common browser window title suffixes so Chrome/Edge window titles match CDP page titles cleanly. */
10223
+ function normalizeBrowserTitle(title) {
10224
+ let s = title.replace(/\u200b/g, "").trim();
10225
+ for (let i = 0; i < 2; i++) {
10226
+ const next = s.replace(BROWSER_SUFFIX_RE, "").trim();
10227
+ if (next === s) break;
10228
+ s = next;
10229
+ }
10230
+ return s.toLowerCase();
10231
+ }
10232
+ /** Verify a CDP WebSocket URL points strictly to the loopback interface on the expected port. */
10233
+ function isLocalCdpWsUrl(wsUrl, expectedPort) {
10234
+ try {
10235
+ const u = new URL(wsUrl);
10236
+ if (u.protocol !== "ws:") return false;
10237
+ const host = u.hostname.toLowerCase();
10238
+ if (host !== "127.0.0.1" && host !== "localhost" && host !== "[::1]" && host !== "::1") return false;
10239
+ if (expectedPort !== void 0) {
10240
+ const port = Number(u.port);
10241
+ if (!Number.isInteger(port) || port !== expectedPort) return false;
10242
+ }
10243
+ return true;
10244
+ } catch {
10245
+ return false;
10246
+ }
10247
+ }
10248
+ /**
10249
+ * Probe candidate localhost debugging ports and return the matching visible page target.
10250
+ * Never falls back to an unrelated tab (`pages[0]`) when `titleHint` fails to match or multiple
10251
+ * tabs are ambiguous — callers fall back to UIA / OCR instead of leaking another tab's DOM.
10252
+ */
9888
10253
  async function findCdpTarget(options = {}) {
9889
10254
  const ports = options.ports && options.ports.length > 0 ? options.ports : DEFAULT_PORTS;
9890
10255
  const timeoutMs = options.timeoutMs ?? 280;
9891
- const hint = options.titleHint?.trim().toLowerCase() ?? "";
10256
+ const hint = options.titleHint ? normalizeBrowserTitle(options.titleHint) : "";
10257
+ const urlHint = options.urlHint?.trim().toLowerCase() ?? "";
9892
10258
  for (const port of ports) {
9893
10259
  if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
9894
10260
  try {
@@ -9896,17 +10262,41 @@ async function findCdpTarget(options = {}) {
9896
10262
  if (!res.ok) continue;
9897
10263
  const list = await res.json();
9898
10264
  if (!Array.isArray(list)) continue;
9899
- const pages = list.filter((t) => t.type === "page" && typeof t.webSocketDebuggerUrl === "string" && !t.url.startsWith("devtools://") && !(options.harnessUrl && isHarnessAddress(t.url, options.harnessUrl)));
10265
+ const pages = list.filter((t) => t.type === "page" && typeof t.webSocketDebuggerUrl === "string" && isLocalCdpWsUrl(t.webSocketDebuggerUrl, port) && !t.url.startsWith("devtools://") && !t.url.startsWith("chrome-extension://") && !(options.harnessUrl && isHarnessAddress(t.url, options.harnessUrl)));
9900
10266
  if (pages.length === 0) continue;
9901
- return {
10267
+ if (urlHint) {
10268
+ const byUrl = pages.find((p) => p.url.toLowerCase().includes(urlHint));
10269
+ if (byUrl) return {
10270
+ port,
10271
+ target: byUrl
10272
+ };
10273
+ }
10274
+ if (hint) {
10275
+ const exact = pages.find((p) => normalizeBrowserTitle(p.title) === hint);
10276
+ if (exact) return {
10277
+ port,
10278
+ target: exact
10279
+ };
10280
+ const contains = pages.filter((p) => {
10281
+ const t = normalizeBrowserTitle(p.title);
10282
+ return t.length >= 2 && (t.includes(hint) || hint.includes(t));
10283
+ });
10284
+ if (contains.length === 1) return {
10285
+ port,
10286
+ target: contains[0]
10287
+ };
10288
+ continue;
10289
+ }
10290
+ if (pages.length === 1) return {
9902
10291
  port,
9903
- target: (hint ? pages.find((p) => p.title.toLowerCase().includes(hint) || hint.includes(p.title.toLowerCase())) : void 0) ?? pages[0]
10292
+ target: pages[0]
9904
10293
  };
9905
10294
  } catch {}
9906
10295
  }
9907
10296
  }
9908
- /** Execute one CDP `Runtime.evaluate` returning JSON on a debugger WebSocket URL. */
9909
- async function evalCdpJson(wsUrl, expression, timeoutMs = 2500) {
10297
+ /** Execute one CDP `Runtime.evaluate` returning JSON on a validated local debugger WebSocket URL. */
10298
+ async function evalCdpJson(wsUrl, expression, timeoutMs = 2500, expectedPort) {
10299
+ if (!isLocalCdpWsUrl(wsUrl, expectedPort)) return void 0;
9910
10300
  const WS = globalThis.WebSocket;
9911
10301
  if (typeof WS !== "function") return void 0;
9912
10302
  return new Promise((resolve) => {
@@ -9977,7 +10367,7 @@ const COLLECT_DOM_SCRIPT = `(() => {
9977
10367
  async function readCdpElements(options = {}) {
9978
10368
  const found = await findCdpTarget(options);
9979
10369
  if (!found?.target.webSocketDebuggerUrl) return void 0;
9980
- const elements = await evalCdpJson(found.target.webSocketDebuggerUrl, COLLECT_DOM_SCRIPT);
10370
+ const elements = await evalCdpJson(found.target.webSocketDebuggerUrl, COLLECT_DOM_SCRIPT, 2500, found.port);
9981
10371
  if (!Array.isArray(elements)) return void 0;
9982
10372
  return {
9983
10373
  port: found.port,
@@ -9990,7 +10380,7 @@ async function readCdpElements(options = {}) {
9990
10380
  async function readCdpText(options = {}) {
9991
10381
  const found = await findCdpTarget(options);
9992
10382
  if (!found?.target.webSocketDebuggerUrl) return void 0;
9993
- const text = await evalCdpJson(found.target.webSocketDebuggerUrl, "String(document.body && document.body.innerText ? document.body.innerText : \"\")");
10383
+ const text = await evalCdpJson(found.target.webSocketDebuggerUrl, "String(document.body && document.body.innerText ? document.body.innerText : \"\")", 2500, found.port);
9994
10384
  if (typeof text !== "string" || text.trim() === "") return void 0;
9995
10385
  const maxTail = options.tail ?? 4e3;
9996
10386
  return {
@@ -10115,17 +10505,20 @@ const coordinate = {
10115
10505
  items: { type: "number" },
10116
10506
  description: "[x, y] in pixels of the latest screenshot."
10117
10507
  };
10118
- /** Reads what a window says through UI Automation (falling back to Windows OCR when UIA exposes no text). */
10119
- async function windowText(computer, hwnd, tail) {
10508
+ /** Reads what a window says through UI Automation (falling back to CDP when enabled, then Windows OCR). */
10509
+ async function windowText(computer, call, hwnd, tail) {
10120
10510
  const maxTail = Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)));
10511
+ const targetWin = hwnd === void 0 ? await computer.foreground().catch(() => void 0) : (await computer.windows().catch(() => [])).find((w) => w.hwnd === hwnd);
10512
+ if (targetWin) computer.assertReadable(call, targetWin, "read text from");
10121
10513
  const result = await computer.helper.call("text", {
10122
10514
  ...hwnd === void 0 ? {} : { hwnd },
10123
10515
  tail: maxTail
10124
10516
  }, 2e4);
10517
+ if (result.exe) computer.assertReadable(call, result, "read text from");
10125
10518
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
10126
10519
  if (!result.text || result.source === "none") {
10127
- if (isBrowser(result)) {
10128
- const s = computer.settings();
10520
+ const s = computer.settings();
10521
+ if (isBrowser(result) && (s.cdpEnabled || s.cdpPort > 0)) {
10129
10522
  const cdp = await readCdpText({
10130
10523
  ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
10131
10524
  titleHint: result.title,
@@ -10224,16 +10617,18 @@ function createTools(host) {
10224
10617
  async execute(args, exec) {
10225
10618
  const call = await host.context(exec);
10226
10619
  const input = args;
10227
- try {
10228
- const outcome = await computer.run(input, call);
10229
- if (outcome.image) return withShot(host, outcome.text, outcome.image, call);
10230
- if (input.action === "screenshot" || input.action === "zoom") return { text: outcome.text };
10231
- const shot = await computer.after([input], call);
10232
- return withShot(host, shot === void 0 && input.action !== "wait" && input.action !== "cursor_position" ? `${outcome.text} ${await computer.describeForeground()}` : outcome.text, shot, call);
10233
- } catch (error) {
10234
- if (call.signal.aborted) await computer.releaseHeld();
10235
- throw error;
10236
- }
10620
+ return computer.lease.withLease(call.session, call.signal, async () => {
10621
+ try {
10622
+ const outcome = await computer.run(input, call);
10623
+ if (outcome.image) return withShot(host, outcome.text, outcome.image, call);
10624
+ if (input.action === "screenshot" || input.action === "zoom") return { text: outcome.text };
10625
+ const shot = await computer.after([input], call);
10626
+ return withShot(host, shot === void 0 && input.action !== "wait" && input.action !== "cursor_position" ? `${outcome.text} ${await computer.describeForeground()}` : outcome.text, shot, call);
10627
+ } catch (error) {
10628
+ if (call.signal.aborted) await computer.releaseHeld();
10629
+ throw error;
10630
+ }
10631
+ });
10237
10632
  },
10238
10633
  presentCall: (args) => card(`电脑操作 · ${Computer.statusOf(args)}`)
10239
10634
  }));
@@ -10295,57 +10690,59 @@ function createTools(host) {
10295
10690
  }
10296
10691
  const finish = rawArgs.finish ?? "screenshot";
10297
10692
  const detail = rawArgs.detail;
10298
- let zoomed;
10299
- let endedWithZoom = false;
10300
10693
  if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array (or pass a saved macro name).");
10301
10694
  if (actions.length > 30) throw new Error("At most 30 actions per batch.");
10302
- const lines = [];
10303
- let failure;
10304
- for (const [index, input] of actions.entries()) {
10305
- if (input.action === "screenshot" || input.action === "zoom" && index !== actions.length - 1) {
10306
- failure = `#${index + 1} ${input.action}: ${input.action === "zoom" ? "only allowed as the last action of a batch" : "not allowed in a batch"}.`;
10307
- break;
10308
- }
10309
- try {
10310
- const stepStart = Date.now();
10311
- if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
10312
- const outcome = await computer.run(input, call);
10313
- if (input.action === "zoom") {
10314
- endedWithZoom = true;
10315
- zoomed = outcome.image;
10316
- }
10317
- if (outcome.skipped) {
10318
- failure = `#${index + 1} ${input.action} skipped: ${outcome.text}`;
10695
+ return computer.lease.withLease(call.session, call.signal, async () => {
10696
+ let zoomed;
10697
+ let endedWithZoom = false;
10698
+ const lines = [];
10699
+ let failure;
10700
+ for (const [index, input] of actions.entries()) {
10701
+ if (input.action === "screenshot" || input.action === "zoom" && index !== actions.length - 1) {
10702
+ failure = `#${index + 1} ${input.action}: ${input.action === "zoom" ? "only allowed as the last action of a batch" : "not allowed in a batch"}.`;
10319
10703
  break;
10320
10704
  }
10321
- lines.push(`#${index + 1} ${outcome.text}`);
10322
- await setTimeout$1(60, void 0, { signal: call.signal });
10323
- if (computer.settings().pauseOnUserInput && (computer.overlay.userTypedSince(stepStart - 1) || computer.overlay.hasUserActions?.())) {
10324
- const notes = await computer.drainUserActionNotes();
10325
- const kind = notes ? "intervened with mouse/keyboard" : "typed on the keyboard";
10326
- failure = `#${index + 1} done, but the user ${kind} meanwhile; remaining actions stopped.${notes} Re-check the screen before continuing.`;
10705
+ try {
10706
+ const stepStart = Date.now();
10707
+ if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
10708
+ const outcome = await computer.run(input, call);
10709
+ if (input.action === "zoom") {
10710
+ endedWithZoom = true;
10711
+ zoomed = outcome.image;
10712
+ }
10713
+ if (outcome.skipped) {
10714
+ failure = `#${index + 1} ${input.action} skipped: ${outcome.text}`;
10715
+ break;
10716
+ }
10717
+ lines.push(`#${index + 1} ${outcome.text}`);
10718
+ await setTimeout$1(60, void 0, { signal: call.signal });
10719
+ if (computer.settings().pauseOnUserInput && (computer.overlay.userTypedSince(stepStart - 1) || computer.overlay.hasUserActions?.())) {
10720
+ const notes = await computer.drainUserActionNotes();
10721
+ const kind = notes ? "intervened with mouse/keyboard" : "typed on the keyboard";
10722
+ failure = `#${index + 1} done, but the user ${kind} meanwhile; remaining actions stopped.${notes} Re-check the screen before continuing.`;
10723
+ break;
10724
+ }
10725
+ } catch (error) {
10726
+ if (call.signal.aborted) {
10727
+ await computer.releaseHeld();
10728
+ throw error;
10729
+ }
10730
+ failure = `#${index + 1} ${input.action} failed: ${error instanceof Error ? error.message : String(error)}`;
10327
10731
  break;
10328
10732
  }
10329
- } catch (error) {
10330
- if (call.signal.aborted) {
10331
- await computer.releaseHeld();
10332
- throw error;
10333
- }
10334
- failure = `#${index + 1} ${input.action} failed: ${error instanceof Error ? error.message : String(error)}`;
10335
- break;
10336
10733
  }
10337
- }
10338
- const done = lines.join("\n");
10339
- const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
10340
- if (endedWithZoom && failure === void 0) return zoomed ? withShot(host, summary, zoomed, call) : { text: summary };
10341
- if (failure === void 0 && finish === "none") return { text: `${summary}\n${await computer.describeForeground()}` };
10342
- if (failure === void 0 && finish === "text") {
10343
- await computer.settle(call.signal);
10344
- return { text: `${summary}\n${await windowText(computer, void 0, void 0).catch((error) => `Could not read the window text: ${error instanceof Error ? error.message : String(error)}`)}` };
10345
- }
10346
- const waited = failure === void 0 && actions[actions.length - 1]?.action === "wait";
10347
- const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot(detail)) : void 0;
10348
- return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
10734
+ const done = lines.join("\n");
10735
+ const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
10736
+ if (endedWithZoom && failure === void 0) return zoomed ? withShot(host, summary, zoomed, call) : { text: summary };
10737
+ if (failure === void 0 && finish === "none") return { text: `${summary}\n${await computer.describeForeground()}` };
10738
+ if (failure === void 0 && finish === "text") {
10739
+ await computer.settle(call.signal);
10740
+ return { text: `${summary}\n${await windowText(computer, call, void 0, void 0).catch((error) => `Could not read the window text: ${error instanceof Error ? error.message : String(error)}`)}` };
10741
+ }
10742
+ const waited = failure === void 0 && actions[actions.length - 1]?.action === "wait";
10743
+ const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot(detail)) : void 0;
10744
+ return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
10745
+ });
10349
10746
  },
10350
10747
  presentCall: (args) => card(`电脑操作 · 批量 ${args.actions?.length ?? 0} 步`)
10351
10748
  }));
@@ -10561,12 +10958,16 @@ function createTools(host) {
10561
10958
  }));
10562
10959
  tools.push(defineTool({
10563
10960
  name: "ui_elements",
10564
- description: "Read the foreground window (or a window by hwnd) through Windows UI Automation, Set-of-Marks annotated screenshot, Windows OCR, or local Chromium CDP. Default: clickable/editable UIA controls with center coordinates. With marks: true: attach a numbered Set-of-Marks screenshot so you can click/type by target \"#12\". With text: true: plain text (auto-falls back to CDP/OCR). With ocr: true: Windows OCR lines + center coordinates. With cdp: true: inspect visible DOM elements over a local Chromium debug port.",
10961
+ description: "Read the foreground window (or a window by hwnd) through Windows UI Automation, Set-of-Marks annotated screenshot, Windows OCR, or local Chromium CDP. Default: clickable/editable UIA controls with center coordinates. With diff: true: return only added/changed/removed controls since the previous UIA read of this window (saves tokens). With marks: true: attach a numbered Set-of-Marks screenshot so you can click/type by target \"#12\". With text: true: plain text (auto-falls back to CDP when enabled, then OCR). With ocr: true: Windows OCR lines + center coordinates. With cdp: true: inspect visible DOM elements when CDP is enabled in settings.",
10565
10962
  parameters: {
10566
10963
  hwnd: {
10567
10964
  type: "integer",
10568
10965
  description: "Window handle; default foreground window."
10569
10966
  },
10967
+ diff: {
10968
+ type: "boolean",
10969
+ description: "Incremental UIA diff: return only added, changed, and removed controls since the last read of this window (captures baseline on first call)."
10970
+ },
10570
10971
  marks: {
10571
10972
  type: "boolean",
10572
10973
  description: "Return a Set-of-Marks numbered screenshot alongside the element list so you can target controls by \"#1\", \"#2\", ..."
@@ -10581,7 +10982,7 @@ function createTools(host) {
10581
10982
  },
10582
10983
  cdp: {
10583
10984
  type: "boolean",
10584
- description: "Inspect visible DOM controls directly over a local Chrome/Edge CDP port (falls back to UIA if unavailable)."
10985
+ description: "Inspect visible DOM controls directly over a local Chrome/Edge CDP port when enabled in settings (falls back cleanly if unavailable)."
10585
10986
  },
10586
10987
  tail: {
10587
10988
  type: "integer",
@@ -10598,15 +10999,83 @@ function createTools(host) {
10598
10999
  },
10599
11000
  output,
10600
11001
  timeoutMs: 3e4,
10601
- isConcurrencySafe: () => true,
10602
11002
  async execute(args, exec) {
10603
- const { hwnd, marks, include_text: includeText, max, text, ocr, cdp, tail } = args;
10604
- if (marks === true) {
10605
- const call = await host.context(exec);
10606
- const { window: win, elements, shot } = await computer.marks(hwnd, max ?? 120);
10607
- const lines = [];
10608
- for (const [index, el] of elements.entries()) {
10609
- const num = el.mark ?? index + 1;
11003
+ const call = await host.context(exec);
11004
+ const { hwnd, diff, marks, include_text: includeText, max, text, ocr, cdp, tail } = args;
11005
+ return computer.lease.withLease(call.session, call.signal, async () => {
11006
+ const targetWin = hwnd === void 0 ? await computer.foreground().catch(() => void 0) : (await computer.windows().catch(() => [])).find((w) => w.hwnd === hwnd);
11007
+ if (targetWin) computer.assertReadable(call, targetWin, "read UI elements of");
11008
+ if (marks === true) {
11009
+ const { window: win, elements, shot } = await computer.marks(hwnd, max ?? 120);
11010
+ if (win.exe) computer.assertReadable(call, win, "read UI elements of");
11011
+ const lines = [];
11012
+ for (const [index, el] of elements.entries()) {
11013
+ const num = el.mark ?? index + 1;
11014
+ const center = await computer.toModel({
11015
+ x: el.x + el.width / 2,
11016
+ y: el.y + el.height / 2
11017
+ });
11018
+ const flags = [
11019
+ el.password ? "password" : "",
11020
+ el.value !== void 0 ? `value="${el.value}"` : "",
11021
+ el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
11022
+ el.disabled ? "disabled" : "",
11023
+ el.editable ? "editable" : ""
11024
+ ].filter(Boolean).join(" ");
11025
+ lines.push(`[#${num}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
11026
+ }
11027
+ const head = `${win.exe ?? "window"} — "${String(win.title ?? "").slice(0, 80)}": ${elements.length} Set-of-Marks elements (use target "#<number>" to click or type; marks expire after the next action or window change).`;
11028
+ return withShot(host, lines.length ? `${head}\n${lines.join("\n")}` : head, shot, call);
11029
+ }
11030
+ if (cdp === true) {
11031
+ const s = computer.settings();
11032
+ if (!s.cdpEnabled && s.cdpPort <= 0) return { text: "Chromium CDP fast-lane is disabled in settings (cdpEnabled: false). Enable it in plugin settings or use ui_elements without cdp / ui_elements({ marks: true })." };
11033
+ const fg = targetWin ?? await computer.foreground().catch(() => void 0);
11034
+ if (fg) computer.assertReadable(call, fg, "read browser DOM of", true);
11035
+ const snap = await readCdpElements({
11036
+ ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
11037
+ ...fg?.title ? { titleHint: fg.title } : {},
11038
+ ...s.harnessUrl ? { harnessUrl: s.harnessUrl } : {}
11039
+ }).catch(() => void 0);
11040
+ if (snap) {
11041
+ const limit = Math.min(200, Math.max(10, max ?? 120));
11042
+ const lines = snap.elements.slice(0, limit).map((el, i) => {
11043
+ const flags = [
11044
+ el.password ? "password" : "",
11045
+ el.value !== void 0 ? `value="${el.value}"` : "",
11046
+ el.editable ? "editable" : "",
11047
+ el.selector ? `selector=${el.selector}` : ""
11048
+ ].filter(Boolean).join(" ");
11049
+ return `[${i}] ${el.role} "${el.name}" viewport=(${el.x + Math.round(el.width / 2)}, ${el.y + Math.round(el.height / 2)})${flags ? ` ${flags}` : ""}`;
11050
+ });
11051
+ return { text: `CDP (port ${snap.port}) — "${snap.title.slice(0, 80)}" (${snap.url}): ${snap.elements.length} DOM elements.\n${lines.join("\n")}` };
11052
+ }
11053
+ return { text: "No matching local Chromium CDP tab found (strict active-tab match; refusing to read unrelated tabs). Use ui_elements without cdp, or ui_elements({ marks: true }) / ui_elements({ ocr: true })." };
11054
+ }
11055
+ if (ocr === true) {
11056
+ const result = await computer.ocr(hwnd);
11057
+ if (result.exe) computer.assertReadable(call, result, "read OCR text from");
11058
+ const limit = Math.min(400, Math.max(10, max ?? 120));
11059
+ const lines = [];
11060
+ for (const [index, line] of (result.lines ?? []).slice(0, limit).entries()) {
11061
+ const center = await computer.toModel({
11062
+ x: line.x + line.width / 2,
11063
+ y: line.y + line.height / 2
11064
+ });
11065
+ lines.push(`[${index}] "${line.text}" @ (${center.x}, ${center.y})${center.offscreen ? " other display" : ""}`);
11066
+ }
11067
+ const head = `${result.exe ?? "screen"} — "${String(result.title ?? "").slice(0, 80)}": ${result.lines?.length ?? 0} OCR lines (${result.language || "auto"}).`;
11068
+ return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} No readable text found by Windows OCR.` };
11069
+ }
11070
+ if (text === true) return { text: await windowText(computer, call, hwnd, tail) };
11071
+ const result = await computer.helper.call("ui", {
11072
+ ...hwnd === void 0 ? {} : { hwnd },
11073
+ includeText: includeText === true,
11074
+ popups: true,
11075
+ maxNodes: Math.min(400, Math.max(10, max ?? 120))
11076
+ }, 2e4);
11077
+ if (result.exe) computer.assertReadable(call, result, "read UI elements of");
11078
+ const formatEl = async (prefix, el, suffix = "") => {
10610
11079
  const center = await computer.toModel({
10611
11080
  x: el.x + el.width / 2,
10612
11081
  y: el.y + el.height / 2
@@ -10616,81 +11085,35 @@ function createTools(host) {
10616
11085
  el.value !== void 0 ? `value="${el.value}"` : "",
10617
11086
  el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
10618
11087
  el.disabled ? "disabled" : "",
10619
- el.editable ? "editable" : ""
11088
+ el.automationId ? `automationId=${JSON.stringify(el.automationId)}` : "",
11089
+ el.focusable !== void 0 ? `focusable=${el.focusable}` : "",
11090
+ el.editable ? "editable" : "",
11091
+ center.offscreen ? "other display" : ""
10620
11092
  ].filter(Boolean).join(" ");
10621
- lines.push(`[#${num}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
10622
- }
10623
- const head = `${win.exe ?? "window"} — "${String(win.title ?? "").slice(0, 80)}": ${elements.length} Set-of-Marks elements (use target "#<number>" to click or type).`;
10624
- return withShot(host, lines.length ? `${head}\n${lines.join("\n")}` : head, shot, call);
10625
- }
10626
- if (cdp === true) {
10627
- const fg = await computer.foreground().catch(() => void 0);
10628
- const s = computer.settings();
10629
- const snap = await readCdpElements({
10630
- ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
10631
- ...fg?.title ? { titleHint: fg.title } : {},
10632
- ...s.harnessUrl ? { harnessUrl: s.harnessUrl } : {}
10633
- }).catch(() => void 0);
10634
- if (snap) {
10635
- const limit = Math.min(200, Math.max(10, max ?? 120));
10636
- const lines = snap.elements.slice(0, limit).map((el, i) => {
10637
- const flags = [
10638
- el.password ? "password" : "",
10639
- el.value !== void 0 ? `value="${el.value}"` : "",
10640
- el.editable ? "editable" : "",
10641
- el.selector ? `selector=${el.selector}` : ""
10642
- ].filter(Boolean).join(" ");
10643
- return `[${i}] ${el.role} "${el.name}" viewport=(${el.x + Math.round(el.width / 2)}, ${el.y + Math.round(el.height / 2)})${flags ? ` ${flags}` : ""}`;
10644
- });
10645
- return { text: `CDP (port ${snap.port}) — "${snap.title.slice(0, 80)}" (${snap.url}): ${snap.elements.length} DOM elements.\n${lines.join("\n")}` };
10646
- }
10647
- return { text: "No local Chromium CDP debug port detected (9222/9229). Use ui_elements without cdp, or ui_elements({ marks: true }) / ui_elements({ ocr: true })." };
10648
- }
10649
- if (ocr === true) {
10650
- const result = await computer.ocr(hwnd);
10651
- const limit = Math.min(400, Math.max(10, max ?? 120));
11093
+ return `${prefix} ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}${suffix}`;
11094
+ };
11095
+ const winHwnd = typeof result.hwnd === "number" ? result.hwnd : targetWin?.hwnd;
11096
+ if (diff === true && typeof winHwnd === "number") {
11097
+ const delta = computer.uiDiff.diff(winHwnd, String(result.title ?? ""), result.elements);
11098
+ if (!delta.isBaseline) {
11099
+ const lines = [];
11100
+ if (delta.titleChanged) lines.push(`~ Title: "${String(delta.previousTitle ?? "").slice(0, 50)}" -> "${String(result.title ?? "").slice(0, 50)}"`);
11101
+ for (const el of delta.added) lines.push(await formatEl("+", el));
11102
+ for (const ch of delta.changed) lines.push(await formatEl("~", ch.element, ` [${ch.changes.join(", ")}]`));
11103
+ for (const el of delta.removed) lines.push(`- ${el.role} "${el.name}"`);
11104
+ const summary = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": diff +${delta.added.length} added, ~${delta.changed.length} changed, -${delta.removed.length} removed (${delta.unchangedCount} unchanged omitted).`;
11105
+ return { text: lines.length ? `${summary}\n${lines.join("\n")}` : `${summary} No UI control changes.` };
11106
+ }
11107
+ } else if (typeof winHwnd === "number") computer.uiDiff.record(winHwnd, String(result.title ?? ""), result.elements);
10652
11108
  const lines = [];
10653
- for (const [index, line] of (result.lines ?? []).slice(0, limit).entries()) {
10654
- const center = await computer.toModel({
10655
- x: line.x + line.width / 2,
10656
- y: line.y + line.height / 2
10657
- });
10658
- lines.push(`[${index}] "${line.text}" @ (${center.x}, ${center.y})${center.offscreen ? " other display" : ""}`);
10659
- }
10660
- const head = `${result.exe ?? "screen"} — "${String(result.title ?? "").slice(0, 80)}": ${result.lines?.length ?? 0} OCR lines (${result.language || "auto"}).`;
10661
- return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} No readable text found by Windows OCR.` };
10662
- }
10663
- if (text === true) return { text: await windowText(computer, hwnd, tail) };
10664
- const result = await computer.helper.call("ui", {
10665
- ...hwnd === void 0 ? {} : { hwnd },
10666
- includeText: includeText === true,
10667
- popups: true,
10668
- maxNodes: Math.min(400, Math.max(10, max ?? 120))
10669
- }, 2e4);
10670
- const lines = [];
10671
- for (const [index, el] of result.elements.entries()) {
10672
- const center = await computer.toModel({
10673
- x: el.x + el.width / 2,
10674
- y: el.y + el.height / 2
10675
- });
10676
- const flags = [
10677
- el.password ? "password" : "",
10678
- el.value !== void 0 ? `value="${el.value}"` : "",
10679
- el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
10680
- el.disabled ? "disabled" : "",
10681
- el.automationId ? `automationId=${JSON.stringify(el.automationId)}` : "",
10682
- el.focusable !== void 0 ? `focusable=${el.focusable}` : "",
10683
- el.editable ? "editable" : "",
10684
- center.offscreen ? "other display" : ""
10685
- ].filter(Boolean).join(" ");
10686
- lines.push(`[${index}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
10687
- }
10688
- const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements.`;
10689
- return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} This window exposes no UI Automation elements; use ui_elements with ocr: true or screenshots.` };
11109
+ for (const [index, el] of result.elements.entries()) lines.push(await formatEl(`[${index}]`, el));
11110
+ const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements${diff === true ? " (baseline captured; next diff: true returns changes only)" : ""}.`;
11111
+ return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} This window exposes no UI Automation elements; use ui_elements with ocr: true or screenshots.` };
11112
+ });
10690
11113
  },
10691
11114
  presentCall: (args) => {
10692
11115
  const a = args;
10693
- return card(a.marks ? "编号标图 (Set-of-Marks)" : a.cdp ? "CDP 读取网页元素" : a.ocr ? "OCR 识别文字" : "读取界面元素");
11116
+ return card(a.marks ? "编号标图 (Set-of-Marks)" : a.cdp ? "CDP 读取网页元素" : a.ocr ? "OCR 识别文字" : a.diff ? "增量读取界面变化" : "读取界面元素");
10694
11117
  }
10695
11118
  }));
10696
11119
  tools.push(defineTool({
@@ -10709,17 +11132,22 @@ function createTools(host) {
10709
11132
  },
10710
11133
  output,
10711
11134
  async execute(args, exec) {
11135
+ const call = await host.context(exec);
10712
11136
  const { action, text } = args;
10713
- if (action === "write") {
10714
- computer.clipboardAgent = (await host.context(exec)).agent;
10715
- await computer.helper.call("clipboard_set", {
10716
- text: text ?? "",
10717
- agent: true
10718
- });
10719
- return { text: `Clipboard set (${(text ?? "").length} characters).` };
10720
- }
10721
- const result = await computer.helper.call("clipboard_get");
10722
- return { text: result.text === "" ? "Clipboard has no text." : `Clipboard text:\n${result.text.slice(0, 2e4)}` };
11137
+ return computer.lease.withLease(call.session, call.signal, async () => {
11138
+ if (action === "write") {
11139
+ computer.clipboardAgent = call.agent;
11140
+ await computer.helper.call("clipboard_set", {
11141
+ text: text ?? "",
11142
+ agent: true
11143
+ });
11144
+ return { text: `Clipboard set (${(text ?? "").length} characters).` };
11145
+ }
11146
+ const fg = await computer.foreground().catch(() => void 0);
11147
+ if (fg && !isHostWindow(fg)) computer.assertReadable(call, fg, "read clipboard while focused on", true);
11148
+ const result = await computer.helper.call("clipboard_get");
11149
+ return { text: result.text === "" ? "Clipboard has no text." : `Clipboard text:\n${result.text.slice(0, 2e4)}` };
11150
+ });
10723
11151
  },
10724
11152
  presentCall: (args) => card(`剪贴板 · ${args.action === "write" ? "写入" : "读取"}`)
10725
11153
  }));
@@ -11103,9 +11531,13 @@ const Config = z.object({
11103
11531
  "zh-CN": { $description: "窗口位移或被新弹窗遮挡时阻止盲点坐标并提示模型先重新看屏" },
11104
11532
  "en-US": { $description: "Guard coordinate clicks when the foreground window moved/resized or is occluded since the last screenshot" }
11105
11533
  }),
11534
+ cdpEnabled: z.boolean().default(false).volatile().i18n({
11535
+ "zh-CN": { $description: "启用可选本机 Chromium CDP 浏览器快车道(仅连接 127.0.0.1 调试端口且严格按当前标签标题匹配,匹配失败自动回退 UIA/OCR)" },
11536
+ "en-US": { $description: "Enable optional local Chromium CDP fast-lane (loopback-only with strict active-tab matching; falls back to UIA/OCR on mismatch)" }
11537
+ }),
11106
11538
  cdpPort: z.natural().max(65535).default(0).volatile().i18n({
11107
- "zh-CN": { $description: "可选 Chromium 远程调试端口(0 为按需自动探测 9222/9229),用于轻量化 CDP 网页元素加速读取" },
11108
- "en-US": { $description: "Optional local Chromium CDP debugging port (0 auto-probes 9222/9229 on demand)" }
11539
+ "zh-CN": { $description: "可选 Chromium 远程调试端口(0 为默认 9222),仅在启用 CDP 开关或显式设置非 0 端口时生效" },
11540
+ "en-US": { $description: "Optional local Chromium CDP debugging port (0 uses 9222 when CDP is enabled)" }
11109
11541
  }),
11110
11542
  blockedApps: z.array(z.string()).default([]).volatile().i18n({
11111
11543
  "zh-CN": { $description: "禁止操控的应用(名称或 exe,如 “alipay”)。常见密码管理器默认已禁止。" },
@@ -11375,8 +11807,12 @@ function apply(ctx, config = {}) {
11375
11807
  }));
11376
11808
  };
11377
11809
  ctx.on("agent/status", ({ agent, status }) => {
11810
+ const target = agent;
11378
11811
  if (status === "running") computer.resetLook();
11379
- if (status === "idle") overlay.forgetResume(agent);
11812
+ if (status === "idle") {
11813
+ overlay.forgetResume(agent);
11814
+ computer.lease.release(target.session.id);
11815
+ }
11380
11816
  if (status === "idle" && computer.clipboardAgent === agent) {
11381
11817
  computer.clipboardAgent = void 0;
11382
11818
  helper.call("clipboard_restore").catch(() => {});
@@ -11393,6 +11829,7 @@ function apply(ctx, config = {}) {
11393
11829
  } catch {}
11394
11830
  }
11395
11831
  overlay.forgetResume(agent);
11832
+ computer.lease.release(target.session.id);
11396
11833
  access.forget(target.session.id);
11397
11834
  if (overlay.controller === agent) overlay.end();
11398
11835
  });