@copylee/dsh-computer-use 0.1.10 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  | 功能 | 说明 |
8
8
  |---|---|
9
9
  | 截图即坐标系 | 模型只用最近一张截图的像素坐标,DPI、缩放、多显示器偏移全部由插件换算,高分屏(200% 缩放)也点得准 |
10
- | 动作后自动回传截图 | 点击 / 输入 / 按键 / 滚动后,**等画面不再变化**(页面加载、动画结束,最多约 2.5 秒)再截图;`wait` 也直接带回截图,“等一下再看”只需一步;画面与上一张截图完全相同时不再发图,只告诉模型“没有可见变化”,省 token |
10
+ | 动作后自动回传截图 | 点击 / 输入 / 按键 / 滚动后,**等画面不再变化**(页面加载、动画结束,最多约 2.5 秒)再截图;`wait` 也直接带回截图,“等一下再看”只需一步,而且画面一静止就提前结束,不会死等满时长;画面与上一张截图完全相同时不再发图,只告诉模型“没有可见变化”,省 token |
11
11
  | 批量动作 | `computer_batch` 一次执行“点输入框 → 输入 → 回车”等多步,最后只截一张图 |
12
12
  | 按应用授权 | 先 `request_access` 列出要操控的应用,经 DSH 原生审批后才能操作;也可改为“全部允许” |
13
13
  | 不会操作自己 | 永远拒绝向 DeepSeek Harness 自身窗口输入;常见密码管理器默认禁止,可再自定义禁用列表 |
@@ -72,7 +72,7 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
72
72
  | 操控期间 DSH 窗口 | 悬浮卡片 | 悬浮卡片 / 最小化 / 保持不变,结束后自动恢复 |
73
73
  | 操作后自动截图 | 开 | 关闭可省 token,但模型需要自己截图 |
74
74
  | 等待稳定 | 400 ms | 动作后至少等这么久,之后画面静止即截图(最多约 2.5 秒) |
75
- | 截图最长边 / 总像素 / JPEG 质量 | 1366 / 1.15MP / 80 | 越大越清晰、越费 token |
75
+ | 截图最长边 / 总像素 / JPEG 质量 | 1366 / 1.15MP / 70 | 越大越清晰、越费 token |
76
76
  | 检测到你在操作时让出控制 | 开 | 键盘输入暂停、窗口被切换时重新看屏幕 |
77
77
  | 键盘静止多久后恢复 | 1500 ms | |
78
78
  | 禁止操控的应用 | 空 | 名称或 exe,如 `alipay` |
@@ -80,6 +80,7 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
80
80
  ## 数据与隐私
81
81
 
82
82
  - 截图只作为当前会话的图片附件发给你选择的模型,插件不上传、不保存到别处。
