@copylee/dsh-computer-use 0.9.0 → 0.10.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
  }
@@ -1206,15 +1238,54 @@ var Computer = class Computer {
1206
1238
  }, 2e4);
1207
1239
  return Array.isArray(result.elements) ? result.elements : [];
1208
1240
  }
1209
- /** Look for a named control in the window, and only if it is not there in its popups. */
1241
+ /** Read visible text and physical bounding boxes via built-in Windows OCR. */
1242
+ async ocr(hwnd) {
1243
+ return this.helper.call("ocr", hwnd === void 0 ? {} : { hwnd }, 2e4);
1244
+ }
1245
+ /**
1246
+ * Look for a named control in the window, then its popups, and when the UIA
1247
+ * tree is empty or sparse (<= 20 controls, e.g. canvas/WebView/game/custom
1248
+ * UIs), fall back to built-in Windows OCR so `target` still finds visible text.
1249
+ */
1210
1250
  async find(target, hwnd) {
1211
1251
  const inWindow = await this.elements("window", hwnd).catch(() => []);
1212
1252
  const match = matchTarget(inWindow, target);
1213
1253
  if (match.kind !== "missing") return match;
1214
1254
  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;
1255
+ if (inPopups.length > 0) {
1256
+ const second = matchTarget(inPopups, target);
1257
+ if (second.kind !== "missing") return second;
1258
+ const combined = matchTarget([...inWindow, ...inPopups], target);
1259
+ if (combined.kind !== "missing") return combined;
1260
+ }
1261
+ const trimmed = target.trim();
1262
+ if (!/^(id[::]|#)/i.test(trimmed) && inWindow.length + inPopups.length <= 20) {
1263
+ const ocr = await this.ocr(hwnd).catch(() => void 0);
1264
+ if (ocr && Array.isArray(ocr.lines) && ocr.lines.length > 0) {
1265
+ const ocrElements = [];
1266
+ for (const line of ocr.lines) {
1267
+ ocrElements.push({
1268
+ role: "Text",
1269
+ name: line.text,
1270
+ x: line.x,
1271
+ y: line.y,
1272
+ width: line.width,
1273
+ height: line.height
1274
+ });
1275
+ for (const word of line.words ?? []) if (word.text.trim() !== "" && word.text !== line.text) ocrElements.push({
1276
+ role: "Text",
1277
+ name: word.text,
1278
+ x: word.x,
1279
+ y: word.y,
1280
+ width: word.width,
1281
+ height: word.height
1282
+ });
1283
+ }
1284
+ const ocrMatch = matchTarget(ocrElements, target);
1285
+ if (ocrMatch.kind !== "missing") return ocrMatch;
1286
+ }
1287
+ }
1288
+ return inPopups.length === 0 ? match : matchTarget([...inWindow, ...inPopups], target);
1218
1289
  }
1219
1290
  /**
1220
1291
  * Where a named control is. It may still be appearing (the menu just
@@ -1659,6 +1730,125 @@ var Computer = class Computer {
1659
1730
  }
1660
1731
  };
1661
1732
  //#endregion
1733
+ //#region lib/types/diagnostics.js
1734
+ /**
1735
+ * Sanitized diagnostic report for troubleshooting and bug reports.
1736
+ * Records only tool names, action kinds, durations and short error messages —
1737
+ * never typed text, clipboard contents, window text, or screenshot images.
1738
+ */
1739
+ const MAX_CALLS = 30;
1740
+ var DiagnosticsLog = class {
1741
+ calls = [];
1742
+ record(entry) {
1743
+ const item = {
1744
+ at: entry.at ?? (/* @__PURE__ */ new Date()).toISOString(),
1745
+ tool: entry.tool,
1746
+ ...entry.action ? { action: entry.action } : {},
1747
+ durationMs: Math.max(0, Math.round(entry.durationMs)),
1748
+ ok: entry.ok,
1749
+ ...entry.error ? { error: sanitizeError(entry.error) } : {}
1750
+ };
1751
+ this.calls.push(item);
1752
+ if (this.calls.length > MAX_CALLS) this.calls.shift();
1753
+ }
1754
+ recent() {
1755
+ return [...this.calls];
1756
+ }
1757
+ };
1758
+ /** Extract a safe short action summary from tool arguments without leaking typed/clipboard text. */
1759
+ function summarizeToolAction(tool, rawArgs) {
1760
+ if (!rawArgs || typeof rawArgs !== "object") return void 0;
1761
+ const args = rawArgs;
1762
+ if (tool === "computer") {
1763
+ const act = typeof args.action === "string" ? args.action : void 0;
1764
+ if (!act) return void 0;
1765
+ const detail = typeof args.detail === "string" ? ` detail=${args.detail}` : "";
1766
+ const force = args.force === true ? " force=true" : "";
1767
+ return `${act}${act === "type" && typeof args.text === "string" ? ` len=${args.text.length}` : ""}${detail}${force}`;
1768
+ }
1769
+ if (tool === "computer_batch" && Array.isArray(args.actions)) {
1770
+ const finish = typeof args.finish === "string" ? ` finish=${args.finish}` : "";
1771
+ return `batch(${args.actions.length})${finish}`;
1772
+ }
1773
+ 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";
1775
+ if (tool === "open_application") return typeof args.name === "string" && /^https?:\/\//i.test(args.name.trim()) ? "url" : "app";
1776
+ }
1777
+ function sanitizeError(raw) {
1778
+ return raw.replace(/[\r\n]+/g, " ").trim().slice(0, 200);
1779
+ }
1780
+ function buildDiagnosticSnapshot(options) {
1781
+ const s = options.settings;
1782
+ const compact = compactLimits({
1783
+ maxLongEdge: s.maxLongEdge,
1784
+ maxPixels: s.maxPixels,
1785
+ jpegQuality: s.jpegQuality
1786
+ });
1787
+ return {
1788
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1789
+ pluginVersion: options.pluginVersion,
1790
+ nodeVersion: process.version,
1791
+ os: `${platform()} ${release()} (${arch()})`,
1792
+ helper: {
1793
+ status: options.helperStatus,
1794
+ nativeAvailable: options.nativeAvailable,
1795
+ ...options.helperError ? { error: sanitizeError(options.helperError) } : {}
1796
+ },
1797
+ displays: options.displays.map((d, index) => ({
1798
+ index,
1799
+ primary: d.primary,
1800
+ width: d.width,
1801
+ height: d.height,
1802
+ dpi: d.dpi,
1803
+ shot: describeScreenshotSize(d, {
1804
+ maxLongEdge: s.maxLongEdge,
1805
+ maxPixels: s.maxPixels
1806
+ }),
1807
+ compactShot: describeScreenshotSize(d, compact)
1808
+ })),
1809
+ settings: {
1810
+ accessMode: s.accessMode,
1811
+ sessionMode: s.sessionMode,
1812
+ defaultSessionEnabled: s.defaultSessionEnabled,
1813
+ overlay: s.overlay,
1814
+ hostWindow: s.hostWindow,
1815
+ cardOpacity: s.cardOpacity,
1816
+ typingMode: s.typingMode,
1817
+ quickSteps: s.quickSteps,
1818
+ autoScreenshot: s.autoScreenshot,
1819
+ autoScreenshotDetail: s.autoScreenshotDetail,
1820
+ settleMs: s.settleMs,
1821
+ maxLongEdge: s.maxLongEdge,
1822
+ maxPixels: s.maxPixels,
1823
+ jpegQuality: s.jpegQuality,
1824
+ pauseOnUserInput: s.pauseOnUserInput,
1825
+ userIdleMs: s.userIdleMs,
1826
+ nativeHelper: s.nativeHelper,
1827
+ blockedAppsCount: s.blockedApps.length,
1828
+ hasCustomHarnessUrl: Boolean(s.harnessUrl)
1829
+ },
1830
+ recentCalls: options.recentCalls
1831
+ };
1832
+ }
1833
+ function formatDiagnosticText(snap) {
1834
+ return [
1835
+ "=== @copylee/dsh-computer-use Diagnostic Report (sanitized) ===",
1836
+ `Generated: ${snap.generatedAt}`,
1837
+ `Plugin: ${snap.pluginVersion} | Node: ${snap.nodeVersion} | OS: ${snap.os}`,
1838
+ `Helper: ${snap.helper.status} | Native koffi available: ${snap.helper.nativeAvailable}${snap.helper.error ? ` | Error: ${snap.helper.error}` : ""}`,
1839
+ "",
1840
+ "--- Displays ---",
1841
+ ...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}`),
1842
+ "",
1843
+ "--- Settings ---",
1844
+ JSON.stringify(snap.settings, null, 2),
1845
+ "",
1846
+ `--- Recent Tool Calls (${snap.recentCalls.length}) ---`,
1847
+ ...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}` : ""}`),
1848
+ ""
1849
+ ].join("\n");
1850
+ }
1851
+ //#endregion
1662
1852
  //#region lib/types/helper-client.js
1663
1853
  /**
1664
1854
  * Builds and drives the Windows helper (helper/CuHelper.cs): compiled once
@@ -2621,7 +2811,8 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
2621
2811
  - 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
2812
  - 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
2813
  - 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.
2814
+ - 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.
2625
2816
  - 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
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.
2627
2818
  - 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.
@@ -2841,6 +3032,7 @@ var SkillStore = class {
2841
3032
  const ENTRY_ID = "copylee-computer-use";
2842
3033
  const DEFAULTS = {
2843
3034
  accessMode: "per-app",
3035
+ sessionMode: "off",
2844
3036
  defaultSessionEnabled: false,
2845
3037
  overlay: true,
2846
3038
  overlayLabel: "DeepSeek Harness",
@@ -2868,10 +3060,12 @@ function resolveConfig(raw) {
2868
3060
  return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : DEFAULTS[key];
2869
3061
  };
2870
3062
  const bool = (key) => typeof out[key] === "boolean" ? out[key] : DEFAULTS[key];
3063
+ const sessionMode = out.sessionMode === "off" || out.sessionMode === "on" || out.sessionMode === "always" ? out.sessionMode : out.defaultSessionEnabled === true ? "on" : DEFAULTS.sessionMode;
2871
3064
  return {
2872
3065
  harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
2873
3066
  accessMode: out.accessMode === "allow-all" || out.accessMode === "per-app" ? out.accessMode : DEFAULTS.accessMode,
2874
- defaultSessionEnabled: bool("defaultSessionEnabled"),
3067
+ sessionMode,
3068
+ defaultSessionEnabled: sessionMode !== "off",
2875
3069
  overlay: bool("overlay"),
2876
3070
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
2877
3071
  hostWindow: out.hostWindow === "pet" || out.hostWindow === "card" || out.hostWindow === "minimize" || out.hostWindow === "keep" ? out.hostWindow : out.minimizeHostWindow === true ? "minimize" : DEFAULTS.hostWindow,
@@ -2969,6 +3163,7 @@ const SCREENSHOTS_ROUTE = "/api/dsh-computer-use/screenshots";
2969
3163
  const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
2970
3164
  const SKILLS_ROUTE = "/api/dsh-computer-use/skills";
2971
3165
  const SESSION_ROUTE = "/api/dsh-computer-use/session";
3166
+ const DIAGNOSTICS_ROUTE = "/api/dsh-computer-use/diagnostics";
2972
3167
  function json(res, status, body) {
2973
3168
  res.writeHead(status, {
2974
3169
  "content-type": "application/json; charset=utf-8",
@@ -3146,6 +3341,8 @@ function skillsRoute(skills) {
3146
3341
  /** Per-session computer-use toggle: GET ?sessionId=... reads resolved state; POST { sessionId, enabled } updates and syncs live agents. */
3147
3342
  function sessionRoute(gate, settings, parentIdsFor, sync) {
3148
3343
  return async (req, res) => {
3344
+ const s = settings();
3345
+ const alwaysOn = s.sessionMode === "always";
3149
3346
  if (req.method === "POST") {
3150
3347
  const input = await body(req);
3151
3348
  const sessionId = typeof input.sessionId === "string" ? input.sessionId.trim() : "";
@@ -3163,14 +3360,16 @@ function sessionRoute(gate, settings, parentIdsFor, sync) {
3163
3360
  });
3164
3361
  return;
3165
3362
  }
3166
- gate.set(sessionId, input.enabled);
3363
+ if (!alwaysOn) gate.set(sessionId, input.enabled);
3167
3364
  sync();
3168
3365
  json(res, 200, {
3169
3366
  ok: true,
3170
3367
  ...gate.status(sessionId, {
3171
- defaultEnabled: settings().defaultSessionEnabled,
3368
+ defaultEnabled: s.defaultSessionEnabled,
3369
+ alwaysOn,
3172
3370
  parentIds: parentIdsFor(sessionId)
3173
- })
3371
+ }),
3372
+ showPill: !alwaysOn
3174
3373
  });
3175
3374
  return;
3176
3375
  }
@@ -3185,10 +3384,51 @@ function sessionRoute(gate, settings, parentIdsFor, sync) {
3185
3384
  json(res, 200, {
3186
3385
  ok: true,
3187
3386
  ...gate.status(sessionId, {
3188
- defaultEnabled: settings().defaultSessionEnabled,
3387
+ defaultEnabled: s.defaultSessionEnabled,
3388
+ alwaysOn,
3189
3389
  parentIds: parentIdsFor(sessionId)
3190
- })
3390
+ }),
3391
+ showPill: !alwaysOn
3392
+ });
3393
+ };
3394
+ }
3395
+ /** Export a sanitized diagnostic report (plain text by default, or JSON with ?format=json). */
3396
+ function diagnosticsRoute(helper, settings, diagnostics, pluginVersion) {
3397
+ return async (req, res) => {
3398
+ const s = settings();
3399
+ let displays = [];
3400
+ let helperStatus = "ready";
3401
+ let helperError;
3402
+ try {
3403
+ displays = await helper.call("displays", {}, 15e3);
3404
+ } catch (error) {
3405
+ helperStatus = "error";
3406
+ helperError = error instanceof Error ? error.message : String(error);
3407
+ }
3408
+ const snapshot = buildDiagnosticSnapshot({
3409
+ pluginVersion,
3410
+ settings: s,
3411
+ displays,
3412
+ helperStatus,
3413
+ ...helperError ? { helperError } : {},
3414
+ nativeAvailable: helper.available === true,
3415
+ recentCalls: diagnostics.recent()
3416
+ });
3417
+ if (new URL(req.url ?? "/api/dsh-computer-use/diagnostics", "http://127.0.0.1").searchParams.get("format") === "json") {
3418
+ json(res, 200, {
3419
+ ok: true,
3420
+ ...snapshot
3421
+ });
3422
+ return;
3423
+ }
3424
+ const text = formatDiagnosticText(snapshot);
3425
+ const stamp = snapshot.generatedAt.slice(0, 10);
3426
+ res.writeHead(200, {
3427
+ "content-type": "text/plain; charset=utf-8",
3428
+ "content-disposition": `attachment; filename="dsh-computer-use-diagnostics-${stamp}.txt"`,
3429
+ "cache-control": "no-store"
3191
3430
  });
3431
+ res.end(text);
3192
3432
  };
3193
3433
  }
3194
3434
  //#endregion
@@ -3489,6 +3729,7 @@ var SessionGate = class {
3489
3729
  }
3490
3730
  /** Effective enabled state for `sessionId`, inheriting ancestors before falling back to `defaultEnabled`. */
3491
3731
  isEnabled(sessionId, options = {}) {
3732
+ if (options.alwaysOn === true) return true;
3492
3733
  if (sessionId) {
3493
3734
  const own = this.entries.get(sessionId);
3494
3735
  if (own !== void 0) return own.enabled;
@@ -3501,6 +3742,14 @@ var SessionGate = class {
3501
3742
  }
3502
3743
  /** Inspect the resolved state plus whether it came from an explicit choice or ancestor inheritance. */
3503
3744
  status(sessionId, options = {}) {
3745
+ if (options.alwaysOn === true) return {
3746
+ sessionId,
3747
+ enabled: true,
3748
+ explicit: false,
3749
+ inherited: false,
3750
+ defaultEnabled: true,
3751
+ alwaysOn: true
3752
+ };
3504
3753
  const defaultEnabled = options.defaultEnabled === true;
3505
3754
  const own = this.entries.get(sessionId);
3506
3755
  if (own !== void 0) return {
@@ -3508,7 +3757,8 @@ var SessionGate = class {
3508
3757
  enabled: own.enabled,
3509
3758
  explicit: true,
3510
3759
  inherited: false,
3511
- defaultEnabled
3760
+ defaultEnabled,
3761
+ alwaysOn: false
3512
3762
  };
3513
3763
  if (options.parentIds) for (const parentId of options.parentIds) {
3514
3764
  const inherited = this.entries.get(parentId);
@@ -3517,7 +3767,8 @@ var SessionGate = class {
3517
3767
  enabled: inherited.enabled,
3518
3768
  explicit: false,
3519
3769
  inherited: true,
3520
- defaultEnabled
3770
+ defaultEnabled,
3771
+ alwaysOn: false
3521
3772
  };
3522
3773
  }
3523
3774
  return {
@@ -3525,7 +3776,8 @@ var SessionGate = class {
3525
3776
  enabled: defaultEnabled,
3526
3777
  explicit: false,
3527
3778
  inherited: false,
3528
- defaultEnabled
3779
+ defaultEnabled,
3780
+ alwaysOn: false
3529
3781
  };
3530
3782
  }
3531
3783
  /** Persist an explicit on/off choice for `sessionId`. */
@@ -9281,14 +9533,22 @@ const coordinate = {
9281
9533
  items: { type: "number" },
9282
9534
  description: "[x, y] in pixels of the latest screenshot."
9283
9535
  };
9284
- /** Reads what a window says through UI Automation: exact text, no image. */
9536
+ /** Reads what a window says through UI Automation (falling back to Windows OCR when UIA exposes no text). */
9285
9537
  async function windowText(computer, hwnd, tail) {
9538
+ const maxTail = Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)));
9286
9539
  const result = await computer.helper.call("text", {
9287
9540
  ...hwnd === void 0 ? {} : { hwnd },
9288
- tail: Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)))
9541
+ tail: maxTail
9289
9542
  }, 2e4);
9290
9543
  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.`;
9544
+ if (!result.text || result.source === "none") {
9545
+ const ocr = await computer.ocr(hwnd).catch(() => void 0);
9546
+ if (ocr && ocr.text && ocr.text.trim() !== "") {
9547
+ const sliced = ocr.text.length > maxTail ? ocr.text.slice(-maxTail) : ocr.text;
9548
+ 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}`;
9549
+ }
9550
+ return `${head}: this window exposes no readable text; use a screenshot.`;
9551
+ }
9292
9552
  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
9553
  }
9294
9554
  const actionProperties = {
@@ -9505,6 +9765,7 @@ function createTools(host) {
9505
9765
  {
9506
9766
  const name = rawName.trim();
9507
9767
  if (name === "") throw new Error("name is required.");
9768
+ 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
9769
  const settings = computer.settings();
9509
9770
  const isUrl = /^https?:\/\//i.test(name);
9510
9771
  const appName = /^ms-settings:/i.test(name) ? "设置" : name;
@@ -9686,7 +9947,7 @@ function createTools(host) {
9686
9947
  }));
9687
9948
  tools.push(defineTool({
9688
9949
  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.",
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).",
9690
9951
  parameters: {
9691
9952
  hwnd: {
9692
9953
  type: "integer",
@@ -9696,6 +9957,10 @@ function createTools(host) {
9696
9957
  type: "boolean",
9697
9958
  description: "Return the window's text content instead of the element list."
9698
9959
  },
9960
+ ocr: {
9961
+ type: "boolean",
9962
+ description: "Recognize visible text lines and clickable center coordinates via built-in Windows OCR."
9963
+ },
9699
9964
  tail: {
9700
9965
  type: "integer",
9701
9966
  description: "text: how many characters from the end to return (default 4000, max 20000); new content is usually at the end."
@@ -9713,7 +9978,21 @@ function createTools(host) {
9713
9978
  timeoutMs: 3e4,
9714
9979
  isConcurrencySafe: () => true,
9715
9980
  async execute(args) {
9716
- const { hwnd, include_text: includeText, max, text, tail } = args;
9981
+ const { hwnd, include_text: includeText, max, text, ocr, tail } = args;
9982
+ if (ocr === true) {
9983
+ const result = await computer.ocr(hwnd);
9984
+ const limit = Math.min(400, Math.max(10, max ?? 120));
9985
+ const lines = [];
9986
+ for (const [index, line] of (result.lines ?? []).slice(0, limit).entries()) {
9987
+ const center = await computer.toModel({
9988
+ x: line.x + line.width / 2,
9989
+ y: line.y + line.height / 2
9990
+ });
9991
+ lines.push(`[${index}] "${line.text}" @ (${center.x}, ${center.y})${center.offscreen ? " other display" : ""}`);
9992
+ }
9993
+ const head = `${result.exe ?? "screen"} — "${String(result.title ?? "").slice(0, 80)}": ${result.lines?.length ?? 0} OCR lines (${result.language || "auto"}).`;
9994
+ return { text: lines.length ? `${head}\n${lines.join("\n")}` : `${head} No readable text found by Windows OCR.` };
9995
+ }
9717
9996
  if (text === true) return { text: await windowText(computer, hwnd, tail) };
9718
9997
  const result = await computer.helper.call("ui", {
9719
9998
  ...hwnd === void 0 ? {} : { hwnd },
@@ -9739,9 +10018,9 @@ function createTools(host) {
9739
10018
  lines.push(`[${index}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
9740
10019
  }
9741
10020
  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.` };
10021
+ 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
10022
  },
9744
- presentCall: () => card("读取界面元素")
10023
+ presentCall: (args) => card(args.ocr ? "OCR 识别文字" : "读取界面元素")
9745
10024
  }));
9746
10025
  tools.push(defineTool({
9747
10026
  name: "clipboard",
@@ -9908,6 +10187,24 @@ function createTools(host) {
9908
10187
  * through DSH approvals, and an orange "DeepSeek is using your computer"
9909
10188
  * overlay that a physical Esc dismisses.
9910
10189
  */
10190
+ function readPluginVersion() {
10191
+ for (const rel of ["../package.json", "../../package.json"]) try {
10192
+ const parsed = JSON.parse(readFileSync(new URL(rel, import.meta.url), "utf8"));
10193
+ if (typeof parsed.version === "string" && parsed.version.trim() !== "") return parsed.version;
10194
+ } catch {}
10195
+ return "0.0.0";
10196
+ }
10197
+ const PLUGIN_VERSION = readPluginVersion();
10198
+ /** Parse `/cu [on|off|toggle|status|reset]` arguments into an action. */
10199
+ function parseCuCommand(rawInput) {
10200
+ const token = rawInput.trim().toLowerCase();
10201
+ if (token === "" || token === "status") return "status";
10202
+ if (token === "on" || token === "enable" || token === "enabled" || token === "true" || token === "1") return "on";
10203
+ if (token === "off" || token === "disable" || token === "disabled" || token === "false" || token === "0") return "off";
10204
+ if (token === "toggle") return "toggle";
10205
+ if (token === "reset" || token === "default") return "reset";
10206
+ return "invalid";
10207
+ }
9911
10208
  const name = "@copylee/dsh-computer-use";
9912
10209
  const inject = ["tools", "attachments"];
9913
10210
  const Config = z.object({
@@ -9925,9 +10222,26 @@ const Config = z.object({
9925
10222
  "zh-CN": { $description: "授权方式。无论哪种,DeepSeek Harness 自身窗口和下方“禁止操控的应用”都不会被操作。" },
9926
10223
  "en-US": { $description: "Access mode. DeepSeek Harness itself and blocked apps are never controlled." }
9927
10224
  }),
10225
+ sessionMode: z.union([
10226
+ z.const("off").i18n({
10227
+ "zh-CN": { $description: "按会话开启(默认关闭,推荐):在输入框左下角显示「电脑控制」开关" },
10228
+ "en-US": { $description: "Per session (default off, recommended): show the composer pill toggle" }
10229
+ }),
10230
+ z.const("on").i18n({
10231
+ "zh-CN": { $description: "新会话默认开启(保留输入框开关,可按会话关闭)" },
10232
+ "en-US": { $description: "Default on for new sessions (keep the composer pill toggle)" }
10233
+ }),
10234
+ z.const("always").i18n({
10235
+ "zh-CN": { $description: "总是开启(所有会话启用,隐藏输入框左下角开关)" },
10236
+ "en-US": { $description: "Always on for all sessions (hide the composer pill)" }
10237
+ })
10238
+ ]).default("off").volatile().i18n({
10239
+ "zh-CN": { $description: "会话启用方式:控制新会话是否默认开启电脑控制,以及是否在输入框左下角显示「电脑控制」胶囊开关。" },
10240
+ "en-US": { $description: "Session activation mode: whether computer use defaults on and whether the composer pill is shown." }
10241
+ }),
9928
10242
  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." }
10243
+ "zh-CN": { $description: "(兼容旧配置)已被「会话启用方式」取代。" },
10244
+ "en-US": { $description: "(Legacy) Superseded by sessionMode." }
9931
10245
  }),
9932
10246
  overlay: z.boolean().default(true).volatile().i18n({
9933
10247
  "zh-CN": { $description: "控制时显示橙色光晕边框和顶部提示条(不会出现在截图里,按 Esc 可停止)" },
@@ -10123,13 +10437,32 @@ function apply(ctx, config = {}) {
10123
10437
  for (const tool of tools) ctx.effect(() => ctx.tools.register(tool), `computer-use: tool ${tool.name}`);
10124
10438
  const OWN_TOOLS = new Set(tools.map((tool) => tool.name));
10125
10439
  const ownToolNames = [...OWN_TOOLS];
10440
+ const diagnostics = new DiagnosticsLog();
10441
+ ctx.on("tools/execute", async (exec, next) => {
10442
+ if (!OWN_TOOLS.has(exec.name)) return next();
10443
+ const started = Date.now();
10444
+ const action = summarizeToolAction(exec.name, exec.arguments);
10445
+ const result = await next();
10446
+ diagnostics.record({
10447
+ tool: exec.name,
10448
+ ...action ? { action } : {},
10449
+ durationMs: Date.now() - started,
10450
+ ok: !result.isError,
10451
+ ...result.isError ? { error: result.error?.message ?? "tool error" } : {}
10452
+ });
10453
+ return result;
10454
+ });
10126
10455
  const sessionGate = new SessionGate(void 0, log);
10127
10456
  const agentsRegistry = () => ctx.get("agents");
10128
10457
  const restricted = /* @__PURE__ */ new Map();
10129
- const isSessionEnabled = (agent) => sessionGate.isEnabled(agent.session.id, {
10130
- defaultEnabled: settings().defaultSessionEnabled,
10131
- parentIds: parentSessionChain(agent, agentsRegistry())
10132
- });
10458
+ const isSessionEnabled = (agent) => {
10459
+ const s = settings();
10460
+ return sessionGate.isEnabled(agent.session.id, {
10461
+ defaultEnabled: s.defaultSessionEnabled,
10462
+ alwaysOn: s.sessionMode === "always",
10463
+ parentIds: parentSessionChain(agent, agentsRegistry())
10464
+ });
10465
+ };
10133
10466
  const syncAgent = (agent) => {
10134
10467
  const enabled = isSessionEnabled(agent);
10135
10468
  const active = restricted.get(agent);
@@ -10326,6 +10659,75 @@ function apply(ctx, config = {}) {
10326
10659
  route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
10327
10660
  route(SKILLS_ROUTE, skillsRoute(skills));
10328
10661
  route(SESSION_ROUTE, sessionRoute(sessionGate, settings, parentIdsFor, syncAllAgents));
10662
+ route(DIAGNOSTICS_ROUTE, diagnosticsRoute(helper, settings, diagnostics, PLUGIN_VERSION));
10663
+ });
10664
+ ctx.inject(["commands"], (cmdCtx) => {
10665
+ const commands = cmdCtx.commands;
10666
+ if (typeof commands?.register !== "function") return;
10667
+ cmdCtx.effect(() => commands.register({
10668
+ name: "cu",
10669
+ description: "切换当前会话的电脑控制开关:/cu [on|off|toggle|status|reset]",
10670
+ handler: (invocation) => {
10671
+ const agent = invocation.agent;
10672
+ const sessionId = agent?.session?.id ?? agent?.session?.header?.id;
10673
+ if (!sessionId) return {
10674
+ kind: "error",
10675
+ text: "无法识别当前会话 ID。"
10676
+ };
10677
+ const action = parseCuCommand(invocation.rawInput ?? "");
10678
+ if (action === "invalid") return {
10679
+ kind: "error",
10680
+ text: "用法:/cu [on | off | toggle | status | reset]"
10681
+ };
10682
+ const parents = parentIdsFor(sessionId);
10683
+ const s = settings();
10684
+ const alwaysOn = s.sessionMode === "always";
10685
+ if (action === "status") {
10686
+ if (alwaysOn) return {
10687
+ kind: "success",
10688
+ text: "电脑控制当前状态:总是开启(在设置页已设为「总是开启」,所有会话均自动启用且隐藏输入框开关)。"
10689
+ };
10690
+ const st = sessionGate.status(sessionId, {
10691
+ defaultEnabled: s.defaultSessionEnabled,
10692
+ alwaysOn: false,
10693
+ parentIds: parents
10694
+ });
10695
+ const source = st.explicit ? "本会话已单独设置" : st.inherited ? "继承自父会话" : "沿用默认设置";
10696
+ return {
10697
+ kind: "success",
10698
+ text: `电脑控制当前状态:${st.enabled ? "已开启" : "已关闭"}(${source})。使用 /cu on 或 /cu off 切换。`
10699
+ };
10700
+ }
10701
+ if (alwaysOn) return {
10702
+ kind: "success",
10703
+ text: "当前在设置页已设为「总是开启」,所有会话均保持开启。如需按会话开关,请在「设置 → 电脑控制 → 会话启用方式」里切换为按会话模式。"
10704
+ };
10705
+ if (action === "reset") {
10706
+ sessionGate.clear(sessionId);
10707
+ syncAllAgents();
10708
+ return {
10709
+ kind: "success",
10710
+ text: `已恢复当前会话的默认状态:${sessionGate.status(sessionId, {
10711
+ defaultEnabled: s.defaultSessionEnabled,
10712
+ alwaysOn: false,
10713
+ parentIds: parents
10714
+ }).enabled ? "已开启" : "已关闭"}。`
10715
+ };
10716
+ }
10717
+ const current = sessionGate.isEnabled(sessionId, {
10718
+ defaultEnabled: s.defaultSessionEnabled,
10719
+ alwaysOn: false,
10720
+ parentIds: parents
10721
+ });
10722
+ const nextEnabled = action === "toggle" ? !current : action === "on";
10723
+ sessionGate.set(sessionId, nextEnabled);
10724
+ syncAllAgents();
10725
+ return {
10726
+ kind: "success",
10727
+ text: `当前会话已${nextEnabled ? "开启" : "关闭"}电脑控制(立即生效,子代理将自动继承)。`
10728
+ };
10729
+ }
10730
+ }), "computer-use: /cu command");
10329
10731
  });
10330
10732
  ctx.inject(["systemPrompt"], (promptCtx) => {
10331
10733
  promptCtx.effect(() => promptCtx.systemPrompt.section({
@@ -10344,4 +10746,4 @@ function apply(ctx, config = {}) {
10344
10746
  });
10345
10747
  }
10346
10748
  //#endregion
10347
- export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, resolveConfig };
10749
+ export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, parseCuCommand, resolveConfig };