@copylee/dsh-computer-use 0.12.0 → 0.13.1

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}.` };
1976
+ }
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
+ }
1775
2003
  }
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)`;
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}` };
2027
+ }
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(", ")}).` };
1779
2041
  }
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.`);
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"}.` };
1784
2057
  }
1785
- if (input.replace === true) {
1786
- await this.sendKeys(call, parseKeys("ctrl+a"));
1787
- await setTimeout$1(50, void 0, { signal: call.signal });
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}.` };
1788
2072
  }
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.` };
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, {
@@ -2694,9 +3024,10 @@ var OverlayController = class {
2694
3024
  workTab;
2695
3025
  starting;
2696
3026
  stopping = false;
2697
- /** Progress card lines: host-provided reasoning and recent operations. */
3027
+ /** Progress card lines: host-provided reasoning, brief mid-turn reply, and recent operations. */
2698
3028
  streamAgent;
2699
3029
  thinking = "";
3030
+ reply = "";
2700
3031
  /** Recent steps (tool actions), oldest first. */
2701
3032
  steps = [];
2702
3033
  resume;
@@ -2798,6 +3129,7 @@ var OverlayController = class {
2798
3129
  await this.ending;
2799
3130
  await this.starting;
2800
3131
  if (agent) this.agent = agent;
3132
+ this.reply = "";
2801
3133
  this.armIdle();
2802
3134
  this.armUnused();
2803
3135
  const settings = this.settings();
@@ -2882,21 +3214,32 @@ var OverlayController = class {
2882
3214
  if (agent !== this.streamAgent) {
2883
3215
  this.streamAgent = agent;
2884
3216
  this.thinking = "";
3217
+ this.reply = "";
2885
3218
  this.steps = [];
2886
3219
  }
2887
3220
  if (frame.type === "start") {
2888
3221
  this.thinking = "";
3222
+ this.reply = "";
2889
3223
  this.schedulePush();
2890
3224
  return;
2891
3225
  }
2892
3226
  if (this.visible && agent === this.agent) this.armIdle();
2893
3227
  const chunk = frame.type === "chunk" ? frame.chunk : void 0;
2894
3228
  if (!chunk) return;
2895
- if (chunk.type === "text-delta" && chunk.text?.trim()) {
2896
- if (this.visible && this.agent && agent === this.agent && !this.paused && !this.stopping) this.end(this.agent, true).catch((error) => this.log(`reply handoff: ${String(error)}`));
3229
+ if (chunk.type === "text-delta" && chunk.text) {
3230
+ if (this.visible && this.agent && agent === this.agent && !this.paused && !this.stopping) {
3231
+ if (this.settings().hostWindow === "pet") {
3232
+ this.reply = plainLine(this.reply + chunk.text).slice(-300);
3233
+ this.schedulePush();
3234
+ if (this.reply.length >= 260) this.end(this.agent, true).catch((error) => this.log(`reply handoff: ${String(error)}`));
3235
+ return;
3236
+ }
3237
+ if (chunk.text.trim()) this.end(this.agent, true).catch((error) => this.log(`reply handoff: ${String(error)}`));
3238
+ }
2897
3239
  return;
2898
3240
  }
2899
3241
  if (chunk.type !== "reasoning-delta" || !chunk.text) return;
3242
+ this.reply = "";
2900
3243
  this.thinking = plainLine(this.thinking + chunk.text).slice(-300);
2901
3244
  this.schedulePush();
2902
3245
  }
@@ -2920,6 +3263,7 @@ var OverlayController = class {
2920
3263
  if (!this.visible) return;
2921
3264
  this.helper.call("pet_update", {
2922
3265
  thinking: this.thinking.trim(),
3266
+ ...this.reply.trim() ? { reply: this.reply.trim() } : {},
2923
3267
  steps: this.steps
2924
3268
  }).catch(() => {});
2925
3269
  }, 80);
@@ -3140,7 +3484,7 @@ var OverlayController = class {
3140
3484
  function promptText(mode) {
3141
3485
  return `# Computer use (Windows desktop)
3142
3486
  You can see and operate the user's Windows computer with the computer, computer_batch, open_application, windows, ui_elements, clipboard and app_skill tools.
3143
- ${mode === "per-app" ? "- Before acting on an app, call request_access once with every app the task needs; the user approves it. Input to apps that are not granted is refused.\n" : ""}- If the task begins with an app, open it right away with open_application (after request_access when the app is not granted yet): it returns the screenshot, so do not take one first. Otherwise start with a screenshot (computer action "screenshot") unless you just received one. All coordinates are pixels of the latest screenshot; the plugin converts them for DPI and scaling.
3487
+ ${mode === "per-app" ? "- Before acting on an app, call request_access once with every app the task needs; the user approves it. Input to apps that are not granted is refused.\n" : "- Access mode is allow-all: you do not need to call list_granted_applications or request_access; open or operate apps directly.\n"}- If the task begins with an app, open it right away with open_application (after request_access when the app is not granted yet): it returns the screenshot, so do not take one first. Otherwise start with a screenshot (computer action "screenshot") unless you just received one. All coordinates are pixels of the latest screenshot; the plugin converts them for DPI and scaling.
3144
3488
  - Open or switch apps with open_application (by name; it also finds desktop shortcuts) rather than hunting through the taskbar or Start menu or starting GUI apps from a shell. Use windows to see which windows exist; each line shows the process .exe. Apps closed to the system tray (QQ, 微信...) are still running: open_application restores them from their tray icon. Do not start a second copy of a running app unless the user explicitly asks for one (then pass new_instance: true), and never show or kill its hidden windows from a shell (Electron / Qt apps freeze, and a second QQ / WeChat asks for another login).
3145
3489
  - When the task is done, tidy up: close windows and dialogs you opened that the user no longer needs (keep the one showing the result they asked for), and call windows tidy to minimize again the apps that were minimized or in the tray before you started. Never close windows the user already had open.
3146
3490
  - The "DeepSeek Harness.exe" window is your own chat interface. While you control the computer it floats as a card that only the user sees: your screenshots show what is underneath it and your clicks and scrolls pass through it, so simply ignore it. Never type into DeepSeek Harness; keys go to the window you were working in.
@@ -3148,7 +3492,7 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
3148
3492
  - 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
3493
  - 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
3494
  - 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.
3495
+ - 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
3496
  - 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
3497
  - 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
3498
  - 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 +3737,7 @@ const DEFAULTS = {
3393
3737
  restorePointer: false,
3394
3738
  protectPasswords: true,
3395
3739
  windowChangeGuard: true,
3740
+ cdpEnabled: false,
3396
3741
  cdpPort: 0
3397
3742
  };
3398
3743
  /** Unwrap `.volatile()` refs (`{ get() }`) and fall back to defaults for bad values. */
@@ -3404,6 +3749,8 @@ function resolveConfig(raw) {
3404
3749
  return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : DEFAULTS[key];
3405
3750
  };
3406
3751
  const bool = (key) => typeof out[key] === "boolean" ? out[key] : DEFAULTS[key];
3752
+ const cdpPort = num("cdpPort", 0, 65535);
3753
+ const cdpEnabled = typeof out.cdpEnabled === "boolean" ? out.cdpEnabled : cdpPort > 0;
3407
3754
  const sessionMode = out.sessionMode === "off" || out.sessionMode === "on" || out.sessionMode === "always" ? out.sessionMode : out.defaultSessionEnabled === true ? "on" : DEFAULTS.sessionMode;
3408
3755
  return {
3409
3756
  harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
@@ -3430,7 +3777,8 @@ function resolveConfig(raw) {
3430
3777
  restorePointer: bool("restorePointer"),
3431
3778
  protectPasswords: bool("protectPasswords"),
3432
3779
  windowChangeGuard: bool("windowChangeGuard"),
3433
- cdpPort: num("cdpPort", 0, 65535),
3780
+ cdpEnabled,
3781
+ cdpPort,
3434
3782
  typingMode: out.typingMode === "stream" || out.typingMode === "type" || out.typingMode === "paste" ? out.typingMode : DEFAULTS.typingMode,
3435
3783
  blockedApps: Array.isArray(out.blockedApps) ? out.blockedApps.filter((item) => typeof item === "string" && item.trim() !== "") : []
3436
3784
  };
@@ -9883,12 +10231,44 @@ function toolAbortedBeforeDispatchResult(prior) {
9883
10231
  * `fetch` + `WebSocket`. Never launches a separate browser and fails quietly
9884
10232
  * back to UIA + OCR when no local debug port is open.
9885
10233
  */
9886
- const DEFAULT_PORTS = [9222, 9229];
9887
- /** Probe candidate localhost debugging ports and return the first matching visible page target. */
10234
+ const DEFAULT_PORTS = [9222];
10235
+ 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;
10236
+ /** Strip common browser window title suffixes so Chrome/Edge window titles match CDP page titles cleanly. */
10237
+ function normalizeBrowserTitle(title) {
10238
+ let s = title.replace(/\u200b/g, "").trim();
10239
+ for (let i = 0; i < 2; i++) {
10240
+ const next = s.replace(BROWSER_SUFFIX_RE, "").trim();
10241
+ if (next === s) break;
10242
+ s = next;
10243
+ }
10244
+ return s.toLowerCase();
10245
+ }
10246
+ /** Verify a CDP WebSocket URL points strictly to the loopback interface on the expected port. */
10247
+ function isLocalCdpWsUrl(wsUrl, expectedPort) {
10248
+ try {
10249
+ const u = new URL(wsUrl);
10250
+ if (u.protocol !== "ws:") return false;
10251
+ const host = u.hostname.toLowerCase();
10252
+ if (host !== "127.0.0.1" && host !== "localhost" && host !== "[::1]" && host !== "::1") return false;
10253
+ if (expectedPort !== void 0) {
10254
+ const port = Number(u.port);
10255
+ if (!Number.isInteger(port) || port !== expectedPort) return false;
10256
+ }
10257
+ return true;
10258
+ } catch {
10259
+ return false;
10260
+ }
10261
+ }
10262
+ /**
10263
+ * Probe candidate localhost debugging ports and return the matching visible page target.
10264
+ * Never falls back to an unrelated tab (`pages[0]`) when `titleHint` fails to match or multiple
10265
+ * tabs are ambiguous — callers fall back to UIA / OCR instead of leaking another tab's DOM.
10266
+ */
9888
10267
  async function findCdpTarget(options = {}) {
9889
10268
  const ports = options.ports && options.ports.length > 0 ? options.ports : DEFAULT_PORTS;
9890
10269
  const timeoutMs = options.timeoutMs ?? 280;
9891
- const hint = options.titleHint?.trim().toLowerCase() ?? "";
10270
+ const hint = options.titleHint ? normalizeBrowserTitle(options.titleHint) : "";
10271
+ const urlHint = options.urlHint?.trim().toLowerCase() ?? "";
9892
10272
  for (const port of ports) {
9893
10273
  if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
9894
10274
  try {
@@ -9896,17 +10276,41 @@ async function findCdpTarget(options = {}) {
9896
10276
  if (!res.ok) continue;
9897
10277
  const list = await res.json();
9898
10278
  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)));
10279
+ 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
10280
  if (pages.length === 0) continue;
9901
- return {
10281
+ if (urlHint) {
10282
+ const byUrl = pages.find((p) => p.url.toLowerCase().includes(urlHint));
10283
+ if (byUrl) return {
10284
+ port,
10285
+ target: byUrl
10286
+ };
10287
+ }
10288
+ if (hint) {
10289
+ const exact = pages.find((p) => normalizeBrowserTitle(p.title) === hint);
10290
+ if (exact) return {
10291
+ port,
10292
+ target: exact
10293
+ };
10294
+ const contains = pages.filter((p) => {
10295
+ const t = normalizeBrowserTitle(p.title);
10296
+ return t.length >= 2 && (t.includes(hint) || hint.includes(t));
10297
+ });
10298
+ if (contains.length === 1) return {
10299
+ port,
10300
+ target: contains[0]
10301
+ };
10302
+ continue;
10303
+ }
10304
+ if (pages.length === 1) return {
9902
10305
  port,
9903
- target: (hint ? pages.find((p) => p.title.toLowerCase().includes(hint) || hint.includes(p.title.toLowerCase())) : void 0) ?? pages[0]
10306
+ target: pages[0]
9904
10307
  };
9905
10308
  } catch {}
9906
10309
  }
9907
10310
  }
9908
- /** Execute one CDP `Runtime.evaluate` returning JSON on a debugger WebSocket URL. */
9909
- async function evalCdpJson(wsUrl, expression, timeoutMs = 2500) {
10311
+ /** Execute one CDP `Runtime.evaluate` returning JSON on a validated local debugger WebSocket URL. */
10312
+ async function evalCdpJson(wsUrl, expression, timeoutMs = 2500, expectedPort) {
10313
+ if (!isLocalCdpWsUrl(wsUrl, expectedPort)) return void 0;
9910
10314
  const WS = globalThis.WebSocket;
9911
10315
  if (typeof WS !== "function") return void 0;
9912
10316
  return new Promise((resolve) => {
@@ -9977,7 +10381,7 @@ const COLLECT_DOM_SCRIPT = `(() => {
9977
10381
  async function readCdpElements(options = {}) {
9978
10382
  const found = await findCdpTarget(options);
9979
10383
  if (!found?.target.webSocketDebuggerUrl) return void 0;
9980
- const elements = await evalCdpJson(found.target.webSocketDebuggerUrl, COLLECT_DOM_SCRIPT);
10384
+ const elements = await evalCdpJson(found.target.webSocketDebuggerUrl, COLLECT_DOM_SCRIPT, 2500, found.port);
9981
10385
  if (!Array.isArray(elements)) return void 0;
9982
10386
  return {
9983
10387
  port: found.port,
@@ -9990,7 +10394,7 @@ async function readCdpElements(options = {}) {
9990
10394
  async function readCdpText(options = {}) {
9991
10395
  const found = await findCdpTarget(options);
9992
10396
  if (!found?.target.webSocketDebuggerUrl) return void 0;
9993
- const text = await evalCdpJson(found.target.webSocketDebuggerUrl, "String(document.body && document.body.innerText ? document.body.innerText : \"\")");
10397
+ const text = await evalCdpJson(found.target.webSocketDebuggerUrl, "String(document.body && document.body.innerText ? document.body.innerText : \"\")", 2500, found.port);
9994
10398
  if (typeof text !== "string" || text.trim() === "") return void 0;
9995
10399
  const maxTail = options.tail ?? 4e3;
9996
10400
  return {
@@ -10115,17 +10519,20 @@ const coordinate = {
10115
10519
  items: { type: "number" },
10116
10520
  description: "[x, y] in pixels of the latest screenshot."
10117
10521
  };
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) {
10522
+ /** Reads what a window says through UI Automation (falling back to CDP when enabled, then Windows OCR). */
10523
+ async function windowText(computer, call, hwnd, tail) {
10120
10524
  const maxTail = Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)));
10525
+ const targetWin = hwnd === void 0 ? await computer.foreground().catch(() => void 0) : (await computer.windows().catch(() => [])).find((w) => w.hwnd === hwnd);
10526
+ if (targetWin) computer.assertReadable(call, targetWin, "read text from");
10121
10527
  const result = await computer.helper.call("text", {
10122
10528
  ...hwnd === void 0 ? {} : { hwnd },
10123
10529
  tail: maxTail
10124
10530
  }, 2e4);
10531
+ if (result.exe) computer.assertReadable(call, result, "read text from");
10125
10532
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
10126
10533
  if (!result.text || result.source === "none") {
10127
- if (isBrowser(result)) {
10128
- const s = computer.settings();
10534
+ const s = computer.settings();
10535
+ if (isBrowser(result) && (s.cdpEnabled || s.cdpPort > 0)) {
10129
10536
  const cdp = await readCdpText({
10130
10537
  ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
10131
10538
  titleHint: result.title,
@@ -10224,16 +10631,18 @@ function createTools(host) {
10224
10631
  async execute(args, exec) {
10225
10632
  const call = await host.context(exec);
10226
10633
  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
- }
10634
+ return computer.lease.withLease(call.session, call.signal, async () => {
10635
+ try {
10636
+ const outcome = await computer.run(input, call);
10637
+ if (outcome.image) return withShot(host, outcome.text, outcome.image, call);
10638
+ if (input.action === "screenshot" || input.action === "zoom") return { text: outcome.text };
10639
+ const shot = await computer.after([input], call);
10640
+ return withShot(host, shot === void 0 && input.action !== "wait" && input.action !== "cursor_position" ? `${outcome.text} ${await computer.describeForeground()}` : outcome.text, shot, call);
10641
+ } catch (error) {
10642
+ if (call.signal.aborted) await computer.releaseHeld();
10643
+ throw error;
10644
+ }
10645
+ });
10237
10646
  },
10238
10647
  presentCall: (args) => card(`电脑操作 · ${Computer.statusOf(args)}`)
10239
10648
  }));
@@ -10295,57 +10704,62 @@ function createTools(host) {
10295
10704
  }
10296
10705
  const finish = rawArgs.finish ?? "screenshot";
10297
10706
  const detail = rawArgs.detail;
10298
- let zoomed;
10299
- let endedWithZoom = false;
10300
10707
  if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array (or pass a saved macro name).");
10301
10708
  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}`;
10709
+ return computer.lease.withLease(call.session, call.signal, async () => {
10710
+ let zoomed;
10711
+ let skippedImage;
10712
+ let endedWithZoom = false;
10713
+ const lines = [];
10714
+ let failure;
10715
+ for (const [index, input] of actions.entries()) {
10716
+ if (input.action === "screenshot" || input.action === "zoom" && index !== actions.length - 1) {
10717
+ failure = `#${index + 1} ${input.action}: ${input.action === "zoom" ? "only allowed as the last action of a batch" : "not allowed in a batch"}.`;
10319
10718
  break;
10320
10719
  }
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.`;
10720
+ try {
10721
+ const stepStart = Date.now();
10722
+ if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
10723
+ const outcome = await computer.run(input, call);
10724
+ if (input.action === "zoom") {
10725
+ endedWithZoom = true;
10726
+ zoomed = outcome.image;
10727
+ }
10728
+ if (outcome.skipped) {
10729
+ skippedImage = outcome.image;
10730
+ failure = `#${index + 1} ${input.action} skipped: ${outcome.text}`;
10731
+ break;
10732
+ }
10733
+ lines.push(`#${index + 1} ${outcome.text}`);
10734
+ await setTimeout$1(60, void 0, { signal: call.signal });
10735
+ if (computer.settings().pauseOnUserInput && (computer.overlay.userTypedSince(stepStart - 1) || computer.overlay.hasUserActions?.())) {
10736
+ const notes = await computer.drainUserActionNotes();
10737
+ const kind = notes ? "intervened with mouse/keyboard" : "typed on the keyboard";
10738
+ failure = `#${index + 1} done, but the user ${kind} meanwhile; remaining actions stopped.${notes} Re-check the screen before continuing.`;
10739
+ break;
10740
+ }
10741
+ } catch (error) {
10742
+ if (call.signal.aborted) {
10743
+ await computer.releaseHeld();
10744
+ throw error;
10745
+ }
10746
+ failure = `#${index + 1} ${input.action} failed: ${error instanceof Error ? error.message : String(error)}`;
10327
10747
  break;
10328
10748
  }
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
10749
  }
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);
10750
+ const done = lines.join("\n");
10751
+ const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
10752
+ if (endedWithZoom && failure === void 0) return zoomed ? withShot(host, summary, zoomed, call) : { text: summary };
10753
+ if (failure === void 0 && finish === "none") return { text: `${summary}\n${await computer.describeForeground()}` };
10754
+ if (failure === void 0 && finish === "text") {
10755
+ await computer.settle(call.signal);
10756
+ 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)}`)}` };
10757
+ }
10758
+ if (skippedImage) return withShot(host, summary, skippedImage, call);
10759
+ const waited = failure === void 0 && actions[actions.length - 1]?.action === "wait";
10760
+ const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot(detail)) : void 0;
10761
+ return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
10762
+ });
10349
10763
  },
