@copylee/dsh-computer-use 0.5.2 → 0.6.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
@@ -13,6 +13,9 @@
13
13
  | 截图即坐标系 | 模型只用最近一张截图的像素坐标,DPI、缩放、多显示器偏移全部由插件换算,高分屏(200% 缩放)也点得准 |
14
14
  | 动作后自动回传截图 | 点击 / 输入 / 按键 / 滚动后,**等画面不再变化**(页面加载、动画结束,最多约 2.5 秒)再截图;`wait` 也直接带回截图,“等一下再看”只需一步,而且画面一静止就提前结束,不会死等满时长;画面与上一张截图完全相同时不再发图,只告诉模型“没有可见变化”,省 token |
15
15
  | 批量动作 | `computer_batch` 一次执行“点输入框 → 输入 → 回车”等多步,最后只截一张图 |
16
+ | 按名称点控件 | 动作里用 `target`(控件的可见名称,如 `"保存"`、`"按钮:确定"`)代替坐标。上一张截图里还没出现的控件也能点,比如上一步才打开的菜单项、才弹出的对话框按钮;最多等 3 秒它出现。重名时不猜,直接把候选和坐标告诉模型 |
17
+ | 等条件而不是等时间 | `wait` 加 `until`(`"window:另存为"`、`"target:保存"`):窗口或控件一出现(或一消失)就继续,超时才报错。配合 `target`,“按 Ctrl+S → 等另存为 → 填文件名 → 点保存”可以写进同一个批量调用 |
18
+ | 把窗口读成文本 | `ui_elements` 加 `text: true` 直接读出文档、网页、聊天回复或日志的文字(默认取末尾 4000 字),比滚动加放大截图快,也能逐字引用;批量调用加 `finish: "text"` 可以用文字代替结尾的截图 |
16
19
  | 按应用授权 | 先 `request_access` 列出要操控的应用,经 DSH 原生审批后才能操作;也可改为“全部允许” |
17
20
  | 不会操作自己 | 永远拒绝向 DeepSeek Harness 自身窗口输入;常见密码管理器默认禁止,可再自定义禁用列表 |
18
21
  | 正在控制的提示 | 橙色光晕 + 胶囊提示条(显示当前动作),**不会出现在截图里** |
@@ -58,11 +61,11 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
58
61
  | 工具 | 作用 |
59
62
  |---|---|
60
63
  | `computer` | 单个动作:`screenshot` `left_click` `double_click` `triple_click` `right_click` `middle_click` `mouse_move` `left_click_drag` `left_mouse_down/up` `scroll` `type` `key` `hold_key` `wait` `zoom` `cursor_position`(沿用通用 computer-use 动作命名,模型上手即会) |
61
- | `computer_batch` | 顺序执行多个动作,遇错即停,最后回传一张截图 |
64
+ | `computer_batch` | 顺序执行多个动作,遇错即停,最后回传一张截图;最后一步可以是 `zoom`(回传放大区域),`finish` 可选 `screenshot` / `text` / `none` |
62
65
  | `app_skill` | 应用技能:`list` 列出、`read` 读取、`append` 追加、`write` 重写某个应用的操作笔记(单份上限 4000 字) |
63
66
  | `open_application` | 按名称(“Chrome”“记事本”“微信”)、exe 路径或网址打开应用;已运行则切到前台,在托盘里则从托盘图标恢复 |
64
67
  | `windows` | 列出窗口(含进程 exe 名)、聚焦 / 最小化 / 最大化 / 还原 / 关闭 |
65
- | `ui_elements` | 前台窗口的 UI Automation 元素列表,坐标已换算到截图坐标系 |
68
+ | `ui_elements` | 前台窗口(含已打开的菜单)的 UI Automation 元素列表,坐标已换算到截图坐标系;`text: true` 改为读出窗口的文字内容 |
66
69
  | `clipboard` | 读 / 写剪贴板文本 |
67
70
  | `switch_display` | 多显示器时切换截图所在屏幕 |
68
71
  | `request_access` / `list_granted_applications` | 按应用授权 |
@@ -202,6 +202,7 @@ namespace DshComputerUse
202
202
  var input = new StreamReader(Console.OpenStandardInput(), utf8);
203
203
  var parser = new JavaScriptSerializer();
204
204
  parser.MaxJsonLength = int.MaxValue;
205
+ Apps.Warm();
205
206
 
206
207
  var hello = new Dictionary<string, object>();
207
208
  hello["event"] = "ready"; hello["version"] = Version; hello["pid"] = Process.GetCurrentProcess().Id;
@@ -280,7 +281,7 @@ namespace DshComputerUse
280
281
  case "clipboard_release": Clip.Release(); return null;
281
282
  case "paste": return Input.Paste(Args.Str(r, "text", ""), Args.Bool(r, "restore", true), Args.Int(r, "waitMs", 250));
282
283
  case "windows": return Windows.List();
283
- case "background": return Windows.Background();
284
+ case "background": return Windows.Background(Args.Bool(r, "tray", true));
284
285
  case "tray_restore": return Tray.Restore(Args.Str(r, "exe", ""));
285
286
  case "card_opacity": CardLayer.SetOpacity(Args.Int(r, "opacity", 100)); return null;
286
287
  case "foreground": return Windows.Describe(Native.GetForegroundWindow());
@@ -293,6 +294,7 @@ namespace DshComputerUse
293
294
  case "clipboard_set": if (Args.Bool(r, "agent", false)) Clip.AgentSet(Args.Str(r, "text", "")); else Clip.Set(Args.Str(r, "text", ""), false); return null;
294
295
  case "clipboard_restore": { var d = new Dictionary<string, object>(); d["restored"] = Clip.RestoreAgent(); return d; }
295
296
  case "ui": return Uia.Elements(r);
297
+ case "text": return Uia.Text(r);
296
298
  case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
297
299
  case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
298
300
  case "window_card": CardLayer.SetOpacity(Args.Int(r, "opacity", 100)); return Windows.Card(new IntPtr(Convert.ToInt64(r["hwnd"])), Args.Int(r, "x", 0), Args.Int(r, "y", 0), Args.Int(r, "width", 0), Args.Int(r, "height", 0));
@@ -1240,7 +1242,7 @@ namespace DshComputerUse
1240
1242
  * Apps that run without any visible window (closed to the system tray):
1241
1243
  * per program, its largest hidden, titled, unowned top-level window.
1242
1244
  */
1243
- public static List<object> Background()
1245
+ public static List<object> Background(bool withTray)
1244
1246
  {
1245
1247
  uint self = (uint)Process.GetCurrentProcess().Id;
1246
1248
  var visible = new HashSet<uint>();
@@ -1284,6 +1286,8 @@ namespace DshComputerUse
1284
1286
  if (byExe.TryGetValue(exe, out prev) && Convert.ToInt32(prev["width"]) * Convert.ToInt32(prev["height"]) >= pair.Value.Value) continue;
1285
1287
  byExe[exe] = d;
1286
1288
  }
1289
+ // Looking through the notification area takes a second or more; skip it when only the list matters.
1290
+ if (!withTray) return new List<object>(byExe.Values);
1287
1291
  var owners = Tray.WindowsByPid();
1288
1292
  var exeOf = new Dictionary<uint, string>();
1289
1293
  foreach (var pid in owners.Keys) exeOf[pid] = Path.GetFileName(ExePath(pid));
