@copylee/dsh-computer-use 0.9.0 → 0.11.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
@@ -1,11 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
4
  import z from "@deepseek-ai/schemastery";
4
5
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
6
+ import { arch, homedir, platform, release, tmpdir } from "node:os";
5
7
  import { execFile, spawn } from "node:child_process";
6
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
8
  import { chmod, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
- import { homedir, tmpdir } from "node:os";
9
9
  import { dirname, join } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
  import { Worker } from "node:worker_threads";
@@ -103,6 +103,38 @@ const DEFAULT_BLOCKED = [
103
103
  "nordpass",
104
104
  "proton pass"
105
105
  ];
106
+ /** Command interpreters and script hosts refused by open_application so it never acts as a hidden shell. */
107
+ const COMMAND_INTERPRETERS = /* @__PURE__ */ new Set([
108
+ "cmd",
109
+ "powershell",
110
+ "pwsh",
111
+ "wscript",
112
+ "cscript",
113
+ "mshta",
114
+ "rundll32",
115
+ "regsvr32",
116
+ "msiexec",
117
+ "conhost",
118
+ "schtasks",
119
+ "forfiles",
120
+ "wsl",
121
+ "bash",
122
+ "sh",
123
+ "命令提示符"
124
+ ]);
125
+ /**
126
+ * True when an open_application target refers to a command interpreter or
127
+ * script host (with or without path/extension/arguments).
128
+ */
129
+ function isCommandInterpreter(target) {
130
+ const trimmed = target.trim();
131
+ if (trimmed === "" || /^https?:\/\//i.test(trimmed)) return false;
132
+ const first = trimmed.startsWith("\"") ? trimmed.slice(1).split("\"")[0] ?? "" : trimmed.split(/\s+/)[0] ?? "";
133
+ const base = normalizeApp((first.split(/[\\/]/).pop() ?? first).replace(/\.(exe|com|bat|cmd)$/i, ""));
134
+ if (COMMAND_INTERPRETERS.has(base)) return true;
135
+ const whole = normalizeApp(trimmed.replace(/\.(exe|com|bat|cmd)$/i, ""));
136
+ return COMMAND_INTERPRETERS.has(whole);
137
+ }
106
138
  function normalizeApp(name) {
107
139
  return name.trim().toLowerCase().replace(/\.exe$/, "").replace(/\s+/g, " ");
108
140
  }
@@ -175,6 +207,24 @@ var AccessControl = class {
175
207
  const set = this.grants.get(session) ?? /* @__PURE__ */ new Set();
176
208
  return names.filter((name) => !set.has(normalizeApp(name)) && ![...set].some((granted) => sameApp(granted, name)));
177
209
  }
210
+ /** Remove matching app grants (or all grants when `name` is "all" / "*"). Returns revoked entries. */
211
+ revoke(session, name) {
212
+ const set = this.grants.get(session);
213
+ if (!set || set.size === 0) return [];
214
+ const q = normalizeApp(name);
215
+ if (q === "" || q === "all" || q === "*") {
216
+ const all = [...set];
217
+ this.grants.delete(session);
218
+ return all;
219
+ }
220
+ const removed = [];
221
+ for (const item of [...set]) if (item === q || sameApp(item, q)) {
222
+ set.delete(item);
223
+ removed.push(item);
224
+ }
225
+ if (set.size === 0) this.grants.delete(session);
226
+ return removed;
227
+ }
178
228
  forget(session) {
179
229
  this.grants.delete(session);
180
230
  }
@@ -957,15 +1007,32 @@ var Computer = class Computer {
957
1007
  }
958
1008
  /** The foreground window as of the model's latest look at the screen. */
959
1009
  seen;
1010
+ /** Snapshot of the foreground window geometry captured during the latest screenshot/marks look. */
1011
+ lastShotWindow;
1012
+ /** Most recent Set-of-Marks element list so `target: "#12"` resolves directly. */
1013
+ lastMarks;
960
1014
  /** The latest foreground window that was not DeepSeek Harness itself. */
961
1015
  lastTarget;
962
1016
  /** A new turn starts: the user may have rearranged things while chatting. */
963
1017
  resetLook() {
964
1018
  this.seen = void 0;
1019
+ this.lastShotWindow = void 0;
965
1020
  }
966
1021
  async remember() {
967
1022
  const now = await this.foreground().catch(() => void 0);
968
- if (!now || !isTransientShell(now)) this.seen = now;
1023
+ if (!now || !isTransientShell(now)) {
1024
+ this.seen = now;
1025
+ this.lastShotWindow = now && !isHostWindow(now) && now.width > 0 && now.height > 0 ? {
1026
+ hwnd: now.hwnd,
1027
+ pid: now.pid,
1028
+ exe: now.exe,
1029
+ title: now.title,
1030
+ x: now.x,
1031
+ y: now.y,
1032
+ width: now.width,
1033
+ height: now.height
1034
+ } : void 0;
1035
+ }
969
1036
  }
970
1037
  /**
971
1038
  * Did another window come to the front since the model last looked, without
@@ -1137,7 +1204,17 @@ var Computer = class Computer {
1137
1204
  }
1138
1205
  async checkPointer(call, point, verb) {
1139
1206
  const target = point ?? await this.cursor();
1140
- this.checkWebContent(await this.assertAllowed(call, await this.windowAt(target), verb), target);
1207
+ const hit = await this.windowAt(target);
1208
+ this.checkWebContent(await this.assertAllowed(call, hit, verb), target);
1209
+ if (point && this.settings().windowChangeGuard && this.lastShotWindow) {
1210
+ const snap = this.lastShotWindow;
1211
+ const cur = await this.foreground().catch(() => void 0);
1212
+ if (cur && cur.hwnd === snap.hwnd) {
1213
+ if (Math.abs(cur.x - snap.x) > 24 || Math.abs(cur.y - snap.y) > 24 || Math.abs(cur.width - snap.width) > 24 || Math.abs(cur.height - snap.height) > 24) throw new Error(`WINDOW_CHANGED: ${cur.exe} ("${cur.title.slice(0, 50)}") moved or resized since your last screenshot. Take a fresh screenshot before clicking coordinates.`);
1214
+ if (point.x >= snap.x && point.x < snap.x + snap.width && point.y >= snap.y && point.y < snap.y + snap.height && hit && hit.hwnd !== snap.hwnd && hit.pid !== snap.pid && !isTransientShell(hit)) throw new Error(`WINDOW_CHANGED: (${point.x}, ${point.y}) is now covered by ${hit.exe} ("${hit.title.slice(0, 50)}") instead of ${snap.exe}. Take a fresh screenshot before clicking.`);
1215
+ }
1216
+ }
1217
+ return hit;
1141
1218
  }
1142
1219
  async checkKeyboard(call, verb) {
1143
1220
  const window = await this.foreground();
@@ -1206,15 +1283,97 @@ var Computer = class Computer {
1206
1283
  }, 2e4);
1207
1284
  return Array.isArray(result.elements) ? result.elements : [];
1208
1285
  }
1209
- /** Look for a named control in the window, and only if it is not there in its popups. */
1286
+ /** Read visible text and physical bounding boxes via built-in Windows OCR. */
1287
+ async ocr(hwnd) {
1288
+ return this.helper.call("ocr", hwnd === void 0 ? {} : { hwnd }, 2e4);
1289
+ }
1290
+ /** Capture a Set-of-Marks annotated screenshot and cache indexed elements so `target: "#N"` works directly. */
1291
+ async marks(hwnd, max = 120) {
1292
+ await this.refreshDisplays();
1293
+ const display = await this.display();
1294
+ const budget = this.shotBudget("high");
1295
+ const out = screenshotSize(display, budget);
1296
+ const raw = await this.helper.call("marks", {
1297
+ ...hwnd === void 0 ? {} : { hwnd },
1298
+ x: display.x,
1299
+ y: display.y,
1300
+ width: display.width,
1301
+ height: display.height,
1302
+ outWidth: out.width,
1303
+ outHeight: out.height,
1304
+ quality: budget.jpegQuality,
1305
+ maxNodes: Math.min(200, Math.max(10, max)),
1306
+ popups: true
1307
+ }, 3e4);
1308
+ const elements = Array.isArray(raw.elements) ? raw.elements : [];
1309
+ const shot = {
1310
+ data: Buffer.from(raw.data, "base64"),
1311
+ width: raw.width,
1312
+ height: raw.height
1313
+ };
1314
+ this.lastShot = {
1315
+ displayKey: displayKey(display),
1316
+ size: {
1317
+ width: shot.width,
1318
+ height: shot.height
1319
+ }
1320
+ };
1321
+ if (typeof raw.hwnd === "number") this.lastMarks = {
1322
+ hwnd: raw.hwnd,
1323
+ at: Date.now(),
1324
+ elements
1325
+ };
1326
+ await this.remember();
1327
+ return {
1328
+ window: raw,
1329
+ elements,
1330
+ shot
1331
+ };
1332
+ }
1333
+ /**
1334
+ * Look for a named control in the window, then its popups, and when the UIA
1335
+ * tree is empty or sparse (<= 20 controls, e.g. canvas/WebView/game/custom
1336
+ * UIs), fall back to built-in Windows OCR so `target` still finds visible text.
1337
+ */
1210
1338
  async find(target, hwnd) {
1211
1339
  const inWindow = await this.elements("window", hwnd).catch(() => []);
1212
1340
  const match = matchTarget(inWindow, target);
1213
1341
  if (match.kind !== "missing") return match;
1214
1342
  const inPopups = await this.elements("popups", hwnd).catch(() => []);
1215
- if (inPopups.length === 0) return match;
1216
- const second = matchTarget(inPopups, target);
1217
- return second.kind === "missing" ? matchTarget([...inWindow, ...inPopups], target) : second;
1343
+ if (inPopups.length > 0) {
1344
+ const second = matchTarget(inPopups, target);
1345
+ if (second.kind !== "missing") return second;
1346
+ const combined = matchTarget([...inWindow, ...inPopups], target);
1347
+ if (combined.kind !== "missing") return combined;
1348
+ }
1349
+ const trimmed = target.trim();
1350
+ if (!/^(id[::]|#)/i.test(trimmed) && inWindow.length + inPopups.length <= 20) {
1351
+ const ocr = await this.ocr(hwnd).catch(() => void 0);
1352
+ if (ocr && Array.isArray(ocr.lines) && ocr.lines.length > 0) {
1353
+ const ocrElements = [];
1354
+ for (const line of ocr.lines) {
1355
+ ocrElements.push({
1356
+ role: "Text",
1357
+ name: line.text,
1358
+ x: line.x,
1359
+ y: line.y,
1360
+ width: line.width,
1361
+ height: line.height
1362
+ });
1363
+ for (const word of line.words ?? []) if (word.text.trim() !== "" && word.text !== line.text) ocrElements.push({
1364
+ role: "Text",
1365
+ name: word.text,
1366
+ x: word.x,
1367
+ y: word.y,
1368
+ width: word.width,
1369
+ height: word.height
1370
+ });
1371
+ }
1372
+ const ocrMatch = matchTarget(ocrElements, target);
1373
+ if (ocrMatch.kind !== "missing") return ocrMatch;
1374
+ }
1375
+ }
1376
+ return inPopups.length === 0 ? match : matchTarget([...inWindow, ...inPopups], target);
1218
1377
  }
1219
1378
  /**
1220
1379
  * Where a named control is. It may still be appearing (the menu just
@@ -1223,10 +1382,23 @@ var Computer = class Computer {
1223
1382
  */
1224
1383
  async locate(target, signal, waitMs = TARGET_WAIT_MS) {
1225
1384
  const started = Date.now();
1385
+ const markMatch = /^#(\d+)$/.exec(target.trim());
1226
1386
  for (;;) {
1227
1387
  if (signal.aborted) throw new Error("Cancelled.");
1228
1388
  const window = await this.foreground();
1229
1389
  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) {
1391
+ 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
+ };
1401
+ }
1230
1402
  const match = await this.find(target, window.hwnd);
1231
1403
  if (match.kind === "found") {
1232
1404
  const el = match.element;
@@ -1452,7 +1624,7 @@ var Computer = class Computer {
1452
1624
  case "triple_click": {
1453
1625
  const { point, label, named } = await this.aim(input, call);
1454
1626
  let p = point;
1455
- if (!named) await this.checkPointer(call, p, "click");
1627
+ const hitWin = !named ? await this.checkPointer(call, p, "click") : void 0;
1456
1628
  const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
1457
1629
  const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
1458
1630
  const modifiers = parseModifiers(input.modifiers ?? input.text);
@@ -1460,6 +1632,18 @@ var Computer = class Computer {
1460
1632
  const semantic = named.element.role === "Edit" || named.element.editable ? "focus" : "invoke";
1461
1633
  if (await this.semanticAction(call, named, semantic)) return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
1462
1634
  }
1635
+ if (action === "left_click" && !named && p && modifiers.length === 0 && s.elementFirstClick) {
1636
+ const hit = await this.helper.call("ui_point_click", {
1637
+ x: p.x,
1638
+ y: p.y,
1639
+ ...hitWin ? { hwnd: hitWin.hwnd } : {}
1640
+ }, 2e3).catch(() => null);
1641
+ if (hit?.ok) {
1642
+ const repeat = this.noteClick(p);
1643
+ const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
1644
+ return { text: `Invoked ${hit.name ? `${hit.role || "control"} "${hit.name.slice(0, 40)}"` : hit.role || "control"}${label} in background (${hit.mechanism || "uia"}).${repeatHint}` };
1645
+ }
1646
+ }
1463
1647
  if (named) p = await this.namedClickPoint(call, input.target, named);
1464
1648
  const labelCoord = input.coordinate ? {
1465
1649
  labelX: Math.round(input.coordinate[0]),
@@ -1473,7 +1657,8 @@ var Computer = class Computer {
1473
1657
  ...labelCoord,
1474
1658
  button,
1475
1659
  count,
1476
- modifiers
1660
+ modifiers,
1661
+ ...s.restorePointer ? { restorePointer: true } : {}
1477
1662
  });
1478
1663
  const clickedAt = p ?? (typeof clickRes?.x === "number" && typeof clickRes?.y === "number" ? {
1479
1664
  x: clickRes.x,
@@ -1534,6 +1719,7 @@ var Computer = class Computer {
1534
1719
  let into = "";
1535
1720
  if (input.target || input.coordinate) {
1536
1721
  const { point, label, named } = await this.aim(input, call);
1722
+ 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.`);
1537
1723
  let p = point;
1538
1724
  const focused = named && await this.semanticAction(call, named, "focus");
1539
1725
  if (!focused) {
@@ -1551,7 +1737,15 @@ var Computer = class Computer {
1551
1737
  into = ` (${focused ? "focused" : "clicked"}${label} first)`;
1552
1738
  }
1553
1739
  await this.checkKeyboard(call, "type into");
1554
- return { text: `${await this.enterText(text, call)}${into}` };
1740
+ if (s.protectPasswords) {
1741
+ const pwd = await this.helper.call("password_focus", {}, 1500).catch(() => null);
1742
+ 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.`);
1743
+ }
1744
+ if (input.replace === true) {
1745
+ await this.sendKeys(call, parseKeys("ctrl+a"));
1746
+ await setTimeout$1(50, void 0, { signal: call.signal });
1747
+ }
1748
+ return { text: `${await this.enterText(text, call)}${input.replace === true ? " (replaced existing text)" : ""}${into}` };
1555
1749
  }
1556
1750
  case "key": {
1557
1751
  const combos = parseKeys(input.text ?? "");
@@ -1659,6 +1853,131 @@ var Computer = class Computer {
1659
1853
  }
1660
1854
  };
1661
1855
  //#endregion
1856
+ //#region lib/types/diagnostics.js
1857
+ /**
1858
+ * Sanitized diagnostic report for troubleshooting and bug reports.
1859
+ * Records only tool names, action kinds, durations and short error messages —
1860
+ * never typed text, clipboard contents, window text, or screenshot images.
1861
+ */
1862
+ const MAX_CALLS = 30;
1863
+ var DiagnosticsLog = class {
1864
+ calls = [];
1865
+ record(entry) {
1866
+ const item = {
1867
+ at: entry.at ?? (/* @__PURE__ */ new Date()).toISOString(),
1868
+ tool: entry.tool,
1869
+ ...entry.action ? { action: entry.action } : {},
1870
+ durationMs: Math.max(0, Math.round(entry.durationMs)),
1871
+ ok: entry.ok,
1872
+ ...entry.error ? { error: sanitizeError(entry.error) } : {}
1873
+ };
1874
+ this.calls.push(item);
1875
+ if (this.calls.length > MAX_CALLS) this.calls.shift();
1876
+ }
1877
+ recent() {
1878
+ return [...this.calls];
1879
+ }
1880
+ };
1881
+ /** Extract a safe short action summary from tool arguments without leaking typed/clipboard text. */
1882
+ function summarizeToolAction(tool, rawArgs) {
1883
+ if (!rawArgs || typeof rawArgs !== "object") return void 0;
1884
+ const args = rawArgs;
1885
+ if (tool === "computer") {
1886
+ const act = typeof args.action === "string" ? args.action : void 0;
1887
+ if (!act) return void 0;
1888
+ const detail = typeof args.detail === "string" ? ` detail=${args.detail}` : "";
1889
+ const force = args.force === true ? " force=true" : "";
1890
+ return `${act}${act === "type" && typeof args.text === "string" ? ` len=${args.text.length}` : ""}${detail}${force}`;
1891
+ }
1892
+ if (tool === "computer_batch") {
1893
+ const finish = typeof args.finish === "string" ? ` finish=${args.finish}` : "";
1894
+ if (typeof args.macro === "string" && args.macro.trim() !== "") return `macro${finish}`;
1895
+ if (Array.isArray(args.actions)) return `batch(${args.actions.length})${finish}`;
1896
+ }
1897
+ if (tool === "windows" || tool === "clipboard" || tool === "app_skill") return typeof args.action === "string" ? args.action : void 0;
1898
+ if (tool === "ui_elements") return args.marks === true ? "marks" : args.cdp === true ? "cdp" : args.ocr === true ? "ocr" : args.text === true ? "text" : "elements";
1899
+ if (tool === "open_application") return typeof args.name === "string" && /^https?:\/\//i.test(args.name.trim()) ? "url" : "app";
1900
+ }
1901
+ function sanitizeError(raw) {
1902
+ return raw.replace(/[\r\n]+/g, " ").trim().slice(0, 200);
1903
+ }
1904
+ function buildDiagnosticSnapshot(options) {
1905
+ const s = options.settings;
1906
+ const compact = compactLimits({
1907
+ maxLongEdge: s.maxLongEdge,
1908
+ maxPixels: s.maxPixels,
1909
+ jpegQuality: s.jpegQuality
1910
+ });
1911
+ return {
1912
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1913
+ pluginVersion: options.pluginVersion,
1914
+ nodeVersion: process.version,
1915
+ os: `${platform()} ${release()} (${arch()})`,
1916
+ helper: {
1917
+ status: options.helperStatus,
1918
+ nativeAvailable: options.nativeAvailable,
1919
+ ...options.helperError ? { error: sanitizeError(options.helperError) } : {}
1920
+ },
1921
+ displays: options.displays.map((d, index) => ({
1922
+ index,
1923
+ primary: d.primary,
1924
+ width: d.width,
1925
+ height: d.height,
1926
+ dpi: d.dpi,
1927
+ shot: describeScreenshotSize(d, {
1928
+ maxLongEdge: s.maxLongEdge,
1929
+ maxPixels: s.maxPixels
1930
+ }),
1931
+ compactShot: describeScreenshotSize(d, compact)
1932
+ })),
1933
+ settings: {
1934
+ accessMode: s.accessMode,
1935
+ sessionMode: s.sessionMode,
1936
+ defaultSessionEnabled: s.defaultSessionEnabled,
1937
+ overlay: s.overlay,
1938
+ hostWindow: s.hostWindow,
1939
+ cardOpacity: s.cardOpacity,
1940
+ typingMode: s.typingMode,
1941
+ quickSteps: s.quickSteps,
1942
+ autoScreenshot: s.autoScreenshot,
1943
+ autoScreenshotDetail: s.autoScreenshotDetail,
1944
+ settleMs: s.settleMs,
1945
+ maxLongEdge: s.maxLongEdge,
1946
+ maxPixels: s.maxPixels,
1947
+ jpegQuality: s.jpegQuality,
1948
+ pauseOnUserInput: s.pauseOnUserInput,
1949
+ userIdleMs: s.userIdleMs,
1950
+ nativeHelper: s.nativeHelper,
1951
+ elementFirstClick: s.elementFirstClick,
1952
+ restorePointer: s.restorePointer,
1953
+ protectPasswords: s.protectPasswords,
1954
+ windowChangeGuard: s.windowChangeGuard,
1955
+ cdpPort: s.cdpPort,
1956
+ blockedAppsCount: s.blockedApps.length,
1957
+ hasCustomHarnessUrl: Boolean(s.harnessUrl)
1958
+ },
1959
+ recentCalls: options.recentCalls
1960
+ };
1961
+ }
1962
+ function formatDiagnosticText(snap) {
1963
+ return [
1964
+ "=== @copylee/dsh-computer-use Diagnostic Report (sanitized) ===",
1965
+ `Generated: ${snap.generatedAt}`,
1966
+ `Plugin: ${snap.pluginVersion} | Node: ${snap.nodeVersion} | OS: ${snap.os}`,
1967
+ `Helper: ${snap.helper.status} | Native koffi available: ${snap.helper.nativeAvailable}${snap.helper.error ? ` | Error: ${snap.helper.error}` : ""}`,
1968
+ "",
1969
+ "--- Displays ---",
1970
+ ...snap.displays.length === 0 ? ["(none)"] : snap.displays.map((d) => `#${d.index}${d.primary ? " (primary)" : ""}: ${d.width}x${d.height} @ ${Math.round(d.dpi / 96 * 100)}% DPI | shot=${d.shot.width}x${d.shot.height} (${d.shot.megapixels}MP, ${d.shot.limitedBy}) | compact=${d.compactShot.width}x${d.compactShot.height}`),
1971
+ "",
1972
+ "--- Settings ---",
1973
+ JSON.stringify(snap.settings, null, 2),
1974
+ "",
1975
+ `--- Recent Tool Calls (${snap.recentCalls.length}) ---`,
1976
+ ...snap.recentCalls.length === 0 ? ["(none)"] : snap.recentCalls.map((c) => `${c.at} | ${c.tool}${c.action ? `:${c.action}` : ""} | ${c.ok ? "OK" : "ERR"} | ${c.durationMs}ms${c.error ? ` | ${c.error}` : ""}`),
1977
+ ""
1978
+ ].join("\n");
1979
+ }
1980
+ //#endregion
1662
1981
  //#region lib/types/helper-client.js
1663
1982
  /**
1664
1983
  * Builds and drives the Windows helper (helper/CuHelper.cs): compiled once
@@ -1936,6 +2255,106 @@ var HelperClient = class HelperClient {
1936
2255
  else entry.reject(new Error(message.error ?? "helper error"));
1937
2256
  }
1938
2257
  };
2258
+ function macroId(name) {
2259
+ return name.trim().toLowerCase().replace(/[\\/:*?"<>|\s.]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "macro";
2260
+ }
2261
+ /** Collect `{{param}}` placeholder names referenced across macro actions. */
2262
+ function extractMacroParams(actions) {
2263
+ const found = /* @__PURE__ */ new Set();
2264
+ const scan = (value) => {
2265
+ if (typeof value !== "string") return;
2266
+ for (const match of value.matchAll(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g)) if (match[1]) found.add(match[1]);
2267
+ };
2268
+ for (const step of actions) {
2269
+ scan(step.target);
2270
+ scan(step.text);
2271
+ scan(step.until);
2272
+ scan(step.modifiers);
2273
+ }
2274
+ return [...found];
2275
+ }
2276
+ /** Substitute `{{param}}` placeholders into a fresh copy of `actions`. */
2277
+ function renderMacroActions(actions, params = {}) {
2278
+ const missing = /* @__PURE__ */ new Set();
2279
+ const replace = (raw) => {
2280
+ if (raw === void 0) return void 0;
2281
+ return raw.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_whole, key) => {
2282
+ if (Object.prototype.hasOwnProperty.call(params, key) && params[key] !== void 0) return String(params[key]);
2283
+ missing.add(key);
2284
+ return `{{${key}}}`;
2285
+ });
2286
+ };
2287
+ const rendered = actions.map((step) => {
2288
+ const out = { ...step };
2289
+ if (step.text !== void 0) out.text = replace(step.text);
2290
+ if (step.target !== void 0) out.target = replace(step.target);
2291
+ if (step.until !== void 0) out.until = replace(step.until);
2292
+ if (step.modifiers !== void 0) out.modifiers = replace(step.modifiers);
2293
+ return out;
2294
+ });
2295
+ if (missing.size > 0) throw new Error(`Macro is missing required parameter(s): ${[...missing].join(", ")}.`);
2296
+ return rendered;
2297
+ }
2298
+ var MacroStore = class {
2299
+ dir;
2300
+ constructor(dir = join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), "computer-use-macros")) {
2301
+ this.dir = dir;
2302
+ }
2303
+ list() {
2304
+ if (!existsSync(this.dir)) return [];
2305
+ const out = [];
2306
+ for (const file of readdirSync(this.dir)) {
2307
+ if (!file.toLowerCase().endsWith(".json")) continue;
2308
+ try {
2309
+ const path = join(this.dir, file);
2310
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
2311
+ if (!Array.isArray(parsed.actions) || parsed.actions.length === 0) continue;
2312
+ const id = macroId(file.slice(0, -5));
2313
+ out.push({
2314
+ id,
2315
+ name: typeof parsed.name === "string" && parsed.name.trim() !== "" ? parsed.name.trim() : id,
2316
+ ...typeof parsed.app === "string" && parsed.app.trim() !== "" ? { app: parsed.app.trim() } : {},
2317
+ description: typeof parsed.description === "string" ? parsed.description.trim() : "",
2318
+ params: extractMacroParams(parsed.actions),
2319
+ actions: parsed.actions,
2320
+ updatedAt: statSync(path).mtimeMs
2321
+ });
2322
+ } catch {}
2323
+ }
2324
+ return out.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
2325
+ }
2326
+ get(nameOrId) {
2327
+ const wanted = macroId(nameOrId);
2328
+ return this.list().find((item) => item.id === wanted || item.name.toLowerCase() === nameOrId.trim().toLowerCase());
2329
+ }
2330
+ save(input) {
2331
+ const name = input.name.trim();
2332
+ if (name === "") throw new Error("Macro name is required.");
2333
+ if (!Array.isArray(input.actions) || input.actions.length === 0) throw new Error("Macro actions must be a non-empty array.");
2334
+ if (input.actions.length > 30) throw new Error(`A macro may contain at most 30 actions.`);
2335
+ const id = macroId(name);
2336
+ const payload = {
2337
+ version: 1,
2338
+ name,
2339
+ ...input.app?.trim() ? { app: input.app.trim() } : {},
2340
+ description: (input.description ?? "").trim().slice(0, 160),
2341
+ actions: input.actions
2342
+ };
2343
+ mkdirSync(this.dir, { recursive: true });
2344
+ const path = join(this.dir, `${id}.json`);
2345
+ const tmp = `${path}.${process.pid}.tmp`;
2346
+ writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n", "utf8");
2347
+ renameSync(tmp, path);
2348
+ return this.get(id);
2349
+ }
2350
+ remove(nameOrId) {
2351
+ const id = this.get(nameOrId)?.id ?? macroId(nameOrId);
2352
+ const path = join(this.dir, `${id}.json`);
2353
+ if (!existsSync(path)) return false;
2354
+ unlinkSync(path);
2355
+ return true;
2356
+ }
2357
+ };
1939
2358
  //#endregion
1940
2359
  //#region lib/types/native/koffi-path.js
1941
2360
  /**
@@ -2621,9 +3040,11 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
2621
3040
  - If the target window is small or partly covered by other windows, maximize it (windows maximize) or minimize what is in the way (windows minimize works for any window) instead of working around it.
2622
3041
  - 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).
2623
3042
  - 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.
2624
- - When the overlay is enabled, a colored target ring 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.
3043
+ - 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.
3044
+ - 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.
3045
+ - 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.
2625
3046
  - 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.
2626
- - App skills: 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.
3047
+ - 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.
2627
3048
  - Saving: in any Save As dialog do not click through folders; press alt+n (file name box), ctrl+a, type the full path including the file name, then Return. Office apps: F12 opens that classic dialog directly. To check a saved file, look at the exact path; never search a whole drive or user profile recursively.
2628
3049
  - Be fast: what the user waits for is mostly the number of calls you make (each costs seconds). Once you have seen the app's window, put everything predictable into ONE computer_batch, including steps whose target is not on screen yet: name the control with target ("保存", "按钮:确定") instead of a coordinate, and use wait with until ("window:另存为") for a dialog to appear before keys meant for it. Do not end a batch with wait or follow it with a wait or a screenshot: its result already is the settled screen. Do not split work into two batches just to look in between when the second does not depend on what you would see (type the text and format it in the same batch). If you will need to read small text, end the batch with zoom; to read what a window says (a document, a page, a reply, a log) use ui_elements with text: true or finish: "text" instead of scrolling and zooming screenshots. Keep your own text between calls to a line. Avoid shell commands for things you can see on screen.
2629
3050
  - When two controls share a name, ui_elements reports automationId; use target "id:<AutomationId>" (or "#<AutomationId>") to pick the intended one.
@@ -2841,6 +3262,7 @@ var SkillStore = class {
2841
3262
  const ENTRY_ID = "copylee-computer-use";
2842
3263
  const DEFAULTS = {
2843
3264
  accessMode: "per-app",
3265
+ sessionMode: "off",
2844
3266
  defaultSessionEnabled: false,
2845
3267
  overlay: true,
2846
3268
  overlayLabel: "DeepSeek Harness",
@@ -2857,7 +3279,12 @@ const DEFAULTS = {
2857
3279
  userIdleMs: 1500,
2858
3280
  typingMode: "stream",
2859
3281
  quickSteps: false,
2860
- nativeHelper: true
3282
+ nativeHelper: true,
3283
+ elementFirstClick: true,
3284
+ restorePointer: false,
3285
+ protectPasswords: true,
3286
+ windowChangeGuard: true,
3287
+ cdpPort: 0
2861
3288
  };
2862
3289
  /** Unwrap `.volatile()` refs (`{ get() }`) and fall back to defaults for bad values. */
2863
3290
  function resolveConfig(raw) {
@@ -2868,10 +3295,12 @@ function resolveConfig(raw) {
2868
3295
  return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : DEFAULTS[key];
2869
3296
  };
2870
3297
  const bool = (key) => typeof out[key] === "boolean" ? out[key] : DEFAULTS[key];
3298
+ const sessionMode = out.sessionMode === "off" || out.sessionMode === "on" || out.sessionMode === "always" ? out.sessionMode : out.defaultSessionEnabled === true ? "on" : DEFAULTS.sessionMode;
2871
3299
  return {
2872
3300
  harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
2873
3301
  accessMode: out.accessMode === "allow-all" || out.accessMode === "per-app" ? out.accessMode : DEFAULTS.accessMode,
2874
- defaultSessionEnabled: bool("defaultSessionEnabled"),
3302
+ sessionMode,
3303
+ defaultSessionEnabled: sessionMode !== "off",
2875
3304
  overlay: bool("overlay"),
2876
3305
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
2877
3306
  hostWindow: out.hostWindow === "pet" || out.hostWindow === "card" || out.hostWindow === "minimize" || out.hostWindow === "keep" ? out.hostWindow : out.minimizeHostWindow === true ? "minimize" : DEFAULTS.hostWindow,
@@ -2886,6 +3315,11 @@ function resolveConfig(raw) {
2886
3315
  userIdleMs: num("userIdleMs", 300, 1e4),
2887
3316
  quickSteps: bool("quickSteps"),
2888
3317
  nativeHelper: bool("nativeHelper"),
3318
+ elementFirstClick: bool("elementFirstClick"),
3319
+ restorePointer: bool("restorePointer"),
3320
+ protectPasswords: bool("protectPasswords"),
3321
+ windowChangeGuard: bool("windowChangeGuard"),
3322
+ cdpPort: num("cdpPort", 0, 65535),
2889
3323
  typingMode: out.typingMode === "stream" || out.typingMode === "type" || out.typingMode === "paste" ? out.typingMode : DEFAULTS.typingMode,
2890
3324
  blockedApps: Array.isArray(out.blockedApps) ? out.blockedApps.filter((item) => typeof item === "string" && item.trim() !== "") : []
2891
3325
  };
@@ -2962,6 +3396,70 @@ async function* retryMalformed(run, attempts = 3) {
2962
3396
  }
2963
3397
  }
2964
3398
  //#endregion
3399
+ //#region lib/types/update-check.js
3400
+ /**
3401
+ * Concurrent plugin update check probing both npmjs and npmmirror so users in
3402
+ * mainland China and overseas both get fast, reliable latest-version feedback.
3403
+ */
3404
+ const REGISTRIES = [{
3405
+ name: "npmjs",
3406
+ url: "https://registry.npmjs.org/@copylee%2fdsh-computer-use/latest"
3407
+ }, {
3408
+ name: "npmmirror",
3409
+ url: "https://registry.npmmirror.com/@copylee%2fdsh-computer-use/latest"
3410
+ }];
3411
+ /** Compare two semver strings (major.minor.patch); returns >0 when `a > b`. */
3412
+ function compareSemver(a, b) {
3413
+ const parse = (v) => {
3414
+ const parts = (v.trim().replace(/^v/i, "").split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10));
3415
+ return [
3416
+ parts[0] || 0,
3417
+ parts[1] || 0,
3418
+ parts[2] || 0
3419
+ ];
3420
+ };
3421
+ const [a1, a2, a3] = parse(a);
3422
+ const [b1, b2, b3] = parse(b);
3423
+ if (a1 !== b1) return a1 - b1;
3424
+ if (a2 !== b2) return a2 - b2;
3425
+ return a3 - b3;
3426
+ }
3427
+ /** Race npmjs & npmmirror concurrently and return the highest valid version found. */
3428
+ async function checkForUpdate(current, fetchImpl = fetch, timeoutMs = 4500) {
3429
+ const results = await Promise.allSettled(REGISTRIES.map(async (reg) => {
3430
+ const res = await fetchImpl(reg.url, {
3431
+ headers: {
3432
+ accept: "application/json",
3433
+ "cache-control": "no-cache"
3434
+ },
3435
+ signal: AbortSignal.timeout(timeoutMs)
3436
+ });
3437
+ if (!res.ok) throw new Error(`${reg.name}: HTTP ${res.status}`);
3438
+ const body = await res.json();
3439
+ if (typeof body.version !== "string" || !/^\d+\.\d+\.\d+/.test(body.version)) throw new Error(`${reg.name}: invalid version`);
3440
+ return {
3441
+ source: reg.name,
3442
+ version: body.version
3443
+ };
3444
+ }));
3445
+ let best;
3446
+ for (const item of results) {
3447
+ if (item.status !== "fulfilled") continue;
3448
+ if (!best || compareSemver(item.value.version, best.version) > 0) best = item.value;
3449
+ }
3450
+ if (!best) return {
3451
+ current,
3452
+ hasUpdate: false,
3453
+ error: "无法连接 npmjs 或 npmmirror 检测更新"
3454
+ };
3455
+ return {
3456
+ current,
3457
+ latest: best.version,
3458
+ hasUpdate: compareSemver(best.version, current) > 0,
3459
+ source: best.source
3460
+ };
3461
+ }
3462
+ //#endregion
2965
3463
  //#region lib/types/routes.js
2966
3464
  const STATUS_ROUTE = "/api/dsh-computer-use/status";
2967
3465
  const PREVIEW_ROUTE = "/api/dsh-computer-use/preview";
@@ -2969,6 +3467,9 @@ const SCREENSHOTS_ROUTE = "/api/dsh-computer-use/screenshots";
2969
3467
  const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
2970
3468
  const SKILLS_ROUTE = "/api/dsh-computer-use/skills";
2971
3469
  const SESSION_ROUTE = "/api/dsh-computer-use/session";
3470
+ const DIAGNOSTICS_ROUTE = "/api/dsh-computer-use/diagnostics";
3471
+ const UPDATE_ROUTE = "/api/dsh-computer-use/update";
3472
+ const WINDOWS_ROUTE = "/api/dsh-computer-use/windows";
2972
3473
  function json(res, status, body) {
2973
3474
  res.writeHead(status, {
2974
3475
  "content-type": "application/json; charset=utf-8",
@@ -2976,7 +3477,7 @@ function json(res, status, body) {
2976
3477
  });
2977
3478
  res.end(JSON.stringify(body));
2978
3479
  }
2979
- function statusRoute(helper, settings, overlay) {
3480
+ function statusRoute(helper, settings, overlay, pluginVersion = "0.0.0") {
2980
3481
  return async (_req, res) => {
2981
3482
  const s = settings();
2982
3483
  const compact = compactLimits({
@@ -2988,6 +3489,7 @@ function statusRoute(helper, settings, overlay) {
2988
3489
  const displays = await helper.call("displays", {}, 3e4);
2989
3490
  json(res, 200, {
2990
3491
  ok: true,
3492
+ version: pluginVersion,
2991
3493
  platform: process.platform,
2992
3494
  helper: "ready",
2993
3495
  displays: displays.map((d) => ({
@@ -3003,6 +3505,7 @@ function statusRoute(helper, settings, overlay) {
3003
3505
  } catch (error) {
3004
3506
  json(res, 200, {
3005
3507
  ok: true,
3508
+ version: pluginVersion,
3006
3509
  platform: process.platform,
3007
3510
  helper: "error",
3008
3511
  error: error instanceof Error ? error.message : String(error),
@@ -3146,6 +3649,8 @@ function skillsRoute(skills) {
3146
3649
  /** Per-session computer-use toggle: GET ?sessionId=... reads resolved state; POST { sessionId, enabled } updates and syncs live agents. */
3147
3650
  function sessionRoute(gate, settings, parentIdsFor, sync) {
3148
3651
  return async (req, res) => {
3652
+ const s = settings();
3653
+ const alwaysOn = s.sessionMode === "always";
3149
3654
  if (req.method === "POST") {
3150
3655
  const input = await body(req);
3151
3656
  const sessionId = typeof input.sessionId === "string" ? input.sessionId.trim() : "";
@@ -3163,14 +3668,16 @@ function sessionRoute(gate, settings, parentIdsFor, sync) {
3163
3668
  });
3164
3669
  return;
3165
3670
  }
3166
- gate.set(sessionId, input.enabled);
3671
+ if (!alwaysOn) gate.set(sessionId, input.enabled);
3167
3672
  sync();
3168
3673
  json(res, 200, {
3169
3674
  ok: true,
3170
3675
  ...gate.status(sessionId, {
3171
- defaultEnabled: settings().defaultSessionEnabled,
3676
+ defaultEnabled: s.defaultSessionEnabled,
3677
+ alwaysOn,
3172
3678
  parentIds: parentIdsFor(sessionId)
3173
- })
3679
+ }),
3680
+ showPill: !alwaysOn
3174
3681
  });
3175
3682
  return;
3176
3683
  }
@@ -3185,12 +3692,89 @@ function sessionRoute(gate, settings, parentIdsFor, sync) {
3185
3692
  json(res, 200, {
3186
3693
  ok: true,
3187
3694
  ...gate.status(sessionId, {
3188
- defaultEnabled: settings().defaultSessionEnabled,
3695
+ defaultEnabled: s.defaultSessionEnabled,
3696
+ alwaysOn,
3189
3697
  parentIds: parentIdsFor(sessionId)
3190
- })
3698
+ }),
3699
+ showPill: !alwaysOn
3700
+ });
3701
+ };
3702
+ }
3703
+ /** Export a sanitized diagnostic report (plain text by default, or JSON with ?format=json). */
3704
+ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
3705
+ return async (req, res) => {
3706
+ const s = settings();
3707
+ let displays = [];
3708
+ let helperStatus = "ready";
3709
+ let helperError;
3710
+ try {
3711
+ displays = await helper.call("displays", {}, 15e3);
3712
+ } catch (error) {
3713
+ helperStatus = "error";
3714
+ helperError = error instanceof Error ? error.message : String(error);
3715
+ }
3716
+ const snapshot = buildDiagnosticSnapshot({
3717
+ pluginVersion,
3718
+ settings: s,
3719
+ displays,
3720
+ helperStatus,
3721
+ ...helperError ? { helperError } : {},
3722
+ nativeAvailable: helper.available === true,
3723
+ recentCalls: diagnostics.recent()
3724
+ });
3725
+ if (new URL(req.url ?? "/api/dsh-computer-use/diagnostics", "http://127.0.0.1").searchParams.get("format") === "json") {
3726
+ json(res, 200, {
3727
+ ok: true,
3728
+ ...snapshot
3729
+ });
3730
+ return;
3731
+ }
3732
+ const text = formatDiagnosticText(snapshot);
3733
+ const stamp = snapshot.generatedAt.slice(0, 10);
3734
+ res.writeHead(200, {
3735
+ "content-type": "text/plain; charset=utf-8",
3736
+ "content-disposition": `attachment; filename="dsh-computer-use-diagnostics-${stamp}.txt"`,
3737
+ "cache-control": "no-store"
3738
+ });
3739
+ res.end(text);
3740
+ };
3741
+ }
3742
+ /** Check npmjs & npmmirror concurrently for a newer plugin version. */
3743
+ function updateRoute(pluginVersion) {
3744
+ return async (_req, res) => {
3745
+ const result = await checkForUpdate(pluginVersion);
3746
+ json(res, 200, {
3747
+ ok: !result.error,
3748
+ ...result
3191
3749
  });
3192
3750
  };
3193
3751
  }
3752
+ /** Passive read-only window list for `@窗口` composer references (never triggers overlay or focus). */
3753
+ function windowsRoute(helper) {
3754
+ return async (req, res) => {
3755
+ const q = (new URL(req.url ?? "/api/dsh-computer-use/windows", "http://127.0.0.1").searchParams.get("q") ?? "").trim().toLowerCase();
3756
+ try {
3757
+ const raw = await helper.call("windows", {}, 8e3);
3758
+ json(res, 200, {
3759
+ ok: true,
3760
+ windows: (Array.isArray(raw) ? raw : []).filter((win) => !isHostWindow(win) && win.title.trim() !== "").filter((win) => q === "" || win.title.toLowerCase().includes(q) || win.exe.toLowerCase().includes(q)).slice(0, 20).map((win) => ({
3761
+ hwnd: win.hwnd,
3762
+ pid: win.pid,
3763
+ exe: win.exe,
3764
+ title: win.title,
3765
+ minimized: win.minimized,
3766
+ foreground: win.foreground === true
3767
+ }))
3768
+ });
3769
+ } catch (error) {
3770
+ json(res, 200, {
3771
+ ok: false,
3772
+ windows: [],
3773
+ error: error instanceof Error ? error.message : String(error)
3774
+ });
3775
+ }
3776
+ };
3777
+ }
3194
3778
  //#endregion
3195
3779
  //#region lib/types/screenshots.js
3196
3780
  /**
@@ -3489,6 +4073,7 @@ var SessionGate = class {
3489
4073
  }
3490
4074
  /** Effective enabled state for `sessionId`, inheriting ancestors before falling back to `defaultEnabled`. */
3491
4075
  isEnabled(sessionId, options = {}) {
4076
+ if (options.alwaysOn === true) return true;
3492
4077
  if (sessionId) {
3493
4078
  const own = this.entries.get(sessionId);
3494
4079
  if (own !== void 0) return own.enabled;
@@ -3501,6 +4086,14 @@ var SessionGate = class {
3501
4086
  }
3502
4087
  /** Inspect the resolved state plus whether it came from an explicit choice or ancestor inheritance. */
3503
4088
  status(sessionId, options = {}) {
4089
+ if (options.alwaysOn === true) return {
4090
+ sessionId,
4091
+ enabled: true,
4092
+ explicit: false,
4093
+ inherited: false,
4094
+ defaultEnabled: true,
4095
+ alwaysOn: true
4096
+ };
3504
4097
  const defaultEnabled = options.defaultEnabled === true;
3505
4098
  const own = this.entries.get(sessionId);
3506
4099
  if (own !== void 0) return {
@@ -3508,7 +4101,8 @@ var SessionGate = class {
3508
4101
  enabled: own.enabled,
3509
4102
  explicit: true,
3510
4103
  inherited: false,
3511
- defaultEnabled
4104
+ defaultEnabled,
4105
+ alwaysOn: false
3512
4106
  };
3513
4107
  if (options.parentIds) for (const parentId of options.parentIds) {
3514
4108
  const inherited = this.entries.get(parentId);
@@ -3517,7 +4111,8 @@ var SessionGate = class {
3517
4111
  enabled: inherited.enabled,
3518
4112
  explicit: false,
3519
4113
  inherited: true,
3520
- defaultEnabled
4114
+ defaultEnabled,
4115
+ alwaysOn: false
3521
4116
  };
3522
4117
  }
3523
4118
  return {
@@ -3525,7 +4120,8 @@ var SessionGate = class {
3525
4120
  enabled: defaultEnabled,
3526
4121
  explicit: false,
3527
4122
  inherited: false,
3528
- defaultEnabled
4123
+ defaultEnabled,
4124
+ alwaysOn: false
3529
4125
  };
3530
4126
  }
3531
4127
  /** Persist an explicit on/off choice for `sessionId`. */
@@ -9167,6 +9763,132 @@ function toolAbortedBeforeDispatchResult(prior) {
9167
9763
  };
9168
9764
  }
9169
9765
  //#endregion
9766
+ //#region lib/types/cdp.js
9767
+ /**
9768
+ * Optional, zero-dependency Chromium CDP browser fast-lane.
9769
+ * When the user's Chrome/Edge exposes a local remote debugging port (e.g. 9222),
9770
+ * reads interactive DOM elements or page text directly over Node's built-in
9771
+ * `fetch` + `WebSocket`. Never launches a separate browser and fails quietly
9772
+ * back to UIA + OCR when no local debug port is open.
9773
+ */
9774
+ const DEFAULT_PORTS = [9222, 9229];
9775
+ /** Probe candidate localhost debugging ports and return the first matching visible page target. */
9776
+ async function findCdpTarget(options = {}) {
9777
+ const ports = options.ports && options.ports.length > 0 ? options.ports : DEFAULT_PORTS;
9778
+ const timeoutMs = options.timeoutMs ?? 280;
9779
+ const hint = options.titleHint?.trim().toLowerCase() ?? "";
9780
+ for (const port of ports) {
9781
+ if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
9782
+ try {
9783
+ const res = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(timeoutMs) });
9784
+ if (!res.ok) continue;
9785
+ const list = await res.json();
9786
+ if (!Array.isArray(list)) continue;
9787
+ const pages = list.filter((t) => t.type === "page" && typeof t.webSocketDebuggerUrl === "string" && !t.url.startsWith("devtools://") && !(options.harnessUrl && isHarnessAddress(t.url, options.harnessUrl)));
9788
+ if (pages.length === 0) continue;
9789
+ return {
9790
+ port,
9791
+ target: (hint ? pages.find((p) => p.title.toLowerCase().includes(hint) || hint.includes(p.title.toLowerCase())) : void 0) ?? pages[0]
9792
+ };
9793
+ } catch {}
9794
+ }
9795
+ }
9796
+ /** Execute one CDP `Runtime.evaluate` returning JSON on a debugger WebSocket URL. */
9797
+ async function evalCdpJson(wsUrl, expression, timeoutMs = 2500) {
9798
+ const WS = globalThis.WebSocket;
9799
+ if (typeof WS !== "function") return void 0;
9800
+ return new Promise((resolve) => {
9801
+ let settled = false;
9802
+ const finish = (value) => {
9803
+ if (settled) return;
9804
+ settled = true;
9805
+ clearTimeout(timer);
9806
+ try {
9807
+ ws.close();
9808
+ } catch {}
9809
+ resolve(value);
9810
+ };
9811
+ const ws = new WS(wsUrl);
9812
+ const timer = setTimeout(() => finish(void 0), timeoutMs);
9813
+ ws.addEventListener("open", () => {
9814
+ ws.send(JSON.stringify({
9815
+ id: 1,
9816
+ method: "Runtime.evaluate",
9817
+ params: {
9818
+ expression,
9819
+ returnByValue: true,
9820
+ awaitPromise: false
9821
+ }
9822
+ }));
9823
+ });
9824
+ ws.addEventListener("message", (event) => {
9825
+ try {
9826
+ const msg = JSON.parse(String(event.data));
9827
+ if (msg.id === 1) finish(msg.result?.result?.value);
9828
+ } catch {
9829
+ finish(void 0);
9830
+ }
9831
+ });
9832
+ ws.addEventListener("error", () => finish(void 0));
9833
+ ws.addEventListener("close", () => finish(void 0));
9834
+ });
9835
+ }
9836
+ const COLLECT_DOM_SCRIPT = `(() => {
9837
+ const sel = 'a[href],button,input,textarea,select,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="textbox"],[contenteditable="true"]';
9838
+ const nodes = Array.from(document.querySelectorAll(sel));
9839
+ const out = [];
9840
+ const vw = window.innerWidth, vh = window.innerHeight;
9841
+ for (const el of nodes) {
9842
+ if (out.length >= 120) break;
9843
+ const r = el.getBoundingClientRect();
9844
+ if (r.width < 2 || r.height < 2 || r.bottom < 0 || r.right < 0 || r.top > vh || r.left > vw) continue;
9845
+ const style = getComputedStyle(el);
9846
+ if (style.visibility === 'hidden' || style.display === 'none' || Number(style.opacity) === 0) continue;
9847
+ const tag = el.tagName.toLowerCase();
9848
+ const type = (el.getAttribute('type') || '').toLowerCase();
9849
+ const isPwd = tag === 'input' && type === 'password';
9850
+ const role = el.getAttribute('role') || (tag === 'a' ? 'Link' : tag === 'button' ? 'Button' : (tag === 'input' || tag === 'textarea' || el.isContentEditable) ? 'Edit' : tag);
9851
+ const name = (el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.innerText || el.getAttribute('title') || el.getAttribute('name') || '').trim().replace(/\\s+/g, ' ').slice(0, 100);
9852
+ const val = isPwd ? '[password]' : (typeof el.value === 'string' && el.value ? el.value.slice(0, 80) : undefined);
9853
+ const css = el.id ? '#' + CSS.escape(el.id) : tag + (el.getAttribute('name') ? '[name="' + el.getAttribute('name').replace(/"/g, '') + '"]' : '');
9854
+ out.push({
9855
+ role, name, selector: css,
9856
+ x: Math.round(r.left), y: Math.round(r.top), width: Math.round(r.width), height: Math.round(r.height),
9857
+ ...(val !== undefined ? { value: val } : {}),
9858
+ ...(tag === 'input' || tag === 'textarea' || el.isContentEditable ? { editable: true } : {}),
9859
+ ...(isPwd ? { password: true } : {}),
9860
+ });
9861
+ }
9862
+ return out;
9863
+ })()`;
9864
+ /** Read visible interactive DOM controls from a local CDP-enabled browser tab. */
9865
+ async function readCdpElements(options = {}) {
9866
+ const found = await findCdpTarget(options);
9867
+ if (!found?.target.webSocketDebuggerUrl) return void 0;
9868
+ const elements = await evalCdpJson(found.target.webSocketDebuggerUrl, COLLECT_DOM_SCRIPT);
9869
+ if (!Array.isArray(elements)) return void 0;
9870
+ return {
9871
+ port: found.port,
9872
+ title: found.target.title,
9873
+ url: found.target.url,
9874
+ elements
9875
+ };
9876
+ }
9877
+ /** Read visible innerText from a local CDP-enabled browser tab (excluding password inputs). */
9878
+ async function readCdpText(options = {}) {
9879
+ const found = await findCdpTarget(options);
9880
+ if (!found?.target.webSocketDebuggerUrl) return void 0;
9881
+ const text = await evalCdpJson(found.target.webSocketDebuggerUrl, "String(document.body && document.body.innerText ? document.body.innerText : \"\")");
9882
+ if (typeof text !== "string" || text.trim() === "") return void 0;
9883
+ const maxTail = options.tail ?? 4e3;
9884
+ return {
9885
+ port: found.port,
9886
+ title: found.target.title,
9887
+ url: found.target.url,
9888
+ text: text.length > maxTail ? text.slice(-maxTail) : text
9889
+ };
9890
+ }
9891
+ //#endregion
9170
9892
  //#region lib/types/tools.js
9171
9893
  /**
9172
9894
  * Model-facing tools. Kept few and terse on purpose: every schema is sent with
@@ -9281,14 +10003,32 @@ const coordinate = {
9281
10003
  items: { type: "number" },
9282
10004
  description: "[x, y] in pixels of the latest screenshot."
9283
10005
  };
9284
- /** Reads what a window says through UI Automation: exact text, no image. */
10006
+ /** Reads what a window says through UI Automation (falling back to Windows OCR when UIA exposes no text). */
9285
10007
  async function windowText(computer, hwnd, tail) {
10008
+ const maxTail = Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)));
9286
10009
  const result = await computer.helper.call("text", {
9287
10010
  ...hwnd === void 0 ? {} : { hwnd },
9288
- tail: Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)))
10011
+ tail: maxTail
9289
10012
  }, 2e4);
9290
10013
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
9291
- if (!result.text || result.source === "none") return `${head}: this window exposes no readable text; use a screenshot.`;
10014
+ if (!result.text || result.source === "none") {
10015
+ if (isBrowser(result)) {
10016
+ const s = computer.settings();
10017
+ const cdp = await readCdpText({
10018
+ ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
10019
+ titleHint: result.title,
10020
+ ...s.harnessUrl ? { harnessUrl: s.harnessUrl } : {},
10021
+ tail: maxTail
10022
+ }).catch(() => void 0);
10023
+ if (cdp && cdp.text.trim() !== "") return `${head}: ${cdp.text.length} characters (CDP fast-lane port ${cdp.port}).\n${cdp.text}`;
10024
+ }
10025
+ const ocr = await computer.ocr(hwnd).catch(() => void 0);
10026
+ if (ocr && ocr.text && ocr.text.trim() !== "") {
10027
+ const sliced = ocr.text.length > maxTail ? ocr.text.slice(-maxTail) : ocr.text;
10028
+ return `${head}: ${ocr.text.length > maxTail ? `last ${sliced.length} of ${ocr.text.length} characters` : `${ocr.text.length} characters`} (Windows OCR, ${ocr.language || "auto"}).\n${sliced}`;
10029
+ }
10030
+ return `${head}: this window exposes no readable text; use a screenshot.`;
10031
+ }
9292
10032
  return `${head}: ${result.truncated ? `last ${result.text.length} of ${result.length} characters` : `${result.length} characters`}${result.source === "labels" ? " (visible labels, top to bottom)" : ""}.\n${result.text}`;
9293
10033
  }
9294
10034
  const actionProperties = {
@@ -9330,7 +10070,7 @@ const actionProperties = {
9330
10070
  },
9331
10071
  target: {
9332
10072
  type: "string",
9333
- description: "Instead of coordinate: the visible name of a control in the foreground window or its open menu, e.g. \"保存\" or \"按钮:保存\". Works for controls that were not in your last screenshot (the item of a menu the previous step opens); waits up to 3 s for it. With type: clicks the field first."
10073
+ description: "Instead of coordinate: the visible name of a control in the foreground window or its open menu, e.g. \"保存\" or \"按钮:保存\", or a Set-of-Marks badge like \"#12\" from ui_elements({ marks: true }). Works for controls that were not in your last screenshot; waits up to 3 s for it. With type: clicks the field first."
9334
10074
  },
9335
10075
  until: {
9336
10076
  type: "string",
@@ -9353,6 +10093,10 @@ const actionProperties = {
9353
10093
  type: "string",
9354
10094
  enum: ["high", "low"],
9355
10095
  description: "Screenshot detail: \"high\" uses full configured resolution; \"low\" uses a smaller, cheaper image for quick visual confirmation."
10096
+ },
10097
+ replace: {
10098
+ type: "boolean",
10099
+ description: "type: select all (Ctrl+A) and replace existing text in the field."
9356
10100
  }
9357
10101
  };
9358
10102
  const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
@@ -9383,12 +10127,11 @@ function createTools(host) {
9383
10127
  }));
9384
10128
  tools.push(defineTool({
9385
10129
  name: "computer_batch",
9386
- description: "Run several computer actions in order in one call, then get one screenshot (taken once the screen settles, so do not end with a wait). Stops at the first failing action and shows you the screen. The screen is not shown to you between actions, so for steps whose target only appears along the way (a menu item, a dialog button) use target instead of coordinate, and wait with until for a window or control to appear. Example: [key \"ctrl+s\", wait until \"window:另存为\", type target \"文件名\" text \"C:\\a.txt\", left_click target \"保存\"].",
10130
+ description: "Run several computer actions in order in one call (or replay a saved macro by name), then get one screenshot (taken once the screen settles, so do not end with a wait). Stops at the first failing action and shows you the screen. The screen is not shown to you between actions, so for steps whose target only appears along the way (a menu item, a dialog button) use target instead of coordinate, and wait with until for a window or control to appear. Example: [key \"ctrl+s\", wait until \"window:另存为\", type target \"文件名\" text \"C:\\a.txt\", left_click target \"保存\"].",
9387
10131
  parameters: {
9388
10132
  actions: {
9389
10133
  type: "array",
9390
- required: true,
9391
- description: "Ordered actions, same fields as the computer tool. zoom is allowed only as the last action (you get the zoomed region instead of the full screenshot).",
10134
+ description: "Ordered actions, same fields as the computer tool (required unless macro is given). zoom is allowed only as the last action.",
9392
10135
  items: {
9393
10136
  type: "object",
9394
10137
  additionalProperties: false,
@@ -9401,6 +10144,16 @@ function createTools(host) {
9401
10144
  }
9402
10145
  }
9403
10146
  },
10147
+ macro: {
10148
+ type: "string",
10149
+ description: "Name of a saved action macro (created via app_skill save_macro) to replay instead of passing actions."
10150
+ },
10151
+ params: {
10152
+ type: "object",
10153
+ additionalProperties: true,
10154
+ properties: {},
10155
+ description: "Parameter values for {{placeholder}} variables when replaying a macro."
10156
+ },
9404
10157
  finish: {
9405
10158
  type: "string",
9406
10159
  enum: [
@@ -9420,12 +10173,19 @@ function createTools(host) {
9420
10173
  timeoutMs: 18e5,
9421
10174
  async execute(args, exec) {
9422
10175
  const call = await host.context(exec);
9423
- const actions = args.actions;
9424
- const finish = args.finish ?? "screenshot";
9425
- const detail = args.detail;
10176
+ const rawArgs = args;
10177
+ let actions = rawArgs.actions;
10178
+ if (typeof rawArgs.macro === "string" && rawArgs.macro.trim() !== "") {
10179
+ if (!host.macros) throw new Error("Macro store is not available.");
10180
+ const saved = host.macros.get(rawArgs.macro);
10181
+ if (!saved) throw new Error(`No saved macro named "${rawArgs.macro}". Use app_skill list_macros to see available macros.`);
10182
+ actions = renderMacroActions(saved.actions, rawArgs.params ?? {});
10183
+ }
10184
+ const finish = rawArgs.finish ?? "screenshot";
10185
+ const detail = rawArgs.detail;
9426
10186
  let zoomed;
9427
10187
  let endedWithZoom = false;
9428
- if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array.");
10188
+ if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array (or pass a saved macro name).");
9429
10189
  if (actions.length > 30) throw new Error("At most 30 actions per batch.");
9430
10190
  const lines = [];
9431
10191
  let failure;
@@ -9505,6 +10265,7 @@ function createTools(host) {
9505
10265
  {
9506
10266
  const name = rawName.trim();
9507
10267
  if (name === "") throw new Error("name is required.");
10268
+ if (isCommandInterpreter(name)) throw new Error(`Refused to launch command interpreter or script host "${name}" via open_application. Use the dedicated shell tool instead.`);
9508
10269
  const settings = computer.settings();
9509
10270
  const isUrl = /^https?:\/\//i.test(name);
9510
10271
  const appName = /^ms-settings:/i.test(name) ? "设置" : name;
@@ -9686,16 +10447,28 @@ function createTools(host) {
9686
10447
  }));
9687
10448
  tools.push(defineTool({
9688
10449
  name: "ui_elements",
9689
- description: "Read the foreground window (or a window by hwnd) through Windows UI Automation. Default: its clickable/editable elements with center coordinates in screenshot pixels (to click precisely, read values, or work without vision). With text: true: what the window says as plain text (a document, a web page, a chat reply, a log) — exact and far cheaper than scrolling and zooming screenshots. Some apps (games, canvas UIs) expose little.",
10450
+ 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.",
9690
10451
  parameters: {
9691
10452
  hwnd: {
9692
10453
  type: "integer",
9693
10454
  description: "Window handle; default foreground window."
9694
10455
  },
10456
+ marks: {
10457
+ type: "boolean",
10458
+ description: "Return a Set-of-Marks numbered screenshot alongside the element list so you can target controls by \"#1\", \"#2\", ..."
10459
+ },
9695
10460
  text: {
9696
10461
  type: "boolean",
9697
10462
  description: "Return the window's text content instead of the element list."
9698
10463
  },
10464
+ ocr: {
10465
+ type: "boolean",
10466
+ description: "Recognize visible text lines and clickable center coordinates via built-in Windows OCR."
10467
+ },
10468
+ cdp: {
10469
+ type: "boolean",
10470
+ description: "Inspect visible DOM controls directly over a local Chrome/Edge CDP port (falls back to UIA if unavailable)."
10471
+ },
9699
10472
  tail: {
9700
10473
  type: "integer",
9701
10474
  description: "text: how many characters from the end to return (default 4000, max 20000); new content is usually at the end."
@@ -9712,8 +10485,67 @@ function createTools(host) {
9712
10485
  output,
9713
10486
  timeoutMs: 3e4,
9714
10487
  isConcurrencySafe: () => true,
9715
- async execute(args) {
9716
- const { hwnd, include_text: includeText, max, text, tail } = args;
10488
+ async execute(args, exec) {
10489
+ const { hwnd, marks, include_text: includeText, max, text, ocr, cdp, tail } = args;
10490
+ if (marks === true) {
10491
+ const call = await host.context(exec);
10492
+ const { window: win, elements, shot } = await computer.marks(hwnd, max ?? 120);
10493
+ const lines = [];
10494
+ for (const [index, el] of elements.entries()) {
10495
+ const num = el.mark ?? index + 1;
10496
+ const center = await computer.toModel({
10497
+ x: el.x + el.width / 2,
10498
+ y: el.y + el.height / 2
10499
+ });
10500
+ const flags = [
10501
+ el.password ? "password" : "",
10502
+ el.value !== void 0 ? `value="${el.value}"` : "",
10503
+ el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
10504
+ el.disabled ? "disabled" : "",
10505
+ el.editable ? "editable" : ""
10506
+ ].filter(Boolean).join(" ");
10507
+ lines.push(`[#${num}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
10508
+ }
10509
+ const head = `${win.exe ?? "window"} — "${String(win.title ?? "").slice(0, 80)}": ${elements.length} Set-of-Marks elements (use target "#<number>" to click or type).`;
10510
+ return withShot(host, lines.length ? `${head}\n${lines.join("\n")}` : head, shot, call);
10511
+ }
10512
+ if (cdp === true) {
10513
+ const fg = await computer.foreground().catch(() => void 0);
10514
+ const s = computer.settings();
10515
+ const snap = await readCdpElements({
10516
+ ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
10517
+ ...fg?.title ? { titleHint: fg.title } : {},
10518
+ ...s.harnessUrl ? { harnessUrl: s.harnessUrl } : {}
10519
+ }).catch(() => void 0);
10520
+ if (snap) {
10521
+ const limit = Math.min(200, Math.max(10, max ?? 120));
10522
+ const lines = snap.elements.slice(0, limit).map((el, i) => {
10523
+ const flags = [
10524
+ el.password ? "password" : "",
10525
+ el.value !== void 0 ? `value="${el.value}"` : "",
10526
+ el.editable ? "editable" : "",
10527
+ el.selector ? `selector=${el.selector}` : ""
10528
+ ].filter(Boolean).join(" ");
10529
+ return `[${i}] ${el.role} "${el.name}" viewport=(${el.x + Math.round(el.width / 2)}, ${el.y + Math.round(el.height / 2)})${flags ? ` ${flags}` : ""}`;
10530
+ });
10531
+ return { text: `CDP (port ${snap.port}) — "${snap.title.slice(0, 80)}" (${snap.url}): ${snap.elements.length} DOM elements.\n${lines.join("\n")}` };
10532
+ }
10533
+ 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 })." };
10534
+ }
10535
+ if (ocr === true) {
10536
+ const result = await computer.ocr(hwnd);
10537
+ const limit = Math.min(400, Math.max(10, max ?? 120));
10538
+ const lines = [];
10539
+ for (const [index, line] of (result.lines ?? []).slice(0, limit).entries()) {
10540
+ const center = await computer.toModel({
10541
+ x: line.x + line.width / 2,
10542
+ y: line.y + line.height / 2
10543
+ });
10544
+ lines.push(`[${index}] "${line.text}" @ (${center.x}, ${center.y})${center.offscreen ? " other display" : ""}`);
10545
+ }
10546
+ const head = `${result.exe ?? "screen"} — "${String(result.title ?? "").slice(0, 80)}": ${result.lines?.length ?? 0} OCR lines (${result.language || "auto"}).`;
10547
+ return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} No readable text found by Windows OCR.` };
10548
+ }
9717
10549
  if (text === true) return { text: await windowText(computer, hwnd, tail) };
9718
10550
  const result = await computer.helper.call("ui", {
9719
10551
  ...hwnd === void 0 ? {} : { hwnd },
@@ -9728,6 +10560,7 @@ function createTools(host) {
9728
10560
  y: el.y + el.height / 2
9729
10561
  });
9730
10562
  const flags = [
10563
+ el.password ? "password" : "",
9731
10564
  el.value !== void 0 ? `value="${el.value}"` : "",
9732
10565
  el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
9733
10566
  el.disabled ? "disabled" : "",
@@ -9739,9 +10572,12 @@ function createTools(host) {
9739
10572
  lines.push(`[${index}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
9740
10573
  }
9741
10574
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements.`;
9742
- return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} This window exposes no UI Automation elements; rely on screenshots.` };
10575
+ 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.` };
9743
10576
  },
9744
- presentCall: () => card("读取界面元素")
10577
+ presentCall: (args) => {
10578
+ const a = args;
10579
+ return card(a.marks ? "编号标图 (Set-of-Marks)" : a.cdp ? "CDP 读取网页元素" : a.ocr ? "OCR 识别文字" : "读取界面元素");
10580
+ }
9745
10581
  }));
9746
10582
  tools.push(defineTool({
9747
10583
  name: "clipboard",
@@ -9823,7 +10659,7 @@ function createTools(host) {
9823
10659
  const skills = host.skills;
9824
10660
  tools.push(defineTool({
9825
10661
  name: "app_skill",
9826
- description: `Your notes on how to operate specific apps (one skill per app, kept across sessions; the user can edit them). open_application already returns the skill of the app it opens. Use "list" to see which apps have one, "read" for an app you reach another way, and "append" / "write" to record what you worked out about an unfamiliar app: reusable operating knowledge only (where things are, shortcuts, quirks, what failed and what works), never task content, personal data or pixel coordinates (they change with the window). Keep each skill under ${SKILL_MAX_CHARS} characters; rewrite it with "write" when it gets long or wrong.`,
10662
+ description: `Your notes and replayable action macros for operating specific apps (kept across sessions). open_application already returns the skill of the app it opens. Use "list"/"read"/"append"/"write" for reusable operating knowledge (shortcuts, quirks, never pixel coordinates). Use "save_macro"/"list_macros"/"delete_macro" to save parameterized computer_batch sequences (with {{param}} placeholders) that can be replayed via computer_batch({ macro, params }). Keep each skill under ${SKILL_MAX_CHARS} characters.`,
9827
10663
  parameters: {
9828
10664
  action: {
9829
10665
  type: "string",
@@ -9831,13 +10667,16 @@ function createTools(host) {
9831
10667
  "list",
9832
10668
  "read",
9833
10669
  "append",
9834
- "write"
10670
+ "write",
10671
+ "save_macro",
10672
+ "list_macros",
10673
+ "delete_macro"
9835
10674
  ],
9836
10675
  required: true
9837
10676
  },
9838
10677
  app: {
9839
10678
  type: "string",
9840
- description: "App name, e.g. \"Obsidian\" (read / append / write)."
10679
+ description: "App name (read / append / write), or optional app tag for save_macro."
9841
10680
  },
9842
10681
  content: {
9843
10682
  type: "string",
@@ -9845,13 +10684,52 @@ function createTools(host) {
9845
10684
  },
9846
10685
  summary: {
9847
10686
  type: "string",
9848
- description: "A few words on what the skill covers, shown in the list (write, or the first append)."
10687
+ description: "A few words on what the skill or macro covers."
10688
+ },
10689
+ macro: {
10690
+ type: "string",
10691
+ description: "Macro name (save_macro / delete_macro)."
10692
+ },
10693
+ actions: {
10694
+ type: "array",
10695
+ description: "Ordered computer_batch actions to save as a replayable macro (save_macro); supports {{param}} placeholders in text/target/until.",
10696
+ items: {
10697
+ type: "object",
10698
+ additionalProperties: false,
10699
+ properties: {
10700
+ ...actionProperties,
10701
+ action: {
10702
+ ...actionProperties.action,
10703
+ enum: BATCH_ACTIONS
10704
+ }
10705
+ }
10706
+ }
9849
10707
  }
9850
10708
  },
9851
10709
  output,
9852
10710
  isConcurrencySafe: () => false,
9853
10711
  async execute(args) {
9854
- const { action, app, content, summary } = args;
10712
+ const { action, app, content, summary, macro, actions } = args;
10713
+ if (action === "list_macros") {
10714
+ const rows = host.macros?.list() ?? [];
10715
+ return { text: rows.length === 0 ? "No saved action macros yet." : rows.map((m) => `${m.name}${m.app ? ` [${m.app}]` : ""}${m.description ? ` — ${m.description}` : ""} (${m.actions.length} steps${m.params.length ? `, params: ${m.params.join(", ")}` : ""})`).join("\n") };
10716
+ }
10717
+ if (action === "save_macro") {
10718
+ if (!host.macros) throw new Error("Macro store is not available.");
10719
+ const saved = host.macros.save({
10720
+ name: String(macro ?? ""),
10721
+ ...app ? { app } : {},
10722
+ ...summary ? { description: summary } : {},
10723
+ actions: actions ?? []
10724
+ });
10725
+ return { text: `Saved macro "${saved.name}" (${saved.actions.length} steps${saved.params.length ? `, params: ${saved.params.join(", ")}` : ""}). Replay with computer_batch({ macro: ${JSON.stringify(saved.name)} }).` };
10726
+ }
10727
+ if (action === "delete_macro") {
10728
+ if (!host.macros) throw new Error("Macro store is not available.");
10729
+ const name = String(macro ?? "").trim();
10730
+ if (name === "") throw new Error("macro name is required.");
10731
+ return { text: host.macros.remove(name) ? `Deleted macro "${name}".` : `No macro named "${name}".` };
10732
+ }
9855
10733
  if (action === "list") {
9856
10734
  const rows = skills.list();
9857
10735
  return { text: rows.length === 0 ? "No app skills yet." : rows.map((skill) => `${skill.app}${skill.summary ? ` — ${skill.summary}` : ""} (${skill.content.length} chars)`).join("\n") };
@@ -9876,12 +10754,20 @@ function createTools(host) {
9876
10754
  }, skills.find(name)?.id) : skills.append(name, text, extra);
9877
10755
  return { text: `Skill for ${saved.app} saved (${saved.content.length} of ${SKILL_MAX_CHARS} characters).` };
9878
10756
  },
9879
- presentCall: (args) => card(`应用技能 · ${{
9880
- list: "列表",
9881
- read: "读取",
9882
- append: "记录",
9883
- write: "重写"
9884
- }[args.action ?? ""] ?? ""}${args.app ? ` · ${args.app}` : ""}`)
10757
+ presentCall: (args) => {
10758
+ const a = args;
10759
+ const label = {
10760
+ list: "列表",
10761
+ read: "读取",
10762
+ append: "记录",
10763
+ write: "重写",
10764
+ save_macro: "保存宏",
10765
+ list_macros: "宏列表",
10766
+ delete_macro: "删除宏"
10767
+ }[a.action ?? ""] ?? "";
10768
+ const suffix = a.macro ?? a.app ?? "";
10769
+ return card(`应用技能 · ${label}${suffix ? ` · ${suffix}` : ""}`);
10770
+ }
9885
10771
  }));
9886
10772
  }
9887
10773
  tools.push(defineTool({
@@ -9908,6 +10794,30 @@ function createTools(host) {
9908
10794
  * through DSH approvals, and an orange "DeepSeek is using your computer"
9909
10795
  * overlay that a physical Esc dismisses.
9910
10796
  */
10797
+ function readPluginVersion() {
10798
+ for (const rel of ["../package.json", "../../package.json"]) try {
10799
+ const parsed = JSON.parse(readFileSync(new URL(rel, import.meta.url), "utf8"));
10800
+ if (typeof parsed.version === "string" && parsed.version.trim() !== "") return parsed.version;
10801
+ } catch {}
10802
+ return "0.0.0";
10803
+ }
10804
+ const PLUGIN_VERSION = readPluginVersion();
10805
+ /** Parse `/cu [on|off|toggle|status|reset|stop|revoke <app>]` arguments into an action. */
10806
+ function parseCuCommand(rawInput) {
10807
+ const token = (rawInput.trim().split(/\s+/).filter(Boolean)[0] ?? "").toLowerCase();
10808
+ if (token === "" || token === "status") return "status";
10809
+ if (token === "on" || token === "enable" || token === "enabled" || token === "true" || token === "1") return "on";
10810
+ if (token === "off" || token === "disable" || token === "disabled" || token === "false" || token === "0") return "off";
10811
+ if (token === "toggle") return "toggle";
10812
+ if (token === "reset" || token === "default") return "reset";
10813
+ if (token === "stop" || token === "cancel" || token === "abort") return "stop";
10814
+ if (token === "revoke" || token === "ungrant") return "revoke";
10815
+ return "invalid";
10816
+ }
10817
+ /** Extract the app name argument after `/cu revoke ...` (empty means all granted apps). */
10818
+ function parseCuRevokeTarget(rawInput) {
10819
+ return rawInput.trim().replace(/^(revoke|ungrant)\s*/i, "").trim();
10820
+ }
9911
10821
  const name = "@copylee/dsh-computer-use";
9912
10822
  const inject = ["tools", "attachments"];
9913
10823
  const Config = z.object({
@@ -9925,9 +10835,26 @@ const Config = z.object({
9925
10835
  "zh-CN": { $description: "授权方式。无论哪种,DeepSeek Harness 自身窗口和下方“禁止操控的应用”都不会被操作。" },
9926
10836
  "en-US": { $description: "Access mode. DeepSeek Harness itself and blocked apps are never controlled." }
9927
10837
  }),
10838
+ sessionMode: z.union([
10839
+ z.const("off").i18n({
10840
+ "zh-CN": { $description: "按会话开启(默认关闭,推荐):在输入框左下角显示「电脑控制」开关" },
10841
+ "en-US": { $description: "Per session (default off, recommended): show the composer pill toggle" }
10842
+ }),
10843
+ z.const("on").i18n({
10844
+ "zh-CN": { $description: "新会话默认开启(保留输入框开关,可按会话关闭)" },
10845
+ "en-US": { $description: "Default on for new sessions (keep the composer pill toggle)" }
10846
+ }),
10847
+ z.const("always").i18n({
10848
+ "zh-CN": { $description: "总是开启(所有会话启用,隐藏输入框左下角开关)" },
10849
+ "en-US": { $description: "Always on for all sessions (hide the composer pill)" }
10850
+ })
10851
+ ]).default("off").volatile().i18n({
10852
+ "zh-CN": { $description: "会话启用方式:控制新会话是否默认开启电脑控制,以及是否在输入框左下角显示「电脑控制」胶囊开关。" },
10853
+ "en-US": { $description: "Session activation mode: whether computer use defaults on and whether the composer pill is shown." }
10854
+ }),
9928
10855
  defaultSessionEnabled: z.boolean().default(false).volatile().i18n({
9929
- "zh-CN": { $description: "新会话默认开启电脑控制。关闭时(推荐),新会话隐藏桌面工具和提示词,需要在输入框点击「电脑控制」胶囊按需开启。" },
9930
- "en-US": { $description: "Enable computer use by default for new sessions. Off (recommended) hides desktop tools and prompt guidance until turned on from the composer pill." }
10856
+ "zh-CN": { $description: "(兼容旧配置)已被「会话启用方式」取代。" },
10857
+ "en-US": { $description: "(Legacy) Superseded by sessionMode." }
9931
10858
  }),
9932
10859
  overlay: z.boolean().default(true).volatile().i18n({
9933
10860
  "zh-CN": { $description: "控制时显示橙色光晕边框和顶部提示条(不会出现在截图里,按 Esc 可停止)" },
@@ -10025,6 +10952,26 @@ const Config = z.object({
10025
10952
  "zh-CN": { $description: "截图、显示器与窗口查询、无浮层时的输入改由 DeepSeek Harness 自带的 koffi 在进程内完成(更快,也不受智能应用控制拦截);关闭则全部交给 C# 辅助程序" },
10026
10953
  "en-US": { $description: "Take screenshots, display and window queries, and input while no overlay is shown in-process through the koffi that DeepSeek Harness ships (faster, and not blocked by Smart App Control); off sends everything to the C# helper" }
10027
10954
  }),
10955
+ elementFirstClick: z.boolean().default(true).volatile().i18n({
10956
+ "zh-CN": { $description: "坐标点击优先走后台 UIA 语义触发(命中原生按钮/复选框/标签页时不移动真实鼠标、不抢焦点)" },
10957
+ "en-US": { $description: "Try background UIA semantic click at coordinate before moving the physical pointer" }
10958
+ }),
10959
+ restorePointer: z.boolean().default(false).volatile().i18n({
10960
+ "zh-CN": { $description: "物理点击完成后立即将真实鼠标还原到原来的位置" },
10961
+ "en-US": { $description: "Restore the physical mouse pointer to its previous position right after a physical click" }
10962
+ }),
10963
+ protectPasswords: z.boolean().default(true).volatile().i18n({
10964
+ "zh-CN": { $description: "密码框硬保护:自动脱敏 UIA/Win32 密码框内容并拒绝向密码框自动输入文本" },
10965
+ "en-US": { $description: "Protect password fields (IsPassword / ES_PASSWORD): mask values and refuse automated typing" }
10966
+ }),
10967
+ windowChangeGuard: z.boolean().default(true).volatile().i18n({
10968
+ "zh-CN": { $description: "窗口位移或被新弹窗遮挡时阻止盲点坐标并提示模型先重新看屏" },
10969
+ "en-US": { $description: "Guard coordinate clicks when the foreground window moved/resized or is occluded since the last screenshot" }
10970
+ }),
10971
+ cdpPort: z.natural().max(65535).default(0).volatile().i18n({
10972
+ "zh-CN": { $description: "可选 Chromium 远程调试端口(0 为按需自动探测 9222/9229),用于轻量化 CDP 网页元素加速读取" },
10973
+ "en-US": { $description: "Optional local Chromium CDP debugging port (0 auto-probes 9222/9229 on demand)" }
10974
+ }),
10028
10975
  blockedApps: z.array(z.string()).default([]).volatile().i18n({
10029
10976
  "zh-CN": { $description: "禁止操控的应用(名称或 exe,如 “alipay”)。常见密码管理器默认已禁止。" },
10030
10977
  "en-US": { $description: "Apps that may never be controlled (names or exe). Common password managers are always blocked." }
@@ -10100,6 +11047,7 @@ function apply(ctx, config = {}) {
10100
11047
  const tools = createTools({
10101
11048
  computer,
10102
11049
  skills,
11050
+ macros: new MacroStore(),
10103
11051
  async saveImage(shot, fileName) {
10104
11052
  const ref = await attachments().saveImage({
10105
11053
  data: shot.data,
@@ -10123,13 +11071,32 @@ function apply(ctx, config = {}) {
10123
11071
  for (const tool of tools) ctx.effect(() => ctx.tools.register(tool), `computer-use: tool ${tool.name}`);
10124
11072
  const OWN_TOOLS = new Set(tools.map((tool) => tool.name));
10125
11073
  const ownToolNames = [...OWN_TOOLS];
11074
+ const diagnostics = new DiagnosticsLog();
11075
+ ctx.on("tools/execute", async (exec, next) => {
11076
+ if (!OWN_TOOLS.has(exec.name)) return next();
11077
+ const started = Date.now();
11078
+ const action = summarizeToolAction(exec.name, exec.arguments);
11079
+ const result = await next();
11080
+ diagnostics.record({
11081
+ tool: exec.name,
11082
+ ...action ? { action } : {},
11083
+ durationMs: Date.now() - started,
11084
+ ok: !result.isError,
11085
+ ...result.isError ? { error: result.error?.message ?? "tool error" } : {}
11086
+ });
11087
+ return result;
11088
+ });
10126
11089
  const sessionGate = new SessionGate(void 0, log);
10127
11090
  const agentsRegistry = () => ctx.get("agents");
10128
11091
  const restricted = /* @__PURE__ */ new Map();
10129
- const isSessionEnabled = (agent) => sessionGate.isEnabled(agent.session.id, {
10130
- defaultEnabled: settings().defaultSessionEnabled,
10131
- parentIds: parentSessionChain(agent, agentsRegistry())
10132
- });
11092
+ const isSessionEnabled = (agent) => {
11093
+ const s = settings();
11094
+ return sessionGate.isEnabled(agent.session.id, {
11095
+ defaultEnabled: s.defaultSessionEnabled,
11096
+ alwaysOn: s.sessionMode === "always",
11097
+ parentIds: parentSessionChain(agent, agentsRegistry())
11098
+ });
11099
+ };
10133
11100
  const syncAgent = (agent) => {
10134
11101
  const enabled = isSessionEnabled(agent);
10135
11102
  const active = restricted.get(agent);
@@ -10320,12 +11287,113 @@ function apply(ctx, config = {}) {
10320
11287
  handler: safe
10321
11288
  }), `computer-use: ${path}`);
10322
11289
  };
10323
- route(STATUS_ROUTE, statusRoute(helper, settings, overlay));
11290
+ route(STATUS_ROUTE, statusRoute(helper, settings, overlay, PLUGIN_VERSION));
10324
11291
  route(PREVIEW_ROUTE, previewRoute(helper, settings, overlay, iconPath));
10325
11292
  route(SCREENSHOTS_ROUTE, screenshotsRoute(screenshots));
10326
11293
  route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
10327
11294
  route(SKILLS_ROUTE, skillsRoute(skills));
10328
11295
  route(SESSION_ROUTE, sessionRoute(sessionGate, settings, parentIdsFor, syncAllAgents));
11296
+ route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION));
11297
+ route(UPDATE_ROUTE, updateRoute(PLUGIN_VERSION));
11298
+ route(WINDOWS_ROUTE, windowsRoute(helper));
11299
+ });
11300
+ ctx.inject(["commands"], (cmdCtx) => {
11301
+ const commands = cmdCtx.commands;
11302
+ if (typeof commands?.register !== "function") return;
11303
+ cmdCtx.effect(() => commands.register({
11304
+ name: "cu",
11305
+ description: "控制当前会话的电脑操控:/cu [on|off|toggle|status|reset|stop|revoke <应用>]",
11306
+ handler: (invocation) => {
11307
+ const agent = invocation.agent;
11308
+ const sessionId = agent?.session?.id ?? agent?.session?.header?.id;
11309
+ const action = parseCuCommand(invocation.rawInput ?? "");
11310
+ if (action === "invalid") return {
11311
+ kind: "error",
11312
+ text: "用法:/cu [on | off | toggle | status | reset | stop | revoke <应用或all>]"
11313
+ };
11314
+ if (action === "stop") {
11315
+ const active = overlay.controller;
11316
+ if (active) {
11317
+ try {
11318
+ active.cancel({ kind: "user" });
11319
+ } catch {}
11320
+ overlay.end(active).catch(() => {});
11321
+ return {
11322
+ kind: "success",
11323
+ text: "已立即中断当前电脑操控并恢复窗口。"
11324
+ };
11325
+ }
11326
+ overlay.end().catch(() => {});
11327
+ return {
11328
+ kind: "success",
11329
+ text: "当前没有正在执行的电脑操控任务。"
11330
+ };
11331
+ }
11332
+ if (!sessionId) return {
11333
+ kind: "error",
11334
+ text: "无法识别当前会话 ID。"
11335
+ };
11336
+ if (action === "revoke") {
11337
+ const target = parseCuRevokeTarget(invocation.rawInput ?? "");
11338
+ const removed = access.revoke(sessionId, target || "all");
11339
+ if (removed.length === 0) return {
11340
+ kind: "success",
11341
+ text: target ? `本会话未找到与「${target}」匹配的应用授权。` : "本会话当前没有任何已授权的应用。"
11342
+ };
11343
+ return {
11344
+ kind: "success",
11345
+ text: `已撤销本会话的应用授权:${removed.join("、")}。`
11346
+ };
11347
+ }
11348
+ const parents = parentIdsFor(sessionId);
11349
+ const s = settings();
11350
+ const alwaysOn = s.sessionMode === "always";
11351
+ if (action === "status") {
11352
+ if (alwaysOn) return {
11353
+ kind: "success",
11354
+ text: "电脑控制当前状态:总是开启(在设置页已设为「总是开启」,所有会话均自动启用且隐藏输入框开关)。"
11355
+ };
11356
+ const st = sessionGate.status(sessionId, {
11357
+ defaultEnabled: s.defaultSessionEnabled,
11358
+ alwaysOn: false,
11359
+ parentIds: parents
11360
+ });
11361
+ const source = st.explicit ? "本会话已单独设置" : st.inherited ? "继承自父会话" : "沿用默认设置";
11362
+ return {
11363
+ kind: "success",
11364
+ text: `电脑控制当前状态:${st.enabled ? "已开启" : "已关闭"}(${source})。使用 /cu on 或 /cu off 切换。`
11365
+ };
11366
+ }
11367
+ if (alwaysOn) return {
11368
+ kind: "success",
11369
+ text: "当前在设置页已设为「总是开启」,所有会话均保持开启。如需按会话开关,请在「设置 → 电脑控制 → 会话启用方式」里切换为按会话模式。"
11370
+ };
11371
+ if (action === "reset") {
11372
+ sessionGate.clear(sessionId);
11373
+ syncAllAgents();
11374
+ return {
11375
+ kind: "success",
11376
+ text: `已恢复当前会话的默认状态:${sessionGate.status(sessionId, {
11377
+ defaultEnabled: s.defaultSessionEnabled,
11378
+ alwaysOn: false,
11379
+ parentIds: parents
11380
+ }).enabled ? "已开启" : "已关闭"}。`
11381
+ };
11382
+ }
11383
+ const current = sessionGate.isEnabled(sessionId, {
11384
+ defaultEnabled: s.defaultSessionEnabled,
11385
+ alwaysOn: false,
11386
+ parentIds: parents
11387
+ });
11388
+ const nextEnabled = action === "toggle" ? !current : action === "on";
11389
+ sessionGate.set(sessionId, nextEnabled);
11390
+ syncAllAgents();
11391
+ return {
11392
+ kind: "success",
11393
+ text: `当前会话已${nextEnabled ? "开启" : "关闭"}电脑控制(立即生效,子代理将自动继承)。`
11394
+ };
11395
+ }
11396
+ }), "computer-use: /cu command");
10329
11397
  });
10330
11398
  ctx.inject(["systemPrompt"], (promptCtx) => {
10331
11399
  promptCtx.effect(() => promptCtx.systemPrompt.section({
@@ -10344,4 +11412,4 @@ function apply(ctx, config = {}) {
10344
11412
  });
10345
11413
  }
10346
11414
  //#endregion
10347
- export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, resolveConfig };
11415
+ export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, parseCuCommand, parseCuRevokeTarget, resolveConfig };