@copylee/dsh-computer-use 0.8.8 → 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
  }
@@ -271,6 +303,30 @@ function screenshotSize(display, limits) {
271
303
  height: Math.max(1, Math.round(height * scale))
272
304
  };
273
305
  }
306
+ /** Output size together with which limit (`longEdge`, `pixels`, or neither) actually constrained it. */
307
+ function describeScreenshotSize(display, limits) {
308
+ const { width, height } = display;
309
+ const edgeScale = limits.maxLongEdge / Math.max(width, height);
310
+ const pixelScale = Math.sqrt(limits.maxPixels / (width * height));
311
+ const scale = Math.min(1, edgeScale, pixelScale);
312
+ const limitedBy = scale >= 1 ? "none" : pixelScale < edgeScale ? "pixels" : "longEdge";
313
+ const outWidth = Math.max(1, Math.round(width * scale));
314
+ const outHeight = Math.max(1, Math.round(height * scale));
315
+ return {
316
+ width: outWidth,
317
+ height: outHeight,
318
+ megapixels: Math.round(outWidth * outHeight / 1e4) / 100,
319
+ limitedBy
320
+ };
321
+ }
322
+ /** Lower-cost screenshot budget for quick confirmation shots (~30–40% fewer bytes). */
323
+ function compactLimits(budget) {
324
+ return {
325
+ maxLongEdge: Math.max(640, Math.min(budget.maxLongEdge, Math.round(budget.maxLongEdge * .78))),
326
+ maxPixels: Math.max(3e5, Math.min(budget.maxPixels, Math.round(budget.maxPixels * .58))),
327
+ jpegQuality: Math.max(45, Math.min(budget.jpegQuality, budget.jpegQuality - 8))
328
+ };
329
+ }
274
330
  /** Screenshot pixels → physical virtual-screen pixels. Throws when outside the image. */
