@copylee/dsh-computer-use 0.10.0 → 0.12.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
@@ -207,6 +207,24 @@ var AccessControl = class {
207
207
  const set = this.grants.get(session) ?? /* @__PURE__ */ new Set();
208
208
  return names.filter((name) => !set.has(normalizeApp(name)) && ![...set].some((granted) => sameApp(granted, name)));
209
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
+ }
210
228
  forget(session) {
211
229
  this.grants.delete(session);
212
230
  }
@@ -989,15 +1007,32 @@ var Computer = class Computer {
989
1007
  }
990
1008
  /** The foreground window as of the model's latest look at the screen. */
991
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;
992
1014
  /** The latest foreground window that was not DeepSeek Harness itself. */
993
1015
  lastTarget;
994
1016
  /** A new turn starts: the user may have rearranged things while chatting. */
995
1017
  resetLook() {
996
1018
  this.seen = void 0;
1019
+ this.lastShotWindow = void 0;
997
1020
  }
998
1021
  async remember() {
999
1022
  const now = await this.foreground().catch(() => void 0);
1000
- 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
+ }
1001
1036
  }
1002
1037
  /**
1003
1038
  * Did another window come to the front since the model last looked, without
@@ -1169,7 +1204,17 @@ var Computer = class Computer {
1169
1204
  }
1170
1205
  async checkPointer(call, point, verb) {
1171
1206
  const target = point ?? await this.cursor();
1172
- 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;
1173
1218
  }
1174
1219
  async checkKeyboard(call, verb) {
1175
1220
  const window = await this.foreground();
@@ -1242,6 +1287,49 @@ var Computer = class Computer {
1242
1287
  async ocr(hwnd) {
1243
1288
  return this.helper.call("ocr", hwnd === void 0 ? {} : { hwnd }, 2e4);
1244
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
+ }
1245
1333
  /**
1246
1334
  * Look for a named control in the window, then its popups, and when the UIA
1247
1335
  * tree is empty or sparse (<= 20 controls, e.g. canvas/WebView/game/custom
@@ -1294,10 +1382,23 @@ var Computer = class Computer {
1294
1382
  */