83
+ - 截图附件存放在 `~/.dsh/attachments`,随会话历史保留(DSH 会校验附件,删掉仍被会话引用的截图会让该会话无法继续,所以插件不会动它们)。会话删除后留下的“孤儿”截图会在 DSH 启动几分钟后及之后每 12 小时自动清理;设置页“截图缓存”可查看占用并立即清理。
83
84
  - helper 源码 `helper/CuHelper.cs` 随包发布,可自行审阅;编译产物缓存在 `%LOCALAPPDATA%\dsh-computer-use\`。
84
85
  - 以管理员身份运行的窗口、UAC 弹窗、锁屏无法被控制(Windows UIPI 限制),遇到时模型会请你手动处理。
85
86
  - 插件注入的系统提示要求模型不代填密码、支付信息、不处理验证码,遇到时交还给你。
package/lib/client.js CHANGED
@@ -40,7 +40,7 @@ window.__ModuleLoader__.load({
40
40
  settleMs: 400,
41
41
  maxLongEdge: 1366,
42
42
  maxPixels: 115e4,
43
- jpegQuality: 80,
43
+ jpegQuality: 70,
44
44
  blockedApps: [],
45
45
  pauseOnUserInput: true,
46
46
  userIdleMs: 1500
@@ -303,6 +303,9 @@ window.__ModuleLoader__.load({
303
303
  * from the host routes in ../routes.ts.
304
304
  */
305
305
  const STATUS_ROUTE = "/api/dsh-computer-use/status";
306
+ const SCREENSHOTS_ROUTE = "/api/dsh-computer-use/screenshots";
307
+ const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
308
+ const mb = (bytes) => `${(bytes / 1048576).toFixed(1)} MB`;
306
309
  const PREVIEW_ROUTE = "/api/dsh-computer-use/preview";
307
310
  const h = react.createElement;
308
311
  function draftFrom(value) {
@@ -533,6 +536,9 @@ window.__ModuleLoader__.load({
533
536
  const [saving, setSaving] = react.useState(false);
534
537
  const [message, setMessage] = react.useState(null);
535
538
  const [status, setStatus] = react.useState(null);
539
+ const [cache, setCache] = react.useState(null);
540
+ const [cacheBusy, setCacheBusy] = react.useState(false);
541
+ const [cacheNote, setCacheNote] = react.useState(null);
536
542
  const dirtyRef = react.useRef(false);
537
543
  dirtyRef.current = dirty;
538
544
  const load = react.useCallback(async (reset) => {
@@ -563,9 +569,44 @@ window.__ModuleLoader__.load({
563
569
  setStatus(null);
564
570
  }
565
571
  }, []);
572
+ const refreshCache = react.useCallback(async () => {
573
+ setCacheBusy(true);
574
+ try {
575
+ const response = await fetch(SCREENSHOTS_ROUTE, { credentials: "same-origin" });
576
+ setCache(await response.json());
577
+ } catch {
578
+ setCache(null);
579
+ } finally {
580
+ setCacheBusy(false);
581
+ }
582
+ }, []);
583
+ const cleanCache = async () => {
584
+ setCacheBusy(true);
585
+ setCacheNote(null);
586
+ try {
587
+ const result = await (await fetch(SCREENSHOTS_CLEAN_ROUTE, {
588
+ method: "POST",
589
+ credentials: "same-origin"
590
+ })).json();
591
+ if (!result.ok) throw new Error(result.error ?? "清理失败");
592
+ setCacheNote({
593
+ kind: "ok",
594
+ text: result.removed ? `已清理 ${result.removed} 张截图` : "没有可清理的截图"
595
+ });
596
+ await refreshCache();
597
+ } catch (error) {
598
+ setCacheNote({
599
+ kind: "error",
600
+ text: `清理失败:${error.message}`
601
+ });
602
+ } finally {
603
+ setCacheBusy(false);
604
+ }
605
+ };
566
606
  react.useEffect(() => {
567
607
  load(true);
568
608
  refreshStatus();
609
+ refreshCache();
569
610
  return ctx.remote.$on?.("settings/document-updated", (ns) => {
570
611
  if (ns === "copylee-computer-use") {
571
612
  load(false);
@@ -767,7 +808,24 @@ window.__ModuleLoader__.load({
767
808
  error: errors.jpegQuality,
768
809
  disabled,
769
810
  onChange: (value) => edit("jpegQuality", value)
770
- })), h("p", { style: S.hint }, "截图越大越清晰、点得越准,但每张图消耗的 token 也越多。默认值(最长边 1366、1.15 百万像素)适合大多数模型。")), h("div", { style: S.actions }, h("button", {
811
+ })), h("p", { style: S.hint }, "截图越大越清晰、点得越准,但每张图消耗的 token 也越多。默认值(最长边 1366、1.15 百万像素)适合大多数模型。")), h("section", { style: S.card }, h("h3", { style: S.cardTitle }, "截图缓存"), h("p", { style: S.hint }, cache === null ? cacheBusy ? "正在统计…" : "无法统计截图缓存。" : !cache.ok ? `统计失败:${cache.error ?? ""}` : `本插件的截图共 ${cache.count} 张,占用 ${mb(cache.bytes)};其中 ${cache.orphans} 张(${mb(cache.orphanBytes)})所属会话已删除,可以安全清理。`), h("p", { style: S.hint }, "截图作为附件保存在会话历史里。仍在会话中的截图不会被删除:删除后继续那个会话会直接报错。删除会话后,它留下的截图会在启动 DeepSeek Harness 几分钟后及之后每 12 小时自动清理,也可以在这里立即清理。"), h("div", { style: S.actions }, h("button", {
812
+ type: "button",
813
+ style: {
814
+ ...S.secondary,
815
+ opacity: cacheBusy || !cache?.orphans ? .5 : 1
816
+ },
817
+ disabled: cacheBusy || !cache?.orphans,
818
+ onClick: () => {
819
+ cleanCache();
820
+ }
821
+ }, "清理已删除会话的截图"), h("button", {
822
+ type: "button",
823
+ style: S.secondary,
824
+ disabled: cacheBusy,
825
+ onClick: () => {
826
+ refreshCache();
827
+ }
828
+ }, cacheBusy ? "统计中…" : "重新统计"), cacheNote === null ? null : h("span", { style: cacheNote.kind === "ok" ? S.ok : S.error }, cacheNote.text))), h("div", { style: S.actions }, h("button", {
771
829
  type: "button",
772
830
  style: {
773
831
  ...S.primary,
package/lib/index.js CHANGED
@@ -4,10 +4,11 @@ import { setTimeout as setTimeout$1 } from "node:timers/promises";
4
4
  import { execFile, spawn } from "node:child_process";
5
5
  import { createHash } from "node:crypto";
6
6
  import { existsSync } from "node:fs";
7
- import { mkdir, readFile, rename, rm } from "node:fs/promises";
8
- import { tmpdir } from "node:os";
7
+ import { chmod, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
+ import { homedir, tmpdir } from "node:os";
9
9
  import { join } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
+ import * as zlib from "node:zlib";
11
12
  import { Context, Service } from "@deepseek-ai/cordis";
12
13
  //#region lib/types/access.js
13
14
  /**
@@ -645,6 +646,26 @@ var Computer = class Computer {
645
646
  if (!fg || !(isHostWindow(fg) || isTransientShell(fg)) || !target || target.hwnd === fg.hwnd) return;
646
647
  if ((await this.focus(target).catch(() => void 0))?.focused) await setTimeout$1(80);
647
648
  }
649
+ /** Wait at most `maxMs`, returning once the screen has been still for ~0.8 s. Returns the time waited. */
650
+ async waitForQuiet(maxMs, signal) {
651
+ const started = Date.now();
652
+ if (maxMs <= 600) {
653
+ await setTimeout$1(maxMs, void 0, { signal });
654
+ return maxMs;
655
+ }
656
+ const display = await this.display();
657
+ if (await this.helper.call("settle", {
658
+ x: display.x,
659
+ y: display.y,
660
+ width: display.width,
661
+ height: display.height,
662
+ minMs: 300,
663
+ maxMs,
664
+ quietMs: 800
665
+ }, maxMs + 1e4).catch(() => null) === null) await setTimeout$1(Math.max(0, maxMs - (Date.now() - started)), void 0, { signal });
666
+ if (signal.aborted) throw new Error("Cancelled.");
667
+ return Date.now() - started;
668
+ }
648
669
  /** Wait until the screen stops changing (bounded), instead of a fixed delay. */
649
670
  async settle(signal) {
650
671
  const s = this.settings();
@@ -761,9 +782,9 @@ var Computer = class Computer {
761
782
  return { text: `Cursor at (${p.x}, ${p.y})${p.offscreen ? " — on another display" : ""}.` };
762
783
  }
763
784
  case "wait": {
764
- const seconds = Math.min(30, Math.max(0, input.duration ?? 1));
765
- await setTimeout$1(seconds * 1e3, void 0, { signal: call.signal });
766
- return { text: `Waited ${seconds}s.` };
785
+ const seconds = Math.min(30, Math.max(0, Number(input.duration ?? 1) || 0));
786
+ const waited = await this.waitForQuiet(seconds * 1e3, call.signal);
787
+ return { text: waited < seconds * 1e3 - 200 ? `Waited ${(waited / 1e3).toFixed(1)}s (the screen settled early).` : `Waited ${seconds}s.` };
767
788
  }
768
789
  case "mouse_move": {
769
790
  const p = await this.point(input.coordinate);
@@ -1335,7 +1356,7 @@ const DEFAULTS = {
1335
1356
  settleMs: 400,
1336
1357
  maxLongEdge: 1366,
1337
1358
  maxPixels: 115e4,
1338
- jpegQuality: 80,
1359
+ jpegQuality: 70,
1339
1360
  blockedApps: [],
1340
1361
  pauseOnUserInput: true,
1341
1362
  userIdleMs: 1500
@@ -1368,6 +1389,8 @@ function resolveConfig(raw) {
1368
1389
  //#region lib/types/routes.js
1369
1390
  const STATUS_ROUTE = "/api/dsh-computer-use/status";
1370
1391
  const PREVIEW_ROUTE = "/api/dsh-computer-use/preview";
1392
+ const SCREENSHOTS_ROUTE = "/api/dsh-computer-use/screenshots";
1393
+ const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
1371
1394
  function json(res, status, body) {
1372
1395
  res.writeHead(status, {
1373
1396
  "content-type": "application/json; charset=utf-8",
@@ -1436,6 +1459,286 @@ function previewRoute(helper, settings, overlay, iconPath) {
1436
1459
  json(res, 200, { ok: true });
1437
1460
  };
1438
1461
  }
1462
+ /** Screenshot cache size and how much of it is orphaned. */
1463
+ function screenshotsRoute(cache) {
1464
+ return async (_req, res) => {
1465
+ try {
1466
+ json(res, 200, {
1467
+ ok: true,
1468
+ ...await cache.stats()
1469
+ });
1470
+ } catch (error) {
1471
+ json(res, 200, {
1472
+ ok: false,
1473
+ error: error instanceof Error ? error.message : String(error)
1474
+ });
1475
+ }
1476
+ };
1477
+ }
1478
+ /** Delete orphaned screenshots now. */
1479
+ function screenshotsCleanRoute(cache) {
1480
+ return async (req, res) => {
1481
+ if (req.method !== "POST") {
1482
+ json(res, 405, {
1483
+ ok: false,
1484
+ error: "POST only"
1485
+ });
1486
+ return;
1487
+ }
1488
+ try {
1489
+ json(res, 200, {
1490
+ ok: true,
1491
+ ...await cache.clean(),
1492
+ ...await cache.stats()
1493
+ });
1494
+ } catch (error) {
1495
+ json(res, 200, {
1496
+ ok: false,
1497
+ error: error instanceof Error ? error.message : String(error)
1498
+ });
1499
+ }
1500
+ };
1501
+ }
1502
+ //#endregion
1503
+ //#region lib/types/screenshots.js
1504
+ /**
1505
+ * Screenshot cache housekeeping. Every screenshot is an image attachment in
1506
+ * DeepSeek Harness's content-addressed store (<DSH_HOME>/attachments/v1/objects/<2>/<sha256>),
1507
+ * which has no retention policy yet. Attachments still referenced by a session
1508
+ * must stay byte-for-byte (DSH verifies their hash, and a missing one fails the
1509
+ * whole turn), so only orphans are removed: screenshots this plugin made that
1510
+ * no session, archive or plugin store references any more (e.g. the session
1511
+ * was deleted).
1512
+ */
1513
+ const HEX = /^[0-9a-f]{64}$/;
1514
+ /** Newly saved screenshots may not be in a session log yet. */
1515
+ const GRACE_MS = 864e5;
1516
+ /** Places outside the session logs that can reference attachments. */
1517
+ const OTHER_REFERENCE_DIRS = [
1518
+ "storages",
1519
+ "rewind-snapshots",
1520
+ "dsh-session-archive",
1521
+ "task-board"
1522
+ ];
1523
+ const MAX_SCANNED_FILE = 67108864;
1524
+ var ScreenshotCache = class {
1525
+ dshHome;
1526
+ indexFile;
1527
+ log;
1528
+ index;
1529
+ saving = Promise.resolve();
1530
+ busy = Promise.resolve();
1531
+ constructor(dshHome = process.env.DSH_HOME || join(homedir(), ".dsh"), indexFile = join(process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local"), "dsh-computer-use", "screenshots.json"), log = () => {}) {
1532
+ this.dshHome = dshHome;
1533
+ this.indexFile = indexFile;
1534
+ this.log = log;
1535
+ }
1536
+ get objects() {
1537
+ return join(this.dshHome, "attachments", "v1", "objects");
1538
+ }
1539
+ path(hex) {
1540
+ return join(this.objects, hex.slice(0, 2), hex);
1541
+ }
1542
+ /** Remember a screenshot attachment ("sha256:<hex>") this plugin saved. */
1543
+ record(attachmentId) {
1544
+ const hex = attachmentId.replace(/^sha256:/, "");
1545
+ if (!HEX.test(hex)) return;
1546
+ this.load().then((index) => {
1547
+ index.set(hex, Date.now());
1548
+ this.persist();
1549
+ }).catch(() => {});
1550
+ }
1551
+ async stats() {
1552
+ return this.exclusive(async () => {
1553
+ const { candidates, orphans } = await this.classify();
1554
+ const sizes = await Promise.all([...candidates].map((hex) => this.size(hex)));
1555
+ let count = 0, bytes = 0, orphanCount = 0, orphanBytes = 0;
1556
+ [...candidates].forEach((hex, i) => {
1557
+ const size = sizes[i];
1558
+ if (size === void 0) return;
1559
+ count++;
1560
+ bytes += size;
1561
+ if (orphans.has(hex)) {
1562
+ orphanCount++;
1563
+ orphanBytes += size;
1564
+ }
1565
+ });
1566
+ return {
1567
+ count,
1568
+ bytes,
1569
+ orphans: orphanCount,
1570
+ orphanBytes
1571
+ };
1572
+ });
1573
+ }
1574
+ /** Delete orphaned screenshots. */
1575
+ async clean() {
1576
+ return this.exclusive(async () => {
1577
+ const { orphans } = await this.classify();
1578
+ const index = await this.load();
1579
+ let removed = 0, bytes = 0;
1580
+ for (const hex of orphans) {
1581
+ const size = await this.size(hex);
1582
+ if (size !== void 0) try {
1583
+ const file = this.path(hex);
1584
+ await chmod(file, 438).catch(() => {});
1585
+ await unlink(file);
1586
+ removed++;
1587
+ bytes += size;
1588
+ } catch (error) {
1589
+ this.log(`screenshot cleanup: ${String(error)}`);
1590
+ continue;
1591
+ }
1592
+ index.delete(hex);
1593
+ }
1594
+ this.persist();
1595
+ await this.saving;
1596
+ if (removed > 0) this.log(`screenshot cleanup: removed ${removed} orphaned screenshots (${(bytes / 1048576).toFixed(1)} MB)`);
1597
+ return {
1598
+ removed,
1599
+ bytes
1600
+ };
1601
+ });
1602
+ }
1603
+ async classify() {
1604
+ const index = await this.load();
1605
+ const scan = await this.scan();
1606
+ let added = false;
1607
+ for (const hex of scan.ours) if (!index.has(hex)) {
1608
+ index.set(hex, 0);
1609
+ added = true;
1610
+ }
1611
+ if (added) this.persist();
1612
+ const now = Date.now();
1613
+ const candidates = new Set(index.keys());
1614
+ const orphans = /* @__PURE__ */ new Set();
1615
+ for (const [hex, savedAt] of index) {
1616
+ if (scan.referenced.has(hex)) continue;
1617
+ if (savedAt > 0 && now - savedAt < GRACE_MS) continue;
1618
+ orphans.add(hex);
1619
+ }
1620
+ return {
1621
+ candidates,
1622
+ orphans
1623
+ };
1624
+ }
1625
+ /** Every attachment id referenced anywhere DSH keeps conversation state. */
1626
+ async scan() {
1627
+ const zstd = zlib.zstdDecompressSync;
1628
+ if (typeof zstd !== "function") throw new Error("This runtime cannot read DeepSeek Harness session logs (no zstd); cleanup skipped.");
1629
+ const referenced = /* @__PURE__ */ new Set();
1630
+ const ours = /* @__PURE__ */ new Set();
1631
+ const sessions = join(this.dshHome, "sessions");
1632
+ for (const file of await walk(sessions)) {
1633
+ const text = await readText(file, zstd);
1634
+ if (text === void 0) throw new Error(`Could not read ${file}; cleanup skipped to stay safe.`);
1635
+ collect(text, referenced, ours);
1636
+ }
1637
+ for (const dir of OTHER_REFERENCE_DIRS) for (const file of await walk(join(this.dshHome, dir))) {
1638
+ const text = await readText(file, zstd);
1639
+ if (text !== void 0) collect(text, referenced, ours);
1640
+ }
1641
+ return {
1642
+ referenced,
1643
+ ours
1644
+ };
1645
+ }
1646
+ async size(hex) {
1647
+ try {
1648
+ return (await stat(this.path(hex))).size;
1649
+ } catch {
1650
+ return;
1651
+ }
1652
+ }
1653
+ async load() {
1654
+ if (this.index) return this.index;
1655
+ try {
1656
+ const raw = JSON.parse(await readFile(this.indexFile, "utf8"));
1657
+ this.index = new Map(Object.entries(raw.screenshots ?? {}).filter(([hex]) => HEX.test(hex)));
1658
+ } catch {
1659
+ this.index = /* @__PURE__ */ new Map();
1660
+ }
1661
+ return this.index;
1662
+ }
1663
+ persist() {
1664
+ const index = this.index;
1665
+ if (!index) return;
1666
+ this.saving = this.saving.then(async () => {
1667
+ await mkdir(join(this.indexFile, ".."), { recursive: true });
1668
+ const tmp = `${this.indexFile}.${process.pid}.tmp`;
1669
+ await writeFile(tmp, JSON.stringify({
1670
+ version: 1,
1671
+ screenshots: Object.fromEntries(index)
1672
+ }));
1673
+ await rename(tmp, this.indexFile);
1674
+ }).catch((error) => this.log(`screenshot index: ${String(error)}`));
1675
+ }
1676
+ exclusive(task) {
1677
+ const run = this.busy.then(task, task);
1678
+ this.busy = run.catch(() => {});
1679
+ return run;
1680
+ }
1681
+ };
1682
+ /** Ids in `text`; ids of our own screenshots (tool results named screenshot.jpg) also go to `ours`. */
1683
+ function collect(text, referenced, ours) {
1684
+ for (const match of text.matchAll(/sha256:([0-9a-f]{64})/g)) referenced.add(match[1]);
1685
+ for (const line of text.split("\n")) {
1686
+ if (!line.includes("\"tool/result\"") || !line.includes("\"screenshot.jpg\"")) continue;
1687
+ for (const match of line.matchAll(/"attachmentId":"sha256:([0-9a-f]{64})"[^{}]*?"name":"screenshot\.jpg"/g)) ours.add(match[1]);
1688
+ }
1689
+ }
1690
+ async function walk(dir) {
1691
+ const out = [];
1692
+ let entries;
1693
+ try {
1694
+ entries = await readdir(dir, { withFileTypes: true });
1695
+ } catch {
1696
+ return out;
1697
+ }
1698
+ for (const entry of entries) {
1699
+ const full = join(dir, entry.name);
1700
+ if (entry.isDirectory()) out.push(...await walk(full));
1701
+ else if (entry.isFile()) out.push(full);
1702
+ }
1703
+ return out;
1704
+ }
1705
+ const ZSTD_MAGIC = Buffer.from([
1706
+ 40,
1707
+ 181,
1708
+ 47,
1709
+ 253
1710
+ ]);
1711
+ /** File text; zstd logs are a sequence of frames (decoded one by one). */
1712
+ async function readText(file, zstd) {
1713
+ try {
1714
+ if ((await stat(file)).size > MAX_SCANNED_FILE) return "";
1715
+ const data = await readFile(file);
1716
+ if (!file.endsWith(".zstd")) return data.toString("utf8");
1717
+ return decodeFrames(data, zstd);
1718
+ } catch {
1719
+ return;
1720
+ }
1721
+ }
1722
+ /** Split at frame magics; when a split falls inside a frame, merge with the next piece and retry. */
1723
+ function decodeFrames(data, zstd) {
1724
+ const starts = [];
1725
+ for (let i = data.indexOf(ZSTD_MAGIC); i >= 0; i = data.indexOf(ZSTD_MAGIC, i + 1)) starts.push(i);
1726
+ if (starts.length === 0) return data.length === 0 ? "" : void 0;
1727
+ const parts = [];
1728
+ let from = 0;
1729
+ while (from < starts.length) {
1730
+ let decoded;
1731
+ let to = from + 1;
1732
+ for (; to <= starts.length; to++) try {
1733
+ decoded = zstd(data.subarray(starts[from], starts[to] ?? data.length));
1734
+ break;
1735
+ } catch {}
1736
+ if (decoded === void 0) return void 0;
1737
+ parts.push(decoded);
1738
+ from = to;
1739
+ }
1740
+ return Buffer.concat(parts).toString("utf8");
1741
+ }
1439
1742
  //#endregion
1440
1743
  //#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
1441
1744
  /**
@@ -7551,7 +7854,7 @@ const Config = z.object({
7551
7854
  "zh-CN": { $description: "截图总像素上限" },
7552
7855
  "en-US": { $description: "Screenshot total pixel limit" }
7553
7856
  }),
7554
- jpegQuality: z.natural().min(30).max(100).default(80).volatile().i18n({
7857
+ jpegQuality: z.natural().min(30).max(100).default(70).volatile().i18n({
7555
7858
  "zh-CN": { $description: "截图 JPEG 质量" },
7556
7859
  "en-US": { $description: "Screenshot JPEG quality" }
7557
7860
  }),
@@ -7602,13 +7905,31 @@ function apply(ctx, config = {}) {
7602
7905
  return cached;
7603
7906
  };
7604
7907
  const attachments = () => ctx.attachments;
7908
+ const screenshots = new ScreenshotCache(void 0, void 0, log);
7909
+ ctx.effect(() => {
7910
+ const sweep = () => {
7911
+ screenshots.clean().catch((error) => log(`screenshot cleanup skipped: ${String(error)}`));
7912
+ };
7913
+ const first = setTimeout(sweep, 12e4);
7914
+ const every = setInterval(sweep, 432e5);
7915
+ first.unref();
7916
+ every.unref();
7917
+ return () => {
7918
+ clearTimeout(first);
7919
+ clearInterval(every);
7920
+ };
7921
+ }, "computer-use: screenshot cleanup");
7605
7922
  const tools = createTools({
7606
7923
  computer,
7607
- saveImage: (shot, fileName) => attachments().saveImage({
7608
- data: shot.data,
7609
- mediaType: "image/jpeg",
7610
- name: fileName
7611
- }),
7924
+ async saveImage(shot, fileName) {
7925
+ const ref = await attachments().saveImage({
7926
+ data: shot.data,
7927
+ mediaType: "image/jpeg",
7928
+ name: fileName
7929
+ });
7930
+ screenshots.record(String(ref.attachmentId));
7931
+ return ref;
7932
+ },
7612
7933
  async context(raw) {
7613
7934
  const exec = raw;
7614
7935
  return {
@@ -7679,6 +8000,8 @@ function apply(ctx, config = {}) {
7679
8000
  };
7680
8001
  route(STATUS_ROUTE, statusRoute(helper, settings, overlay));
7681
8002
  route(PREVIEW_ROUTE, previewRoute(helper, settings, overlay, iconPath));
8003
+ route(SCREENSHOTS_ROUTE, screenshotsRoute(screenshots));
8004
+ route(SCREENSHOTS_CLEAN_ROUTE, screenshotsCleanRoute(screenshots));
7682
8005
  });
7683
8006
  ctx.inject(["systemPrompt"], (promptCtx) => {
7684
8007
  let registered;
@@ -116,6 +116,8 @@ export declare class Computer {
116
116
  * in front instead of refusing.
117
117
  */
118
118
  private refocusFromHost;
119
+ /** Wait at most `maxMs`, returning once the screen has been still for ~0.8 s. Returns the time waited. */
120
+ waitForQuiet(maxMs: number, signal: AbortSignal): Promise<number>;
119
121
  /** Wait until the screen stops changing (bounded), instead of a fixed delay. */
120
122
  settle(signal: AbortSignal): Promise<void>;
121
123
  windowAt(point: Point): Promise<WindowInfo | undefined>;
@@ -7,8 +7,11 @@ import { type Display } from './coords.js';
7
7
  import type { Settings } from './computer.js';
8
8
  import type { HelperLike } from './helper-client.js';
9
9
  import type { OverlayController } from './overlay.js';
10
+ import type { ScreenshotCache } from './screenshots.js';
10
11
  export declare const STATUS_ROUTE = "/api/dsh-computer-use/status";
11
12
  export declare const PREVIEW_ROUTE = "/api/dsh-computer-use/preview";
13
+ export declare const SCREENSHOTS_ROUTE = "/api/dsh-computer-use/screenshots";
14
+ export declare const SCREENSHOTS_CLEAN_ROUTE = "/api/dsh-computer-use/screenshots/clean";
12
15
  type Handler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;
13
16
  export interface StatusBody {
14
17
  ok: true;
@@ -26,4 +29,8 @@ export interface StatusBody {
26
29
  export declare function statusRoute(helper: HelperLike, settings: () => Settings, overlay: OverlayController): Handler;
27
30
  /** Show the overlay for a few seconds so the user can see how it looks (skipped while an agent is controlling). */
28
31
  export declare function previewRoute(helper: HelperLike, settings: () => Settings, overlay: OverlayController, iconPath: string): Handler;
32
+ /** Screenshot cache size and how much of it is orphaned. */
33
+ export declare function screenshotsRoute(cache: ScreenshotCache): Handler;
34
+ /** Delete orphaned screenshots now. */
35
+ export declare function screenshotsCleanRoute(cache: ScreenshotCache): Handler;
29
36
  export {};
@@ -0,0 +1,41 @@
1
+ export interface ScreenshotStats {
2
+ /** Screenshots this plugin knows about that still exist on disk. */
3
+ count: number;
4
+ bytes: number;
5
+ /** Of those, the ones no longer referenced anywhere (safe to delete). */
6
+ orphans: number;
7
+ orphanBytes: number;
8
+ }
9
+ export interface CleanResult {
10
+ removed: number;
11
+ bytes: number;
12
+ }
13
+ type ZstdDecompress = (data: Uint8Array) => Buffer;
14
+ export declare class ScreenshotCache {
15
+ private readonly dshHome;
16
+ private readonly indexFile;
17
+ private readonly log;
18
+ private index;
19
+ private saving;
20
+ private busy;
21
+ constructor(dshHome?: string, indexFile?: string, log?: (message: string) => void);
22
+ private get objects();
23
+ private path;
24
+ /** Remember a screenshot attachment ("sha256:<hex>") this plugin saved. */
25
+ record(attachmentId: string): void;
26
+ stats(): Promise<ScreenshotStats>;
27
+ /** Delete orphaned screenshots. */
28
+ clean(): Promise<CleanResult>;
29
+ private classify;
30
+ /** Every attachment id referenced anywhere DSH keeps conversation state. */
31
+ private scan;
32
+ private size;
33
+ private load;
34
+ private persist;
35
+ private exclusive;
36
+ }
37
+ /** Ids in `text`; ids of our own screenshots (tool results named screenshot.jpg) also go to `ours`. */
38
+ export declare function collect(text: string, referenced: Set<string>, ours: Set<string>): void;
39
+ /** Split at frame magics; when a split falls inside a frame, merge with the next piece and retry. */
40
+ export declare function decodeFrames(data: Buffer, zstd: ZstdDecompress): string | undefined;
41
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.1.10",
3
+ "version": "0.2.1",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "type": "module",
6
6
  "author": "copylee",