275
331
  function toPhysical(point, display, shot) {
276
332
  const { x, y } = point;
@@ -776,6 +832,12 @@ const UNCHANGED_TEXT = "The screen looks exactly as in your previous screenshot:
776
832
  const TARGET_WAIT_MS = 3e3;
777
833
  /** Pause between looks while waiting for a control or a window. */
778
834
  const POLL_MS = 200;
835
+ /** Same-spot click warning window (2 minutes) and radius (±24 physical pixels). */
836
+ const REPEAT_WINDOW_MS = 12e4;
837
+ const REPEAT_RADIUS_PX = 24;
838
+ function displayKey(display) {
839
+ return `${display.x},${display.y},${display.width},${display.height}`;
840
+ }
779
841
  var Computer = class Computer {
780
842
  helper;
781
843
  access;
@@ -784,6 +846,10 @@ var Computer = class Computer {
784
846
  displays = [];
785
847
  displayIndex = -1;
786
848
  heldButton = false;
849
+ /** Dimensions of the latest full-display screenshot shown to the model (keeps coordinate conversion exact across detail modes). */
850
+ lastShot;
851
+ /** Recent click locations (fallback repeat counter when helper does not report repeat). */
852
+ clickHistory = [];
787
853
  /** The agent that last wrote the clipboard; when it goes idle the user's clipboard comes back. */
788
854
  clipboardAgent;
789
855
  constructor(helper, access, overlay, settings) {
@@ -808,17 +874,27 @@ var Computer = class Computer {
808
874
  const rows = await this.refreshDisplays();
809
875
  if (!Number.isInteger(index) || index < 0 || index >= rows.length) throw new Error(`Display ${index} does not exist; there are ${rows.length} (0-${rows.length - 1}).`);
810
876
  this.displayIndex = index;
877
+ this.lastShot = void 0;
811
878
  return rows[index];
812
879
  }
813
880
  get currentIndex() {
814
881
  return Math.max(0, this.displayIndex);
815
882
  }
816
- shotSize(display) {
883
+ shotBudget(detail = "high") {
817
884
  const s = this.settings();
818
- return screenshotSize(display, {
885
+ const base = {
819
886
  maxLongEdge: s.maxLongEdge,
820
- maxPixels: s.maxPixels
821
- });
887
+ maxPixels: s.maxPixels,
888
+ jpegQuality: s.jpegQuality
889
+ };
890
+ return detail === "low" ? compactLimits(base) : base;
891
+ }
892
+ shotSize(display, detail = "high") {
893
+ return screenshotSize(display, this.shotBudget(detail));
894
+ }
895
+ /** Coordinate space of the latest full screenshot of `display` (or its default full size before any capture). */
896
+ coordSize(display) {
897
+ return this.lastShot?.displayKey === displayKey(display) ? this.lastShot.size : this.shotSize(display);
822
898
  }
823
899
  async point(coordinate, field = "coordinate") {
824
900
  if (!Array.isArray(coordinate) || coordinate.length !== 2) throw new Error(`${field} must be [x, y] in screenshot pixels.`);
@@ -826,35 +902,88 @@ var Computer = class Computer {
826
902
  return toPhysical({
827
903
  x: coordinate[0],
828
904
  y: coordinate[1]
829
- }, display, this.shotSize(display));
905
+ }, display, this.coordSize(display));
830
906
  }
831
907
  async toModel(point) {
832
908
  const display = await this.display();
833
909
  return {
834
- ...toScreenshot(point, display, this.shotSize(display)),
910
+ ...toScreenshot(point, display, this.coordSize(display)),
835
911
  offscreen: !contains$1(display, point)
836
912
  };
837
913
  }
838
- async screenshot() {
914
+ /** Unconditional full screenshot (used when the model must see a fresh frame, e.g. after pause/switch). */
915
+ async screenshot(detail = "high") {
839
916
  await this.refreshDisplays();
840
917
  const display = await this.display();
841
- const size = this.shotSize(display);
842
- const shot = await this.capture(display, size, { mark: true });
918
+ const budget = this.shotBudget(detail);
919
+ const size = screenshotSize(display, budget);
920
+ const shot = await this.capture(display, size, {
921
+ mark: true,
922
+ slot: "full",
923
+ quality: budget.jpegQuality
924
+ });
925
+ this.lastShot = {
926
+ displayKey: displayKey(display),
927
+ size: {
928
+ width: shot.width,
929
+ height: shot.height
930
+ }
931
+ };
843
932
  await this.remember();
844
933
  return shot;
845
934
  }
846
935
  /**
847
- * A fresh screenshot, or 'unchanged' when the screen looks the same as in
848
- * the last one the model saw (saves an image and tells it the action had no
849
- * visible effect).
936
+ * Explicit model-requested screenshot: deduplicates against the last full
937
+ * screenshot shown to the model unless `force: true` or higher detail is asked.
938
+ */
939
+ async takeScreenshot(options = {}) {
940
+ const detail = options.detail ?? "high";
941
+ if (options.force) return this.screenshot(detail);
942
+ await this.refreshDisplays();
943
+ const display = await this.display();
944
+ const budget = this.shotBudget(detail);
945
+ const size = screenshotSize(display, budget);
946
+ const shot = await this.capture(display, size, {
947
+ compare: true,
948
+ threshold: UNCHANGED_DIFF,
949
+ slot: "full",
950
+ quality: budget.jpegQuality
951
+ });
952
+ if (shot) this.lastShot = {
953
+ displayKey: displayKey(display),
954
+ size: {
955
+ width: shot.width,
956
+ height: shot.height
957
+ }
958
+ };
959
+ await this.remember();
960
+ return shot ?? "unchanged";
961
+ }
962
+ /**
963
+ * A fresh post-action screenshot, or 'unchanged' when the screen looks the
964
+ * same as in the last one the model saw (saves an image and tells it the
965
+ * action had no visible effect). Respects `autoScreenshotDetail` unless
966
+ * overridden by an explicit `detail`.
850
967
  */
851
- async freshShot() {
968
+ async freshShot(detail) {
852
969
  await this.refreshDisplays();
853
970
  const display = await this.display();
854
- const shot = await this.capture(display, this.shotSize(display), {
971
+ const effective = detail ?? (this.settings().autoScreenshotDetail === "compact" ? "low" : "high");
972
+ const budget = this.shotBudget(effective);
973
+ const size = screenshotSize(display, budget);
974
+ const shot = await this.capture(display, size, {
855
975
  compare: true,
856
- threshold: UNCHANGED_DIFF
976
+ threshold: UNCHANGED_DIFF,
977
+ slot: "full",
978
+ quality: budget.jpegQuality
857
979
  });
980
+ if (shot) this.lastShot = {
981
+ displayKey: displayKey(display),
982
+ size: {
983
+ width: shot.width,
984
+ height: shot.height
985
+ }
986
+ };
858
987
  await this.remember();
859
988
  return shot ?? "unchanged";
860
989
  }
@@ -881,6 +1010,7 @@ var Computer = class Computer {
881
1010
  return now && now.hwnd !== seen.hwnd && now.pid !== seen.pid ? now : void 0;
882
1011
  }
883
1012
  async capture(rect, out, options = {}) {
1013
+ const { quality, ...rest } = options;
884
1014
  const result = await this.helper.call("screenshot", {
885
1015
  x: rect.x,
886
1016
  y: rect.y,
@@ -888,8 +1018,8 @@ var Computer = class Computer {
888
1018
  height: rect.height,
889
1019
  outWidth: out.width,
890
1020
  outHeight: out.height,
891
- quality: this.settings().jpegQuality,
892
- ...options
1021
+ quality: quality ?? this.settings().jpegQuality,
1022
+ ...rest
893
1023
  }, 3e4);
894
1024
  if (result.unchanged || result.data === void 0) return void 0;
895
1025
  return {
@@ -898,16 +1028,36 @@ var Computer = class Computer {
898
1028
  height: result.height
899
1029
  };
900
1030
  }
901
- async zoom(region) {
1031
+ async zoom(region, options = {}) {
902
1032
  if (!Array.isArray(region)) throw new Error("zoom needs region: [x1, y1, x2, y2] in screenshot pixels.");
903
1033
  const display = await this.display();
904
- const rect = regionToPhysical(region, display, this.shotSize(display));
905
- const s = this.settings();
906
- const out = screenshotSize(rect, {
907
- maxLongEdge: s.maxLongEdge,
908
- maxPixels: s.maxPixels
909
- });
910
- return await this.capture(rect, out);
1034
+ const rect = regionToPhysical(region, display, this.coordSize(display));
1035
+ const budget = this.shotBudget(options.detail ?? "high");
1036
+ const out = screenshotSize(rect, budget);
1037
+ return await this.capture(rect, out, {
1038
+ mark: true,
1039
+ ...options.force ? {} : {
1040
+ compare: true,
1041
+ threshold: UNCHANGED_DIFF
1042
+ },
1043
+ slot: "zoom",
1044
+ quality: budget.jpegQuality
1045
+ }) ?? "unchanged";
1046
+ }
1047
+ /** Record a physical click position and return how many times this spot (±24 px) was clicked in the last 2 minutes. */
1048
+ noteClick(point, helperRepeat) {
1049
+ const now = Date.now();
1050
+ while (this.clickHistory.length > 0 && now - this.clickHistory[0].at > REPEAT_WINDOW_MS) this.clickHistory.shift();
1051
+ let local = 0;
1052
+ if (point) {
1053
+ this.clickHistory.push({
1054
+ x: point.x,
1055
+ y: point.y,
1056
+ at: now
1057
+ });
1058
+ for (const entry of this.clickHistory) if (Math.abs(entry.x - point.x) <= REPEAT_RADIUS_PX && Math.abs(entry.y - point.y) <= REPEAT_RADIUS_PX) local++;
1059
+ }
1060
+ return typeof helperRepeat === "number" && Number.isFinite(helperRepeat) && helperRepeat > 0 ? helperRepeat : local;
911
1061
  }
912
1062
  async foreground() {
913
1063
  const win = await this.helper.call("foreground");
@@ -1088,15 +1238,54 @@ var Computer = class Computer {
1088
1238
  }, 2e4);
1089
1239
  return Array.isArray(result.elements) ? result.elements : [];
1090
1240
  }
1091
- /** 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
+ */
1092
1250
  async find(target, hwnd) {
1093
1251
  const inWindow = await this.elements("window", hwnd).catch(() => []);
1094
1252
  const match = matchTarget(inWindow, target);
1095
1253
  if (match.kind !== "missing") return match;
1096
1254
  const inPopups = await this.elements("popups", hwnd).catch(() => []);
1097
- if (inPopups.length === 0) return match;
1098
- const second = matchTarget(inPopups, target);
1099
- 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);
1100
1289
  }
1101
1290
  /**
1102
1291
  * Where a named control is. It may still be appearing (the menu just
@@ -1290,14 +1479,22 @@ var Computer = class Computer {
1290
1479
  if (KEYBOARD.has(action)) await this.refocusFromHost();
1291
1480
  switch (action) {
1292
1481
  case "screenshot": {
1293
- const shot = await this.screenshot();
1482
+ const shot = await this.takeScreenshot({
1483
+ force: input.force === true,
1484
+ ...input.detail ? { detail: input.detail } : {}
1485
+ });
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).` };
1294
1487
  return {
1295
1488
  text: `Screenshot ${shot.width}x${shot.height} of display ${this.currentIndex}.`,
1296
1489
  image: shot
1297
1490
  };
1298
1491
  }
1299
1492
  case "zoom": {
1300
- const shot = await this.zoom(input.region);
1493
+ const shot = await this.zoom(input.region, {
1494
+ force: input.force === true,
1495
+ ...input.detail ? { detail: input.detail } : {}
1496
+ });
1497
+ if (shot === "unchanged") return { text: `Zoomed view of region [${(input.region ?? []).join(", ")}] is unchanged from your previous zoom of this region (pass force: true to capture anyway).` };
1301
1498
  return {
1302
1499
  text: `Zoomed view of region [${(input.region ?? []).join(", ")}] at ${shot.width}x${shot.height}. Pixel positions in this image are NOT screen coordinates; keep using full-screenshot coordinates for actions.`,
1303
1500
  image: shot
@@ -1335,13 +1532,27 @@ var Computer = class Computer {
1335
1532
  if (await this.semanticAction(call, named, semantic)) return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
1336
1533
  }
1337
1534
  if (named) p = await this.namedClickPoint(call, input.target, named);
1338
- await this.helper.call("click", {
1535
+ const labelCoord = input.coordinate ? {
1536
+ labelX: Math.round(input.coordinate[0]),
1537
+ labelY: Math.round(input.coordinate[1])
1538
+ } : p ? await this.toModel(p).then((m) => ({
1539
+ labelX: m.x,
1540
+ labelY: m.y
1541
+ })) : {};
1542
+ const clickRes = await this.helper.call("click", {
1339
1543
  ...p ?? {},
1544
+ ...labelCoord,
1340
1545
  button,
1341
1546
  count,
1342
1547
  modifiers
1343
1548
  });
1344
- return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.` };
1549
+ const clickedAt = p ?? (typeof clickRes?.x === "number" && typeof clickRes?.y === "number" ? {
1550
+ x: clickRes.x,
1551
+ y: clickRes.y
1552
+ } : void 0);
1553
+ const repeat = this.noteClick(clickedAt, clickRes?.repeat);
1554
+ const repeatHint = repeat >= 3 ? ` (same spot clicked ${repeat} times — screenshot before clicking again)` : "";
1555
+ return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.${repeatHint}` };
1345
1556
  }
1346
1557
  case "left_click_drag": {
1347
1558
  const from = await this.point(input.start_coordinate, "start_coordinate");
@@ -1494,12 +1705,12 @@ var Computer = class Computer {
1494
1705
  * (vision models only). A wait already waited, so it is captured at once:
1495
1706
  * "wait, then look" should be one step, not two.
1496
1707
  */
1497
- async after(inputs, call) {
1708
+ async after(inputs, call, detail) {
1498
1709
  if (!this.settings().autoScreenshot || !call.vision) return void 0;
1499
1710
  const mutating = inputs.some((input) => MUTATING.has(input.action));
1500
1711
  if (!mutating && !inputs.some((input) => input.action === "wait")) return void 0;
1501
1712
  if (mutating) await this.settle(call.signal);
1502
- return this.freshShot();
1713
+ return this.freshShot(detail ?? inputs.at(-1)?.detail);
1503
1714
  }
1504
1715
  /** Bring a window forward and verify it is the foreground window. */
1505
1716
  async focus(win) {
@@ -1519,6 +1730,125 @@ var Computer = class Computer {
1519
1730
  }
1520
1731
  };
1521
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
1522
1852
  //#region lib/types/helper-client.js
1523
1853
  /**
1524
1854
  * Builds and drives the Windows helper (helper/CuHelper.cs): compiled once
@@ -2480,7 +2810,9 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
2480
2810
  - The "DeepSeek Harness.exe" window is your own chat interface. While you control the computer it floats as a card that only the user sees: your screenshots show what is underneath it and your clicks and scrolls pass through it, so simply ignore it. Never type into DeepSeek Harness; keys go to the window you were working in.
2481
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.
2482
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).
2483
- - 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.
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.
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.
2484
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.
2485
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.
2486
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.
@@ -2700,11 +3032,14 @@ var SkillStore = class {
2700
3032
  const ENTRY_ID = "copylee-computer-use";
2701
3033
  const DEFAULTS = {
2702
3034
  accessMode: "per-app",
3035
+ sessionMode: "off",
3036
+ defaultSessionEnabled: false,
2703
3037
  overlay: true,
2704
3038
  overlayLabel: "DeepSeek Harness",
2705
3039
  hostWindow: "pet",
2706
3040
  cardOpacity: 80,
2707
3041
  autoScreenshot: true,
3042
+ autoScreenshotDetail: "standard",
2708
3043
  settleMs: 400,
2709
3044
  maxLongEdge: 1366,
2710
3045
  maxPixels: 115e4,
@@ -2725,14 +3060,18 @@ function resolveConfig(raw) {
2725
3060
  return typeof value === "number" && Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : DEFAULTS[key];
2726
3061
  };
2727
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;
2728
3064
  return {
2729
3065
  harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
2730
3066
  accessMode: out.accessMode === "allow-all" || out.accessMode === "per-app" ? out.accessMode : DEFAULTS.accessMode,
3067
+ sessionMode,
3068
+ defaultSessionEnabled: sessionMode !== "off",
2731
3069
  overlay: bool("overlay"),
2732
3070
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
2733
3071
  hostWindow: out.hostWindow === "pet" || out.hostWindow === "card" || out.hostWindow === "minimize" || out.hostWindow === "keep" ? out.hostWindow : out.minimizeHostWindow === true ? "minimize" : DEFAULTS.hostWindow,
2734
3072
  cardOpacity: num("cardOpacity", 30, 100),
2735
3073
  autoScreenshot: bool("autoScreenshot"),
3074
+ autoScreenshotDetail: out.autoScreenshotDetail === "compact" || out.autoScreenshotDetail === "standard" ? out.autoScreenshotDetail : DEFAULTS.autoScreenshotDetail,
2736
3075
  settleMs: num("settleMs", 0, 5e3),
2737
3076
  maxLongEdge: num("maxLongEdge", 640, 3840),
2738
3077
  maxPixels: num("maxPixels", 3e5, 8e6),
@@ -2823,6 +3162,8 @@ const PREVIEW_ROUTE = "/api/dsh-computer-use/preview";
2823
3162
  const SCREENSHOTS_ROUTE = "/api/dsh-computer-use/screenshots";
2824
3163
  const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
2825
3164
  const SKILLS_ROUTE = "/api/dsh-computer-use/skills";
3165
+ const SESSION_ROUTE = "/api/dsh-computer-use/session";
3166
+ const DIAGNOSTICS_ROUTE = "/api/dsh-computer-use/diagnostics";
2826
3167
  function json(res, status, body) {
2827
3168
  res.writeHead(status, {
2828
3169
  "content-type": "application/json; charset=utf-8",
@@ -2833,6 +3174,11 @@ function json(res, status, body) {
2833
3174
  function statusRoute(helper, settings, overlay) {
2834
3175
  return async (_req, res) => {
2835
3176
  const s = settings();
3177
+ const compact = compactLimits({
3178
+ maxLongEdge: s.maxLongEdge,
3179
+ maxPixels: s.maxPixels,
3180
+ jpegQuality: s.jpegQuality
3181
+ });
2836
3182
  try {
2837
3183
  const displays = await helper.call("displays", {}, 3e4);
2838
3184
  json(res, 200, {
@@ -2841,10 +3187,11 @@ function statusRoute(helper, settings, overlay) {
2841
3187
  helper: "ready",
2842
3188
  displays: displays.map((d) => ({
2843
3189
  ...d,
2844
- shot: screenshotSize(d, {
3190
+ shot: describeScreenshotSize(d, {
2845
3191
  maxLongEdge: s.maxLongEdge,
2846
3192
  maxPixels: s.maxPixels
2847
- })
3193
+ }),
3194
+ compactShot: describeScreenshotSize(d, compact)
2848
3195
  })),
2849
3196
  controlling: overlay.controller !== void 0
2850
3197
  });
@@ -2991,6 +3338,99 @@ function skillsRoute(skills) {
2991
3338
  });
2992
3339
  };
2993
3340
  }
3341
+ /** Per-session computer-use toggle: GET ?sessionId=... reads resolved state; POST { sessionId, enabled } updates and syncs live agents. */
3342
+ function sessionRoute(gate, settings, parentIdsFor, sync) {
3343
+ return async (req, res) => {
3344
+ const s = settings();
3345
+ const alwaysOn = s.sessionMode === "always";
3346
+ if (req.method === "POST") {
3347
+ const input = await body(req);
3348
+ const sessionId = typeof input.sessionId === "string" ? input.sessionId.trim() : "";
3349
+ if (sessionId === "") {
3350
+ json(res, 400, {
3351
+ ok: false,
3352
+ error: "sessionId is required"
3353
+ });
3354
+ return;
3355
+ }
3356
+ if (typeof input.enabled !== "boolean") {
3357
+ json(res, 400, {
3358
+ ok: false,
3359
+ error: "enabled must be a boolean"
3360
+ });
3361
+ return;
3362
+ }
3363
+ if (!alwaysOn) gate.set(sessionId, input.enabled);
3364
+ sync();
3365
+ json(res, 200, {
3366
+ ok: true,
3367
+ ...gate.status(sessionId, {
3368
+ defaultEnabled: s.defaultSessionEnabled,
3369
+ alwaysOn,
3370
+ parentIds: parentIdsFor(sessionId)
3371
+ }),
3372
+ showPill: !alwaysOn
3373
+ });
3374
+ return;
3375
+ }
3376
+ const sessionId = (new URL(req.url ?? "/api/dsh-computer-use/session", "http://127.0.0.1").searchParams.get("sessionId") ?? "").trim();
3377
+ if (sessionId === "") {
3378
+ json(res, 400, {
3379
+ ok: false,
3380
+ error: "sessionId is required"
3381
+ });
3382
+ return;
3383
+ }
3384
+ json(res, 200, {
3385
+ ok: true,
3386
+ ...gate.status(sessionId, {
3387
+ defaultEnabled: s.defaultSessionEnabled,
3388
+ alwaysOn,
3389
+ parentIds: parentIdsFor(sessionId)
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"
3430
+ });
3431
+ res.end(text);
3432
+ };
3433
+ }
2994
3434
  //#endregion
2995
3435
  //#region lib/types/screenshots.js
2996
3436
  /**
@@ -3232,6 +3672,173 @@ function decodeFrames(data, zstd) {
3232
3672
  return Buffer.concat(parts).toString("utf8");
3233
3673
  }
3234
3674
  //#endregion
3675
+ //#region lib/types/sessions.js
3676
+ /**
3677
+ * Per-session toggle for computer-use tools and system prompt guidance.
3678
+ *
3679
+ * Each session remembers its explicit on/off choice on disk so restarts and
3680
+ * resumed sessions keep the user's decision. Subagents and forked sessions
3681
+ * inherit their ancestor's choice unless overridden. New sessions without an
3682
+ * explicit decision fall back to `defaultEnabled` (off by default).
3683
+ */
3684
+ const MAX_ENTRIES = 500;
3685
+ function defaultSessionsFile() {
3686
+ return join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "dsh-computer-use", "sessions.json");
3687
+ }
3688
+ /**
3689
+ * Walk an agent's parent chain (nearest ancestor first), combining durable
3690
+ * `session.header.parentSession` with runtime parent ownership for subagents.
3691
+ */
3692
+ function parentSessionChain(agent, registry) {
3693
+ if (!agent) return [];
3694
+ const chain = [];
3695
+ const seen = /* @__PURE__ */ new Set([agent.session.id]);
3696
+ let current = agent;
3697
+ for (let depth = 0; depth < 16 && current; depth++) {
3698
+ let parentId = current.session.header?.parentSession;
3699
+ let parentAgent = parentId ? registry?.get?.(parentId) : void 0;
3700
+ if (!parentId && registry?.list && registry.isOwnedBy) {
3701
+ const currentId = current.id ?? current.session.id;
3702
+ const isOwnedBy = registry.isOwnedBy;
3703
+ const owner = registry.list().find((candidate) => candidate !== current && isOwnedBy(currentId, candidate));
3704
+ if (owner) {
3705
+ parentAgent = owner;
3706
+ parentId = owner.session.id;
3707
+ }
3708
+ }
3709
+ if (!parentId || seen.has(parentId)) break;
3710
+ seen.add(parentId);
3711
+ chain.push(parentId);
3712
+ current = parentAgent;
3713
+ }
3714
+ return chain;
3715
+ }
3716
+ var SessionGate = class {
3717
+ storeFile;
3718
+ log;
3719
+ entries = /* @__PURE__ */ new Map();
3720
+ saving = Promise.resolve();
3721
+ constructor(storeFile = defaultSessionsFile(), log = () => {}) {
3722
+ this.storeFile = storeFile;
3723
+ this.log = log;
3724
+ if (this.storeFile !== null) this.loadSync(this.storeFile);
3725
+ }
3726
+ /** Explicit decision stored for `sessionId`, or undefined when unset. */
3727
+ explicit(sessionId) {
3728
+ return this.entries.get(sessionId)?.enabled;
3729
+ }
3730
+ /** Effective enabled state for `sessionId`, inheriting ancestors before falling back to `defaultEnabled`. */
3731
+ isEnabled(sessionId, options = {}) {
3732
+ if (options.alwaysOn === true) return true;
3733
+ if (sessionId) {
3734
+ const own = this.entries.get(sessionId);
3735
+ if (own !== void 0) return own.enabled;
3736
+ }
3737
+ if (options.parentIds) for (const parentId of options.parentIds) {
3738
+ const inherited = this.entries.get(parentId);
3739
+ if (inherited !== void 0) return inherited.enabled;
3740
+ }
3741
+ return options.defaultEnabled === true;
3742
+ }
3743
+ /** Inspect the resolved state plus whether it came from an explicit choice or ancestor inheritance. */
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
+ };
3753
+ const defaultEnabled = options.defaultEnabled === true;
3754
+ const own = this.entries.get(sessionId);
3755
+ if (own !== void 0) return {
3756
+ sessionId,
3757
+ enabled: own.enabled,
3758
+ explicit: true,
3759
+ inherited: false,
3760
+ defaultEnabled,
3761
+ alwaysOn: false
3762
+ };
3763
+ if (options.parentIds) for (const parentId of options.parentIds) {
3764
+ const inherited = this.entries.get(parentId);
3765
+ if (inherited !== void 0) return {
3766
+ sessionId,
3767
+ enabled: inherited.enabled,
3768
+ explicit: false,
3769
+ inherited: true,
3770
+ defaultEnabled,
3771
+ alwaysOn: false
3772
+ };
3773
+ }
3774
+ return {
3775
+ sessionId,
3776
+ enabled: defaultEnabled,
3777
+ explicit: false,
3778
+ inherited: false,
3779
+ defaultEnabled,
3780
+ alwaysOn: false
3781
+ };
3782
+ }
3783
+ /** Persist an explicit on/off choice for `sessionId`. */
3784
+ set(sessionId, enabled) {
3785
+ const id = sessionId.trim();
3786
+ if (id === "") return;
3787
+ this.entries.set(id, {
3788
+ enabled,
3789
+ updatedAt: Date.now()
3790
+ });
3791
+ this.trim();
3792
+ this.persist();
3793
+ }
3794
+ /** Remove an explicit choice so the session falls back to inheritance / default. */
3795
+ clear(sessionId) {
3796
+ if (this.entries.delete(sessionId)) this.persist();
3797
+ }
3798
+ /** Wait for any pending write to settle (used by tests). */
3799
+ flush() {
3800
+ return this.saving;
3801
+ }
3802
+ trim() {
3803
+ if (this.entries.size <= MAX_ENTRIES) return;
3804
+ const sorted = [...this.entries.entries()].sort((a, b) => b[1].updatedAt - a[1].updatedAt);
3805
+ this.entries.clear();
3806
+ for (const [id, entry] of sorted.slice(0, MAX_ENTRIES)) this.entries.set(id, entry);
3807
+ }
3808
+ loadSync(file) {
3809
+ try {
3810
+ const map = JSON.parse(readFileSync(file, "utf8"))?.sessions;
3811
+ if (!map || typeof map !== "object") return;
3812
+ for (const [id, value] of Object.entries(map)) if (typeof value === "boolean") this.entries.set(id, {
3813
+ enabled: value,
3814
+ updatedAt: 0
3815
+ });
3816
+ else if (value && typeof value === "object" && typeof value.enabled === "boolean") {
3817
+ const updatedAt = typeof value.updatedAt === "number" && Number.isFinite(value.updatedAt) ? value.updatedAt : 0;
3818
+ this.entries.set(id, {
3819
+ enabled: value.enabled,
3820
+ updatedAt
3821
+ });
3822
+ }
3823
+ this.trim();
3824
+ } catch {}
3825
+ }
3826
+ persist() {
3827
+ const file = this.storeFile;
3828
+ if (file === null) return;
3829
+ const snapshot = Object.fromEntries(this.entries);
3830
+ this.saving = this.saving.then(async () => {
3831
+ await mkdir(dirname(file), { recursive: true });
3832
+ const tmp = `${file}.${process.pid}.tmp`;
3833
+ await writeFile(tmp, JSON.stringify({
3834
+ version: 1,
3835
+ sessions: snapshot
3836
+ }));
3837
+ await rename(tmp, file);
3838
+ }).catch((error) => this.log(`session toggle save: ${String(error)}`));
3839
+ }
3840
+ };
3841
+ //#endregion
3235
3842
  //#region node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.0-rc.2_@deepseek-ai+cordis@4.0.4_@deepseek-ai+dsh-invariants_0d6b19188928ab894325adc32e18b0b5/node_modules/@deepseek-ai/dsh-scope/lib/index.js
3236
3843
  /**
3237
3844
  * Shared insertion-ordered storage and effect ownership for scope-aware registries.
@@ -8926,14 +9533,22 @@ const coordinate = {
8926
9533
  items: { type: "number" },
8927
9534
  description: "[x, y] in pixels of the latest screenshot."
8928
9535
  };
8929
- /** 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). */
8930
9537
  async function windowText(computer, hwnd, tail) {
9538
+ const maxTail = Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)));
8931
9539
  const result = await computer.helper.call("text", {
8932
9540
  ...hwnd === void 0 ? {} : { hwnd },
8933
- tail: Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)))
9541
+ tail: maxTail
8934
9542
  }, 2e4);
8935
9543
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
8936
- 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
+ }
8937
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}`;
8938
9553
  }
8939
9554
  const actionProperties = {
@@ -8989,6 +9604,15 @@ const actionProperties = {
8989
9604
  type: "array",
8990
9605
  items: { type: "number" },
8991
9606
  description: "zoom: [x1, y1, x2, y2] in screenshot pixels."
9607
+ },
9608
+ force: {
9609
+ type: "boolean",
9610
+ description: "screenshot / zoom: capture and return a fresh image even when the pixels look identical to your previous view."
9611
+ },
9612
+ detail: {
9613
+ type: "string",
9614
+ enum: ["high", "low"],
9615
+ description: "Screenshot detail: \"high\" uses full configured resolution; \"low\" uses a smaller, cheaper image for quick visual confirmation."
8992
9616
  }
8993
9617
  };
8994
9618
  const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
@@ -9007,6 +9631,7 @@ function createTools(host) {
9007
9631
  try {
9008
9632
  const outcome = await computer.run(input, call);
9009
9633
  if (outcome.image) return withShot(host, outcome.text, outcome.image, call);
9634
+ if (input.action === "screenshot" || input.action === "zoom") return { text: outcome.text };
9010
9635
  const shot = await computer.after([input], call);
9011
9636
  return withShot(host, shot === void 0 && input.action !== "wait" && input.action !== "cursor_position" ? `${outcome.text} ${await computer.describeForeground()}` : outcome.text, shot, call);
9012
9637
  } catch (error) {
@@ -9044,6 +9669,11 @@ function createTools(host) {
9044
9669
  "none"
9045
9670
  ],
9046
9671
  description: "What to return after the actions: screenshot (default), text (what the foreground window says, read as text: cheaper and exact when you only need the words), or none."
9672
+ },
9673
+ detail: {
9674
+ type: "string",
9675
+ enum: ["high", "low"],
9676
+ description: "Detail for the final screenshot when finish is \"screenshot\": \"low\" uses a smaller, cheaper image for quick confirmation."
9047
9677
  }
9048
9678
  },
9049
9679
  output,
@@ -9052,7 +9682,9 @@ function createTools(host) {
9052
9682
  const call = await host.context(exec);
9053
9683
  const actions = args.actions;
9054
9684
  const finish = args.finish ?? "screenshot";
9685
+ const detail = args.detail;
9055
9686
  let zoomed;
9687
+ let endedWithZoom = false;
9056
9688
  if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array.");
9057
9689
  if (actions.length > 30) throw new Error("At most 30 actions per batch.");
9058
9690
  const lines = [];
@@ -9066,7 +9698,10 @@ function createTools(host) {
9066
9698
  const stepStart = Date.now();
9067
9699
  if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
9068
9700
  const outcome = await computer.run(input, call);
9069
- if (input.action === "zoom") zoomed = outcome.image;
9701
+ if (input.action === "zoom") {
9702
+ endedWithZoom = true;
9703
+ zoomed = outcome.image;
9704
+ }
9070
9705
  if (outcome.skipped) {
9071
9706
  failure = `#${index + 1} ${input.action} skipped: the user was typing on the keyboard. Re-check the screen before continuing.`;
9072
9707
  break;
@@ -9088,14 +9723,14 @@ function createTools(host) {
9088
9723
  }
9089
9724
  const done = lines.join("\n");
9090
9725
  const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
9091
- if (zoomed !== void 0 && failure === void 0) return withShot(host, summary, zoomed, call);
9726
+ if (endedWithZoom && failure === void 0) return zoomed ? withShot(host, summary, zoomed, call) : { text: summary };
9092
9727
  if (failure === void 0 && finish === "none") return { text: `${summary}\n${await computer.describeForeground()}` };
9093
9728
  if (failure === void 0 && finish === "text") {
9094
9729
  await computer.settle(call.signal);
9095
9730
  return { text: `${summary}\n${await windowText(computer, void 0, void 0).catch((error) => `Could not read the window text: ${error instanceof Error ? error.message : String(error)}`)}` };
9096
9731
  }
9097
9732
  const waited = failure === void 0 && actions[actions.length - 1]?.action === "wait";
9098
- const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot()) : void 0;
9733
+ const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot(detail)) : void 0;
9099
9734
  return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