10350
10764
  presentCall: (args) => card(`电脑操作 · 批量 ${args.actions?.length ?? 0} 步`)
10351
10765
  }));
@@ -10447,6 +10861,12 @@ function createTools(host) {
10447
10861
  if (now?.exe.toLowerCase() === browser.exe && !existing.has(now.hwnd)) {
10448
10862
  openedUrlWindow = now;
10449
10863
  how = `Opened ${name} in a new browser window.`;
10864
+ const blankTitle = (t) => /^(?:$|无标题|untitled|new tab|新标签页|about:blank)(?:\s*[-–—].*)?$/i.test(t.trim());
10865
+ if (blankTitle(now.title)) for (let j = 0; j < 12; j++) {
10866
+ await setTimeout$1(200, void 0, { signal: call.signal });
10867
+ const cur = await computer.foreground().catch(() => void 0);
10868
+ if (!cur || cur.hwnd !== now.hwnd || !blankTitle(cur.title)) break;
10869
+ }
10450
10870
  break;
10451
10871
  }
10452
10872
  continue;
@@ -10561,12 +10981,16 @@ function createTools(host) {
10561
10981
  }));
10562
10982
  tools.push(defineTool({
10563
10983
  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.",
10984
+ 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
10985
  parameters: {
10566
10986
  hwnd: {
10567
10987
  type: "integer",
10568
10988
  description: "Window handle; default foreground window."
10569
10989
  },
10990
+ diff: {
10991
+ type: "boolean",
10992
+ description: "Incremental UIA diff: return only added, changed, and removed controls since the last read of this window (captures baseline on first call)."
10993
+ },
10570
10994
  marks: {
10571
10995
  type: "boolean",
10572
10996
  description: "Return a Set-of-Marks numbered screenshot alongside the element list so you can target controls by \"#1\", \"#2\", ..."
@@ -10581,7 +11005,7 @@ function createTools(host) {
10581
11005
  },
10582
11006
  cdp: {
10583
11007
  type: "boolean",
10584
- description: "Inspect visible DOM controls directly over a local Chrome/Edge CDP port (falls back to UIA if unavailable)."
11008
+ description: "Inspect visible DOM controls directly over a local Chrome/Edge CDP port when enabled in settings (falls back cleanly if unavailable)."
10585
11009
  },
10586
11010
  tail: {
10587
11011
  type: "integer",
@@ -10598,15 +11022,83 @@ function createTools(host) {
10598
11022
  },
10599
11023
  output,
10600
11024
  timeoutMs: 3e4,
10601
- isConcurrencySafe: () => true,
10602
11025
  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;
11026
+ const call = await host.context(exec);
11027
+ const { hwnd, diff, marks, include_text: includeText, max, text, ocr, cdp, tail } = args;
11028
+ return computer.lease.withLease(call.session, call.signal, async () => {
11029
+ const targetWin = hwnd === void 0 ? await computer.foreground().catch(() => void 0) : (await computer.windows().catch(() => [])).find((w) => w.hwnd === hwnd);
11030
+ if (targetWin) computer.assertReadable(call, targetWin, "read UI elements of");
11031
+ if (marks === true) {
11032
+ const { window: win, elements, shot } = await computer.marks(hwnd, max ?? 120);
11033
+ if (win.exe) computer.assertReadable(call, win, "read UI elements of");
11034
+ const lines = [];
11035
+ for (const [index, el] of elements.entries()) {
11036
+ const num = el.mark ?? index + 1;
11037
+ const center = await computer.toModel({
11038
+ x: el.x + el.width / 2,
11039
+ y: el.y + el.height / 2
11040
+ });
11041
+ const flags = [
11042
+ el.password ? "password" : "",
11043
+ el.value !== void 0 ? `value="${el.value}"` : "",
11044
+ el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
11045
+ el.disabled ? "disabled" : "",
11046
+ el.editable ? "editable" : ""
11047
+ ].filter(Boolean).join(" ");
11048
+ lines.push(`[#${num}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
11049
+ }
11050
+ 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).`;
11051
+ return withShot(host, lines.length ? `${head}\n${lines.join("\n")}` : head, shot, call);
11052
+ }
11053
+ if (cdp === true) {
11054
+ const s = computer.settings();
11055
+ 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 })." };
11056
+ const fg = targetWin ?? await computer.foreground().catch(() => void 0);
11057
+ if (fg) computer.assertReadable(call, fg, "read browser DOM of", true);
11058
+ const snap = await readCdpElements({
11059
+ ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
11060
+ ...fg?.title ? { titleHint: fg.title } : {},
11061
+ ...s.harnessUrl ? { harnessUrl: s.harnessUrl } : {}
11062
+ }).catch(() => void 0);
11063
+ if (snap) {
11064
+ const limit = Math.min(200, Math.max(10, max ?? 120));
11065
+ const lines = snap.elements.slice(0, limit).map((el, i) => {
11066
+ const flags = [
11067
+ el.password ? "password" : "",
11068
+ el.value !== void 0 ? `value="${el.value}"` : "",
11069
+ el.editable ? "editable" : "",
11070
+ el.selector ? `selector=${el.selector}` : ""
11071
+ ].filter(Boolean).join(" ");
11072
+ return `[${i}] ${el.role} "${el.name}" viewport=(${el.x + Math.round(el.width / 2)}, ${el.y + Math.round(el.height / 2)})${flags ? ` ${flags}` : ""}`;
11073
+ });
11074
+ return { text: `CDP (port ${snap.port}) — "${snap.title.slice(0, 80)}" (${snap.url}): ${snap.elements.length} DOM elements.\n${lines.join("\n")}` };
11075
+ }
11076
+ 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 })." };
11077
+ }
11078
+ if (ocr === true) {
11079
+ const result = await computer.ocr(hwnd);
11080
+ if (result.exe) computer.assertReadable(call, result, "read OCR text from");
11081
+ const limit = Math.min(400, Math.max(10, max ?? 120));
11082
+ const lines = [];
11083
+ for (const [index, line] of (result.lines ?? []).slice(0, limit).entries()) {
11084
+ const center = await computer.toModel({
11085
+ x: line.x + line.width / 2,
11086
+ y: line.y + line.height / 2
11087
+ });
11088
+ lines.push(`[${index}] "${line.text}" @ (${center.x}, ${center.y})${center.offscreen ? " other display" : ""}`);
11089
+ }
11090
+ const head = `${result.exe ?? "screen"} — "${String(result.title ?? "").slice(0, 80)}": ${result.lines?.length ?? 0} OCR lines (${result.language || "auto"}).`;
11091
+ return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} No readable text found by Windows OCR.` };
11092
+ }
11093
+ if (text === true) return { text: await windowText(computer, call, hwnd, tail) };
11094
+ const result = await computer.helper.call("ui", {
11095
+ ...hwnd === void 0 ? {} : { hwnd },
11096
+ includeText: includeText === true,
11097
+ popups: true,
11098
+ maxNodes: Math.min(400, Math.max(10, max ?? 120))
11099
+ }, 2e4);
11100
+ if (result.exe) computer.assertReadable(call, result, "read UI elements of");
11101
+ const formatEl = async (prefix, el, suffix = "") => {
10610
11102
  const center = await computer.toModel({
10611
11103
  x: el.x + el.width / 2,
10612
11104
  y: el.y + el.height / 2
@@ -10616,81 +11108,35 @@ function createTools(host) {
10616
11108
  el.value !== void 0 ? `value="${el.value}"` : "",
10617
11109
  el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
10618
11110
  el.disabled ? "disabled" : "",
10619
- el.editable ? "editable" : ""
11111
+ el.automationId ? `automationId=${JSON.stringify(el.automationId)}` : "",
11112
+ el.focusable !== void 0 ? `focusable=${el.focusable}` : "",
11113
+ el.editable ? "editable" : "",
11114
+ center.offscreen ? "other display" : ""
10620
11115
  ].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));
11116
+ return `${prefix} ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}${suffix}`;
11117
+ };
11118
+ const winHwnd = typeof result.hwnd === "number" ? result.hwnd : targetWin?.hwnd;
11119
+ if (diff === true && typeof winHwnd === "number") {
11120
+ const delta = computer.uiDiff.diff(winHwnd, String(result.title ?? ""), result.elements);
11121
+ if (!delta.isBaseline) {
11122
+ const lines = [];
11123
+ if (delta.titleChanged) lines.push(`~ Title: "${String(delta.previousTitle ?? "").slice(0, 50)}" -> "${String(result.title ?? "").slice(0, 50)}"`);
11124
+ for (const el of delta.added) lines.push(await formatEl("+", el));
11125
+ for (const ch of delta.changed) lines.push(await formatEl("~", ch.element, ` [${ch.changes.join(", ")}]`));
11126
+ for (const el of delta.removed) lines.push(`- ${el.role} "${el.name}"`);
11127
+ 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).`;
11128
+ return { text: lines.length ? `${summary}\n${lines.join("\n")}` : `${summary} No UI control changes.` };
11129
+ }
11130
+ } else if (typeof winHwnd === "number") computer.uiDiff.record(winHwnd, String(result.title ?? ""), result.elements);
10652
11131
  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.` };
11132
+ for (const [index, el] of result.elements.entries()) lines.push(await formatEl(`[${index}]`, el));
11133
+ const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements${diff === true ? " (baseline captured; next diff: true returns changes only)" : ""}.`;
11134
+ 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.` };
11135
+ });
10690
11136
  },
10691
11137
  presentCall: (args) => {
10692
11138
  const a = args;
10693
- return card(a.marks ? "编号标图 (Set-of-Marks)" : a.cdp ? "CDP 读取网页元素" : a.ocr ? "OCR 识别文字" : "读取界面元素");
11139
+ return card(a.marks ? "编号标图 (Set-of-Marks)" : a.cdp ? "CDP 读取网页元素" : a.ocr ? "OCR 识别文字" : a.diff ? "增量读取界面变化" : "读取界面元素");
10694
11140
  }
10695
11141
  }));
10696
11142
  tools.push(defineTool({
@@ -10709,17 +11155,22 @@ function createTools(host) {
10709
11155
  },
10710
11156
  output,
10711
11157
  async execute(args, exec) {
11158
+ const call = await host.context(exec);
10712
11159
  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)}` };
11160
+ return computer.lease.withLease(call.session, call.signal, async () => {
11161
+ if (action === "write") {
11162
+ computer.clipboardAgent = call.agent;
11163
+ await computer.helper.call("clipboard_set", {
11164
+ text: text ?? "",
11165
+ agent: true
11166
+ });
11167
+ return { text: `Clipboard set (${(text ?? "").length} characters).` };
11168
+ }
11169
+ const fg = await computer.foreground().catch(() => void 0);
11170
+ if (fg && !isHostWindow(fg)) computer.assertReadable(call, fg, "read clipboard while focused on", true);
11171
+ const result = await computer.helper.call("clipboard_get");
11172
+ return { text: result.text === "" ? "Clipboard has no text." : `Clipboard text:\n${result.text.slice(0, 2e4)}` };
11173
+ });
10723
11174
  },
10724
11175
  presentCall: (args) => card(`剪贴板 · ${args.action === "write" ? "写入" : "读取"}`)
10725
11176
  }));