1295
1383
  async locate(target, signal, waitMs = TARGET_WAIT_MS) {
1296
1384
  const started = Date.now();
1385
+ const markMatch = /^#(\d+)$/.exec(target.trim());
1297
1386
  for (;;) {
1298
1387
  if (signal.aborted) throw new Error("Cancelled.");
1299
1388
  const window = await this.foreground();
1300
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
+ }
1301
1402
  const match = await this.find(target, window.hwnd);
1302
1403
  if (match.kind === "found") {
1303
1404
  const el = match.element;
@@ -1447,6 +1548,31 @@ var Computer = class Computer {
1447
1548
  await setTimeout$1(POLL_MS, void 0, { signal });
1448
1549
  }
1449
1550
  }
1551
+ /** Drain buffered physical user actions and format them in screenshot coordinates for the model. */
1552
+ async drainUserActionNotes() {
1553
+ if (!this.settings().reportUserActions) return "";
1554
+ return this.formatUserActions(this.overlay.drainUserActions?.() ?? []);
1555
+ }
1556
+ /** Format physical user takeover actions into concise screenshot-coordinate context for the model. */
1557
+ async formatUserActions(actions) {
1558
+ if (actions.length === 0) return "";
1559
+ const lines = [];
1560
+ for (const [index, a] of actions.entries()) {
1561
+ const coord = a.x !== void 0 && a.y !== void 0 ? await this.toModel({
1562
+ x: a.x,
1563
+ y: a.y
1564
+ }).then((p) => ` at (${p.x}, ${p.y})${p.offscreen ? " (other display)" : ""}`).catch(() => "") : "";
1565
+ const win = a.exe ? ` in ${a.exe}${a.title ? ` ("${a.title.slice(0, 50)}")` : ""}` : "";
1566
+ const target = a.password ? "PasswordField" : a.role && a.name ? `${a.role} "${a.name}"` : a.name ? `"${a.name}"` : a.role ?? "";
1567
+ let desc;
1568
+ if (a.kind === "double_click") desc = `Double-clicked${target ? ` ${target}` : ""}${coord}${win}`;
1569
+ else if (a.kind === "click") desc = `${a.button === "right" ? "Right-clicked" : a.button === "middle" ? "Middle-clicked" : "Left-clicked"}${target ? ` ${target}` : ""}${coord}${win}`;
1570
+ else if (a.kind === "scroll") desc = `Scrolled ${a.direction ?? "down"}${coord}${win}`;
1571
+ else desc = `Typed${a.keys && a.keys > 1 ? ` (${a.keys} keys)` : ""}${target ? ` into ${target}` : ""}${win}`;
1572
+ lines.push(`${index + 1}. ${desc}`);
1573
+ }
1574
+ return `\nRecent user actions during takeover (screenshot coordinates):\n${lines.join("\n")}\nRespect what the user just did and adapt your plan accordingly (do not undo or overwrite their changes).`;
1575
+ }
1450
1576
  /** Run one action. Returns text plus an image for screenshot/zoom. */
1451
1577
  async run(input, call) {
1452
1578
  if (call.signal.aborted) throw new Error("Cancelled.");
@@ -1456,8 +1582,20 @@ var Computer = class Computer {
1456
1582
  const wasPaused = this.overlay.paused;
1457
1583
  if (await this.overlay.yieldToUser(call.signal, s.pauseOnUserInput && INPUT.has(action)) && INPUT.has(action)) {
1458
1584
  await this.overlay.begin(call.agent, Computer.statusOf(input));
1585
+ const drained = s.reportUserActions ? this.overlay.drainUserActions?.() ?? [] : [];
1586
+ const userNotes = await this.formatUserActions(drained);
1459
1587
  return {
1460
- text: `Not done: ${wasPaused ? "the user paused computer use (Esc) and has now resumed" : "the user was typing on the keyboard, so you were paused until they stopped"}. ${action} was NOT performed. Look at the new screenshot and re-plan before acting.`,
1588
+ text: `Not done: ${wasPaused ? "the user paused computer use (Esc) and has now resumed" : drained.some((a) => a.kind === "click" || a.kind === "double_click" || a.kind === "scroll") ? "the user took over with mouse/keyboard, so you waited until they finished" : "the user was typing on the keyboard, so you were paused until they stopped"}. ${action} was NOT performed.${userNotes}\nLook at the new screenshot and re-plan before acting.`,
1589
+ ...call.vision ? { image: await this.screenshot() } : {},
1590
+ skipped: true
1591
+ };
1592
+ }
1593
+ if (s.pauseOnUserInput && s.reportUserActions && INPUT.has(action) && this.overlay.hasUserActions?.()) {
1594
+ const drained = this.overlay.drainUserActions?.() ?? [];
1595
+ const userNotes = await this.formatUserActions(drained);
1596
+ await this.overlay.status("检测到你刚操作了桌面,同步给 AI");
1597
+ return {
1598
+ text: `Not done: the user intervened on the desktop before this step. ${action} was NOT performed.${userNotes}\nLook at the new screenshot and re-plan before acting.`,
1461
1599
  ...call.vision ? { image: await this.screenshot() } : {},
1462
1600
  skipped: true
1463
1601
  };
@@ -1466,10 +1604,12 @@ var Computer = class Computer {
1466
1604
  const changed = await this.foregroundChanged();
1467
1605
  if (changed && !isHostWindow(changed) && !isTransientShell(changed)) {
1468
1606
  await this.overlay.status("检测到窗口切换,重新查看屏幕");
1607
+ const drained = s.reportUserActions ? this.overlay.drainUserActions?.() ?? [] : [];
1608
+ const userNotes = await this.formatUserActions(drained);
1469
1609
  const image = call.vision ? await this.screenshot() : void 0;
1470
1610
  if (!image) this.seen = changed;
1471
1611
  return {
1472
- text: `Not done: since your last look the foreground window changed to ${changed.exe} ("${changed.title.slice(0, 60)}") without you acting, most likely the user opened it. ${action} was NOT performed. Look at the new screenshot and decide whether to continue there, switch back, or ask the user.`,
1612
+ text: `Not done: since your last look the foreground window changed to ${changed.exe} ("${changed.title.slice(0, 60)}") without you acting, most likely the user opened it. ${action} was NOT performed.${userNotes}\nLook at the new screenshot and decide whether to continue there, switch back, or ask the user.`,
1473
1613
  ...image ? { image } : {},
1474
1614
  skipped: true
1475
1615
  };
@@ -1479,13 +1619,15 @@ var Computer = class Computer {
1479
1619
  if (KEYBOARD.has(action)) await this.refocusFromHost();
1480
1620
  switch (action) {
1481
1621
  case "screenshot": {
1622
+ const drained = s.reportUserActions ? this.overlay.drainUserActions?.() ?? [] : [];
1623
+ const userNotes = await this.formatUserActions(drained);
1482
1624
  const shot = await this.takeScreenshot({
1483
- force: input.force === true,
1625
+ force: input.force === true || drained.length > 0,
1484
1626
  ...input.detail ? { detail: input.detail } : {}
1485
1627
  });
1486
- 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).` };
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}` };
1487
1629
  return {
1488
- text: `Screenshot ${shot.width}x${shot.height} of display ${this.currentIndex}.`,
1630
+ text: `Screenshot ${shot.width}x${shot.height} of display ${this.currentIndex}.${userNotes}`,
1489
1631
  image: shot
1490
1632
  };
1491
1633
  }
@@ -1523,7 +1665,7 @@ var Computer = class Computer {
1523
1665
  case "triple_click": {
1524
1666
  const { point, label, named } = await this.aim(input, call);
1525
1667
  let p = point;
1526
- if (!named) await this.checkPointer(call, p, "click");
1668
+ const hitWin = !named ? await this.checkPointer(call, p, "click") : void 0;
1527
1669
  const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
1528
1670
  const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
1529
1671
  const modifiers = parseModifiers(input.modifiers ?? input.text);
@@ -1531,6 +1673,18 @@ var Computer = class Computer {
1531
1673
  const semantic = named.element.role === "Edit" || named.element.editable ? "focus" : "invoke";
1532
1674
  if (await this.semanticAction(call, named, semantic)) return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
1533
1675
  }
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
+ }
1687
+ }
1534
1688
  if (named) p = await this.namedClickPoint(call, input.target, named);
1535
1689
  const labelCoord = input.coordinate ? {
1536
1690
  labelX: Math.round(input.coordinate[0]),
@@ -1544,7 +1698,8 @@ var Computer = class Computer {
1544
1698
  ...labelCoord,
1545
1699
  button,
1546
1700
  count,
1547
- modifiers
1701
+ modifiers,
1702
+ ...s.restorePointer ? { restorePointer: true } : {}
1548
1703
  });
1549
1704
  const clickedAt = p ?? (typeof clickRes?.x === "number" && typeof clickRes?.y === "number" ? {
1550
1705
  x: clickRes.x,
@@ -1605,6 +1760,7 @@ var Computer = class Computer {
1605
1760
  let into = "";
1606
1761
  if (input.target || input.coordinate) {
1607
1762
  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.`);
1608
1764
  let p = point;
1609
1765
  const focused = named && await this.semanticAction(call, named, "focus");
1610
1766
  if (!focused) {
@@ -1622,7 +1778,15 @@ var Computer = class Computer {
1622
1778
  into = ` (${focused ? "focused" : "clicked"}${label} first)`;
1623
1779
  }
1624
1780
  await this.checkKeyboard(call, "type into");
1625
- return { text: `${await this.enterText(text, call)}${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.`);
1784
+ }
1785
+ if (input.replace === true) {
1786
+ await this.sendKeys(call, parseKeys("ctrl+a"));
1787
+ await setTimeout$1(50, void 0, { signal: call.signal });
1788
+ }
1789
+ return { text: `${await this.enterText(text, call)}${input.replace === true ? " (replaced existing text)" : ""}${into}` };
1626
1790
  }
1627
1791
  case "key": {
1628
1792
  const combos = parseKeys(input.text ?? "");
@@ -1766,12 +1930,13 @@ function summarizeToolAction(tool, rawArgs) {
1766
1930
  const force = args.force === true ? " force=true" : "";
1767
1931
  return `${act}${act === "type" && typeof args.text === "string" ? ` len=${args.text.length}` : ""}${detail}${force}`;
1768
1932
  }
1769
- if (tool === "computer_batch" && Array.isArray(args.actions)) {
1933
+ if (tool === "computer_batch") {
1770
1934
  const finish = typeof args.finish === "string" ? ` finish=${args.finish}` : "";
1771
- return `batch(${args.actions.length})${finish}`;
1935
+ if (typeof args.macro === "string" && args.macro.trim() !== "") return `macro${finish}`;
1936
+ if (Array.isArray(args.actions)) return `batch(${args.actions.length})${finish}`;
1772
1937
  }
1773
1938
  if (tool === "windows" || tool === "clipboard" || tool === "app_skill") return typeof args.action === "string" ? args.action : void 0;
1774
- if (tool === "ui_elements") return args.ocr === true ? "ocr" : args.text === true ? "text" : "elements";
1939
+ if (tool === "ui_elements") return args.marks === true ? "marks" : args.cdp === true ? "cdp" : args.ocr === true ? "ocr" : args.text === true ? "text" : "elements";
1775
1940
  if (tool === "open_application") return typeof args.name === "string" && /^https?:\/\//i.test(args.name.trim()) ? "url" : "app";
1776
1941
  }
1777
1942
  function sanitizeError(raw) {
@@ -1812,6 +1977,7 @@ function buildDiagnosticSnapshot(options) {
1812
1977
  defaultSessionEnabled: s.defaultSessionEnabled,
1813
1978
  overlay: s.overlay,
1814
1979
  hostWindow: s.hostWindow,
1980
+ petSize: s.petSize,
1815
1981
  cardOpacity: s.cardOpacity,
1816
1982
  typingMode: s.typingMode,
1817
1983
  quickSteps: s.quickSteps,
@@ -1822,8 +1988,14 @@ function buildDiagnosticSnapshot(options) {
1822
1988
  maxPixels: s.maxPixels,
1823
1989
  jpegQuality: s.jpegQuality,
1824
1990
  pauseOnUserInput: s.pauseOnUserInput,
1991
+ reportUserActions: s.reportUserActions,
1825
1992
  userIdleMs: s.userIdleMs,
1826
1993
  nativeHelper: s.nativeHelper,
1994
+ elementFirstClick: s.elementFirstClick,
1995
+ restorePointer: s.restorePointer,
1996
+ protectPasswords: s.protectPasswords,
1997
+ windowChangeGuard: s.windowChangeGuard,
1998
+ cdpPort: s.cdpPort,
1827
1999
  blockedAppsCount: s.blockedApps.length,
1828
2000
  hasCustomHarnessUrl: Boolean(s.harnessUrl)
1829
2001
  },
@@ -2112,7 +2284,8 @@ var HelperClient = class HelperClient {
2112
2284
  for (const listener of this.listeners) try {
2113
2285
  listener({
2114
2286
  event: message.event,
2115
- ...message.reason === void 0 ? {} : { reason: message.reason }
2287
+ ...message.reason === void 0 ? {} : { reason: message.reason },
2288
+ ...message.data !== void 0 && message.data !== null && typeof message.data === "object" ? { data: message.data } : {}
2116
2289
  });
2117
2290
  } catch {}
2118
2291
  return;
@@ -2126,6 +2299,106 @@ var HelperClient = class HelperClient {
2126
2299
  else entry.reject(new Error(message.error ?? "helper error"));
2127
2300
  }
2128
2301
  };
2302
+ function macroId(name) {
2303
+ return name.trim().toLowerCase().replace(/[\\/:*?"<>|\s.]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "macro";
2304
+ }
2305
+ /** Collect `{{param}}` placeholder names referenced across macro actions. */
2306
+ function extractMacroParams(actions) {
2307
+ const found = /* @__PURE__ */ new Set();
2308
+ const scan = (value) => {
2309
+ if (typeof value !== "string") return;
2310
+ for (const match of value.matchAll(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g)) if (match[1]) found.add(match[1]);
2311
+ };
2312
+ for (const step of actions) {
2313
+ scan(step.target);
2314
+ scan(step.text);
2315
+ scan(step.until);
2316
+ scan(step.modifiers);
2317
+ }
2318
+ return [...found];
2319
+ }
2320
+ /** Substitute `{{param}}` placeholders into a fresh copy of `actions`. */
2321
+ function renderMacroActions(actions, params = {}) {
2322
+ const missing = /* @__PURE__ */ new Set();
2323
+ const replace = (raw) => {
2324
+ if (raw === void 0) return void 0;
2325
+ return raw.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_whole, key) => {
2326
+ if (Object.prototype.hasOwnProperty.call(params, key) && params[key] !== void 0) return String(params[key]);
2327
+ missing.add(key);
2328
+ return `{{${key}}}`;
2329
+ });
2330
+ };
2331
+ const rendered = actions.map((step) => {
2332
+ const out = { ...step };
2333
+ if (step.text !== void 0) out.text = replace(step.text);
2334
+ if (step.target !== void 0) out.target = replace(step.target);
2335
+ if (step.until !== void 0) out.until = replace(step.until);
2336
+ if (step.modifiers !== void 0) out.modifiers = replace(step.modifiers);
2337
+ return out;
2338
+ });
2339
+ if (missing.size > 0) throw new Error(`Macro is missing required parameter(s): ${[...missing].join(", ")}.`);
2340
+ return rendered;
2341
+ }
2342
+ var MacroStore = class {
2343
+ dir;
2344
+ constructor(dir = join(process.env.DSH_HOME ?? join(homedir(), ".dsh"), "computer-use-macros")) {
2345
+ this.dir = dir;
2346
+ }
2347
+ list() {
2348
+ if (!existsSync(this.dir)) return [];
2349
+ const out = [];
2350
+ for (const file of readdirSync(this.dir)) {
2351
+ if (!file.toLowerCase().endsWith(".json")) continue;
2352
+ try {
2353
+ const path = join(this.dir, file);
2354
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
2355
+ if (!Array.isArray(parsed.actions) || parsed.actions.length === 0) continue;
2356
+ const id = macroId(file.slice(0, -5));
2357
+ out.push({
2358
+ id,
2359
+ name: typeof parsed.name === "string" && parsed.name.trim() !== "" ? parsed.name.trim() : id,
2360
+ ...typeof parsed.app === "string" && parsed.app.trim() !== "" ? { app: parsed.app.trim() } : {},
2361
+ description: typeof parsed.description === "string" ? parsed.description.trim() : "",
2362
+ params: extractMacroParams(parsed.actions),
2363
+ actions: parsed.actions,
2364
+ updatedAt: statSync(path).mtimeMs
2365
+ });
2366
+ } catch {}
2367
+ }
2368
+ return out.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
2369
+ }
2370
+ get(nameOrId) {
2371
+ const wanted = macroId(nameOrId);
2372
+ return this.list().find((item) => item.id === wanted || item.name.toLowerCase() === nameOrId.trim().toLowerCase());
2373
+ }
2374
+ save(input) {
2375
+ const name = input.name.trim();
2376
+ if (name === "") throw new Error("Macro name is required.");
2377
+ if (!Array.isArray(input.actions) || input.actions.length === 0) throw new Error("Macro actions must be a non-empty array.");
2378
+ if (input.actions.length > 30) throw new Error(`A macro may contain at most 30 actions.`);
2379
+ const id = macroId(name);
2380
+ const payload = {
2381
+ version: 1,
2382
+ name,
2383
+ ...input.app?.trim() ? { app: input.app.trim() } : {},
2384
+ description: (input.description ?? "").trim().slice(0, 160),
2385
+ actions: input.actions
2386
+ };
2387
+ mkdirSync(this.dir, { recursive: true });
2388
+ const path = join(this.dir, `${id}.json`);
2389
+ const tmp = `${path}.${process.pid}.tmp`;
2390
+ writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n", "utf8");
2391
+ renameSync(tmp, path);
2392
+ return this.get(id);
2393
+ }
2394
+ remove(nameOrId) {
2395
+ const id = this.get(nameOrId)?.id ?? macroId(nameOrId);
2396
+ const path = join(this.dir, `${id}.json`);
2397
+ if (!existsSync(path)) return false;
2398
+ unlinkSync(path);
2399
+ return true;
2400
+ }
2401
+ };
2129
2402
  //#endregion
2130
2403
  //#region lib/types/native/koffi-path.js
2131
2404
  /**
@@ -2325,6 +2598,33 @@ var NativeHelper = class {
2325
2598
  * agent, and typing on the keyboard makes the agent wait. While controlling,
2326
2599
  * the DeepSeek Harness window can shrink into an always-on-top card.
2327
2600
  */
2601
+ const MAX_USER_ACTIONS = 20;
2602
+ function parseUserAction(raw) {
2603
+ const kind = raw.kind;
2604
+ if (kind !== "click" && kind !== "double_click" && kind !== "scroll" && kind !== "type") return void 0;
2605
+ const out = {
2606
+ at: Date.now(),
2607
+ kind
2608
+ };
2609
+ if (raw.button === "left" || raw.button === "right" || raw.button === "middle") out.button = raw.button;
2610
+ if (raw.direction === "up" || raw.direction === "down" || raw.direction === "left" || raw.direction === "right") out.direction = raw.direction;
2611
+ if (typeof raw.x === "number" && Number.isFinite(raw.x)) out.x = Math.round(raw.x);
2612
+ if (typeof raw.y === "number" && Number.isFinite(raw.y)) out.y = Math.round(raw.y);
2613
+ if (typeof raw.exe === "string" && raw.exe.trim() !== "") out.exe = raw.exe.trim();
2614
+ if (typeof raw.title === "string" && raw.title.trim() !== "") out.title = raw.title.trim().slice(0, 80);
2615
+ if (typeof raw.role === "string" && raw.role.trim() !== "") out.role = raw.role.trim();
2616
+ if (typeof raw.name === "string" && raw.name.trim() !== "") out.name = raw.name.trim().slice(0, 60);
2617
+ if (raw.password === true) out.password = true;
2618
+ if (typeof raw.keys === "number" && Number.isFinite(raw.keys)) out.keys = Math.max(1, Math.round(raw.keys));
2619
+ return out;
2620
+ }
2621
+ function userActionCardSummary(a) {
2622
+ const target = a.password ? "密码框" : a.name ? `「${a.name.slice(0, 16)}」` : a.role ? a.role : a.exe ?? "桌面";
2623
+ if (a.kind === "double_click") return `你双击了 ${target}`;
2624
+ if (a.kind === "click") return `你${a.button === "right" ? "右键" : a.button === "middle" ? "中键" : "点击"}了 ${target}`;
2625
+ if (a.kind === "scroll") return `你滚动了 ${a.exe ?? "页面"}`;
2626
+ return `你在 ${target} 输入了文字`;
2627
+ }
2328
2628
  /** Markdown reduced to one plain line for the progress card. */
2329
2629
  function plainLine(text) {
2330
2630
  return text.replace(/```[\s\S]*?(```|$)/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, " ").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm, "").replace(/(\*\*|__|`|~~)/g, "").replace(/\s+/g, " ");
@@ -2410,10 +2710,12 @@ var OverlayController = class {
2410
2710
  cardOpacity = 100;
2411
2711
  /** Paused by Esc or the pill; actions wait until resumed. */
2412
2712
  paused = false;
2413
- /** When the user last typed on the physical keyboard while the overlay was up (ms epoch). */
2713
+ /** When the user last typed or clicked physically while the overlay was up (ms epoch). */
2414
2714
  lastUserInput = 0;
2415
- /** Which physical key that was (helper reason, e.g. "vk=0x41"), for the log. */
2715
+ /** Which physical key/action that was, for the log. */
2416
2716
  lastUserKey = "";
2717
+ /** Bounded sanitized ring buffer of physical user actions since the model last saw them. */
2718
+ userActions = [];
2417
2719
  constructor(helper, settings, log, iconPath = "") {
2418
2720
  this.helper = helper;
2419
2721
  this.settings = settings;
@@ -2426,6 +2728,13 @@ var OverlayController = class {
2426
2728
  else if (event.event === "user_input") {
2427
2729
  this.lastUserInput = Date.now();
2428
2730
  this.lastUserKey = event.reason ?? "";
2731
+ } else if (event.event === "user_action" && event.data) {
2732
+ const parsed = parseUserAction(event.data);
2733
+ if (!parsed) return;
2734
+ this.lastUserInput = parsed.at;
2735
+ this.lastUserKey = parsed.kind;
2736
+ this.recordUserAction(parsed);
2737
+ this.step(userActionCardSummary(parsed));
2429
2738
  } else if (event.event === "message" && event.reason) {
2430
2739
  const agent = this.agent;
2431
2740
  if (!agent) return;
@@ -2434,6 +2743,31 @@ var OverlayController = class {
2434
2743
  }
2435
2744
  });
2436
2745
  }
2746
+ recordUserAction(action) {
2747
+ const prev = this.userActions.at(-1);
2748
+ if (action.kind === "type" && prev?.kind === "type" && prev.exe === action.exe && prev.role === action.role && prev.name === action.name && action.at - prev.at < 8e3) {
2749
+ prev.keys = (prev.keys ?? 1) + (action.keys ?? 1);
2750
+ prev.at = action.at;
2751
+ return;
2752
+ }
2753
+ if (action.kind === "double_click" && prev?.kind === "click" && prev.button === "left" && action.at - prev.at <= 700 && prev.x !== void 0 && action.x !== void 0 && Math.abs(prev.x - action.x) <= 8 && prev.y !== void 0 && action.y !== void 0 && Math.abs(prev.y - action.y) <= 8) {
2754
+ this.userActions[this.userActions.length - 1] = action;
2755
+ return;
2756
+ }
2757
+ this.userActions.push(action);
2758
+ if (this.userActions.length > MAX_USER_ACTIONS) this.userActions.shift();
2759
+ }
2760
+ /** Whether the user has performed physical mouse/keyboard actions not yet reported to the model. */
2761
+ hasUserActions() {
2762
+ return this.userActions.length > 0;
2763
+ }
2764
+ /** Return and clear buffered user takeover actions so the model receives them once. */
2765
+ drainUserActions() {
2766
+ if (this.userActions.length === 0) return [];
2767
+ const items = this.userActions;
2768
+ this.userActions = [];
2769
+ return items;
2770
+ }
2437
2771
  /** The agent currently driving the computer, if any. */
2438
2772
  get controller() {
2439
2773
  return this.agent;
@@ -2470,6 +2804,7 @@ var OverlayController = class {
2470
2804
  if (!this.visible) {
2471
2805
  this.visible = true;
2472
2806
  this.paused = false;
2807
+ this.userActions = [];
2473
2808
  this.starting = this.start(agent, status, settings);
2474
2809
  try {
2475
2810
  await this.starting;
@@ -2518,6 +2853,7 @@ var OverlayController = class {
2518
2853
  idleMs: settings.userIdleMs,
2519
2854
  glow: settings.overlay,
2520
2855
  pet,
2856
+ petSize: settings.petSize,
2521
2857
  petOpacity: settings.cardOpacity,
2522
2858
  thinking: this.thinking
2523
2859
  }).catch((error) => this.log(`overlay: ${String(error)}`));
@@ -2812,9 +3148,10 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
2812
3148
  - 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).
2813
3149
  - 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.
2814
3150
  - 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.
2815
- - 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.
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.
3152
+ - 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.
2816
3153
  - 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.
2817
- - 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.
3154
+ - 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.
2818
3155
  - 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.
2819
3156
  - 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.
2820
3157
  - When two controls share a name, ui_elements reports automationId; use target "id:<AutomationId>" (or "#<AutomationId>") to pick the intended one.
@@ -2822,7 +3159,7 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
2822
3159
  - To see more of a page or list, scroll (action "scroll" with coordinate over the area, scroll_direction, scroll_amount 5-10) instead of hunting with zoom; for long web pages Page Down / End keys also work.
2823
3160
  - If a dedicated tool fits the whole task better (an API, or browser automation attached to the user's own browser), choose it at the start; do not switch tools halfway through a task that is going fine on screen.
2824
3161
  - Do not enter passwords, payment details or solve CAPTCHAs: stop and ask the user to do that step. Ask before irreversible actions (sending messages, deleting, purchasing) unless the user clearly asked for them.
2825
- - The user sees an orange border and can press Esc to pause you at any time. If they pause, type on the keyboard or switch windows, you wait; when an action reports it was not performed, re-check the screen instead of repeating it blindly.`;
3162
+ - The user sees an orange border and can press Esc to pause you at any time, or intervene directly with mouse clicks, scrolling, or typing. When an action reports the user intervened (along with a list of recent user actions such as which button/tab they clicked and where), inspect the new screenshot, respect their intent, and adapt your plan instead of undoing or repeating over what they just did.`;
2826
3163
  }
2827
3164
  //#endregion
2828
3165
  //#region lib/types/skills.js
@@ -3037,6 +3374,7 @@ const DEFAULTS = {
3037
3374
  overlay: true,
3038
3375
  overlayLabel: "DeepSeek Harness",
3039
3376
  hostWindow: "pet",
3377
+ petSize: "standard",
3040
3378
  cardOpacity: 80,
3041
3379
  autoScreenshot: true,
3042
3380
  autoScreenshotDetail: "standard",
@@ -3046,10 +3384,16 @@ const DEFAULTS = {
3046
3384
  jpegQuality: 70,
3047
3385
  blockedApps: [],
3048
3386
  pauseOnUserInput: true,
3387
+ reportUserActions: true,
3049
3388
  userIdleMs: 1500,
3050
3389
  typingMode: "stream",
3051
3390
  quickSteps: false,
3052
- nativeHelper: true
3391
+ nativeHelper: true,
3392
+ elementFirstClick: true,
3393
+ restorePointer: false,
3394
+ protectPasswords: true,
3395
+ windowChangeGuard: true,
3396
+ cdpPort: 0
3053
3397
  };
3054
3398
  /** Unwrap `.volatile()` refs (`{ get() }`) and fall back to defaults for bad values. */
3055
3399
  function resolveConfig(raw) {
@@ -3069,6 +3413,7 @@ function resolveConfig(raw) {
3069
3413
  overlay: bool("overlay"),
3070
3414
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
3071
3415
  hostWindow: out.hostWindow === "pet" || out.hostWindow === "card" || out.hostWindow === "minimize" || out.hostWindow === "keep" ? out.hostWindow : out.minimizeHostWindow === true ? "minimize" : DEFAULTS.hostWindow,
3416
+ petSize: out.petSize === "compact" || out.petSize === "standard" || out.petSize === "detailed" ? out.petSize : DEFAULTS.petSize,
3072
3417
  cardOpacity: num("cardOpacity", 30, 100),
3073
3418
  autoScreenshot: bool("autoScreenshot"),
3074
3419
  autoScreenshotDetail: out.autoScreenshotDetail === "compact" || out.autoScreenshotDetail === "standard" ? out.autoScreenshotDetail : DEFAULTS.autoScreenshotDetail,
@@ -3077,9 +3422,15 @@ function resolveConfig(raw) {
3077
3422
  maxPixels: num("maxPixels", 3e5, 8e6),
3078
3423
  jpegQuality: num("jpegQuality", 30, 100),
3079
3424
  pauseOnUserInput: bool("pauseOnUserInput"),
3425
+ reportUserActions: bool("reportUserActions"),
3080
3426
  userIdleMs: num("userIdleMs", 300, 1e4),
3081
3427
  quickSteps: bool("quickSteps"),
3082
3428
  nativeHelper: bool("nativeHelper"),
3429
+ elementFirstClick: bool("elementFirstClick"),
3430
+ restorePointer: bool("restorePointer"),
3431
+ protectPasswords: bool("protectPasswords"),
3432
+ windowChangeGuard: bool("windowChangeGuard"),
3433
+ cdpPort: num("cdpPort", 0, 65535),
3083
3434
  typingMode: out.typingMode === "stream" || out.typingMode === "type" || out.typingMode === "paste" ? out.typingMode : DEFAULTS.typingMode,
3084
3435
  blockedApps: Array.isArray(out.blockedApps) ? out.blockedApps.filter((item) => typeof item === "string" && item.trim() !== "") : []
3085
3436
  };
@@ -3156,6 +3507,70 @@ async function* retryMalformed(run, attempts = 3) {
3156
3507
  }
3157
3508
  }
3158
3509
  //#endregion
3510
+ //#region lib/types/update-check.js
3511
+ /**
3512
+ * Concurrent plugin update check probing both npmjs and npmmirror so users in
3513
+ * mainland China and overseas both get fast, reliable latest-version feedback.
3514
+ */
3515
+ const REGISTRIES = [{
3516
+ name: "npmjs",
3517
+ url: "https://registry.npmjs.org/@copylee%2fdsh-computer-use/latest"
3518
+ }, {
3519
+ name: "npmmirror",
3520
+ url: "https://registry.npmmirror.com/@copylee%2fdsh-computer-use/latest"
3521
+ }];
3522
+ /** Compare two semver strings (major.minor.patch); returns >0 when `a > b`. */
3523
+ function compareSemver(a, b) {
3524
+ const parse = (v) => {
3525
+ const parts = (v.trim().replace(/^v/i, "").split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10));
3526
+ return [
3527
+ parts[0] || 0,
3528
+ parts[1] || 0,
3529
+ parts[2] || 0
3530
+ ];
3531
+ };
3532
+ const [a1, a2, a3] = parse(a);
3533
+ const [b1, b2, b3] = parse(b);
3534
+ if (a1 !== b1) return a1 - b1;
3535
+ if (a2 !== b2) return a2 - b2;
3536
+ return a3 - b3;
3537
+ }
3538
+ /** Race npmjs & npmmirror concurrently and return the highest valid version found. */
3539
+ async function checkForUpdate(current, fetchImpl = fetch, timeoutMs = 4500) {
3540
+ const results = await Promise.allSettled(REGISTRIES.map(async (reg) => {
3541
+ const res = await fetchImpl(reg.url, {
3542
+ headers: {
3543
+ accept: "application/json",
3544
+ "cache-control": "no-cache"
3545
+ },
3546
+ signal: AbortSignal.timeout(timeoutMs)
3547
+ });
3548
+ if (!res.ok) throw new Error(`${reg.name}: HTTP ${res.status}`);
3549
+ const body = await res.json();
3550
+ if (typeof body.version !== "string" || !/^\d+\.\d+\.\d+/.test(body.version)) throw new Error(`${reg.name}: invalid version`);
3551
+ return {
3552
+ source: reg.name,
3553
+ version: body.version
3554
+ };
3555
+ }));
3556
+ let best;
3557
+ for (const item of results) {
3558
+ if (item.status !== "fulfilled") continue;
3559
+ if (!best || compareSemver(item.value.version, best.version) > 0) best = item.value;
3560
+ }
3561
+ if (!best) return {
3562
+ current,
3563
+ hasUpdate: false,
3564
+ error: "无法连接 npmjs 或 npmmirror 检测更新"
3565
+ };
3566
+ return {
3567
+ current,
3568
+ latest: best.version,
3569
+ hasUpdate: compareSemver(best.version, current) > 0,
3570
+ source: best.source
3571
+ };
3572
+ }
3573
+ //#endregion
3159
3574
  //#region lib/types/routes.js
3160
3575
  const STATUS_ROUTE = "/api/dsh-computer-use/status";
3161
3576
  const PREVIEW_ROUTE = "/api/dsh-computer-use/preview";
@@ -3164,6 +3579,8 @@ const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
3164
3579
  const SKILLS_ROUTE = "/api/dsh-computer-use/skills";
3165
3580
  const SESSION_ROUTE = "/api/dsh-computer-use/session";
3166
3581
  const DIAGNOSTICS_ROUTE = "/api/dsh-computer-use/diagnostics";
3582
+ const UPDATE_ROUTE = "/api/dsh-computer-use/update";
3583
+ const WINDOWS_ROUTE = "/api/dsh-computer-use/windows";
3167
3584
  function json(res, status, body) {
3168
3585
  res.writeHead(status, {
3169
3586
  "content-type": "application/json; charset=utf-8",
@@ -3171,7 +3588,7 @@ function json(res, status, body) {
3171
3588
  });
3172
3589
  res.end(JSON.stringify(body));
3173
3590
  }
3174
- function statusRoute(helper, settings, overlay) {
3591
+ function statusRoute(helper, settings, overlay, pluginVersion = "0.0.0") {
3175
3592
  return async (_req, res) => {
3176
3593
  const s = settings();
3177
3594
  const compact = compactLimits({
@@ -3183,6 +3600,7 @@ function statusRoute(helper, settings, overlay) {
3183
3600
  const displays = await helper.call("displays", {}, 3e4);
3184
3601
  json(res, 200, {
3185
3602
  ok: true,
3603
+ version: pluginVersion,
3186
3604
  platform: process.platform,
3187
3605
  helper: "ready",
3188
3606
  displays: displays.map((d) => ({
@@ -3198,6 +3616,7 @@ function statusRoute(helper, settings, overlay) {
3198
3616
  } catch (error) {
3199
3617
  json(res, 200, {
3200
3618
  ok: true,
3619
+ version: pluginVersion,
3201
3620
  platform: process.platform,
3202
3621
  helper: "error",
3203
3622
  error: error instanceof Error ? error.message : String(error),
@@ -3234,6 +3653,7 @@ function previewRoute(helper, settings, overlay, iconPath) {
3234
3653
  idleMs: s.userIdleMs,
3235
3654
  glow: s.overlay,
3236
3655
  pet,
3656
+ petSize: s.petSize,
3237
3657
  petOpacity: s.cardOpacity
3238
3658
  });
3239
3659
  if (pet) await helper.call("pet_update", {
@@ -3431,6 +3851,42 @@ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
3431
3851
  res.end(text);
3432
3852
  };
3433
3853
  }
3854
+ /** Check npmjs & npmmirror concurrently for a newer plugin version. */
3855
+ function updateRoute(pluginVersion) {
3856
+ return async (_req, res) => {
3857
+ const result = await checkForUpdate(pluginVersion);
3858
+ json(res, 200, {
3859
+ ok: !result.error,
3860
+ ...result
3861
+ });
3862
+ };
3863
+ }
3864
+ /** Passive read-only window list for `@窗口` composer references (never triggers overlay or focus). */
3865
+ function windowsRoute(helper) {
3866
+ return async (req, res) => {
3867
+ const q = (new URL(req.url ?? "/api/dsh-computer-use/windows", "http://127.0.0.1").searchParams.get("q") ?? "").trim().toLowerCase();
3868
+ try {
3869
+ const raw = await helper.call("windows", {}, 8e3);
3870
+ json(res, 200, {
3871
+ ok: true,
3872
+ 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) => ({
3873
+ hwnd: win.hwnd,
3874
+ pid: win.pid,
3875
+ exe: win.exe,
3876
+ title: win.title,
3877
+ minimized: win.minimized,
3878
+ foreground: win.foreground === true
3879
+ }))
3880
+ });
3881
+ } catch (error) {
3882
+ json(res, 200, {
3883
+ ok: false,
3884
+ windows: [],
3885
+ error: error instanceof Error ? error.message : String(error)
3886
+ });
3887
+ }
3888
+ };
3889
+ }
3434
3890
  //#endregion
3435
3891
  //#region lib/types/screenshots.js
3436
3892
  /**
@@ -9419,6 +9875,132 @@ function toolAbortedBeforeDispatchResult(prior) {
9419
9875
  };
9420
9876
  }
9421
9877
  //#endregion
9878
+ //#region lib/types/cdp.js
9879
+ /**
9880
+ * Optional, zero-dependency Chromium CDP browser fast-lane.
9881
+ * When the user's Chrome/Edge exposes a local remote debugging port (e.g. 9222),
9882
+ * reads interactive DOM elements or page text directly over Node's built-in
9883
+ * `fetch` + `WebSocket`. Never launches a separate browser and fails quietly
9884
+ * back to UIA + OCR when no local debug port is open.
9885
+ */
9886
+ const DEFAULT_PORTS = [9222, 9229];
9887
+ /** Probe candidate localhost debugging ports and return the first matching visible page target. */
9888
+ async function findCdpTarget(options = {}) {
9889
+ const ports = options.ports && options.ports.length > 0 ? options.ports : DEFAULT_PORTS;
9890
+ const timeoutMs = options.timeoutMs ?? 280;
9891
+ const hint = options.titleHint?.trim().toLowerCase() ?? "";
9892
+ for (const port of ports) {
9893
+ if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
9894
+ try {
9895
+ const res = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(timeoutMs) });
9896
+ if (!res.ok) continue;
9897
+ const list = await res.json();
9898
+ 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)));
9900
+ if (pages.length === 0) continue;
9901
+ return {
9902
+ port,
9903
+ target: (hint ? pages.find((p) => p.title.toLowerCase().includes(hint) || hint.includes(p.title.toLowerCase())) : void 0) ?? pages[0]
9904
+ };
9905
+ } catch {}
9906
+ }
9907
+ }
9908
+ /** Execute one CDP `Runtime.evaluate` returning JSON on a debugger WebSocket URL. */
9909
+ async function evalCdpJson(wsUrl, expression, timeoutMs = 2500) {
9910
+ const WS = globalThis.WebSocket;
9911
+ if (typeof WS !== "function") return void 0;
9912
+ return new Promise((resolve) => {
9913
+ let settled = false;
9914
+ const finish = (value) => {
9915
+ if (settled) return;
9916
+ settled = true;
9917
+ clearTimeout(timer);
9918
+ try {
9919
+ ws.close();
9920
+ } catch {}
9921
+ resolve(value);
9922
+ };
9923
+ const ws = new WS(wsUrl);
9924
+ const timer = setTimeout(() => finish(void 0), timeoutMs);
9925
+ ws.addEventListener("open", () => {
9926
+ ws.send(JSON.stringify({
9927
+ id: 1,
9928
+ method: "Runtime.evaluate",
9929
+ params: {
9930
+ expression,
9931
+ returnByValue: true,
9932
+ awaitPromise: false
9933
+ }
9934
+ }));
9935
+ });
9936
+ ws.addEventListener("message", (event) => {
9937
+ try {
9938
+ const msg = JSON.parse(String(event.data));
9939
+ if (msg.id === 1) finish(msg.result?.result?.value);
9940
+ } catch {
9941
+ finish(void 0);
9942
+ }
9943
+ });
9944
+ ws.addEventListener("error", () => finish(void 0));
9945
+ ws.addEventListener("close", () => finish(void 0));
9946
+ });
9947
+ }
9948
+ const COLLECT_DOM_SCRIPT = `(() => {
9949
+ const sel = 'a[href],button,input,textarea,select,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="textbox"],[contenteditable="true"]';
9950
+ const nodes = Array.from(document.querySelectorAll(sel));
9951
+ const out = [];
9952
+ const vw = window.innerWidth, vh = window.innerHeight;
9953
+ for (const el of nodes) {
9954
+ if (out.length >= 120) break;
9955
+ const r = el.getBoundingClientRect();
9956
+ if (r.width < 2 || r.height < 2 || r.bottom < 0 || r.right < 0 || r.top > vh || r.left > vw) continue;
9957
+ const style = getComputedStyle(el);
9958
+ if (style.visibility === 'hidden' || style.display === 'none' || Number(style.opacity) === 0) continue;
9959
+ const tag = el.tagName.toLowerCase();
9960
+ const type = (el.getAttribute('type') || '').toLowerCase();
9961
+ const isPwd = tag === 'input' && type === 'password';
9962
+ const role = el.getAttribute('role') || (tag === 'a' ? 'Link' : tag === 'button' ? 'Button' : (tag === 'input' || tag === 'textarea' || el.isContentEditable) ? 'Edit' : tag);
9963
+ const name = (el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.innerText || el.getAttribute('title') || el.getAttribute('name') || '').trim().replace(/\\s+/g, ' ').slice(0, 100);
9964
+ const val = isPwd ? '[password]' : (typeof el.value === 'string' && el.value ? el.value.slice(0, 80) : undefined);
9965
+ const css = el.id ? '#' + CSS.escape(el.id) : tag + (el.getAttribute('name') ? '[name="' + el.getAttribute('name').replace(/"/g, '') + '"]' : '');
9966
+ out.push({
9967
+ role, name, selector: css,
9968
+ x: Math.round(r.left), y: Math.round(r.top), width: Math.round(r.width), height: Math.round(r.height),
9969
+ ...(val !== undefined ? { value: val } : {}),
9970
+ ...(tag === 'input' || tag === 'textarea' || el.isContentEditable ? { editable: true } : {}),
9971
+ ...(isPwd ? { password: true } : {}),
9972
+ });
9973
+ }
9974
+ return out;
9975
+ })()`;
9976
+ /** Read visible interactive DOM controls from a local CDP-enabled browser tab. */
9977
+ async function readCdpElements(options = {}) {
9978
+ const found = await findCdpTarget(options);
9979
+ if (!found?.target.webSocketDebuggerUrl) return void 0;
9980
+ const elements = await evalCdpJson(found.target.webSocketDebuggerUrl, COLLECT_DOM_SCRIPT);
9981
+ if (!Array.isArray(elements)) return void 0;
9982
+ return {
9983
+ port: found.port,
9984
+ title: found.target.title,
9985
+ url: found.target.url,
9986
+ elements
9987
+ };
9988
+ }
9989
+ /** Read visible innerText from a local CDP-enabled browser tab (excluding password inputs). */
9990
+ async function readCdpText(options = {}) {
9991
+ const found = await findCdpTarget(options);
9992
+ if (!found?.target.webSocketDebuggerUrl) return void 0;
9993
+ const text = await evalCdpJson(found.target.webSocketDebuggerUrl, "String(document.body && document.body.innerText ? document.body.innerText : \"\")");
9994
+ if (typeof text !== "string" || text.trim() === "") return void 0;
9995
+ const maxTail = options.tail ?? 4e3;
9996
+ return {
9997
+ port: found.port,
9998
+ title: found.target.title,
9999
+ url: found.target.url,
10000
+ text: text.length > maxTail ? text.slice(-maxTail) : text
10001
+ };
10002
+ }
10003
+ //#endregion
9422
10004
  //#region lib/types/tools.js
9423
10005
  /**
9424
10006
  * Model-facing tools. Kept few and terse on purpose: every schema is sent with
@@ -9542,6 +10124,16 @@ async function windowText(computer, hwnd, tail) {
9542
10124
  }, 2e4);
9543
10125
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
9544
10126
  if (!result.text || result.source === "none") {
10127
+ if (isBrowser(result)) {
10128
+ const s = computer.settings();
10129
+ const cdp = await readCdpText({
10130
+ ...s.cdpPort > 0 ? { ports: [s.cdpPort] } : {},
10131
+ titleHint: result.title,
10132
+ ...s.harnessUrl ? { harnessUrl: s.harnessUrl } : {},
10133
+ tail: maxTail
10134
+ }).catch(() => void 0);
10135
+ if (cdp && cdp.text.trim() !== "") return `${head}: ${cdp.text.length} characters (CDP fast-lane port ${cdp.port}).\n${cdp.text}`;
10136
+ }
9545
10137
  const ocr = await computer.ocr(hwnd).catch(() => void 0);
9546
10138
  if (ocr && ocr.text && ocr.text.trim() !== "") {
9547
10139
  const sliced = ocr.text.length > maxTail ? ocr.text.slice(-maxTail) : ocr.text;
@@ -9590,7 +10182,7 @@ const actionProperties = {
9590
10182
  },
9591
10183
  target: {
9592
10184
  type: "string",
9593
- 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."
10185
+ 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."
9594
10186
  },
9595
10187
  until: {
9596
10188
  type: "string",
@@ -9613,6 +10205,10 @@ const actionProperties = {
9613
10205
  type: "string",
9614
10206
  enum: ["high", "low"],
9615
10207
  description: "Screenshot detail: \"high\" uses full configured resolution; \"low\" uses a smaller, cheaper image for quick visual confirmation."
10208
+ },
10209
+ replace: {
10210
+ type: "boolean",
10211
+ description: "type: select all (Ctrl+A) and replace existing text in the field."
9616
10212
  }
9617
10213
  };
9618
10214
  const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
@@ -9643,12 +10239,11 @@ function createTools(host) {
9643
10239
  }));
9644
10240
  tools.push(defineTool({
9645
10241
  name: "computer_batch",
9646
- 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 \"保存\"].",
10242
+ 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 \"保存\"].",
9647
10243
  parameters: {
9648
10244
  actions: {
9649
10245
  type: "array",
9650
- required: true,
9651
- 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).",
10246
+ description: "Ordered actions, same fields as the computer tool (required unless macro is given). zoom is allowed only as the last action.",
9652
10247
  items: {
9653
10248
  type: "object",
9654
10249
  additionalProperties: false,
@@ -9661,6 +10256,16 @@ function createTools(host) {
9661
10256
  }
9662
10257
  }
9663
10258
  },
10259
+ macro: {
10260
+ type: "string",
10261
+ description: "Name of a saved action macro (created via app_skill save_macro) to replay instead of passing actions."
10262
+ },
10263
+ params: {
10264
+ type: "object",
10265
+ additionalProperties: true,
10266
+ properties: {},
10267
+ description: "Parameter values for {{placeholder}} variables when replaying a macro."
10268
+ },
9664
10269
  finish: {
9665
10270
  type: "string",
9666
10271
  enum: [
@@ -9680,12 +10285,19 @@ function createTools(host) {
9680
10285
  timeoutMs: 18e5,
9681
10286
  async execute(args, exec) {
9682
10287
  const call = await host.context(exec);
9683
- const actions = args.actions;
9684
- const finish = args.finish ?? "screenshot";
9685
- const detail = args.detail;
10288
+ const rawArgs = args;
10289
+ let actions = rawArgs.actions;
10290
+ if (typeof rawArgs.macro === "string" && rawArgs.macro.trim() !== "") {
10291
+ if (!host.macros) throw new Error("Macro store is not available.");
10292
+ const saved = host.macros.get(rawArgs.macro);
10293
+ if (!saved) throw new Error(`No saved macro named "${rawArgs.macro}". Use app_skill list_macros to see available macros.`);
10294
+ actions = renderMacroActions(saved.actions, rawArgs.params ?? {});
10295
+ }
10296
+ const finish = rawArgs.finish ?? "screenshot";
10297
+ const detail = rawArgs.detail;
9686
10298
  let zoomed;
9687
10299
  let endedWithZoom = false;
9688
- if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array.");
10300
+ if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array (or pass a saved macro name).");
9689
10301
  if (actions.length > 30) throw new Error("At most 30 actions per batch.");
9690
10302
  const lines = [];
9691
10303
  let failure;
@@ -9703,13 +10315,15 @@ function createTools(host) {
9703
10315
  zoomed = outcome.image;
9704
10316
  }
9705
10317
  if (outcome.skipped) {
9706
- failure = `#${index + 1} ${input.action} skipped: the user was typing on the keyboard. Re-check the screen before continuing.`;
10318
+ failure = `#${index + 1} ${input.action} skipped: ${outcome.text}`;
9707
10319
  break;
9708
10320
  }
9709
10321
  lines.push(`#${index + 1} ${outcome.text}`);
9710
10322
  await setTimeout$1(60, void 0, { signal: call.signal });
9711
- if (computer.settings().pauseOnUserInput && computer.overlay.userTypedSince(stepStart - 1)) {
9712
- failure = `#${index + 1} done, but the user typed on the keyboard meanwhile; remaining actions stopped. Re-check the screen before continuing.`;
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.`;
9713
10327
  break;
9714
10328
  }
9715
10329
  } catch (error) {
@@ -9947,12 +10561,16 @@ function createTools(host) {
9947
10561
  }));
9948
10562
  tools.push(defineTool({
9949
10563
  name: "ui_elements",
9950
- description: "Read the foreground window (or a window by hwnd) through Windows UI Automation or built-in Windows OCR. Default: clickable/editable UIA controls with center coordinates in screenshot pixels. With text: true: plain text of the window (automatically falls back to Windows OCR when UIA exposes none). With ocr: true: recognize visible text lines and clickable center coordinates directly via Windows OCR (works on canvas UIs, games, images, and custom-drawn apps).",
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.",
9951
10565
  parameters: {
9952
10566
  hwnd: {
9953
10567
  type: "integer",
9954
10568
  description: "Window handle; default foreground window."
9955
10569
  },
10570
+ marks: {
10571
+ type: "boolean",
10572
+ description: "Return a Set-of-Marks numbered screenshot alongside the element list so you can target controls by \"#1\", \"#2\", ..."
10573
+ },
9956
10574
  text: {
9957
10575
  type: "boolean",
9958
10576
  description: "Return the window's text content instead of the element list."
@@ -9961,6 +10579,10 @@ function createTools(host) {
9961
10579
  type: "boolean",
9962
10580
  description: "Recognize visible text lines and clickable center coordinates via built-in Windows OCR."
9963
10581
  },
10582
+ cdp: {
10583
+ type: "boolean",
10584
+ description: "Inspect visible DOM controls directly over a local Chrome/Edge CDP port (falls back to UIA if unavailable)."
10585
+ },
9964
10586
  tail: {
9965
10587
  type: "integer",
9966
10588
  description: "text: how many characters from the end to return (default 4000, max 20000); new content is usually at the end."
@@ -9977,8 +10599,53 @@ function createTools(host) {
9977
10599
  output,
9978
10600
  timeoutMs: 3e4,
9979
10601
  isConcurrencySafe: () => true,
9980
- async execute(args) {
9981
- const { hwnd, include_text: includeText, max, text, ocr, tail } = args;
10602
+ 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;
10610
+ const center = await computer.toModel({
10611
+ x: el.x + el.width / 2,
10612
+ y: el.y + el.height / 2
10613
+ });
10614
+ const flags = [
10615
+ el.password ? "password" : "",
10616
+ el.value !== void 0 ? `value="${el.value}"` : "",
10617
+ el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
10618
+ el.disabled ? "disabled" : "",
10619
+ el.editable ? "editable" : ""
10620
+ ].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
+ }
9982
10649
  if (ocr === true) {
9983
10650
  const result = await computer.ocr(hwnd);
9984
10651
  const limit = Math.min(400, Math.max(10, max ?? 120));
@@ -10007,6 +10674,7 @@ function createTools(host) {
10007
10674
  y: el.y + el.height / 2
10008
10675
  });
10009
10676
  const flags = [
10677
+ el.password ? "password" : "",
10010
10678
  el.value !== void 0 ? `value="${el.value}"` : "",
10011
10679
  el.checked !== void 0 ? el.checked ? "checked" : "unchecked" : "",
10012
10680
  el.disabled ? "disabled" : "",
@@ -10020,7 +10688,10 @@ function createTools(host) {
10020
10688
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements.`;
10021
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.` };
10022
10690
  },
10023
- presentCall: (args) => card(args.ocr ? "OCR 识别文字" : "读取界面元素")
10691
+ presentCall: (args) => {
10692
+ const a = args;
10693
+ return card(a.marks ? "编号标图 (Set-of-Marks)" : a.cdp ? "CDP 读取网页元素" : a.ocr ? "OCR 识别文字" : "读取界面元素");
10694
+ }
10024
10695
  }));
10025
10696
  tools.push(defineTool({
10026
10697
  name: "clipboard",
@@ -10102,7 +10773,7 @@ function createTools(host) {
10102
10773
  const skills = host.skills;
10103
10774
  tools.push(defineTool({
10104
10775
  name: "app_skill",
10105
- 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.`,
10776
+ 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.`,
10106
10777
  parameters: {
10107
10778
  action: {
10108
10779
  type: "string",
@@ -10110,13 +10781,16 @@ function createTools(host) {
10110
10781
  "list",
10111
10782
  "read",
10112
10783
  "append",
10113
- "write"
10784
+ "write",
10785
+ "save_macro",
10786
+ "list_macros",
10787
+ "delete_macro"
10114
10788
  ],
10115
10789
  required: true
10116
10790
  },
10117
10791
  app: {
10118
10792
  type: "string",
10119
- description: "App name, e.g. \"Obsidian\" (read / append / write)."
10793
+ description: "App name (read / append / write), or optional app tag for save_macro."
10120
10794
  },
10121
10795
  content: {
10122
10796
  type: "string",
@@ -10124,13 +10798,52 @@ function createTools(host) {
10124
10798
  },
10125
10799
  summary: {
10126
10800
  type: "string",
10127
- description: "A few words on what the skill covers, shown in the list (write, or the first append)."
10801
+ description: "A few words on what the skill or macro covers."
10802
+ },
10803
+ macro: {
10804
+ type: "string",
10805
+ description: "Macro name (save_macro / delete_macro)."
10806
+ },
10807
+ actions: {
10808
+ type: "array",
10809
+ description: "Ordered computer_batch actions to save as a replayable macro (save_macro); supports {{param}} placeholders in text/target/until.",
10810
+ items: {
10811
+ type: "object",
10812
+ additionalProperties: false,
10813
+ properties: {
10814
+ ...actionProperties,
10815
+ action: {
10816
+ ...actionProperties.action,
10817
+ enum: BATCH_ACTIONS
10818
+ }
10819
+ }
10820
+ }
10128
10821
  }
10129
10822
  },
10130
10823
  output,
10131
10824
  isConcurrencySafe: () => false,
10132
10825
  async execute(args) {
10133
- const { action, app, content, summary } = args;
10826
+ const { action, app, content, summary, macro, actions } = args;
10827
+ if (action === "list_macros") {
10828
+ const rows = host.macros?.list() ?? [];
10829
+ 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") };
10830
+ }
10831
+ if (action === "save_macro") {
10832
+ if (!host.macros) throw new Error("Macro store is not available.");
10833
+ const saved = host.macros.save({
10834
+ name: String(macro ?? ""),
10835
+ ...app ? { app } : {},
10836
+ ...summary ? { description: summary } : {},
10837
+ actions: actions ?? []
10838
+ });
10839
+ 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)} }).` };
10840
+ }
10841
+ if (action === "delete_macro") {
10842
+ if (!host.macros) throw new Error("Macro store is not available.");
10843
+ const name = String(macro ?? "").trim();
10844
+ if (name === "") throw new Error("macro name is required.");
10845
+ return { text: host.macros.remove(name) ? `Deleted macro "${name}".` : `No macro named "${name}".` };
10846
+ }
10134
10847
  if (action === "list") {
10135
10848
  const rows = skills.list();
10136
10849
  return { text: rows.length === 0 ? "No app skills yet." : rows.map((skill) => `${skill.app}${skill.summary ? ` — ${skill.summary}` : ""} (${skill.content.length} chars)`).join("\n") };
@@ -10155,12 +10868,20 @@ function createTools(host) {
10155
10868
  }, skills.find(name)?.id) : skills.append(name, text, extra);
10156
10869
  return { text: `Skill for ${saved.app} saved (${saved.content.length} of ${SKILL_MAX_CHARS} characters).` };
10157
10870
  },
10158
- presentCall: (args) => card(`应用技能 · ${{
10159
- list: "列表",
10160
- read: "读取",
10161
- append: "记录",
10162
- write: "重写"
10163
- }[args.action ?? ""] ?? ""}${args.app ? ` · ${args.app}` : ""}`)
10871
+ presentCall: (args) => {
10872
+ const a = args;
10873
+ const label = {
10874
+ list: "列表",
10875
+ read: "读取",
10876
+ append: "记录",
10877
+ write: "重写",
10878
+ save_macro: "保存宏",
10879
+ list_macros: "宏列表",
10880
+ delete_macro: "删除宏"
10881
+ }[a.action ?? ""] ?? "";
10882
+ const suffix = a.macro ?? a.app ?? "";
10883
+ return card(`应用技能 · ${label}${suffix ? ` · ${suffix}` : ""}`);
10884
+ }
10164
10885
  }));
10165
10886
  }
10166
10887
  tools.push(defineTool({
@@ -10195,16 +10916,22 @@ function readPluginVersion() {
10195
10916
  return "0.0.0";
10196
10917
  }
10197
10918
  const PLUGIN_VERSION = readPluginVersion();
10198
- /** Parse `/cu [on|off|toggle|status|reset]` arguments into an action. */
10919
+ /** Parse `/cu [on|off|toggle|status|reset|stop|revoke <app>]` arguments into an action. */
10199
10920
  function parseCuCommand(rawInput) {
10200
- const token = rawInput.trim().toLowerCase();
10921
+ const token = (rawInput.trim().split(/\s+/).filter(Boolean)[0] ?? "").toLowerCase();
10201
10922
  if (token === "" || token === "status") return "status";
10202
10923
  if (token === "on" || token === "enable" || token === "enabled" || token === "true" || token === "1") return "on";
10203
10924
  if (token === "off" || token === "disable" || token === "disabled" || token === "false" || token === "0") return "off";
10204
10925
  if (token === "toggle") return "toggle";
10205
10926
  if (token === "reset" || token === "default") return "reset";
10927
+ if (token === "stop" || token === "cancel" || token === "abort") return "stop";
10928
+ if (token === "revoke" || token === "ungrant") return "revoke";
10206
10929
  return "invalid";
10207
10930
  }
10931
+ /** Extract the app name argument after `/cu revoke ...` (empty means all granted apps). */
10932
+ function parseCuRevokeTarget(rawInput) {
10933
+ return rawInput.trim().replace(/^(revoke|ungrant)\s*/i, "").trim();
10934
+ }
10208
10935
  const name = "@copylee/dsh-computer-use";
10209
10936
  const inject = ["tools", "attachments"];
10210
10937
  const Config = z.object({
@@ -10272,6 +10999,23 @@ const Config = z.object({
10272
10999
  "zh-CN": { $description: "操控期间 DeepSeek Harness 窗口怎么摆放(结束后自动恢复原尺寸和位置)" },
10273
11000
  "en-US": { $description: "What to do with the DeepSeek Harness window while controlling (restored afterwards)" }
10274
11001
  }),
11002
+ petSize: z.union([
11003
+ z.const("compact").i18n({
11004
+ "zh-CN": { $description: "紧凑小卡片(最省视野,单行当前操作)" },
11005
+ "en-US": { $description: "Compact (minimal footprint, current action line only)" }
11006
+ }),
11007
+ z.const("standard").i18n({
11008
+ "zh-CN": { $description: "标准卡片(单行思考 + 操作进度,推荐)" },
11009
+ "en-US": { $description: "Standard (one-line thinking + action breadcrumb, recommended)" }
11010
+ }),
11011
+ z.const("detailed").i18n({
11012
+ "zh-CN": { $description: "详情大卡片(双行思考 + 最近 3 步时间线)" },
11013
+ "en-US": { $description: "Detailed (two-line thinking + recent 3-step timeline)" }
11014
+ })
11015
+ ]).default("standard").volatile().i18n({
11016
+ "zh-CN": { $description: "迷你进度卡片尺寸与默认展示的信息量" },
11017
+ "en-US": { $description: "Size and default information density of the mini progress card" }
11018
+ }),
10275
11019
  cardOpacity: z.natural().min(30).max(100).default(80).volatile().i18n({
10276
11020
  "zh-CN": { $description: "悬浮卡片不透明度(%):调低可透过卡片看清下面的操作过程;鼠标停在卡片上时变为不透明" },
10277
11021
  "en-US": { $description: "Card opacity (%): lower lets you watch the work underneath; it turns opaque while the pointer rests on it" }
@@ -10328,8 +11072,12 @@ const Config = z.object({
10328
11072
  "en-US": { $description: "Screenshot JPEG quality" }
10329
11073
  }),
10330
11074
  pauseOnUserInput: z.boolean().default(true).volatile().i18n({
10331
- "zh-CN": { $description: "检测到你在操作时让出控制:你用键盘打字时暂停、停手后继续;你切换或打开了新窗口时,AI 重新看屏幕再决定(鼠标移动不会触发)" },
10332
- "en-US": { $description: "Yield to you: pause while you type, and re-check the screen when you bring up another window (mouse movement is ignored)" }
11075
+ "zh-CN": { $description: "检测到你在操作时让出控制:你用键盘打字或点击鼠标/滚轮时暂停、停手后继续;你切换或打开了新窗口时,AI 重新看屏幕再决定(纯鼠标移动不会触发)" },
11076
+ "en-US": { $description: "Yield to you: pause while you type or click/scroll physically, and re-check the screen when you switch windows (pure mouse movement is ignored)" }
11077
+ }),
11078
+ reportUserActions: z.boolean().default(true).volatile().i18n({
11079
+ "zh-CN": { $description: "将你接管期间的脱敏操作摘要(点击了哪个窗口的哪个控件与坐标、滚动或按键输入,绝不记录输入明文与密码)反馈给模型,帮助它理解你的意图" },
11080
+ "en-US": { $description: "Report sanitized summaries of your physical clicks/scrolls/typing (window, control name & screenshot coords; never typed text or passwords) back to the model so it understands your intent" }
10333
11081
  }),
10334
11082
  userIdleMs: z.natural().min(300).max(1e4).default(1500).volatile().i18n({
10335
11083
  "zh-CN": { $description: "键盘停止多少毫秒后恢复操作" },
@@ -10339,6 +11087,26 @@ const Config = z.object({
10339
11087
  "zh-CN": { $description: "截图、显示器与窗口查询、无浮层时的输入改由 DeepSeek Harness 自带的 koffi 在进程内完成(更快,也不受智能应用控制拦截);关闭则全部交给 C# 辅助程序" },
10340
11088
  "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" }
10341
11089
  }),
11090
+ elementFirstClick: z.boolean().default(true).volatile().i18n({
11091
+ "zh-CN": { $description: "坐标点击优先走后台 UIA 语义触发(命中原生按钮/复选框/标签页时不移动真实鼠标、不抢焦点)" },
11092
+ "en-US": { $description: "Try background UIA semantic click at coordinate before moving the physical pointer" }
11093
+ }),
11094
+ restorePointer: z.boolean().default(false).volatile().i18n({
11095
+ "zh-CN": { $description: "物理点击完成后立即将真实鼠标还原到原来的位置" },
11096
+ "en-US": { $description: "Restore the physical mouse pointer to its previous position right after a physical click" }
11097
+ }),
11098
+ protectPasswords: z.boolean().default(true).volatile().i18n({
11099
+ "zh-CN": { $description: "密码框硬保护:自动脱敏 UIA/Win32 密码框内容并拒绝向密码框自动输入文本" },
11100
+ "en-US": { $description: "Protect password fields (IsPassword / ES_PASSWORD): mask values and refuse automated typing" }
11101
+ }),
11102
+ windowChangeGuard: z.boolean().default(true).volatile().i18n({
11103
+ "zh-CN": { $description: "窗口位移或被新弹窗遮挡时阻止盲点坐标并提示模型先重新看屏" },
11104
+ "en-US": { $description: "Guard coordinate clicks when the foreground window moved/resized or is occluded since the last screenshot" }
11105
+ }),
11106
+ 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)" }
11109
+ }),
10342
11110
  blockedApps: z.array(z.string()).default([]).volatile().i18n({
10343
11111
  "zh-CN": { $description: "禁止操控的应用(名称或 exe,如 “alipay”)。常见密码管理器默认已禁止。" },
10344
11112
  "en-US": { $description: "Apps that may never be controlled (names or exe). Common password managers are always blocked." }
@@ -10414,6 +11182,7 @@ function apply(ctx, config = {}) {
10414
11182
  const tools = createTools({
10415
11183
  computer,
10416
11184
  skills,
11185
+ macros: new MacroStore(),
10417
11186
  async saveImage(shot, fileName) {
10418
11187
  const ref = await attachments().saveImage({
10419
11188
  data: shot.data,
@@ -10653,32 +11422,64 @@ function apply(ctx, config = {}) {
10653
11422
  handler: safe
10654
11423
  }), `computer-use: ${path}`);
10655
11424
  };
10656
- route(STATUS_ROUTE, statusRoute(helper, settings, overlay));
11425
+ route(STATUS_ROUTE, statusRoute(helper, settings, overlay, PLUGIN_VERSION));
10657
11426
  route(PREVIEW_ROUTE, previewRoute(helper, settings, overlay, iconPath));
10658
11427
  route(SCREENSHOTS_ROUTE, screenshotsRoute(screenshots));
10659
11428
  route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
10660
11429
  route(SKILLS_ROUTE, skillsRoute(skills));
10661
11430
  route(SESSION_ROUTE, sessionRoute(sessionGate, settings, parentIdsFor, syncAllAgents));
10662
11431
  route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION));
11432
+ route(UPDATE_ROUTE, updateRoute(PLUGIN_VERSION));
11433
+ route(WINDOWS_ROUTE, windowsRoute(helper));
10663
11434
  });
10664
11435
  ctx.inject(["commands"], (cmdCtx) => {
10665
11436
  const commands = cmdCtx.commands;
10666
11437
  if (typeof commands?.register !== "function") return;
10667
11438
  cmdCtx.effect(() => commands.register({
10668
11439
  name: "cu",
10669
- description: "切换当前会话的电脑控制开关:/cu [on|off|toggle|status|reset]",
11440
+ description: "控制当前会话的电脑操控:/cu [on|off|toggle|status|reset|stop|revoke <应用>]",
10670
11441
  handler: (invocation) => {
10671
11442
  const agent = invocation.agent;
10672
11443
  const sessionId = agent?.session?.id ?? agent?.session?.header?.id;
10673
- if (!sessionId) return {
10674
- kind: "error",
10675
- text: "无法识别当前会话 ID。"
10676
- };
10677
11444
  const action = parseCuCommand(invocation.rawInput ?? "");
10678
11445
  if (action === "invalid") return {
10679
11446
  kind: "error",
10680
- text: "用法:/cu [on | off | toggle | status | reset]"
11447
+ text: "用法:/cu [on | off | toggle | status | reset | stop | revoke <应用或all>]"
11448
+ };
11449
+ if (action === "stop") {
11450
+ const active = overlay.controller;
11451
+ if (active) {
11452
+ try {
11453
+ active.cancel({ kind: "user" });
11454
+ } catch {}
11455
+ overlay.end(active).catch(() => {});
11456
+ return {
11457
+ kind: "success",
11458
+ text: "已立即中断当前电脑操控并恢复窗口。"
11459
+ };
11460
+ }
11461
+ overlay.end().catch(() => {});
11462
+ return {
11463
+ kind: "success",
11464
+ text: "当前没有正在执行的电脑操控任务。"
11465
+ };
11466
+ }
11467
+ if (!sessionId) return {
11468
+ kind: "error",
11469
+ text: "无法识别当前会话 ID。"
10681
11470
  };
11471
+ if (action === "revoke") {
11472
+ const target = parseCuRevokeTarget(invocation.rawInput ?? "");
11473
+ const removed = access.revoke(sessionId, target || "all");
11474
+ if (removed.length === 0) return {
11475
+ kind: "success",
11476
+ text: target ? `本会话未找到与「${target}」匹配的应用授权。` : "本会话当前没有任何已授权的应用。"
11477
+ };
11478
+ return {
11479
+ kind: "success",
11480
+ text: `已撤销本会话的应用授权:${removed.join("、")}。`
11481
+ };
11482
+ }
10682
11483
  const parents = parentIdsFor(sessionId);
10683
11484
  const s = settings();
10684
11485
  const alwaysOn = s.sessionMode === "always";
@@ -10746,4 +11547,4 @@ function apply(ctx, config = {}) {
10746
11547
  });
10747
11548
  }
10748
11549
  //#endregion
10749
- export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, parseCuCommand, resolveConfig };
11550
+ export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, parseCuCommand, parseCuRevokeTarget, resolveConfig };