9100
9735
  },
9101
9736
  presentCall: (args) => card(`电脑操作 · 批量 ${args.actions?.length ?? 0} 步`)
@@ -9130,6 +9765,7 @@ function createTools(host) {
9130
9765
  {
9131
9766
  const name = rawName.trim();
9132
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.`);
9133
9769
  const settings = computer.settings();
9134
9770
  const isUrl = /^https?:\/\//i.test(name);
9135
9771
  const appName = /^ms-settings:/i.test(name) ? "设置" : name;
@@ -9311,7 +9947,7 @@ function createTools(host) {
9311
9947
  }));
9312
9948
  tools.push(defineTool({
9313
9949
  name: "ui_elements",
9314
- 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).",
9315
9951
  parameters: {
9316
9952
  hwnd: {
9317
9953
  type: "integer",
@@ -9321,6 +9957,10 @@ function createTools(host) {
9321
9957
  type: "boolean",
9322
9958
  description: "Return the window's text content instead of the element list."
9323
9959
  },
9960
+ ocr: {
9961
+ type: "boolean",
9962
+ description: "Recognize visible text lines and clickable center coordinates via built-in Windows OCR."
9963
+ },
9324
9964
  tail: {
9325
9965
  type: "integer",
9326
9966
  description: "text: how many characters from the end to return (default 4000, max 20000); new content is usually at the end."
@@ -9338,7 +9978,21 @@ function createTools(host) {
9338
9978
  timeoutMs: 3e4,
9339
9979
  isConcurrencySafe: () => true,
9340
9980
  async execute(args) {
9341
- 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
+ }
9342
9996
  if (text === true) return { text: await windowText(computer, hwnd, tail) };
9343
9997
  const result = await computer.helper.call("ui", {
9344
9998
  ...hwnd === void 0 ? {} : { hwnd },
@@ -9364,9 +10018,9 @@ function createTools(host) {
9364
10018
  lines.push(`[${index}] ${el.role} "${el.name}" @ (${center.x}, ${center.y})${flags ? ` ${flags}` : ""}`);
9365
10019
  }
9366
10020
  const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}": ${result.elements.length} elements.`;
9367
- 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.` };
9368
10022
  },
9369
- presentCall: () => card("读取界面元素")
10023
+ presentCall: (args) => card(args.ocr ? "OCR 识别文字" : "读取界面元素")
9370
10024
  }));
9371
10025
  tools.push(defineTool({
9372
10026
  name: "clipboard",
@@ -9533,6 +10187,24 @@ function createTools(host) {
9533
10187
  * through DSH approvals, and an orange "DeepSeek is using your computer"
9534
10188
  * overlay that a physical Esc dismisses.
9535
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
+ }
9536
10208
  const name = "@copylee/dsh-computer-use";
9537
10209
  const inject = ["tools", "attachments"];
9538
10210
  const Config = z.object({
@@ -9550,6 +10222,27 @@ const Config = z.object({
9550
10222
  "zh-CN": { $description: "授权方式。无论哪种,DeepSeek Harness 自身窗口和下方“禁止操控的应用”都不会被操作。" },
9551
10223
  "en-US": { $description: "Access mode. DeepSeek Harness itself and blocked apps are never controlled." }
9552
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
+ }),
10242
+ defaultSessionEnabled: z.boolean().default(false).volatile().i18n({
10243
+ "zh-CN": { $description: "(兼容旧配置)已被「会话启用方式」取代。" },
10244
+ "en-US": { $description: "(Legacy) Superseded by sessionMode." }
10245
+ }),
9553
10246
  overlay: z.boolean().default(true).volatile().i18n({
9554
10247
  "zh-CN": { $description: "控制时显示橙色光晕边框和顶部提示条(不会出现在截图里,按 Esc 可停止)" },
9555
10248
  "en-US": { $description: "Show the orange glow and status pill while controlling (hidden from screenshots; Esc stops)" }
@@ -9608,6 +10301,16 @@ const Config = z.object({
9608
10301
  "zh-CN": { $description: "每次操作后自动回传截图(省去一轮调用)" },
9609
10302
  "en-US": { $description: "Return a screenshot after every action (saves a round trip)" }
9610
10303
  }),
10304
+ autoScreenshotDetail: z.union([z.const("standard").i18n({
10305
+ "zh-CN": { $description: "标准(使用上方截图分辨率与质量)" },
10306
+ "en-US": { $description: "Standard (use the full screenshot limits below)" }
10307
+ }), z.const("compact").i18n({
10308
+ "zh-CN": { $description: "紧凑(自动降一档,省约 30%–40% 字节;显式 screenshot / zoom 仍保持标准清晰度)" },
10309
+ "en-US": { $description: "Compact (downscale auto-screenshots to save ~30-40% bytes; explicit screenshot/zoom keep full clarity)" }
10310
+ })]).default("standard").volatile().i18n({
10311
+ "zh-CN": { $description: "操作后自动回传截图的清晰度档位" },
10312
+ "en-US": { $description: "Detail tier for automatic post-action screenshots" }
10313
+ }),
9611
10314
  settleMs: z.natural().max(5e3).default(400).volatile().i18n({
9612
10315
  "zh-CN": { $description: "操作后至少等待的毫秒数;之后画面静止即截图(最多约 2.5 秒)" },
9613
10316
  "en-US": { $description: "Minimum wait after an action; then the screenshot is taken once the screen stops changing (up to ~2.5 s)" }
@@ -9641,6 +10344,9 @@ const Config = z.object({
9641
10344
  "en-US": { $description: "Apps that may never be controlled (names or exe). Common password managers are always blocked." }
9642
10345
  })
9643
10346
  });
10347
+ function isAgentLike(value) {
10348
+ return value !== null && typeof value === "object" && typeof value.session?.id === "string";
10349
+ }
9644
10350
  function apply(ctx, config = {}) {
9645
10351
  if (process.platform !== "win32") {
9646
10352
  ctx.logger.warn("dsh-computer-use only supports Windows; no tools registered.");
@@ -9730,6 +10436,88 @@ function apply(ctx, config = {}) {
9730
10436
  });
9731
10437
  for (const tool of tools) ctx.effect(() => ctx.tools.register(tool), `computer-use: tool ${tool.name}`);
9732
10438
  const OWN_TOOLS = new Set(tools.map((tool) => tool.name));
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
+ });
10455
+ const sessionGate = new SessionGate(void 0, log);
10456
+ const agentsRegistry = () => ctx.get("agents");
10457
+ const restricted = /* @__PURE__ */ new Map();
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
+ };
10466
+ const syncAgent = (agent) => {
10467
+ const enabled = isSessionEnabled(agent);
10468
+ const active = restricted.get(agent);
10469
+ if (enabled) {
10470
+ if (active) {
10471
+ restricted.delete(agent);
10472
+ try {
10473
+ active();
10474
+ } catch {}
10475
+ }
10476
+ return;
10477
+ }
10478
+ if (active) return;
10479
+ const restrict = agent.ctx?.tools?.restrict;
10480
+ if (typeof restrict !== "function") return;
10481
+ try {
10482
+ const dispose = restrict.call(agent.ctx.tools, { deny: ownToolNames });
10483
+ restricted.set(agent, dispose);
10484
+ } catch (error) {
10485
+ log(`session toggle restrict skipped for ${agent.session.id}: ${String(error)}`);
10486
+ }
10487
+ };
10488
+ const syncAllAgents = () => {
10489
+ const list = agentsRegistry()?.list?.();
10490
+ if (!list) return;
10491
+ for (const agent of list) syncAgent(agent);
10492
+ };
10493
+ const parentIdsFor = (sessionId) => {
10494
+ const registry = agentsRegistry();
10495
+ const agent = registry?.get?.(sessionId);
10496
+ return agent ? parentSessionChain(agent, registry) : [];
10497
+ };
10498
+ ctx.effect(() => ctx.tools.guard((exec) => {
10499
+ if (!OWN_TOOLS.has(exec.name)) return void 0;
10500
+ const agent = exec.agent;
10501
+ if (!agent || isSessionEnabled(agent)) return void 0;
10502
+ return "Computer use is disabled for this session. Ask the user to enable the \"电脑控制\" (Computer use) toggle in the chat composer.";
10503
+ }), "computer-use: session guard");
10504
+ ctx.effect(() => {
10505
+ syncAllAgents();
10506
+ return () => {
10507
+ for (const dispose of restricted.values()) try {
10508
+ dispose();
10509
+ } catch {}
10510
+ restricted.clear();
10511
+ };
10512
+ }, "computer-use: session restrictions");
10513
+ ctx.on("agent/created", ({ agent }) => {
10514
+ syncAgent(agent);
10515
+ });
10516
+ ctx.on("agent/pre-step", ({ agent }, next) => {
10517
+ syncAgent(agent);
10518
+ return next();
10519
+ });
10520
+ ctx.on("loader/volatile-update", (() => syncAllAgents()));
9733
10521
  ctx.on("tools/pre-execute", async (exec, next) => {
9734
10522
  if (exec.name !== "request_access" || settings().accessMode !== "per-app") return next();
9735
10523
  const agent = exec.agent;
@@ -9827,8 +10615,16 @@ function apply(ctx, config = {}) {
9827
10615
  if (status === "idle" && overlay.controller === agent) overlay.end(agent);
9828
10616
  });
9829
10617
  ctx.on("agent/disposed", ({ agent }) => {
10618
+ const target = agent;
10619
+ const dispose = restricted.get(target);
10620
+ if (dispose) {
10621
+ restricted.delete(target);
10622
+ try {
10623
+ dispose();
10624
+ } catch {}
10625
+ }
9830
10626
  overlay.forgetResume(agent);
9831
- access.forget(agent.session.id);
10627
+ access.forget(target.session.id);
9832
10628
  if (overlay.controller === agent) overlay.end();
9833
10629
  });
9834
10630
  ctx.inject(["webServer"], (webCtx) => {
@@ -9862,31 +10658,92 @@ function apply(ctx, config = {}) {
9862
10658
  route(SCREENSHOTS_ROUTE, screenshotsRoute(screenshots));
9863
10659
  route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
9864
10660
  route(SKILLS_ROUTE, skillsRoute(skills));
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");
9865
10731
  });
9866
10732
  ctx.inject(["systemPrompt"], (promptCtx) => {
9867
- let registered;
9868
- let dispose;
9869
- const refresh = () => {
9870
- const mode = settings().accessMode;
9871
- if (mode === registered) return;
9872
- dispose?.();
9873
- registered = mode;
9874
- dispose = promptCtx.systemPrompt.section({
9875
- name: "computer-use:guide",
9876
- order: 72,
9877
- text: promptText(mode)
9878
- });
9879
- };
9880
- promptCtx.effect(() => {
9881
- refresh();
9882
- return () => {
9883
- dispose?.();
9884
- dispose = void 0;
9885
- registered = void 0;
9886
- };
9887
- }, "computer-use: prompt");
9888
- promptCtx.on("loader/volatile-update", (() => refresh()));
10733
+ promptCtx.effect(() => promptCtx.systemPrompt.section({
10734
+ name: "computer-use:guide",
10735
+ order: 72,
10736
+ text: (assembleCtx) => {
10737
+ const c = assembleCtx;
10738
+ const agent = isAgentLike(c?.agent) ? c.agent : isAgentLike(c?.scope) ? c.scope : void 0;
10739
+ const s = settings();
10740
+ if (agent) {
10741
+ if (!isSessionEnabled(agent)) return "";
10742
+ } else if (!s.defaultSessionEnabled) return "";
10743
+ return promptText(s.accessMode);
10744
+ }
10745
+ }), "computer-use: prompt");
9889
10746
  });
9890
10747
  }
9891
10748
  //#endregion
9892
- export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, resolveConfig };
10749
+ export { Config, DEFAULTS, ENTRY_ID, apply, inject, name, parseCuCommand, resolveConfig };