@@ -11103,9 +11554,13 @@ const Config = z.object({
11103
11554
  "zh-CN": { $description: "窗口位移或被新弹窗遮挡时阻止盲点坐标并提示模型先重新看屏" },
11104
11555
  "en-US": { $description: "Guard coordinate clicks when the foreground window moved/resized or is occluded since the last screenshot" }
11105
11556
  }),
11557
+ cdpEnabled: z.boolean().default(false).volatile().i18n({
11558
+ "zh-CN": { $description: "启用可选本机 Chromium CDP 浏览器快车道(仅连接 127.0.0.1 调试端口且严格按当前标签标题匹配,匹配失败自动回退 UIA/OCR)" },
11559
+ "en-US": { $description: "Enable optional local Chromium CDP fast-lane (loopback-only with strict active-tab matching; falls back to UIA/OCR on mismatch)" }
11560
+ }),
11106
11561
  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)" }
11562
+ "zh-CN": { $description: "可选 Chromium 远程调试端口(0 为默认 9222),仅在启用 CDP 开关或显式设置非 0 端口时生效" },
11563
+ "en-US": { $description: "Optional local Chromium CDP debugging port (0 uses 9222 when CDP is enabled)" }
11109
11564
  }),
11110
11565
  blockedApps: z.array(z.string()).default([]).volatile().i18n({
11111
11566
  "zh-CN": { $description: "禁止操控的应用(名称或 exe,如 “alipay”)。常见密码管理器默认已禁止。" },
@@ -11375,8 +11830,12 @@ function apply(ctx, config = {}) {
11375
11830
  }));
11376
11831
  };
11377
11832
  ctx.on("agent/status", ({ agent, status }) => {
11833
+ const target = agent;
11378
11834
  if (status === "running") computer.resetLook();
11379
- if (status === "idle") overlay.forgetResume(agent);
11835
+ if (status === "idle") {
11836
+ overlay.forgetResume(agent);
11837
+ computer.lease.release(target.session.id);
11838
+ }
11380
11839
  if (status === "idle" && computer.clipboardAgent === agent) {
11381
11840
  computer.clipboardAgent = void 0;
11382
11841
  helper.call("clipboard_restore").catch(() => {});
@@ -11393,6 +11852,7 @@ function apply(ctx, config = {}) {
11393
11852
  } catch {}
11394
11853
  }
11395
11854
  overlay.forgetResume(agent);
11855
+ computer.lease.release(target.session.id);
11396
11856
  access.forget(target.session.id);
11397
11857
  if (overlay.controller === agent) overlay.end();
11398
11858
  });