@@ -1596,10 +1600,28 @@ namespace DshComputerUse
1596
1600
  {
1597
1601
  static List<KeyValuePair<string, string>> cache;
1598
1602
  static DateTime cachedAt;
1603
+ static readonly object Gate = new object();
1604
+
1605
+ /// <summary>
1606
+ /// Listing the Start menu takes about two seconds the first time. Do it
1607
+ /// while the model is still thinking, not inside its first open_application.
1608
+ /// </summary>
1609
+ public static void Warm()
1610
+ {
1611
+ var worker = new Thread(delegate () { try { Windows.List(); } catch (Exception) { } try { All(); } catch (Exception) { } });
1612
+ worker.IsBackground = true;
1613
+ worker.SetApartmentState(ApartmentState.STA);
1614
+ worker.Start();
1615
+ }
1599
1616
 
1600
1617
  static List<KeyValuePair<string, string>> All()
1601
1618
  {
1602
- if (cache != null && (DateTime.UtcNow - cachedAt).TotalSeconds < 120) return cache;
1619
+ lock (Gate) { return Load(); }
1620
+ }
1621
+
1622
+ static List<KeyValuePair<string, string>> Load()
1623
+ {
1624
+ if (cache != null && (DateTime.UtcNow - cachedAt).TotalSeconds < 600) return cache;
1603
1625
  var list = new List<KeyValuePair<string, string>>();
1604
1626
  Type t = Type.GetTypeFromProgID("Shell.Application");
1605
1627
  dynamic shell = Activator.CreateInstance(t);
@@ -1678,13 +1700,25 @@ namespace DshComputerUse
1678
1700
  IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
1679
1701
  int max = Args.Int(r, "maxNodes", 150);
1680
1702
  bool all = Args.Bool(r, "includeText", false);
1703
+ bool popups = Args.Bool(r, "popups", false);
1704
+ bool popupsOnly = Args.Bool(r, "popupsOnly", false);
1681
1705
  List<object> result = null; Exception error = null;
1682
1706
  var worker = new Thread(delegate ()
1683
1707
  {
1684
1708
  try
1685
1709
  {
1686
- result = Collect(hwnd, max, all);
1687
- if (result.Count < 4) { Thread.Sleep(400); result = Collect(hwnd, max, all); } // Chromium builds its tree lazily
1710
+ if (popupsOnly) result = new List<object>();
1711
+ else
1712
+ {
1713
+ result = Collect(hwnd, max, all);
1714
+ if (result.Count < 4) { Thread.Sleep(400); result = Collect(hwnd, max, all); } // Chromium builds its tree lazily
1715
+ }
1716
+ // An open menu or flyout is a window of its own, not a descendant of the one it belongs to.
1717
+ if (popups || popupsOnly) foreach (var extra in Popups(hwnd))
1718
+ {
1719
+ if (result.Count >= max) break;
1720
+ try { result.AddRange(Collect(extra, max - result.Count, all)); } catch (Exception) { }
1721
+ }
1688
1722
  }
1689
1723
  catch (Exception ex) { error = ex; }
1690
1724
  });
@@ -1698,6 +1732,117 @@ namespace DshComputerUse
1698
1732
  return d;
1699
1733
  }
1700
1734
 
1735
+ /// <summary>Other visible top-level windows of the same process: menus, flyouts, dropdown lists.</summary>
1736
+ static List<IntPtr> Popups(IntPtr hwnd)
1737
+ {
1738
+ var list = new List<IntPtr>();
1739
+ uint owner; Native.GetWindowThreadProcessId(hwnd, out owner);
1740
+ Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
1741
+ {
1742
+ if (h == hwnd || !Native.IsWindowVisible(h) || Native.IsIconic(h)) return true;
1743
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
1744
+ if (pid == owner && list.Count < 6) list.Add(h);
1745
+ return true;
1746
+ };
1747
+ Native.EnumWindows(cb, IntPtr.Zero);
1748
+ GC.KeepAlive(cb);
1749
+ return list;
1750
+ }
1751
+
1752
+ /// <summary>
1753
+ /// What a window says, as text: the document or edit control's own text
1754
+ /// when it offers one, else its value, else the visible labels in order.
1755
+ /// </summary>
1756
+ public static object Text(Dictionary<string, object> r)
1757
+ {
1758
+ IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
1759
+ int tail = Math.Max(200, Math.Min(20000, Args.Int(r, "tail", 4000)));
1760
+ string text = ""; string source = "none"; Exception error = null;
1761
+ var worker = new Thread(delegate ()
1762
+ {
1763
+ try { text = Read(hwnd, out source); }
1764
+ catch (Exception ex) { error = ex; }
1765
+ });
1766
+ worker.IsBackground = true;
1767
+ worker.SetApartmentState(ApartmentState.MTA);
1768
+ worker.Start();
1769
+ if (!worker.Join(Args.Int(r, "timeoutMs", 8000))) throw new Exception("UI Automation timed out on this window");
1770
+ if (error != null) throw error;
1771
+ var d = Windows.Describe(hwnd);
1772
+ d["length"] = text.Length;
1773
+ d["truncated"] = text.Length > tail;
1774
+ d["text"] = text.Length > tail ? text.Substring(text.Length - tail) : text;
1775
+ d["source"] = source;
1776
+ return d;
1777
+ }
1778
+
1779
+ const int ReadLimit = 200000;
1780
+
1781
+ static string Read(IntPtr hwnd, out string source)
1782
+ {
1783
+ var root = AutomationElement.FromHandle(hwnd);
1784
+ var visible = new PropertyCondition(AutomationElement.IsOffscreenProperty, false);
1785
+
1786
+ // 1. The largest element with a text pattern: an editor's document, a browser's page.
1787
+ var withText = root.FindAll(TreeScope.Subtree, new AndCondition(visible, new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true)));
1788
+ string best = ""; double bestArea = -1;
1789
+ int looked = 0;
1790
+ foreach (AutomationElement el in withText)
1791
+ {
1792
+ if (++looked > 40) break;
1793
+ try
1794
+ {
1795
+ var rect = el.Current.BoundingRectangle;
1796
+ double area = rect.IsEmpty ? 0 : rect.Width * rect.Height;
1797
+ if (area <= bestArea) continue;
1798
+ object pattern;
1799
+ if (!el.TryGetCurrentPattern(TextPattern.Pattern, out pattern)) continue;
1800
+ string got = ((TextPattern)pattern).DocumentRange.GetText(ReadLimit);
1801
+ if (got == null || got.Trim().Length == 0) continue;
1802
+ best = got; bestArea = area;
1803
+ }
1804
+ catch (Exception) { }
1805
+ }
1806
+ if (best.Length > 0) { source = "text"; return best; }
1807
+
1808
+ // 2. The longest value of an edit or document control.
1809
+ var withValue = root.FindAll(TreeScope.Subtree, new AndCondition(visible, new PropertyCondition(AutomationElement.IsValuePatternAvailableProperty, true)));
1810
+ looked = 0;
1811
+ foreach (AutomationElement el in withValue)
1812
+ {
1813
+ if (++looked > 200) break;
1814
+ try
1815
+ {
1816
+ object pattern;
1817
+ if (!el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern)) continue;
1818
+ string got = ((ValuePattern)pattern).Current.Value;
1819
+ if (got != null && got.Length > best.Length) best = got;
1820
+ }
1821
+ catch (Exception) { }
1822
+ }
1823
+ if (best.Trim().Length > 0) { source = "value"; return best.Length > ReadLimit ? best.Substring(best.Length - ReadLimit) : best; }
1824
+
1825
+ // 3. Whatever labels are showing, in tree (reading) order.
1826
+ var cache = new CacheRequest();
1827
+ cache.Add(AutomationElement.NameProperty);
1828
+ cache.AutomationElementMode = AutomationElementMode.None;
1829
+ cache.TreeScope = TreeScope.Element;
1830
+ AutomationElementCollection labels;
1831
+ using (cache.Activate()) { labels = root.FindAll(TreeScope.Descendants, visible); }
1832
+ var sb = new StringBuilder();
1833
+ string last = null;
1834
+ foreach (AutomationElement el in labels)
1835
+ {
1836
+ string name = el.GetCachedPropertyValue(AutomationElement.NameProperty) as string;
1837
+ if (string.IsNullOrEmpty(name) || name == last) continue;
1838
+ last = name;
1839
+ sb.Append(name).Append('\n');
1840
+ if (sb.Length > ReadLimit) break;
1841
+ }
1842
+ source = sb.Length > 0 ? "labels" : "none";
1843
+ return sb.ToString();
1844
+ }
1845
+
1701
1846
  static List<object> Collect(IntPtr hwnd, int max, bool includeText)
