@copylee/dsh-computer-use 0.2.2 → 0.4.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,8 +1,8 @@
1
1
  import { createRequire } from "node:module";
2
+ import { createHash, randomUUID } from "node:crypto";
2
3
  import z from "@deepseek-ai/schemastery";
3
4
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
4
5
  import { execFile, spawn } from "node:child_process";
5
- import { createHash } from "node:crypto";
6
6
  import { existsSync } from "node:fs";
7
7
  import { chmod, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
8
  import { homedir, tmpdir } from "node:os";
@@ -125,7 +125,7 @@ function sameApp(a, b) {
125
125
  */
126
126
  function isTransientShell(win) {
127
127
  const exe = win.exe.toLowerCase();
128
- if (exe === "textinputhost.exe") return true;
128
+ if (exe === "textinputhost.exe" || exe === "cu-helper.exe") return true;
129
129
  return exe === "explorer.exe" && (win.className === "XamlExplorerHostIslandWindow" || /贴靠助手|snap assist/i.test(win.title));
130
130
  }
131
131
  function isHostWindow(win) {
@@ -426,7 +426,8 @@ function keyCode(name) {
426
426
  */
427
427
  function parseKeys(text) {
428
428
  const combos = [];
429
- for (const chord of text.trim().split(/\s+/).filter(Boolean)) {
429
+ const joined = text.trim().replace(/\b(page|print|caps|num|scroll)\s+(up|down|screen|lock)\b/gi, "$1$2");
430
+ for (const chord of joined.split(/\s+/).filter(Boolean)) {
430
431
  const parts = chord === "+" ? ["+"] : chord.split(/(?<!^)\+(?!$)/);
431
432
  const combo = [];
432
433
  for (const part of parts) {
@@ -568,6 +569,7 @@ var Computer = class Computer {
568
569
  this.access = access;
569
570
  this.overlay = overlay;
570
571
  this.settings = settings;
572
+ overlay.onStart = () => this.noteStart();
571
573
  }
572
574
  async refreshDisplays() {
573
575
  const rows = await this.helper.call("displays");
@@ -643,7 +645,8 @@ var Computer = class Computer {
643
645
  this.seen = void 0;
644
646
  }
645
647
  async remember() {
646
- this.seen = await this.foreground().catch(() => void 0);
648
+ const now = await this.foreground().catch(() => void 0);
649
+ if (!now || !isTransientShell(now)) this.seen = now;
647
650
  }
648
651
  /**
649
652
  * Did another window come to the front since the model last looked, without
@@ -653,7 +656,7 @@ var Computer = class Computer {
653
656
  const seen = this.seen;
654
657
  if (!seen) return void 0;
655
658
  const now = await this.foreground().catch(() => void 0);
656
- return now && now.hwnd !== seen.hwnd ? now : void 0;
659
+ return now && now.hwnd !== seen.hwnd && now.pid !== seen.pid ? now : void 0;
657
660
  }
658
661
  async capture(rect, out, options = {}) {
659
662
  const result = await this.helper.call("screenshot", {
@@ -742,6 +745,31 @@ var Computer = class Computer {
742
745
  async windows() {
743
746
  return this.helper.call("windows");
744
747
  }
748
+ /** Windows when control started (hwnd -> minimized), and windows brought back from the tray since. */
749
+ before;
750
+ fromTray = /* @__PURE__ */ new Set();
751
+ /** Remember the window layout at the start of a task, to tell what the agent opened or restored. */
752
+ async noteStart() {
753
+ const rows = await this.windows().catch(() => []);
754
+ this.before = new Map((Array.isArray(rows) ? rows : []).map((row) => [row.hwnd, row.minimized]));
755
+ this.fromTray.clear();
756
+ }
757
+ noteFromTray(hwnd) {
758
+ this.fromTray.add(hwnd);
759
+ }
760
+ /** How a window relates to the layout before the task: opened by the agent, or restored from minimized / tray. */
761
+ origin(win) {
762
+ if (this.fromTray.has(win.hwnd)) return win.minimized ? void 0 : "tray";
763
+ if (!this.before) return void 0;
764
+ const was = this.before.get(win.hwnd);
765
+ if (was === void 0) return "opened";
766
+ return was && !win.minimized ? "minimized" : void 0;
767
+ }
768
+ /** Programs running without any visible window (closed to the system tray); `tray` = has a tray icon. */
769
+ async backgroundApps() {
770
+ const rows = await this.helper.call("background", {}, 15e3).catch(() => []);
771
+ return Array.isArray(rows) ? rows : [];
772
+ }
745
773
  async cursor() {
746
774
  return this.helper.call("cursor");
747
775
  }
@@ -1247,8 +1275,37 @@ var HelperClient = class {
1247
1275
  * agent, and typing on the keyboard makes the agent wait. While controlling,
1248
1276
  * the DeepSeek Harness window can shrink into an always-on-top card.
1249
1277
  */
1250
- /** Without a status change from the host, hide after this long without actions. */
1251
- const IDLE_HIDE_MS = 9e4;
1278
+ /** Markdown reduced to one plain line for the progress card. */
1279
+ function plainLine(text) {
1280
+ return text.replace(/```[\s\S]*?(```|$)/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, " ").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+[.)])\s+/gm, "").replace(/(\*\*|__|`|~~)/g, "").replace(/\s+/g, " ");
1281
+ }
1282
+ /** Friendly names of common tools on the card's activity line. */
1283
+ const TOOL_NAMES = {
1284
+ computer: "操作电脑",
1285
+ computer_batch: "批量操作",
1286
+ open_application: "打开应用",
1287
+ windows: "窗口",
1288
+ ui_elements: "读取界面元素",
1289
+ clipboard: "剪贴板",
1290
+ request_access: "请求授权",
1291
+ pwsh: "运行命令",
1292
+ bash: "运行命令",
1293
+ shell: "运行命令",
1294
+ read: "读取文件",
1295
+ write: "写入文件",
1296
+ edit: "编辑文件",
1297
+ web_search: "搜索网页",
1298
+ web_fetch: "读取网页",
1299
+ todo_write: "更新待办"
1300
+ };
1301
+ /** How long the "done" card stays up after a run (longer while the pointer rests on it). */
1302
+ const FINISH_HOLD_MS = 4e3;
1303
+ /**
1304
+ * Fallback only (the host normally reports the agent going idle): hide after
1305
+ * this long without any sign of life from the agent. Model output and tool
1306
+ * starts of any plugin count, so a slow shell command does not end the run.
1307
+ */
1308
+ const IDLE_HIDE_MS = 6e5;
1252
1309
  /** A pause longer than this ends the tool call with a message for the model. */
1253
1310
  const MAX_PAUSE_MS = 15e5;
1254
1311
  /** Card rectangle in the bottom-right corner of a display's work area. */
@@ -1274,6 +1331,22 @@ var OverlayController = class {
1274
1331
  idleTimer;
1275
1332
  hostWindows = [];
1276
1333
  stopping = false;
1334
+ /** Progress card lines: the reply as it streams, and what the agent is doing. */
1335
+ streamAgent;
1336
+ text = "";
1337
+ thinking = "";
1338
+ /** Recent steps (tool actions), oldest first. */
1339
+ steps = [];
1340
+ /** Whether the agent is thinking now (newer than the last step). */
1341
+ thinkingLatest = false;
1342
+ freshAttempt = true;
1343
+ pushTimer;
1344
+ /** An instruction the user typed into the progress card. */
1345
+ onMessage;
1346
+ /** Called when control starts (before the first action), e.g. to remember the window layout. */
1347
+ onStart;
1348
+ /** Opacity the card was last given, to apply setting changes while it floats. */
1349
+ cardOpacity = 100;
1277
1350
  /** Paused by Esc or the pill; actions wait until resumed. */
1278
1351
  paused = false;
1279
1352
  /** When the user last typed on the physical keyboard while the overlay was up (ms epoch). */
@@ -1292,6 +1365,11 @@ var OverlayController = class {
1292
1365
  else if (event.event === "user_input") {
1293
1366
  this.lastUserInput = Date.now();
1294
1367
  this.lastUserKey = event.reason ?? "";
1368
+ } else if (event.event === "message" && event.reason) {
1369
+ const agent = this.agent;
1370
+ if (!agent) return;
1371
+ this.step(`你:${event.reason}`);
1372
+ this.onMessage?.(agent, event.reason);
1295
1373
  }
1296
1374
  });
1297
1375
  }
@@ -1328,19 +1406,101 @@ var OverlayController = class {
1328
1406
  if (!this.visible) {
1329
1407
  this.visible = true;
1330
1408
  this.paused = false;
1409
+ await this.onStart?.().catch((error) => this.log(`overlay start: ${String(error)}`));
1331
1410
  await this.shrinkHost(settings.hostWindow);
1332
- if (settings.overlay) await this.helper.call("overlay_show", {
1333
- label: `${settings.overlayLabel || "DeepSeek Harness"} 正在操控你的电脑`,
1334
- status,
1335
- icon: this.iconPath,
1336
- idleMs: settings.userIdleMs
1337
- }).catch((error) => this.log(`overlay: ${String(error)}`));
1411
+ const pet = settings.hostWindow === "pet";
1412
+ if (settings.overlay || pet) {
1413
+ if (this.streamAgent !== agent) {
1414
+ this.text = "";
1415
+ this.thinking = "";
1416
+ }
1417
+ this.steps = status ? [status] : [];
1418
+ this.thinkingLatest = false;
1419
+ await this.helper.call("overlay_show", {
1420
+ label: pet ? `${settings.overlayLabel || "DeepSeek Harness"} 正在操控` : `${settings.overlayLabel || "DeepSeek Harness"} 正在操控你的电脑`,
1421
+ status,
1422
+ icon: this.iconPath,
1423
+ iconLight: this.iconPath.replace(/deepseek-white\.png$/, "deepseek-black.png"),
1424
+ idleMs: settings.userIdleMs,
1425
+ glow: settings.overlay,
1426
+ pet,
1427
+ petOpacity: settings.cardOpacity,
1428
+ text: this.text
1429
+ }).catch((error) => this.log(`overlay: ${String(error)}`));
1430
+ }
1338
1431
  return;
1339
1432
  }
1433
+ if (settings.hostWindow === "pet" && !this.hostWindows.some((win) => win.mode === "card")) await this.cardIfShown();
1434
+ if (this.hostWindows.some((win) => win.mode === "card") && settings.cardOpacity !== this.cardOpacity) {
1435
+ this.cardOpacity = settings.cardOpacity;
1436
+ await this.helper.call("card_opacity", { opacity: settings.cardOpacity }).catch(() => {});
1437
+ }
1340
1438
  await this.status(status);
1341
1439
  }
1342
1440
  async status(status) {
1343
- if (this.visible && this.settings().overlay) await this.helper.call("overlay_status", { status }).catch(() => {});
1441
+ const settings = this.settings();
1442
+ if (!this.visible) return;
1443
+ if (settings.hostWindow === "pet") {
1444
+ this.step(status);
1445
+ return;
1446
+ }
1447
+ if (settings.overlay) await this.helper.call("overlay_status", { status }).catch(() => {});
1448
+ }
1449
+ /** One more step on the card's timeline. */
1450
+ step(text) {
1451
+ const line = plainLine(text).trim();
1452
+ if (line === "" || this.steps.at(-1) === line) return;
1453
+ this.steps = [...this.steps, line].slice(-8);
1454
+ this.thinkingLatest = false;
1455
+ this.schedulePush();
1456
+ }
1457
+ /** Live model output (DSH agent/assistant-stream) for the progress card. */
1458
+ stream(agent, frame) {
1459
+ if (agent !== this.streamAgent) {
1460
+ this.streamAgent = agent;
1461
+ this.text = "";
1462
+ this.thinking = "";
1463
+ this.steps = [];
1464
+ }
1465
+ if (frame.type === "start") {
1466
+ this.freshAttempt = true;
1467
+ this.thinking = "";
1468
+ return;
1469
+ }
1470
+ if (this.visible && agent === this.agent) this.armIdle();
1471
+ const chunk = frame.type === "chunk" ? frame.chunk : void 0;
1472
+ if (!chunk) return;
1473
+ if (chunk.type === "text-delta" && chunk.text) {
1474
+ if (this.freshAttempt) {
1475
+ this.text = "";
1476
+ this.freshAttempt = false;
1477
+ }
1478
+ this.text = plainLine(this.text + chunk.text).slice(-2e3);
1479
+ } else if (chunk.type === "reasoning-delta" && chunk.text) {
1480
+ this.thinking = plainLine(this.thinking + chunk.text).slice(-300);
1481
+ this.thinkingLatest = true;
1482
+ } else return;
1483
+ this.schedulePush();
1484
+ }
1485
+ /** A tool of another plugin started (computer-use tools report their own steps). */
1486
+ toolStarted(agent, name, detail) {
1487
+ if (agent !== this.streamAgent) return;
1488
+ if (this.visible && agent === this.agent) this.armIdle();
1489
+ this.step(`${TOOL_NAMES[name] ?? name}${detail ? `:${detail}` : ""}`);
1490
+ }
1491
+ schedulePush() {
1492
+ if (!this.visible || this.settings().hostWindow !== "pet" || this.agent !== this.streamAgent || this.pushTimer) return;
1493
+ this.pushTimer = setTimeout(() => {
1494
+ this.pushTimer = void 0;
1495
+ if (!this.visible) return;
1496
+ this.helper.call("pet_update", {
1497
+ text: this.text,
1498
+ thinking: this.thinking.trim(),
1499
+ steps: this.steps,
1500
+ thinkingLatest: this.thinkingLatest
1501
+ }).catch(() => {});
1502
+ }, 80);
1503
+ this.pushTimer.unref?.();
1344
1504
  }
1345
1505
  /** Agent finished (idle), was cancelled, or the plugin is stopping. */
1346
1506
  async end(agent) {
@@ -1351,7 +1511,15 @@ var OverlayController = class {
1351
1511
  this.paused = false;
1352
1512
  if (!this.visible) return;
1353
1513
  this.visible = false;
1354
- await this.helper.call("overlay_hide").catch(() => {});
1514
+ if (this.pushTimer) {
1515
+ clearTimeout(this.pushTimer);
1516
+ this.pushTimer = void 0;
1517
+ }
1518
+ if (this.settings().hostWindow === "pet" && !this.stopping) await this.helper.call("pet_finish", {
1519
+ text: this.text,
1520
+ holdMs: FINISH_HOLD_MS
1521
+ }).catch(() => {});
1522
+ else await this.helper.call("overlay_hide").catch(() => {});
1355
1523
  await this.restoreHost();
1356
1524
  }
1357
1525
  stop(reason) {
@@ -1381,7 +1549,7 @@ var OverlayController = class {
1381
1549
  try {
1382
1550
  const rows = (await this.helper.call("windows")).filter((row) => isHostWindow(row) && !row.minimized);
1383
1551
  if (rows.length === 0) return;
1384
- if (mode === "minimize") {
1552
+ if (mode === "minimize" || mode === "pet") {
1385
1553
  for (const row of rows) await this.helper.call("window_cmd", {
1386
1554
  hwnd: row.hwnd,
1387
1555
  op: "minimize"
@@ -1398,8 +1566,10 @@ var OverlayController = class {
1398
1566
  const cy = main.y + main.height / 2;
1399
1567
  const display = displays.find((d) => cx >= d.x && cx < d.x + d.width && cy >= d.y && cy < d.y + d.height) ?? displays.find((d) => d.primary) ?? displays[0];
1400
1568
  if (!display) return;
1569
+ this.cardOpacity = this.settings().cardOpacity;
1401
1570
  await this.helper.call("window_card", {
1402
1571
  hwnd: main.hwnd,
1572
+ opacity: this.cardOpacity,
1403
1573
  ...cardRect(display)
1404
1574
  });
1405
1575
  this.hostWindows = [{
@@ -1410,6 +1580,21 @@ var OverlayController = class {
1410
1580
  this.log(`host window ${mode}: ${String(error)}`);
1411
1581
  }
1412
1582
  }
1583
+ /**
1584
+ * Pet mode minimizes DeepSeek Harness; if the user opens it again while the
1585
+ * agent works, it floats as the see-through card instead of covering the
1586
+ * screen (the agent neither sees nor clicks it).
1587
+ */
1588
+ async cardIfShown() {
1589
+ try {
1590
+ if ((await this.helper.call("windows")).filter((row) => isHostWindow(row) && !row.minimized).length === 0) return;
1591
+ const before = this.hostWindows;
1592
+ await this.shrinkHost("card");
1593
+ this.hostWindows = [...this.hostWindows, ...before.filter((win) => !this.hostWindows.some((card) => card.hwnd === win.hwnd))];
1594
+ } catch (error) {
1595
+ this.log(`host window card: ${String(error)}`);
1596
+ }
1597
+ }
1413
1598
  async restoreHost() {
1414
1599
  const windows = this.hostWindows;
1415
1600
  this.hostWindows = [];
@@ -1433,13 +1618,14 @@ function promptText(mode) {
1433
1618
  return `# Computer use (Windows desktop)
1434
1619
  You can see and operate the user's Windows computer with the computer, computer_batch, open_application, windows, ui_elements and clipboard tools.
1435
1620
  ${mode === "per-app" ? "- Before acting on an app, call request_access once with every app the task needs; the user approves it. Input to apps that are not granted is refused.\n" : ""}- Start with a screenshot (computer action "screenshot") unless you just received one. All coordinates are pixels of the latest screenshot; the plugin converts them for DPI and scaling.
1436
- - Open or switch apps with open_application (by name; it also finds desktop shortcuts) rather than hunting through the taskbar or Start menu or starting GUI apps from a shell. Use windows to see which windows exist; each line shows the process .exe.
1621
+ - Open or switch apps with open_application (by name; it also finds desktop shortcuts) rather than hunting through the taskbar or Start menu or starting GUI apps from a shell. Use windows to see which windows exist; each line shows the process .exe. Apps closed to the system tray (QQ, 微信...) are still running: open_application restores them from their tray icon. Do not start a second copy of a running app unless the user explicitly asks for one (then pass new_instance: true), and never show or kill its hidden windows from a shell (Electron / Qt apps freeze, and a second QQ / WeChat asks for another login).
1622
+ - When the task is done, tidy up: close windows and dialogs you opened that the user no longer needs (keep the one showing the result they asked for), and call windows tidy to minimize again the apps that were minimized or in the tray before you started. Never close windows the user already had open.
1437
1623
  - 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.
1438
1624
  - 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.
1439
1625
  - 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).
1440
1626
  - 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.
1441
1627
  - 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.
1442
- - Office apps: F12 opens the classic Save As dialog, where you can type a full path in the file name box.
1628
+ - 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.
1443
1629
  - Be efficient: every tool call costs the user several seconds. Put predictable sequences (click a field, type, press Return; open a menu and pick an item you can already see) into one computer_batch. Avoid shell commands for things you can see on screen.
1444
1630
  - To see more of a page or list, scroll (action "scroll" with coordinate over the area, scroll_direction, scroll_amount 5-10) instead of hunting with zoom; for long web pages Page Down / End keys also work.
1445
1631
  - If a dedicated tool fits the whole task better (an API, or browser automation attached to the user's own browser), choose it at the start; do not switch tools halfway through a task that is going fine on screen.
@@ -1454,7 +1640,8 @@ const DEFAULTS = {
1454
1640
  accessMode: "per-app",
1455
1641
  overlay: true,
1456
1642
  overlayLabel: "DeepSeek Harness",
1457
- hostWindow: "card",
1643
+ hostWindow: "pet",
1644
+ cardOpacity: 80,
1458
1645
  autoScreenshot: true,
1459
1646
  settleMs: 400,
1460
1647
  maxLongEdge: 1366,
@@ -1478,7 +1665,8 @@ function resolveConfig(raw) {
1478
1665
  accessMode: out.accessMode === "allow-all" || out.accessMode === "per-app" ? out.accessMode : DEFAULTS.accessMode,
1479
1666
  overlay: bool("overlay"),
1480
1667
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
1481
- hostWindow: out.hostWindow === "card" || out.hostWindow === "minimize" || out.hostWindow === "keep" ? out.hostWindow : out.minimizeHostWindow === true ? "minimize" : DEFAULTS.hostWindow,
1668
+ hostWindow: out.hostWindow === "pet" || out.hostWindow === "card" || out.hostWindow === "minimize" || out.hostWindow === "keep" ? out.hostWindow : out.minimizeHostWindow === true ? "minimize" : DEFAULTS.hostWindow,
1669
+ cardOpacity: num("cardOpacity", 30, 100),
1482
1670
  autoScreenshot: bool("autoScreenshot"),
1483
1671
  settleMs: num("settleMs", 0, 5e3),
1484
1672
  maxLongEdge: num("maxLongEdge", 640, 3840),
@@ -2501,7 +2689,7 @@ function deepFreeze(value) {
2501
2689
  * Random v4 UUID, minted from `crypto.getRandomValues`.
2502
2690
  * @returns the UUID string.
2503
2691
  */
2504
- function randomUUID() {
2692
+ function randomUUID$1() {
2505
2693
  const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
2506
2694
  const hex = Array.from(bytes, (byte, index) => {
2507
2695
  return (index === 6 ? byte & 15 | 64 : index === 8 ? byte & 63 | 128 : byte).toString(16).padStart(2, "0");
@@ -2553,7 +2741,7 @@ function freezeMessage(message) {
2553
2741
  function createMessage(input) {
2554
2742
  return deepFreeze(structuredClone({
2555
2743
  ...input,
2556
- id: brandString(randomUUID())
2744
+ id: brandString(randomUUID$1())
2557
2745
  }));
2558
2746
  }
2559
2747
  /**
@@ -7473,6 +7661,12 @@ function attachmentSchema() {
7473
7661
  }
7474
7662
  };
7475
7663
  }
7664
+ /** windows list notes about the layout before the task. */
7665
+ const ORIGIN = {
7666
+ opened: " | opened during this task",
7667
+ minimized: " | was minimized before this task",
7668
+ tray: " | was in the system tray before this task"
7669
+ };
7476
7670
  const output = {
7477
7671
  schema: {
7478
7672
  type: "object",
@@ -7666,22 +7860,29 @@ function createTools(host) {
7666
7860
  tools.push(defineTool({
7667
7861
  name: "open_application",
7668
7862
  description: "Open an app by name (e.g. \"Chrome\", \"记事本\", \"微信\", \"Excel\"), an .exe path, or a URL, or bring it to the front if it is already running. Faster and more reliable than clicking the taskbar or Start menu. Returns a screenshot.",
7669
- parameters: { name: {
7670
- type: "string",
7671
- required: true,
7672
- description: "App name as shown in the Start menu, an executable path, or an http(s) URL."
7673
- } },
7863
+ parameters: {
7864
+ name: {
7865
+ type: "string",
7866
+ required: true,
7867
+ description: "App name as shown in the Start menu, an executable path, or an http(s) URL."
7868
+ },
7869
+ new_instance: {
7870
+ type: "boolean",
7871
+ description: "Start another copy even though the app is already running. Only when the user explicitly asks for a second window / instance / account."
7872
+ }
7873
+ },
7674
7874
  output,
7675
7875
  timeoutMs: 18e5,
7676
7876
  async execute(args, exec) {
7677
7877
  const call = await host.context(exec);
7678
7878
  const name = String(args.name ?? "").trim();
7879
+ const newInstance = args.new_instance === true;
7679
7880
  if (name === "") throw new Error("name is required.");
7680
7881
  const settings = computer.settings();
7681
7882
  const isUrl = /^https?:\/\//i.test(name);
7682
7883
  const appName = /^ms-settings:/i.test(name) ? "设置" : name;
7683
7884
  if (settings.accessMode === "per-app" && !isUrl && computer.access.missing(call.session, [appName]).length > 0) {
7684
- const running = (await computer.windows()).find((win) => appMatches(appName, win));
7885
+ const running = (await computer.windows()).find((win) => appMatches(appName, win)) ?? (await computer.backgroundApps()).find((win) => appMatches(appName, win));
7685
7886
  if (!running || !computer.access.isGranted(call.session, running)) throw new Error(`"${appName}" is not granted for this session. Call request_access with ["${appName}"] first.`);
7686
7887
  }
7687
7888
  await computer.overlay.begin(call.agent, `打开 ${name}`);
@@ -7689,9 +7890,14 @@ function createTools(host) {
7689
7890
  const before = await computer.foreground();
7690
7891
  let how;
7691
7892
  const isUri = isUrl || /^[a-z][a-z0-9+.-]+:(?![\/])/i.test(name);
7692
- const running = isUri ? void 0 : (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
7893
+ const running = isUri || newInstance ? void 0 : (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
7894
+ const hidden = running || isUri || newInstance ? void 0 : (await computer.backgroundApps()).find((win) => !isHostWindow(win) && appMatches(name, win));
7693
7895
  if (running) how = (await computer.focus(running)).focused ? `Brought ${running.exe} ("${running.title.slice(0, 60)}") to the front.` : `Tried to bring ${running.exe} to the front, but Windows kept another window focused.`;
7694
- else {
7896
+ else if (hidden) {
7897
+ const restored = await computer.helper.call("tray_restore", { exe: hidden.exe }, 2e4);
7898
+ if (restored.window) computer.noteFromTray(restored.window.hwnd);
7899
+ how = restored.window ? `${hidden.exe} was already running in the system tray: restored its window from the tray icon (no second instance started).` : `${hidden.exe} is already running in the background${restored.icon ? " (system tray)" : ""}, but its window did not come back automatically. Open it from its notification-area icon (click ^ "show hidden icons" on the taskbar first). Do not launch it again (that starts a second instance and login), and never force its hidden window visible from a shell (Electron / Qt apps freeze).`;
7900
+ } else {
7695
7901
  const app = (isUri ? [] : await computer.helper.call("apps", {
7696
7902
  query: name,
7697
7903
  limit: 5
@@ -7713,6 +7919,23 @@ function createTools(host) {
7713
7919
  },
7714
7920
  presentCall: (args) => card(`打开应用 · ${args.name ?? ""}`)
7715
7921
  }));
7922
+ /** Put back what the task changed: re-minimize restored windows, report the ones it opened. */
7923
+ async function tidy(call) {
7924
+ await computer.overlay.begin(call.agent, "整理窗口");
7925
+ const rows = (await computer.windows()).filter((win) => !isHostWindow(win));
7926
+ const minimized = [];
7927
+ for (const win of rows) {
7928
+ const origin = computer.origin(win);
7929
+ if (origin !== "minimized" && origin !== "tray") continue;
7930
+ await computer.helper.call("window_cmd", {
7931
+ hwnd: win.hwnd,
7932
+ op: "minimize"
7933
+ }).catch(() => {});
7934
+ minimized.push(`${win.exe} ("${win.title.slice(0, 40)}")`);
7935
+ }
7936
+ const opened = rows.filter((win) => computer.origin(win) === "opened");
7937
+ return { text: [minimized.length ? `Minimized again (they were minimized or in the tray before): ${minimized.join(", ")}.` : "Nothing to minimize again.", opened.length ? `Opened during this task, still open:\n${opened.map((win) => `hwnd=${win.hwnd} | ${win.exe} | "${win.title.slice(0, 60)}"`).join("\n")}\nClose the ones the user does not need (windows close); keep any that shows the result they asked for.` : "No windows opened during this task are left."].join("\n") };
7938
+ }
7716
7939
  tools.push(defineTool({
7717
7940
  name: "windows",
7718
7941
  description: "List top-level windows (with process .exe names), or focus / minimize / maximize / restore / close one. Use it to find the right window instead of guessing from titles; the \"DeepSeek Harness.exe\" window is your own chat UI.",
@@ -7725,9 +7948,11 @@ function createTools(host) {
7725
7948
  "minimize",
7726
7949
  "maximize",
7727
7950
  "restore",
7728
- "close"
7951
+ "close",
7952
+ "tidy"
7729
7953
  ],
7730
- required: true
7954
+ required: true,
7955
+ description: "tidy: when the task is done, minimize again every window that was minimized or in the system tray before you started, and list the windows you opened."
7731
7956
  },
7732
7957
  hwnd: {
7733
7958
  type: "integer",
@@ -7743,9 +7968,15 @@ function createTools(host) {
7743
7968
  const call = await host.context(exec);
7744
7969
  const { action, hwnd, name } = args;
7745
7970
  const rows = await computer.windows();
7746
- if (action === "list") return { text: (await Promise.all(rows.map(async (win) => `hwnd=${win.hwnd} | ${win.exe} | "${win.title.slice(0, 70)}"${win.foreground ? " | FOREGROUND" : ""}${win.minimized ? " | minimized" : ` | ${await computer.windowBox(win)}`}${isHostWindow(win) ? " | (your own DeepSeek Harness chat window)" : ""}`))).join("\n") || "No windows." };
7971
+ if (action === "list") {
7972
+ const lines = await Promise.all(rows.map(async (win) => `hwnd=${win.hwnd} | ${win.exe} | "${win.title.slice(0, 70)}"${win.foreground ? " | FOREGROUND" : ""}${win.minimized ? " | minimized" : ` | ${await computer.windowBox(win)}`}${isHostWindow(win) ? " | (your own DeepSeek Harness chat window)" : ""}${ORIGIN[computer.origin(win) ?? ""] ?? ""}`));
7973
+ const tray = (await computer.backgroundApps()).filter((win) => win.tray && !isHostWindow(win));
7974
+ if (tray.length > 0) lines.push(`Running in the system tray without a window (open_application restores them; never relaunch them): ${tray.map((win) => `${win.exe} ("${win.title.slice(0, 30)}")`).join(", ")}`);
7975
+ return { text: lines.join("\n") || "No windows." };
7976
+ }
7977
+ if (action === "tidy") return tidy(call);
7747
7978
  const target = hwnd !== void 0 ? rows.find((win) => win.hwnd === hwnd) : name ? rows.find((win) => !isHostWindow(win) && appMatches(name, win)) ?? rows.find((win) => !isHostWindow(win) && win.title.toLowerCase().includes(name.toLowerCase())) ?? rows.find((win) => appMatches(name, win)) : void 0;
7748
- if (!target) throw new Error("Window not found; call windows with action \"list\".");
7979
+ if (!target) throw new Error("Window not found; call windows with action \"list\". An app closed to the system tray has no window: bring it back with open_application.");
7749
7980
  const settings = computer.settings();
7750
7981
  const denial = computer.access.denial(call.session, target, settings.accessMode, settings.blockedApps, action);
7751
7982
  if (denial && action !== "minimize") throw new Error(denial);
@@ -7763,7 +7994,7 @@ function createTools(host) {
7763
7994
  const shot = await computer.after([{ action: "key" }], call);
7764
7995
  return withShot(host, shot ? text : `${text} ${await computer.describeForeground()}`, shot, call);
7765
7996
  },
7766
- presentCall: (args) => card(`窗口 · ${args.action ?? ""}`)
7997
+ presentCall: (args) => card(args.action === "tidy" ? "整理窗口" : `窗口 · ${args.action ?? ""}`)
7767
7998
  }));
7768
7999
  tools.push(defineTool({
7769
8000
  name: "ui_elements",
@@ -7905,6 +8136,12 @@ function createTools(host) {
7905
8136
  }
7906
8137
  //#endregion
7907
8138
  //#region lib/types/index.js
8139
+ /**
8140
+ * @copylee/dsh-computer-use host bundle: Claude-style computer use for the
8141
+ * Windows desktop — screenshots in, mouse and keyboard out, per-app grants
8142
+ * through DSH approvals, and an orange "DeepSeek is using your computer"
8143
+ * overlay that a physical Esc dismisses.
8144
+ */
7908
8145
  const name = "@copylee/dsh-computer-use";
7909
8146
  const inject = ["tools", "attachments"];
7910
8147
  const Config = z.object({
@@ -7927,6 +8164,10 @@ const Config = z.object({
7927
8164
  "en-US": { $description: "Name in the pill: \"<name> 正在操控你的电脑\"" }
7928
8165
  }),
7929
8166
  hostWindow: z.union([
8167
+ z.const("pet").i18n({
8168
+ "zh-CN": { $description: "最小化,改用右下角迷你进度卡片(两行滚动显示回复和思考 / 工具调用)" },
8169
+ "en-US": { $description: "Minimize it and show a mini progress card (reply + thinking / tool calls)" }
8170
+ }),
7930
8171
  z.const("card").i18n({
7931
8172
  "zh-CN": { $description: "缩成右下角置顶悬浮卡片" },
7932
8173
  "en-US": { $description: "Shrink to an always-on-top card" }
@@ -7939,10 +8180,14 @@ const Config = z.object({
7939
8180
  "zh-CN": { $description: "保持不变" },
7940
8181
  "en-US": { $description: "Leave it as is" }
7941
8182
  })
7942
- ]).default("card").volatile().i18n({
8183
+ ]).default("pet").volatile().i18n({
7943
8184
  "zh-CN": { $description: "操控期间 DeepSeek Harness 窗口怎么摆放(结束后自动恢复原尺寸和位置)" },
7944
8185
  "en-US": { $description: "What to do with the DeepSeek Harness window while controlling (restored afterwards)" }
7945
8186
  }),
8187
+ cardOpacity: z.natural().min(30).max(100).default(80).volatile().i18n({
8188
+ "zh-CN": { $description: "悬浮卡片不透明度(%):调低可透过卡片看清下面的操作过程;鼠标停在卡片上时变为不透明" },
8189
+ "en-US": { $description: "Card opacity (%): lower lets you watch the work underneath; it turns opaque while the pointer rests on it" }
8190
+ }),
7946
8191
  typingMode: z.union([
7947
8192
  z.const("stream").i18n({
7948
8193
  "zh-CN": { $description: "流式:长文本按段落逐段粘贴,看得到一段段出现(推荐)" },
@@ -8063,6 +8308,7 @@ function apply(ctx, config = {}) {
8063
8308
  }
8064
8309
  });
8065
8310
  for (const tool of tools) ctx.effect(() => ctx.tools.register(tool), `computer-use: tool ${tool.name}`);
8311
+ const OWN_TOOLS = new Set(tools.map((tool) => tool.name));
8066
8312
  ctx.on("tools/pre-execute", async (exec, next) => {
8067
8313
  if (exec.name !== "request_access" || settings().accessMode !== "per-app") return next();
8068
8314
  const agent = exec.agent;
@@ -8082,6 +8328,39 @@ function apply(ctx, config = {}) {
8082
8328
  }
8083
8329
  };
8084
8330
  });
8331
+ ctx.on("agent/assistant-stream", ({ agent, frame }) => {
8332
+ overlay.stream(agent, frame);
8333
+ });
8334
+ ctx.on("tools/pre-execute", (exec, next) => {
8335
+ if (!OWN_TOOLS.has(exec.name)) {
8336
+ const args = exec.arguments ?? {};
8337
+ const detail = [
8338
+ args.command,
8339
+ args.description,
8340
+ args.query,
8341
+ args.path,
8342
+ args.url
8343
+ ].find((value) => typeof value === "string");
8344
+ overlay.toolStarted(exec.agent, exec.name, (detail ?? "").split("\n")[0].slice(0, 120));
8345
+ }
8346
+ return next();
8347
+ });
8348
+ overlay.onMessage = (agent, text) => {
8349
+ const steer = agent.steer;
8350
+ if (typeof steer !== "function") {
8351
+ log("progress card: this agent cannot take steering");
8352
+ return;
8353
+ }
8354
+ steer.call(agent, Object.freeze({
8355
+ id: randomUUID(),
8356
+ role: "user",
8357
+ content: [{
8358
+ type: "text",
8359
+ text
8360
+ }],
8361
+ source: { kind: "user" }
8362
+ }));
8363
+ };
8085
8364
  ctx.on("agent/status", ({ agent, status }) => {
8086
8365
  if (status === "running") computer.resetLook();
8087
8366
  if (status === "idle" && computer.clipboardAgent === agent) {
@@ -8,6 +8,8 @@ export interface Settings {
8
8
  overlay: boolean;
9
9
  overlayLabel: string;
10
10
  hostWindow: HostWindowMode;
11
+ /** Card opacity in percent while controlling (it turns opaque when the pointer rests on it). */
12
+ cardOpacity: number;
11
13
  maxLongEdge: number;
12
14
  maxPixels: number;
13
15
  jpegQuality: number;
@@ -125,6 +127,18 @@ export declare class Computer {
125
127
  settle(signal: AbortSignal): Promise<void>;
126
128
  windowAt(point: Point): Promise<WindowInfo | undefined>;
127
129
  windows(): Promise<WindowInfo[]>;
130
+ /** Windows when control started (hwnd -> minimized), and windows brought back from the tray since. */
131
+ private before;
132
+ private readonly fromTray;
133
+ /** Remember the window layout at the start of a task, to tell what the agent opened or restored. */
134
+ noteStart(): Promise<void>;
135
+ noteFromTray(hwnd: number): void;
136
+ /** How a window relates to the layout before the task: opened by the agent, or restored from minimized / tray. */
137
+ origin(win: WindowInfo): 'opened' | 'minimized' | 'tray' | undefined;
138
+ /** Programs running without any visible window (closed to the system tray); `tray` = has a tray icon. */
139
+ backgroundApps(): Promise<Array<WindowInfo & {
140
+ tray: boolean;
141
+ }>>;
128
142
  cursor(): Promise<Point>;
129
143
  /** Short description of the frontmost window, for result text. */
130
144
  describeForeground(): Promise<string>;
@@ -1,9 +1,3 @@
1
- /**
2
- * @copylee/dsh-computer-use host bundle: Claude-style computer use for the
3
- * Windows desktop — screenshots in, mouse and keyboard out, per-app grants
4
- * through DSH approvals, and an orange "DeepSeek is using your computer"
5
- * overlay that a physical Esc dismisses.
6
- */
7
1
  import type { Context } from '@deepseek-ai/cordis';
8
2
  import z from '@deepseek-ai/schemastery';
9
3
  import { type AccessMode } from './access.js';
@@ -17,6 +11,7 @@ export interface Config {
17
11
  overlay?: boolean;
18
12
  overlayLabel?: string;
19
13
  hostWindow?: HostWindowMode;
14
+ cardOpacity?: number;
20
15
  /** @deprecated replaced by hostWindow: 'minimize' */
21
16
  minimizeHostWindow?: boolean;
22
17
  autoScreenshot?: boolean;