1702
1847
  {
1703
1848
  var root = AutomationElement.FromHandle(hwnd);
package/lib/client.js CHANGED
@@ -1073,7 +1073,7 @@ window.__ModuleLoader__.load({
1073
1073
  onClick: () => {
1074
1074
  refreshStatus();
1075
1075
  }
1076
- }, "刷新状态"), h("span", { style: S.hint }, "预览会显示 3 秒光晕和提示条(按已保存的设置)。"))), h("section", { style: S.card }, h("h3", { style: S.cardTitle }, "授权"), h("div", { style: S.label }, "授权方式", h(Select, {
1076
+ }, "刷新状态"), h("span", { style: S.hint }, "预览 4 秒:按已保存的设置显示光晕,以及迷你进度卡片或提示条。"))), h("section", { style: S.card }, h("h3", { style: S.cardTitle }, "授权"), h("div", { style: S.label }, "授权方式", h(Select, {
1077
1077
  label: "授权方式",
1078
1078
  disabled,
1079
1079
  value: draft.accessMode,
package/lib/index.js CHANGED
@@ -249,7 +249,7 @@ function regionToPhysical(region, display, shot) {
249
249
  };
250
250
  }
251
251
  /** Is a physical point on this display? */
252
- function contains(display, point) {
252
+ function contains$1(display, point) {
253
253
  return point.x >= display.x && point.y >= display.y && point.x < display.x + display.width && point.y < display.y + display.height;
254
254
  }
255
255
  //#endregion
@@ -446,6 +446,134 @@ function parseModifiers(text) {
446
446
  return parseKeys(text.replace(/\s+/g, "")).flat();
447
447
  }
448
448
  //#endregion
449
+ //#region lib/types/target.js
450
+ /**
451
+ * Finding a control by what it says instead of where it is. A batch can then
452
+ * act on things that were not on screen in the model's last screenshot (the
453
+ * item of a menu it is about to open, the button of a dialog about to appear),
454
+ * which is what lets one call cover a whole sequence.
455
+ */
456
+ /** Words a model may put before the colon, and the control types they stand for. */
457
+ const ROLES = {
458
+ button: ["Button", "SplitButton"],
459
+ 按钮: ["Button", "SplitButton"],
460
+ menu: ["MenuItem", "Menu"],
461
+ menuitem: ["MenuItem"],
462
+ 菜单: ["MenuItem", "Menu"],
463
+ 菜单项: ["MenuItem"],
464
+ edit: ["Edit", "Document"],
465
+ input: ["Edit", "Document"],
466
+ textbox: ["Edit", "Document"],
467
+ 输入框: ["Edit", "Document"],
468
+ 文本框: ["Edit", "Document"],
469
+ tab: ["TabItem"],
470
+ 标签: ["TabItem"],
471
+ 标签页: ["TabItem"],
472
+ 选项卡: ["TabItem"],
473
+ link: ["Hyperlink"],
474
+ 链接: ["Hyperlink"],
475
+ checkbox: ["CheckBox"],
476
+ 复选框: ["CheckBox"],
477
+ radio: ["RadioButton"],
478
+ 单选: ["RadioButton"],
479
+ 单选框: ["RadioButton"],
480
+ combo: ["ComboBox"],
481
+ combobox: ["ComboBox"],
482
+ 下拉框: ["ComboBox"],
483
+ item: [
484
+ "ListItem",
485
+ "TreeItem",
486
+ "DataItem"
487
+ ],
488
+ listitem: ["ListItem"],
489
+ 列表项: ["ListItem", "DataItem"],
490
+ treeitem: ["TreeItem"],
491
+ text: ["Text"],
492
+ 文本: ["Text"],
493
+ 文字: ["Text"]
494
+ };
495
+ /** "按钮:保存" → Button named 保存; a colon that is not after a known role stays part of the name. */
496
+ function parseTarget(target) {
497
+ const text = target.trim();
498
+ const colon = text.search(/[::]/);
499
+ if (colon > 0) {
500
+ const roles = ROLES[text.slice(0, colon).trim().toLowerCase().replace(/[\s_-]/g, "")];
501
+ const name = text.slice(colon + 1).trim();
502
+ if (roles && name !== "") return {
503
+ role: roles[0],
504
+ roles,
505
+ name
506
+ };
507
+ }
508
+ return { name: text };
509
+ }
510
+ /**
511
+ * Names as people read them: without the accelerator ("保存(S)", "&File"),
512
+ * the trailing ellipsis of commands that open a dialog, and case.
513
+ */
514
+ function normalizeName(name) {
515
+ return name.replace(/\s*[((]&?[A-Za-z0-9][))]/g, "").replace(/&(?=\S)/g, "").replace(/(\.{3}|…)\s*$/, "").replace(/\s+/g, " ").trim().toLowerCase();
516
+ }
517
+ const center = (el) => `${Math.round(el.x + el.width / 2)},${Math.round(el.y + el.height / 2)}`;
518
+ /**
519
+ * Pick the element a target means. An exact name beats a name that starts with
520
+ * the text, which beats one that merely contains it; within the best tier,
521
+ * enabled controls beat disabled ones and real controls beat static text.
522
+ * Several different places left after that is an ambiguity, not a guess.
523
+ */
524
+ function matchTarget(elements, target) {
525
+ const query = parseTarget(target);
526
+ const wanted = normalizeName(query.name);
527
+ if (wanted === "") return {
528
+ kind: "missing",
529
+ suggestions: []
530
+ };
531
+ const pool = query.roles ? elements.filter((el) => query.roles.includes(el.role)) : elements;
532
+ const tiers = [
533
+ [],
534
+ [],
535
+ []
536
+ ];
537
+ for (const el of pool) {
538
+ const name = normalizeName(el.name);
539
+ if (name === "") continue;
540
+ if (name === wanted) tiers[0].push(el);
541
+ else if (name.startsWith(wanted)) tiers[1].push(el);
542
+ else if (name.includes(wanted)) tiers[2].push(el);
543
+ }
544
+ let best = tiers.find((tier) => tier.length > 0);
545
+ if (!best) return {
546
+ kind: "missing",
547
+ suggestions: suggest(elements, wanted)
548
+ };
549
+ const enabled = best.filter((el) => !el.disabled);
550
+ if (enabled.length > 0) best = enabled;
551
+ const controls = best.filter((el) => el.role !== "Text");
552
+ if (controls.length > 0) best = controls;
553
+ const places = /* @__PURE__ */ new Map();
554
+ for (const el of best) if (!places.has(center(el))) places.set(center(el), el);
555
+ const unique = [...places.values()].filter((el, _index, all) => !all.some((other) => other !== el && contains(other, el)));
556
+ if (unique.length === 1) return {
557
+ kind: "found",
558
+ element: unique[0]
559
+ };
560
+ return {
561
+ kind: "ambiguous",
562
+ candidates: unique.slice(0, 8)
563
+ };
564
+ }
565
+ /** `outer` strictly encloses `inner`: keep the inner, more specific one. */
566
+ function contains(inner, outer) {
567
+ return outer !== inner && outer.x <= inner.x && outer.y <= inner.y && outer.x + outer.width >= inner.x + inner.width && outer.y + outer.height >= inner.y + inner.height && (outer.width > inner.width || outer.height > inner.height);
568
+ }
569
+ /** Names worth offering when nothing matched: those sharing characters first, then whatever is there. */
570
+ function suggest(elements, wanted) {
571
+ const names = [...new Set(elements.filter((el) => el.role !== "Text" && el.name.trim() !== "").map((el) => el.name.trim()))];
572
+ const chars = new Set(wanted);
573
+ const score = (name) => [...new Set(normalizeName(name))].filter((char) => chars.has(char)).length;
574
+ return names.sort((a, b) => score(b) - score(a)).slice(0, 12);
575
+ }
576
+ //#endregion
449
577
  //#region lib/types/text.js
450
578
  /**
451
579
  * Split text for streamed entry: paste block by block so the user watches it
@@ -454,10 +582,13 @@ function parseModifiers(text) {
454
582
  *
455
583
  * Blocks end after a blank-line separator, never inside a ``` / ~~~ fence and
456
584
  * never inside a paragraph (a half-pasted **bold** or link may not re-render).
457
- * Joining the blocks gives back the original text exactly.
585
+ * Text with no blank line at all (a story written one paragraph per line) is
586
+ * split at its line ends instead, or it would go in as a single block; a table
587
+ * keeps its rows together. Joining the blocks gives back the original text exactly.
458
588
  */
459
589
  function splitBlocks(text, minChars = 80) {
460
590
  const lines = text.split(/(?<=\n)/);
591
+ const byLine = !/\n[ \t]*\r?\n/.test(text) && !/^\s*(```|~~~|\|)/m.test(text);
461
592
  const blocks = [];
462
593
  let current = "";
463
594
  let fence;
@@ -470,7 +601,7 @@ function splitBlocks(text, minChars = 80) {
470
601
  else if (marker.startsWith(fence)) fence = void 0;
471
602
  }
472
603
  const blank = bare.trim() === "";
473
- if (fence === void 0 && !blank && previousBlank && current.length >= minChars) {
604
+ if (fence === void 0 && !blank && (previousBlank || byLine && current !== "") && current.length >= minChars) {
474
605
  blocks.push(current);
475
606
  current = "";
476
607
  }
@@ -554,6 +685,10 @@ const KEYBOARD = /* @__PURE__ */ new Set([
554
685
  const UNCHANGED_DIFF = 5e-4;
555
686
  /** Text returned instead of an identical screenshot. */
556
687
  const UNCHANGED_TEXT = "The screen looks exactly as in your previous screenshot: the action had no visible effect.";
688
+ /** How long a named control may take to appear before the action gives up. */
689
+ const TARGET_WAIT_MS = 3e3;
690
+ /** Pause between looks while waiting for a control or a window. */
691
+ const POLL_MS = 200;
557
692
  var Computer = class Computer {
558
693
  helper;
559
694
  access;
@@ -610,7 +745,7 @@ var Computer = class Computer {
610
745
  const display = await this.display();
611
746
  return {
612
747
  ...toScreenshot(point, display, this.shotSize(display)),
613
- offscreen: !contains(display, point)
748
+ offscreen: !contains$1(display, point)
614
749
  };
615
750
  }
616
751
  async screenshot() {
@@ -766,8 +901,8 @@ var Computer = class Computer {
766
901
  return was && !win.minimized ? "minimized" : void 0;
767
902
  }
768
903
  /** 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(() => []);
904
+ async backgroundApps(tray = true) {
905
+ const rows = await this.helper.call("background", { tray }, 15e3).catch(() => []);
771
906
  return Array.isArray(rows) ? rows : [];
772
907
  }
773
908
  async cursor() {
@@ -794,7 +929,7 @@ var Computer = class Computer {
794
929
  }
795
930
  /** Overlay status line for an action (Chinese, shown to the user). */
796
931
  static statusOf(input) {
797
- const at = input.coordinate ? ` (${input.coordinate.join(", ")})` : "";
932
+ const at = input.target ? ` “${input.target.slice(0, 20)}”` : input.coordinate ? ` (${input.coordinate.join(", ")})` : "";
798
933
  switch (input.action) {
799
934
  case "screenshot": return "查看屏幕";
800
935
  case "zoom": return "放大查看";
@@ -811,10 +946,134 @@ var Computer = class Computer {
811
946
  case "type": return `输入 “${(input.text ?? "").slice(0, 16)}${(input.text ?? "").length > 16 ? "…" : ""}”`;
812
947
  case "key": return `按键 ${input.text ?? ""}`;
813
948
  case "hold_key": return `按住 ${input.text ?? ""}`;
814
- case "wait": return "等待";
949
+ case "wait": return input.until ? `等待 ${input.until.slice(0, 24)}${input.gone ? " 消失" : ""}` : "等待";
815
950
  case "cursor_position": return "读取光标位置";
816
951
  }
817
952
  }
953
+ /**
954
+ * Controls of the foreground window, in physical pixels. `where` picks the
955
+ * window itself or its popups (open menus and flyouts are windows of their
956
+ * own). They are read separately because scanning both costs a second or
957
+ * more on a file dialog, and the control is nearly always in the window.
958
+ */
959
+ async elements(where = "window") {
960
+ const result = await this.helper.call("ui", {
961
+ includeText: true,
962
+ maxNodes: 400,
963
+ ...where === "popups" ? { popupsOnly: true } : {}
964
+ }, 2e4);
965
+ return Array.isArray(result.elements) ? result.elements : [];
966
+ }
967
+ /** Look for a named control in the window, and only if it is not there in its popups. */
968
+ async find(target) {
969
+ const inWindow = await this.elements("window").catch(() => []);
970
+ const match = matchTarget(inWindow, target);
971
+ if (match.kind !== "missing") return match;
972
+ const inPopups = await this.elements("popups").catch(() => []);
973
+ if (inPopups.length === 0) return match;
974
+ const second = matchTarget(inPopups, target);
975
+ return second.kind === "missing" ? matchTarget([...inWindow, ...inPopups], target) : second;
976
+ }
977
+ /**
978
+ * Where a named control is. It may still be appearing (the menu just
979
+ * opened), so look again for a few seconds before giving up; an ambiguous
980
+ * name fails at once, with the candidates, rather than clicking a guess.
981
+ */
982
+ async locate(target, signal, waitMs = TARGET_WAIT_MS) {
983
+ const started = Date.now();
984
+ for (;;) {
985
+ if (signal.aborted) throw new Error("Cancelled.");
986
+ const match = await this.find(target);
987
+ if (match.kind === "found") {
988
+ const el = match.element;
989
+ return {
990
+ point: {
991
+ x: Math.round(el.x + el.width / 2),
992
+ y: Math.round(el.y + el.height / 2)
993
+ },
994
+ element: el
995
+ };
996
+ }
997
+ if (match.kind === "ambiguous") {
998
+ const list = await Promise.all(match.candidates.map(async (el) => {
999
+ const at = await this.toModel({
1000
+ x: el.x + el.width / 2,
1001
+ y: el.y + el.height / 2
1002
+ });
1003
+ return `${el.role} "${el.name}" @ (${at.x}, ${at.y})`;
1004
+ }));
1005
+ throw new Error(`target "${target}" matches ${match.candidates.length} controls: ${list.join("; ")}. Use one of these coordinates, or a more specific name.`);
1006
+ }
1007
+ if (Date.now() - started >= waitMs) {
1008
+ const near = match.suggestions.length ? ` Controls there now: ${match.suggestions.map((name) => `"${name.slice(0, 40)}"`).join(", ")}.` : " The window exposes no named controls; use coordinates from a screenshot.";
1009
+ throw new Error(`No control named "${target}" in the foreground window.${near}`);
1010
+ }
1011
+ await setTimeout$1(POLL_MS, void 0, { signal });
1012
+ }
1013
+ }
1014
+ /** The point an action aims at: a named control, a coordinate, or nothing (the cursor). */
1015
+ async aim(input, call) {
1016
+ if (typeof input.target === "string" && input.target.trim() !== "") {
1017
+ const { point, element } = await this.locate(input.target, call.signal);
1018
+ return {
1019
+ point,
1020
+ label: ` on ${element.role} "${element.name.slice(0, 60)}"`
1021
+ };
1022
+ }
1023
+ if (input.coordinate) return {
1024
+ point: await this.point(input.coordinate),
1025
+ label: ` at (${input.coordinate.join(", ")})`
1026
+ };
1027
+ return {
1028
+ point: void 0,
1029
+ label: " at the cursor"
1030
+ };
1031
+ }
1032
+ /** wait with `until`: done as soon as the window or control is there (or gone). */
1033
+ async waitUntil(input, signal) {
1034
+ const until = (input.until ?? "").trim();
1035
+ const split = until.search(/[::]/);
1036
+ const prefix = split > 0 ? until.slice(0, split).trim().toLowerCase() : "";
1037
+ const kind = prefix === "window" ? "window" : "target";
1038
+ const subject = (prefix === "window" || prefix === "target" ? until.slice(split + 1) : until).trim();
1039
+ if (subject === "") throw new Error("wait until needs \"window:<title or exe>\" or \"target:<control name>\".");
1040
+ const gone = input.gone === true;
1041
+ const timeout = Math.min(60, Math.max(.2, Number(input.duration ?? 10) || 10)) * 1e3;
1042
+ const needle = subject.toLowerCase();
1043
+ let suggestions = [];
1044
+ let firstSeen;
1045
+ const present = async () => {
1046
+ if (kind === "window") {
1047
+ const matches = (win) => win.title.toLowerCase().includes(needle) || win.exe.toLowerCase().includes(needle) || appMatches(subject, win);
1048
+ const fg = await this.foreground().catch(() => void 0);
1049
+ if (fg && matches(fg)) return true;
1050
+ const rows = await this.windows().catch(() => []);
1051
+ const found = (Array.isArray(rows) ? rows : []).filter((win) => !win.minimized && matches(win));
1052
+ if (gone || found.length === 0) return found.length > 0;
1053
+ if (found.some((win) => win.foreground === true)) return true;
1054
+ if (fg && found.some((win) => win.hwnd === fg.hwnd || win.pid === fg.pid)) return true;
1055
+ firstSeen ??= Date.now();
1056
+ return Date.now() - firstSeen > 1500;
1057
+ }
1058
+ const match = await this.find(subject);
1059
+ if (match.kind === "missing") suggestions = match.suggestions;
1060
+ return match.kind !== "missing";
1061
+ };
1062
+ const started = Date.now();
1063
+ for (;;) {
1064
+ if (signal.aborted) throw new Error("Cancelled.");
1065
+ if (await present() !== gone) {
1066
+ const text = `${kind === "window" ? "Window" : "Control"} "${subject}" ${gone ? "is gone" : "is there"} after ${((Date.now() - started) / 1e3).toFixed(1)}s.`;
1067
+ await this.settle(signal);
1068
+ return text;
1069
+ }
1070
+ if (Date.now() - started >= timeout) {
1071
+ const near = !gone && kind === "target" && suggestions.length ? ` Controls there now: ${suggestions.map((name) => `"${name.slice(0, 40)}"`).join(", ")}.` : "";
1072
+ throw new Error(`Timed out after ${Math.round(timeout / 1e3)}s waiting for ${kind === "window" ? "window" : "control"} "${subject}" to ${gone ? "disappear" : "appear"}.${near}`);
1073
+ }
1074
+ await setTimeout$1(POLL_MS, void 0, { signal });
1075
+ }
1076
+ }
818
1077
  /** Run one action. Returns text plus an image for screenshot/zoom. */
819
1078
  async run(input, call) {
820
1079
  if (call.signal.aborted) throw new Error("Cancelled.");
@@ -865,21 +1124,23 @@ var Computer = class Computer {
865
1124
  return { text: `Cursor at (${p.x}, ${p.y})${p.offscreen ? " — on another display" : ""}.` };
866
1125
  }
867
1126
  case "wait": {
1127
+ if (input.until) return { text: await this.waitUntil(input, call.signal) };
868
1128
  const seconds = Math.min(30, Math.max(0, Number(input.duration ?? 1) || 0));
869
1129
  const waited = await this.waitForQuiet(seconds * 1e3, call.signal);
870
1130
  return { text: waited < seconds * 1e3 - 200 ? `Waited ${(waited / 1e3).toFixed(1)}s (the screen settled early).` : `Waited ${seconds}s.` };
871
1131
  }
872
1132
  case "mouse_move": {
873
- const p = await this.point(input.coordinate);
1133
+ const { point: p, label } = await this.aim(input, call);
1134
+ if (!p) throw new Error("mouse_move needs coordinate or target.");
874
1135
  await this.helper.call("move", { ...p });
875
- return { text: `Moved the mouse to (${input.coordinate.join(", ")}).` };
1136
+ return { text: `Moved the mouse${label.replace(/^ (at|on)/, " to")}.` };
876
1137
  }
877
1138
  case "left_click":
878
1139
  case "right_click":
879
1140
  case "middle_click":
880
1141
  case "double_click":
881
1142
  case "triple_click": {
882
- const p = input.coordinate ? await this.point(input.coordinate) : void 0;
1143
+ const { point: p, label } = await this.aim(input, call);
883
1144
  await this.checkPointer(call, p, "click");
884
1145
  const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
885
1146
  const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
@@ -890,7 +1151,7 @@ var Computer = class Computer {
890
1151
  count,
891
1152
  modifiers
892
1153
  });
893
- return { text: `${action.replace("_", " ")}${input.coordinate ? ` at (${input.coordinate.join(", ")})` : " at the cursor"}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.` };
1154
+ return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.` };
894
1155
  }
895
1156
  case "left_click_drag": {
896
1157
  const from = await this.point(input.start_coordinate, "start_coordinate");
@@ -918,7 +1179,7 @@ var Computer = class Computer {
918
1179
  return { text: `Left button ${action === "left_mouse_down" ? "down" : "up"}.` };
919
1180
  }
920
1181
  case "scroll": {
921
- const p = input.coordinate ? await this.point(input.coordinate) : void 0;
1182
+ const { point: p } = await this.aim(input, call);
922
1183
  await this.checkPointer(call, p, "scroll");
923
1184
  const amount = Math.max(1, Math.min(30, Math.round(input.scroll_amount ?? 3)));
924
1185
  const direction = input.scroll_direction ?? "down";
@@ -935,8 +1196,21 @@ var Computer = class Computer {
935
1196
  case "type": {
936
1197
  const text = input.text ?? "";
937
1198
  if (text === "") throw new Error("type needs text.");
1199
+ let into = "";
1200
+ if (input.target || input.coordinate) {
1201
+ const { point: p, label } = await this.aim(input, call);
1202
+ await this.checkPointer(call, p, "click");
1203
+ await this.helper.call("click", {
1204
+ ...p ?? {},
1205
+ button: "left",
1206
+ count: 1,
1207
+ modifiers: []
1208
+ });
1209
+ await setTimeout$1(120, void 0, { signal: call.signal });
1210
+ into = ` (clicked${label} first)`;
1211
+ }
938
1212
  await this.checkKeyboard(call, "type into");
939
- return { text: await this.enterText(text, call) };
1213
+ return { text: `${await this.enterText(text, call)}${into}` };
940
1214
  }
941
1215
  case "key": {
942
1216
  const combos = parseKeys(input.text ?? "");
@@ -1617,7 +1891,7 @@ var OverlayController = class {
1617
1891
  function promptText(mode) {
1618
1892
  return `# Computer use (Windows desktop)
1619
1893
  You can see and operate the user's Windows computer with the computer, computer_batch, open_application, windows, ui_elements, clipboard and app_skill tools.
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.
1894
+ ${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" : ""}- If the task begins with an app, open it right away with open_application (after request_access when the app is not granted yet): it returns the screenshot, so do not take one first. Otherwise 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.
1621
1895
  - 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
1896
  - 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.
1623
1897
  - 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.
@@ -1627,7 +1901,7 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
1627
1901
  - 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.
1628
1902
  - 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.
1629
1903
  - 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.
1630
- - 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.
1904
+ - Be fast: what the user waits for is mostly the number of calls you make (each costs seconds). Once you have seen the app's window, put everything predictable into ONE computer_batch, including steps whose target is not on screen yet: name the control with target ("保存", "按钮:确定") instead of a coordinate, and use wait with until ("window:另存为") for a dialog to appear before keys meant for it. Do not end a batch with wait or follow it with a wait or a screenshot: its result already is the settled screen. Do not split work into two batches just to look in between when the second does not depend on what you would see (type the text and format it in the same batch). If you will need to read small text, end the batch with zoom; to read what a window says (a document, a page, a reply, a log) use ui_elements with text: true or finish: "text" instead of scrolling and zooming screenshots. Keep your own text between calls to a line. Avoid shell commands for things you can see on screen.
1631
1905
  - 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.
1632
1906
  - 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.
1633
1907
  - Do not enter passwords, payment details or solve CAPTCHAs: stop and ask the user to do that step. Ask before irreversible actions (sending messages, deleting, purchasing) unless the user clearly asked for them.
@@ -1943,16 +2217,31 @@ function previewRoute(helper, settings, overlay, iconPath) {
1943
2217
  return;
1944
2218
  }
1945
2219
  const s = settings();
2220
+ const pet = s.hostWindow === "pet";
1946
2221
  await helper.call("overlay_show", {
1947
- label: `${s.overlayLabel} 正在操控你的电脑`,
1948
- status: "预览 · 3 秒后消失",
2222
+ label: pet ? `${s.overlayLabel} 正在操控` : `${s.overlayLabel} 正在操控你的电脑`,
2223
+ status: pet ? "预览" : "预览 · 4 秒后消失",
1949
2224
  icon: iconPath,
2225
+ iconLight: iconPath.replace(/deepseek-white\.png$/, "deepseek-black.png"),
1950
2226
  idleMs: s.userIdleMs,
1951
- glow: s.overlay
2227
+ glow: s.overlay,
2228
+ pet,
2229
+ petOpacity: s.cardOpacity,
2230
+ text: ""
1952
2231
  });
2232
+ if (pet) await helper.call("pet_update", {
2233
+ text: "这是预览:操控电脑时,这里滚动显示 AI 的回复正文。",
2234
+ thinking: "第二行显示思考过程和最近几步操作",
2235
+ steps: [
2236
+ "打开应用",
2237
+ "输入文字",
2238
+ "预览 · 4 秒后消失"
2239
+ ],
2240
+ thinkingLatest: false
2241
+ }).catch(() => {});
1953
2242
  setTimeout(() => {
1954
2243
  if (overlay.controller === void 0) helper.call("overlay_hide").catch(() => {});
1955
- }, 3e3).unref();
2244
+ }, 4e3).unref();
1956
2245
  json(res, 200, { ok: true });
1957
2246
  };
1958
2247
  }
@@ -7979,6 +8268,16 @@ const coordinate = {
7979
8268
  items: { type: "number" },
7980
8269
  description: "[x, y] in pixels of the latest screenshot."
7981
8270
  };
8271
+ /** Reads what a window says through UI Automation: exact text, no image. */
8272
+ async function windowText(computer, hwnd, tail) {
8273
+ const result = await computer.helper.call("text", {
8274
+ ...hwnd === void 0 ? {} : { hwnd },
8275
+ tail: Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)))
8276
+ }, 2e4);
8277
+ const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
8278
+ if (!result.text || result.source === "none") return `${head}: this window exposes no readable text; use a screenshot.`;
8279
+ 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}`;
8280
+ }
7982
8281
  const actionProperties = {
7983
8282
  action: {
7984
8283
  type: "string",
@@ -8014,7 +8313,19 @@ const actionProperties = {
8014
8313
  },
8015
8314
  duration: {
8016
8315
  type: "number",
8017
- description: "Seconds for wait / hold_key."
8316
+ description: "Seconds for wait / hold_key (with until: the timeout, default 10)."
8317
+ },
8318
+ target: {
8319
+ type: "string",
8320
+ description: "Instead of coordinate: the visible name of a control in the foreground window or its open menu, e.g. \"保存\" or \"按钮:保存\". Works for controls that were not in your last screenshot (the item of a menu the previous step opens); waits up to 3 s for it. With type: clicks the field first."
8321
+ },
8322
+ until: {
8323
+ type: "string",
8324
+ description: "wait: return as soon as this is there, \"window:<title or exe part>\" or \"target:<control name>\", instead of waiting a fixed time."
8325
+ },
8326
+ gone: {
8327
+ type: "boolean",
8328
+ description: "wait until: wait for it to disappear instead."
8018
8329
  },
8019
8330
  region: {
8020
8331
  type: "array",
@@ -8022,7 +8333,7 @@ const actionProperties = {
8022
8333
  description: "zoom: [x1, y1, x2, y2] in screenshot pixels."
8023
8334
  }
8024
8335
  };
8025
- const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot" && action !== "zoom");
8336
+ const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
8026
8337
  function createTools(host) {
8027
8338
  const { computer } = host;
8028
8339
  const tools = [];
@@ -8049,40 +8360,55 @@ function createTools(host) {
8049
8360
  }));
8050
8361
  tools.push(defineTool({
8051
8362
  name: "computer_batch",
8052
- description: "Run several computer actions in order in one call (e.g. click a field, type, press Return), then get one screenshot. Stops at the first failing action. Use it when you are confident about the next few steps; the screen is not re-checked between actions.",
8053
- parameters: { actions: {
8054
- type: "array",
8055
- required: true,
8056
- description: "Ordered actions, same fields as the computer tool (screenshot and zoom are not allowed here).",
8057
- items: {
8058
- type: "object",
8059
- additionalProperties: false,
8060
- properties: {
8061
- ...actionProperties,
8062
- action: {
8063
- ...actionProperties.action,
8064
- enum: BATCH_ACTIONS
8363
+ description: "Run several computer actions in order in one call, then get one screenshot (taken once the screen settles, so do not end with a wait). Stops at the first failing action and shows you the screen. The screen is not shown to you between actions, so for steps whose target only appears along the way (a menu item, a dialog button) use target instead of coordinate, and wait with until for a window or control to appear. Example: [key \"ctrl+s\", wait until \"window:另存为\", type target \"文件名\" text \"C:\\a.txt\", left_click target \"保存\"].",
8364
+ parameters: {
8365
+ actions: {
8366
+ type: "array",
8367
+ required: true,
8368
+ description: "Ordered actions, same fields as the computer tool. zoom is allowed only as the last action (you get the zoomed region instead of the full screenshot).",
8369
+ items: {
8370
+ type: "object",
8371
+ additionalProperties: false,
8372
+ properties: {
8373
+ ...actionProperties,
8374
+ action: {
8375
+ ...actionProperties.action,
8376
+ enum: BATCH_ACTIONS
8377
+ }
8065
8378
  }
8066
8379
  }
8380
+ },
8381
+ finish: {
8382
+ type: "string",
8383
+ enum: [
8384
+ "screenshot",
8385
+ "text",
8386
+ "none"
8387
+ ],
8388
+ 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."
8067
8389
  }
8068
- } },
8390
+ },
8069
8391
  output,
8070
8392
  timeoutMs: 18e5,
8071
8393
  async execute(args, exec) {
8072
8394
  const call = await host.context(exec);
8073
8395
  const actions = args.actions;
8396
+ const finish = args.finish ?? "screenshot";
8397
+ let zoomed;
8074
8398
  if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array.");
8075
8399
  if (actions.length > 30) throw new Error("At most 30 actions per batch.");
8076
8400
  const lines = [];
8077
8401
  let failure;
8078
8402
  for (const [index, input] of actions.entries()) {
8079
- if (input.action === "screenshot" || input.action === "zoom") {
8080
- failure = `#${index + 1} ${input.action}: not allowed in a batch.`;
8403
+ if (input.action === "screenshot" || input.action === "zoom" && index !== actions.length - 1) {
8404
+ failure = `#${index + 1} ${input.action}: ${input.action === "zoom" ? "only allowed as the last action of a batch" : "not allowed in a batch"}.`;
8081
8405
  break;
8082
8406
  }
8083
8407
  try {
8084
8408
  const stepStart = Date.now();
8409
+ if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
8085
8410
  const outcome = await computer.run(input, call);
8411
+ if (input.action === "zoom") zoomed = outcome.image;
8086
8412
  if (outcome.skipped) {
8087
8413
  failure = `#${index + 1} ${input.action} skipped: the user was typing on the keyboard. Re-check the screen before continuing.`;
8088
8414
  break;
@@ -8103,8 +8429,15 @@ function createTools(host) {
8103
8429
  }
8104
8430
  }
8105
8431
  const done = lines.join("\n");
8106
- const shot = call.vision && computer.settings().autoScreenshot ? await computer.settle(call.signal).then(() => computer.freshShot()) : void 0;
8107
8432
  const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
8433
+ if (zoomed !== void 0 && failure === void 0) return withShot(host, summary, zoomed, call);
8434
+ if (failure === void 0 && finish === "none") return { text: `${summary}\n${await computer.describeForeground()}` };
8435
+ if (failure === void 0 && finish === "text") {
8436
+ await computer.settle(call.signal);
8437
+ 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)}`)}` };
8438
+ }
8439
+ const waited = failure === void 0 && actions[actions.length - 1]?.action === "wait";
8440
+ const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot()) : void 0;
8108
8441
  return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
8109
8442
  },
8110
8443
  presentCall: (args) => card(`电脑操作 · 批量 ${args.actions?.length ?? 0} 步`)
@@ -8127,15 +8460,26 @@ function createTools(host) {
8127
8460
  timeoutMs: 18e5,
8128
8461
  async execute(args, exec) {
8129
8462
  const call = await host.context(exec);
8130
- const name = String(args.name ?? "").trim();
8131
- const newInstance = args.new_instance === true;
8463
+ const text = await openApp(String(args.name ?? ""), args.new_instance === true, call);
8464
+ await computer.settle(call.signal);
8465
+ return withShot(host, text, call.vision ? await computer.screenshot() : void 0, call);
8466
+ },
8467
+ presentCall: (args) => card(`打开应用 · ${args.name ?? ""}`)
8468
+ }));
8469
+ /** Open an app or bring it forward; returns what happened, the foreground window and the app's skill notes. */
8470
+ async function openApp(rawName, newInstance, call) {
8471
+ {
8472
+ const name = rawName.trim();
8132
8473
  if (name === "") throw new Error("name is required.");
8133
8474
  const settings = computer.settings();
8134
8475
  const isUrl = /^https?:\/\//i.test(name);
8135
8476
  const appName = /^ms-settings:/i.test(name) ? "设置" : name;
8136
8477
  if (settings.accessMode === "per-app" && !isUrl && computer.access.missing(call.session, [appName]).length > 0) {
8137
- const running = (await computer.windows()).find((win) => appMatches(appName, win)) ?? (await computer.backgroundApps()).find((win) => appMatches(appName, win));
8138
- if (!running || !computer.access.isGranted(call.session, running)) throw new Error(`"${appName}" is not granted for this session. Call request_access with ["${appName}"] first.`);
8478
+ const running = (await computer.windows()).find((win) => appMatches(appName, win)) ?? (await computer.backgroundApps(false)).find((win) => appMatches(appName, win));
8479
+ if (!running || !computer.access.isGranted(call.session, running)) {
8480
+ if (call.autoApprove !== true || normalizeApp(appName).includes("deepseek harness")) throw new Error(`"${appName}" is not granted for this session. Call request_access with ["${appName}"] first.`);
8481
+ computer.access.grant(call.session, [appName]);
8482
+ }
8139
8483
  }
8140
8484
  await computer.overlay.begin(call.agent, `打开 ${name}`);
8141
8485
  await computer.overlay.yieldToUser(call.signal, false);
@@ -8143,7 +8487,7 @@ function createTools(host) {
8143
8487
  let how;
8144
8488
  const isUri = isUrl || /^[a-z][a-z0-9+.-]+:(?![\/])/i.test(name);
8145
8489
  const running = isUri || newInstance ? void 0 : (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
8146
- const hidden = running || isUri || newInstance ? void 0 : (await computer.backgroundApps()).find((win) => !isHostWindow(win) && appMatches(name, win));
8490
+ const hidden = running || isUri || newInstance ? void 0 : (await computer.backgroundApps(false)).find((win) => !isHostWindow(win) && appMatches(name, win));
8147
8491
  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.`;
8148
8492
  else if (hidden) {
8149
8493
  const restored = await computer.helper.call("tray_restore", { exe: hidden.exe }, 2e4);
@@ -8157,11 +8501,11 @@ function createTools(host) {
8157
8501
  if (app) await computer.helper.call("launch", { appId: app.id });
8158
8502
  else await computer.helper.call("launch", { target: name });
8159
8503
  how = app ? `Launched "${app.name}".` : isUrl ? `Opened ${name} in the default browser.` : `Started "${name}".`;
8160
- for (let i = 0; i < 32; i++) {
8161
- await setTimeout$1(250, void 0, { signal: call.signal });
8504
+ for (let i = 0; i < 80; i++) {
8505
+ await setTimeout$1(100, void 0, { signal: call.signal });
8162
8506
  const now = await computer.foreground();
8163
8507
  if (now && now.hwnd !== before?.hwnd && !isHostWindow(now) && !isTransientShell(now) && (now.exe.toLowerCase() !== "explorer.exe" || now.className === "CabinetWClass")) break;
8164
- if (i >= 4 && i % 4 === 0 && !isUri) {
8508
+ if (i >= 10 && i % 10 === 0 && !isUri) {
8165
8509
  const opened = (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
8166
8510
  if (opened) {
8167
8511
  await computer.focus(opened).catch(() => void 0);
@@ -8172,12 +8516,9 @@ function createTools(host) {
8172
8516
  }
8173
8517
  const fg = await computer.foreground();
8174
8518
  if (fg && !isHostWindow(fg) && settings.accessMode === "per-app" && (computer.access.missing(call.session, [appName]).length === 0 || isUrl)) computer.access.grant(call.session, [fg.exe]);
8175
- await computer.settle(call.signal);
8176
- const shot = call.vision ? await computer.screenshot() : void 0;
8177
- return withShot(host, `${how} ${await computer.describeForeground()}${skillNote(call.session, name, fg)}`, shot, call);
8178
- },
8179
- presentCall: (args) => card(`打开应用 · ${args.name ?? ""}`)
8180
- }));
8519
+ return `${how} ${await computer.describeForeground()}${skillNote(call.session, name, fg)}`;
8520
+ }
8521
+ }
8181
8522
  /** Skills already handed to a session, so each is attached once. */
8182
8523
  const told = /* @__PURE__ */ new Map();
8183
8524
  /** The app's skill, appended to open_application's result the first time in a session. */
@@ -8269,12 +8610,20 @@ function createTools(host) {
8269
8610
  }));
8270
8611
  tools.push(defineTool({
8271
8612
  name: "ui_elements",
8272
- description: "List clickable/editable UI elements of the foreground window (or a window by hwnd) from Windows UI Automation, with center coordinates in screenshot pixels. Useful to click precisely, read values, or work without vision. Some apps (games, canvas UIs) expose little.",
8613
+ 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.",
8273
8614
  parameters: {
8274
8615
  hwnd: {
8275
8616
  type: "integer",
8276
8617
  description: "Window handle; default foreground window."
8277
8618
  },
8619
+ text: {
8620
+ type: "boolean",
8621
+ description: "Return the window's text content instead of the element list."
8622
+ },
8623
+ tail: {
8624
+ type: "integer",
8625
+ description: "text: how many characters from the end to return (default 4000, max 20000); new content is usually at the end."
8626
+ },
8278
8627
  include_text: {
8279
8628
  type: "boolean",
8280
8629
  description: "Also list static text elements."
@@ -8288,10 +8637,12 @@ function createTools(host) {
8288
8637
  timeoutMs: 3e4,
8289
8638
  isConcurrencySafe: () => true,
8290
8639
  async execute(args) {
8291
- const { hwnd, include_text: includeText, max } = args;
8640
+ const { hwnd, include_text: includeText, max, text, tail } = args;
8641
+ if (text === true) return { text: await windowText(computer, hwnd, tail) };
8292
8642
  const result = await computer.helper.call("ui", {
8293
8643
  ...hwnd === void 0 ? {} : { hwnd },
8294
8644
  includeText: includeText === true,
8645
+ popups: true,
8295
8646
  maxNodes: Math.min(400, Math.max(10, max ?? 120))
8296
8647
  }, 2e4);
8297
8648
  const lines = [];
@@ -8608,6 +8959,15 @@ function apply(ctx, config = {}) {
8608
8959
  return cached;
8609
8960
  };
8610
8961
  const attachments = () => ctx.attachments;
8962
+ /** "never" comes from the full-access / auto presets: the user opted out of approval prompts. */
8963
+ const approvalPolicy = (agent) => {
8964
+ const approval = ctx.get("approval");
8965
+ try {
8966
+ return approval?.effectivePolicy?.(agent.session);
8967
+ } catch {
8968
+ return;
8969
+ }
8970
+ };
8611
8971
  const screenshots = new ScreenshotCache(void 0, void 0, log);
8612
8972
  ctx.effect(() => {
8613
8973
  const sweep = () => {
@@ -8641,7 +9001,8 @@ function apply(ctx, config = {}) {
8641
9001
  session: exec.agent?.session.id ?? "default",
8642
9002
  agent: exec.agent,
8643
9003
  signal: exec.signal,
8644
- vision: await supportsVision(exec.agent, exec.signal)
9004
+ vision: await supportsVision(exec.agent, exec.signal),
9005
+ autoApprove: exec.agent !== void 0 && approvalPolicy(exec.agent) === "never"
8645
9006
  };
8646
9007
  }
8647
9008
  });
@@ -1,6 +1,7 @@
1
1
  import { type AccessControl, type AccessMode, type WindowLike } from './access.js';
2
2
  import { type Display, type Point, type Size } from './coords.js';
3
3
  import type { HelperLike } from './helper-client.js';
4
+ import { type UiElement } from './target.js';
4
5
  import type { CancellableAgent, HostWindowMode, OverlayController } from './overlay.js';
5
6
  export interface Settings {
6
7
  accessMode: AccessMode;
@@ -48,6 +49,8 @@ export interface CallContext {
48
49
  signal: AbortSignal;
49
50
  /** Whether the conversation model can look at images. */
50
51
  vision: boolean;
52
+ /** The session never prompts for approval (full access / auto review): access requests are granted as they come. */
53
+ autoApprove?: boolean;
51
54
  }
52
55
  export declare const ACTIONS: readonly ["screenshot", "left_click", "right_click", "middle_click", "double_click", "triple_click", "mouse_move", "left_click_drag", "left_mouse_down", "left_mouse_up", "scroll", "type", "key", "hold_key", "wait", "zoom", "cursor_position"];
53
56
  export type Action = typeof ACTIONS[number];
@@ -61,6 +64,12 @@ export interface ActionInput {
61
64
  scroll_amount?: number;
62
65
  duration?: number;
63
66
  region?: number[];
67
+ /** A control named by what it says, instead of a coordinate. */
68
+ target?: string;
69
+ /** wait: what to wait for ("window:记事本", "target:保存"). */
70
+ until?: string;
71
+ /** wait: wait for it to disappear instead. */
72
+ gone?: boolean;
64
73
  }
65
74
  export interface ActionOutcome {
66
75
  text: string;
@@ -136,7 +145,7 @@ export declare class Computer {
136
145
  /** How a window relates to the layout before the task: opened by the agent, or restored from minimized / tray. */
137
146
  origin(win: WindowInfo): 'opened' | 'minimized' | 'tray' | undefined;
138
147
  /** Programs running without any visible window (closed to the system tray); `tray` = has a tray icon. */
139
- backgroundApps(): Promise<Array<WindowInfo & {
148
+ backgroundApps(tray?: boolean): Promise<Array<WindowInfo & {
140
149
  tray: boolean;
141
150
  }>>;
142
151
  cursor(): Promise<Point>;
@@ -147,6 +156,28 @@ export declare class Computer {
147
156
  private checkKeyboard;
148
157
  /** Overlay status line for an action (Chinese, shown to the user). */
149
158
  static statusOf(input: ActionInput): string;
159
+ /**
160
+ * Controls of the foreground window, in physical pixels. `where` picks the
161
+ * window itself or its popups (open menus and flyouts are windows of their
162
+ * own). They are read separately because scanning both costs a second or
163
+ * more on a file dialog, and the control is nearly always in the window.
164
+ */
165
+ elements(where?: 'window' | 'popups'): Promise<UiElement[]>;
166
+ /** Look for a named control in the window, and only if it is not there in its popups. */
167
+ private find;
168
+ /**
169
+ * Where a named control is. It may still be appearing (the menu just
170
+ * opened), so look again for a few seconds before giving up; an ambiguous
171
+ * name fails at once, with the candidates, rather than clicking a guess.
172
+ */
173
+ locate(target: string, signal: AbortSignal, waitMs?: number): Promise<{
174
+ point: Point;
175
+ element: UiElement;
176
+ }>;
177
+ /** The point an action aims at: a named control, a coordinate, or nothing (the cursor). */
178
+ private aim;
179
+ /** wait with `until`: done as soon as the window or control is there (or gone). */
180
+ private waitUntil;
150
181
  /** Run one action. Returns text plus an image for screenshot/zoom. */
151
182
  run(input: ActionInput, call: CallContext): Promise<ActionOutcome>;
152
183
  /**
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Finding a control by what it says instead of where it is. A batch can then
3
+ * act on things that were not on screen in the model's last screenshot (the
4
+ * item of a menu it is about to open, the button of a dialog about to appear),
5
+ * which is what lets one call cover a whole sequence.
6
+ */
7
+ /** One UI Automation element as the helper reports it (physical pixels). */
8
+ export interface UiElement {
9
+ role: string;
10
+ name: string;
11
+ value?: string;
12
+ checked?: boolean;
13
+ disabled?: boolean;
14
+ x: number;
15
+ y: number;
16
+ width: number;
17
+ height: number;
18
+ }
19
+ export interface TargetQuery {
20
+ /** UI Automation control type, when the target named one ("按钮:保存"). */
21
+ role?: string;
22
+ name: string;
23
+ }
24
+ export type TargetMatch = {
25
+ kind: 'found';
26
+ element: UiElement;
27
+ } | {
28
+ kind: 'ambiguous';
29
+ candidates: UiElement[];
30
+ } | {
31
+ kind: 'missing';
32
+ suggestions: string[];
33
+ };
34
+ /** "按钮:保存" → Button named 保存; a colon that is not after a known role stays part of the name. */
35
+ export declare function parseTarget(target: string): TargetQuery & {
36
+ roles?: string[];
37
+ };
38
+ /**
39
+ * Names as people read them: without the accelerator ("保存(S)", "&File"),
40
+ * the trailing ellipsis of commands that open a dialog, and case.
41
+ */
42
+ export declare function normalizeName(name: string): string;
43
+ /**
44
+ * Pick the element a target means. An exact name beats a name that starts with
45
+ * the text, which beats one that merely contains it; within the best tier,
46
+ * enabled controls beat disabled ones and real controls beat static text.
47
+ * Several different places left after that is an ambiguity, not a guess.
48
+ */
49
+ export declare function matchTarget(elements: readonly UiElement[], target: string): TargetMatch;
@@ -5,7 +5,9 @@
5
5
  *
6
6
  * Blocks end after a blank-line separator, never inside a ``` / ~~~ fence and
7
7
  * never inside a paragraph (a half-pasted **bold** or link may not re-render).
8
- * Joining the blocks gives back the original text exactly.
8
+ * Text with no blank line at all (a story written one paragraph per line) is
9
+ * split at its line ends instead, or it would go in as a single block; a table
10
+ * keeps its rows together. Joining the blocks gives back the original text exactly.
9
11
  */
10
12
  export declare function splitBlocks(text: string, minChars?: number): string[];
11
13
  /** Pieces of at most ~`size` characters, broken after whitespace where possible (for paced typing). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.5.2",
3
+ "version": "0.6.1",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "type": "module",
6
6
  "author": "copylee",