@copylee/dsh-computer-use 0.8.1 → 0.8.2

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
@@ -22,7 +22,7 @@
22
22
  | 截图即坐标系 | 模型只用最近一张截图的像素坐标,DPI、缩放、多显示器偏移全部由插件换算,高分屏(200% 缩放)也点得准 |
23
23
  | 动作后自动回传截图 | 点击 / 输入 / 按键 / 滚动后,**等画面不再变化**(页面加载、动画结束,最多约 2.5 秒)再截图;`wait` 也直接带回截图,“等一下再看”只需一步,而且画面一静止就提前结束,不会死等满时长;画面与上一张截图完全相同时不再发图,只告诉模型“没有可见变化”,省 token |
24
24
  | 批量动作 | `computer_batch` 一次执行“点输入框 → 输入 → 回车”等多步,最后只截一张图 |
25
- | 按名称点控件 | 动作里用 `target`(控件的可见名称,如 `"保存"`、`"按钮:确定"`)代替坐标。上一张截图里还没出现的控件也能点,比如上一步才打开的菜单项、才弹出的对话框按钮;最多等 3 秒它出现。重名时不猜,直接把候选和坐标告诉模型 |
25
+ | 按名称点控件 | 动作里用 `target`(控件的可见名称,如 `"保存"`、`"按钮:确定"`)代替坐标。上一张截图里还没出现的控件也能点,比如上一步才打开的菜单项、才弹出的对话框按钮;最多等 3 秒它出现。重名时不猜,直接把候选和坐标告诉模型;`ui_elements` 现在会返回 `automationId`,重名时可用 `target: "id:<AutomationId>"`(或 `"#<AutomationId>"`)明确指定 |
26
26
  | 等条件而不是等时间 | `wait` 加 `until`(`"window:另存为"`、`"target:保存"`):窗口或控件一出现(或一消失)就继续,超时才报错。配合 `target`,“按 Ctrl+S → 等另存为 → 填文件名 → 点保存”可以写进同一个批量调用 |
27
27
  | 把窗口读成文本 | `ui_elements` 加 `text: true` 直接读出文档、网页、聊天回复或日志的文字(默认取末尾 4000 字),比滚动加放大截图快,也能逐字引用;批量调用加 `finish: "text"` 可以用文字代替结尾的截图 |
28
28
  | 按应用授权 | 先 `request_access` 列出要操控的应用,经 DSH 原生审批后才能操作;也可改为“全部允许” |
@@ -37,6 +37,8 @@
37
37
  | 应用技能 | AI 对各个应用的操作笔记,每个应用一份 Markdown(`~/.dsh/computer-use-skills/`)。AI 摸索清楚一个不熟悉的应用后用 `app_skill` 自己记下来(只记操作规律,不记任务内容),以后 `open_application` 打开该应用时自动附带,不占系统提示。自带 Word、PowerPoint、Excel、Chrome、文件资源管理器、Obsidian、Typora、微信、QQ、记事本十份内置技能(含各应用的快捷键清单,PowerPoint 含原生公式和动画的做法);AI 在内置技能上追加的笔记单独保存,内置部分随插件更新;设置页“应用技能”里可以查看、修改、删除、新建,内置技能可覆盖和恢复 |
38
38
  | 打开应用 | `open_application` 同时搜索开始菜单和桌面快捷方式(含公共桌面),便携软件也能按名字打开。已经关到系统托盘的应用(QQ、微信等)会像人一样点托盘图标把窗口叫回来(必要时先展开“显示隐藏的图标”),不会再启动第二个实例、也不会重复登录;你明确要多开时(如微信双开)AI 会用 `new_instance` 另开一个。任务结束时 AI 会收拾现场:关掉自己打开、你不再需要的窗口,`windows tidy` 把原本最小化或在托盘里的应用重新最小化 |
39
39
  | 看不见图的模型 | `ui_elements` 用 Windows UI Automation 列出可点击元素和坐标,纯文本模型也能用。Chromium / Electron 会先唤醒无障碍树,同时保留浏览器标签栏、地址栏等控件;支持识别常见网页编辑器,并返回应用提供的 AutomationId、焦点能力和编辑器标记 |
40
+ | 返回 DSH | 操控结束时恢复桌面窗口并切回前台。若从 DSH Web 标签开始,会返回记录的浏览器窗口并尝试选回该标签。反代或自定义域名可在插件配置中将 `harnessUrl` 设为实际 Web GUI 地址 |
41
+ | UIA 动作 | 按名称或 ID 单击时,支持 UIA Invoke 的控件优先执行语义动作,输入框可通过 UIA 聚焦。缺少对应能力时重新确认控件后使用坐标。多击、右键和组合键点击仍使用坐标 |
40
42
  | 零原生依赖 | 截图、窗口查询和输入直接调用 DeepSeek Harness 自带的 koffi,不需要额外安装;浮层、UI Automation、剪贴板等由一个小 helper 负责,首次使用时用 Windows 自带的 .NET Framework `csc.exe` 编译(约 1 秒,之后缓存)。不需要 node-gyp,也不受 Electron ABI 影响。开启了智能应用控制(Smart App Control)时,helper 改为在系统自带的 PowerShell 里运行 |
41
43
 
42
44
  ## 安装
@@ -72,7 +74,7 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
72
74
  | `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 动作命名,模型上手即会) |
73
75
  | `computer_batch` | 顺序执行多个动作,遇错即停,最后回传一张截图;最后一步可以是 `zoom`(回传放大区域),`finish` 可选 `screenshot` / `text` / `none` |
74
76
  | `app_skill` | 应用技能:`list` 列出、`read` 读取、`append` 追加、`write` 重写某个应用的操作笔记(单份上限 4000 字) |
75
- | `open_application` | 按名称(“Chrome”“记事本”“微信”)、exe 路径或网址打开应用;已运行则切到前台,在托盘里则从托盘图标恢复 |
77
+ | `open_application` | 按名称(“Chrome”“记事本”“微信”)或 exe 路径打开应用,已运行则切到前台,在托盘里则恢复。HTTP(S) 网址在受支持的默认浏览器中显式新开窗口 |
76
78
  | `windows` | 列出窗口(含进程 exe 名)、聚焦 / 最小化 / 最大化 / 还原 / 关闭 |
77
79
  | `ui_elements` | 前台窗口(含已打开的菜单)的 UI Automation 元素列表,坐标已换算到截图坐标系;`text: true` 改为读出窗口的文字内容 |
78
80
  | `clipboard` | 读 / 写剪贴板文本 |
@@ -288,10 +288,18 @@ namespace DshComputerUse
288
288
  case "card_opacity": CardLayer.SetOpacity(Args.Int(r, "opacity", 100)); return null;
289
289
  case "foreground": return Windows.Describe(Native.GetForegroundWindow());
290
290
  case "window_at": return Windows.At(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
291
- case "focus": return Windows.Focus(new IntPtr(Convert.ToInt64(r["hwnd"])));
291
+ case "focus":
292
+ var focusHwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
293
+ uint focusPid;
294
+ if (Args.Has(r, "pid") && (Native.GetWindowThreadProcessId(focusHwnd, out focusPid) == 0 || focusPid != Convert.ToUInt32(r["pid"])))
295
+ throw new Exception("window no longer belongs to the original process");
296
+ return Windows.Focus(focusHwnd);
292
297
  case "window_cmd": return Windows.Command(new IntPtr(Convert.ToInt64(r["hwnd"])), Args.Str(r, "op", ""));
293
298
  case "apps": return Apps.Search(Args.Str(r, "query", ""), Args.Int(r, "limit", 8));
294
299
  case "launch": return Apps.Launch(r);
300
+ case "open_url": return Apps.OpenUrl(Args.Str(r, "url", ""));
301
+ case "browser_tab": return Uia.BrowserTab(r);
302
+ case "act": return Uia.Act(r);
295
303
  case "clipboard_get": { var d = new Dictionary<string, object>(); d["text"] = Clip.Get(); return d; }
296
304
  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;
297
305
  case "clipboard_restore": { var d = new Dictionary<string, object>(); d["restored"] = Clip.RestoreAgent(); return d; }
@@ -1600,6 +1608,32 @@ namespace DshComputerUse
1600
1608
 
1601
1609
  internal static class Apps
1602
1610
  {
1611
+ [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
1612
+ static extern int AssocQueryString(uint flags, uint str, string association, string verb, StringBuilder output, ref uint length);
1613
+
1614
+ public static object OpenUrl(string value)
1615
+ {
1616
+ Uri url;
1617
+ if (!Uri.TryCreate(value, UriKind.Absolute, out url) || (url.Scheme != "http" && url.Scheme != "https"))
1618
+ throw new Exception("Expected an HTTP(S) URL");
1619
+ const uint executable = 2;
1620
+ var path = new StringBuilder(32768);
1621
+ uint length = (uint)path.Capacity;
1622
+ if (AssocQueryString(0, executable, url.Scheme, "open", path, ref length) != 0)
1623
+ throw new Exception("Could not resolve the default browser for " + url.Scheme);
1624
+ string exe = Path.GetFileName(path.ToString()).ToLowerInvariant();
1625
+ string flag;
1626
+ switch (exe)
1627
+ {
1628
+ case "chrome.exe": case "msedge.exe": case "brave.exe": case "vivaldi.exe": case "chromium.exe":
1629
+ flag = "--new-window"; break;
1630
+ case "firefox.exe": flag = "-new-window"; break;
1631
+ default: throw new Exception("Cannot safely open a new window in the default browser (" + exe + ")");
1632
+ }
1633
+ string escapedUrl = url.AbsoluteUri.Replace("\"", "%22").Replace("\\", "%5C");
1634
+ using (var process = Process.Start(new ProcessStartInfo(path.ToString(), flag + " \"" + escapedUrl + "\"") { UseShellExecute = false })) { }
1635
+ return new Dictionary<string, object> { { "exe", exe } };
1636
+ }
1603
1637
  static List<KeyValuePair<string, string>> cache;
1604
1638
  static DateTime cachedAt;
1605
1639
  static readonly object Gate = new object();
@@ -1741,6 +1775,128 @@ namespace DshComputerUse
1741
1775
  // than creating an unbounded number of stuck threads on repeated reads.
1742
1776
  static readonly SemaphoreSlim WindowCollectors = new SemaphoreSlim(4, 4);
1743
1777
 
1778
+ static bool SameWindow(IntPtr hwnd, uint expectedPid)
1779
+ {
1780
+ uint pid;
1781
+ return expectedPid != 0 && Native.GetWindowThreadProcessId(hwnd, out pid) != 0 && pid == expectedPid;
1782
+ }
1783
+
1784
+ static bool IsActionWindow(IntPtr hwnd, uint pid, Native.POINT point)
1785
+ {
1786
+ if (!SameWindow(hwnd, pid) || Native.GetForegroundWindow() != hwnd) return false;
1787
+ var hit = Windows.At(point.X, point.Y);
1788
+ return hit.ContainsKey("hwnd") && Convert.ToInt64(hit["hwnd"]) == hwnd.ToInt64();
1789
+ }
1790
+
1791
+ public static object Act(Dictionary<string, object> r)
1792
+ {
1793
+ var hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
1794
+ uint pid = Convert.ToUInt32(r["pid"]);
1795
+ var point = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
1796
+ string runtimeId = Args.Str(r, "runtimeId", "");
1797
+ string action = Args.Str(r, "action", "");
1798
+ var result = new Dictionary<string, object> { { "performed", false } };
1799
+ if (runtimeId.Length == 0 || !IsActionWindow(hwnd, pid, point))
1800
+ throw new Exception("The named target window changed");
1801
+
1802
+ // FromPoint is scoped to the visible hit. Ancestors are searched only
1803
+ // for the exact listed element; no action is attempted on a substitute.
1804
+ var hit = AutomationElement.FromPoint(new System.Windows.Point(point.X, point.Y));
1805
+ AutomationElement target = null;
1806
+ for (var el = hit; el != null; el = TreeWalker.ControlViewWalker.GetParent(el))
1807
+ {
1808
+ if (String.Join(",", el.GetRuntimeId()) == runtimeId) { target = el; break; }
1809
+ if (el.Current.ControlType == ControlType.Window) break;
1810
+ }
1811
+ if (target == null || target.Current.IsOffscreen || !target.Current.IsEnabled)
1812
+ throw new Exception("The named target changed or is no longer actionable");
1813
+ object pattern = null;
1814
+ if (action == "invoke" && !target.TryGetCurrentPattern(InvokePattern.Pattern, out pattern)) return result;
1815
+ if (action == "focus" && !target.Current.IsKeyboardFocusable) return result;
1816
+ if (action != "invoke" && action != "focus") return result;
1817
+ if (!IsActionWindow(hwnd, pid, point))
1818
+ throw new Exception("The named target window changed");
1819
+
1820
+ // A provider error after dispatch is indeterminate. Let it surface
1821
+ // rather than claiming the host can safely click again.
1822
+ if (action == "invoke") ((InvokePattern)pattern).Invoke();
1823
+ else
1824
+ {
1825
+ target.SetFocus();
1826
+ for (int i = 0; i < 10 && !target.Current.HasKeyboardFocus; i++) Thread.Sleep(25);
1827
+ if (!target.Current.HasKeyboardFocus) throw new Exception("Could not verify focus on the named control");
1828
+ }
1829
+ result["performed"] = true;
1830
+ return result;
1831
+ }
1832
+
1833
+ static bool BrowserChrome(AutomationElement element)
1834
+ {
1835
+ // Page content can supply arbitrary UIA names and IDs.
1836
+ for (var parent = TreeWalker.ControlViewWalker.GetParent(element); parent != null; parent = TreeWalker.ControlViewWalker.GetParent(parent))
1837
+ {
1838
+ if (parent.Current.ControlType == ControlType.Document) return false;
1839
+ if (parent.Current.ControlType == ControlType.Window) return true;
1840
+ }
1841
+ return false;
1842
+ }
1843
+
1844
+ public static object BrowserTab(Dictionary<string, object> r)
1845
+ {
1846
+ IntPtr hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
1847
+ uint pid = Convert.ToUInt32(r["pid"]);
1848
+ string select = Args.Str(r, "select", "");
1849
+ if (!SameWindow(hwnd, pid) || !WindowCollectors.Wait(0)) return null;
1850
+ var clock = Stopwatch.StartNew();
1851
+ Dictionary<string, object> result = null;
1852
+ var worker = new Thread(delegate ()
1853
+ {
1854
+ try
1855
+ {
1856
+ var root = AutomationElement.FromHandle(hwnd);
1857
+ var controls = root.FindAll(TreeScope.Descendants, new OrCondition(
1858
+ new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
1859
+ new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem)));
1860
+ var state = new Dictionary<string, object>();
1861
+ foreach (AutomationElement el in controls)
1862
+ {
1863
+ if (el.Current.IsOffscreen) continue;
1864
+ object pattern;
1865
+ if (el.Current.ControlType == ControlType.Edit)
1866
+ {
1867
+ string id = el.Current.AutomationId;
1868
+ string name = el.Current.Name;
1869
+ if (id != "view_1012" && id != "urlbar-input" && name != "Address and search bar" && name != "地址和搜索栏") continue;
1870
+ if (BrowserChrome(el) && el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
1871
+ state["url"] = ((ValuePattern)pattern).Current.Value;
1872
+ }
1873
+ else if (el.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern) && BrowserChrome(el))
1874
+ {
1875
+ var tab = (SelectionItemPattern)pattern;
1876
+ string id = String.Join(",", el.GetRuntimeId());
1877
+ if (select.Length > 0 && id == select)
1878
+ {
1879
+ if (clock.ElapsedMilliseconds < 1200 && SameWindow(hwnd, pid) && Native.GetForegroundWindow() == hwnd)
1880
+ {
1881
+ if (!tab.Current.IsSelected) tab.Select();
1882
+ state["selected"] = true;
1883
+ }
1884
+ break;
1885
+ }
1886
+ if (tab.Current.IsSelected) state["tab"] = id;
1887
+ }
1888
+ }
1889
+ result = state;
1890
+ }
1891
+ catch (Exception) { }
1892
+ finally { WindowCollectors.Release(); }
1893
+ });
1894
+ worker.IsBackground = true;
1895
+ worker.SetApartmentState(ApartmentState.MTA);
1896
+ worker.Start();
1897
+ return worker.Join(1250) ? result : null;
1898
+ }
1899
+
1744
1900
  static List<object> CollectWindow(IntPtr hwnd, int max, bool includeText)
1745
1901
  {
1746
1902
  IntPtr render = ChromiumRoot(hwnd);
@@ -1805,12 +1961,19 @@ namespace DshComputerUse
1805
1961
  {
1806
1962
  result = CollectWindow(hwnd, max, all);
1807
1963
  if (result.Count < 4) { Thread.Sleep(400); result = CollectWindow(hwnd, max, all); } // Chromium builds its tree lazily
1964
+ foreach (Dictionary<string, object> item in result) item["windowHwnd"] = hwnd.ToInt64();
1808
1965
  }
1809
1966
  // An open menu or flyout is a window of its own, not a descendant of the one it belongs to.
1810
1967
  if (popups || popupsOnly) foreach (var extra in Popups(hwnd))
1811
1968
  {
1812
1969
  if (result.Count >= max) break;
1813
- try { result.AddRange(CollectWindow(extra, max - result.Count, all)); } catch (Exception) { }
1970
+ try
1971
+ {
1972
+ var popup = CollectWindow(extra, max - result.Count, all);
1973
+ foreach (Dictionary<string, object> item in popup) item["windowHwnd"] = extra.ToInt64();
1974
+ result.AddRange(popup);
1975
+ }
1976
+ catch (Exception) { }
1814
1977
  }
1815
1978
  }
1816
1979
  catch (Exception ex) { error = ex; }
@@ -1949,6 +2112,7 @@ namespace DshComputerUse
1949
2112
  cache.Add(AutomationElement.BoundingRectangleProperty);
1950
2113
  cache.Add(AutomationElement.IsEnabledProperty);
1951
2114
  cache.Add(AutomationElement.AutomationIdProperty);
2115
+ cache.Add(AutomationElement.RuntimeIdProperty);
1952
2116
  cache.Add(AutomationElement.ClassNameProperty);
1953
2117
  cache.Add(AutomationElement.IsKeyboardFocusableProperty);
1954
2118
  cache.Add(ValuePattern.ValueProperty);
@@ -1974,7 +2138,9 @@ namespace DshComputerUse
1974
2138
  if (type == ControlType.Group) d["editable"] = true;
1975
2139
  d["name"] = name.Length > 120 ? name.Substring(0, 120) + "…" : name;
1976
2140
  string aid = (el.GetCachedPropertyValue(AutomationElement.AutomationIdProperty) as string) ?? "";
1977
- if (aid.Length > 0) d["automationId"] = aid.Length > 120 ? aid.Substring(0, 120) + "…" : aid;
2141
+ if (aid.Length > 0) d["automationId"] = aid;
2142
+ var runtimeId = el.GetCachedPropertyValue(AutomationElement.RuntimeIdProperty, true) as int[];
2143
+ if (runtimeId != null && runtimeId.Length > 0) d["runtimeId"] = String.Join(",", runtimeId);
1978
2144
  d["focusable"] = (bool)el.GetCachedPropertyValue(AutomationElement.IsKeyboardFocusableProperty);
1979
2145
  object value = el.GetCachedPropertyValue(ValuePattern.ValueProperty, true);
1980
2146
  if (value is string && ((string)value).Length > 0) { var v = (string)value; d["value"] = v.Length > 120 ? v.Substring(0, 120) + "…" : v; }
package/lib/client.js CHANGED
@@ -28,6 +28,14 @@ window.__ModuleLoader__.load({
28
28
  //#endregion
29
29
  let react = require("react");
30
30
  react = __toESM(react, 1);
31
+ //#region lib/types/browser-host.js
32
+ function httpOrigin(value) {
33
+ try {
34
+ const url = new URL(value);
35
+ if (url.protocol === "http:" || url.protocol === "https:") return url.origin;
36
+ } catch {}
37
+ }
38
+ //#endregion
31
39
  //#region lib/types/settings.js
32
40
  /** The Loader entry id (settings namespace); see cordis.patch.yml. */
33
41
  const ENTRY_ID = "copylee-computer-use";
@@ -59,6 +67,7 @@ window.__ModuleLoader__.load({
59
67
  };
60
68
  const bool = (key) => typeof out[key] === "boolean" ? out[key] : DEFAULTS[key];
61
69
  return {
70
+ harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
62
71
  accessMode: out.accessMode === "allow-all" || out.accessMode === "per-app" ? out.accessMode : DEFAULTS.accessMode,
63
72
  overlay: bool("overlay"),
64
73
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
package/lib/index.js CHANGED
@@ -192,6 +192,37 @@ var AccessControl = class {
192
192
  }
193
193
  };
194
194
  //#endregion
195
+ //#region lib/types/browser-host.js
196
+ function isBrowser(win) {
197
+ return /^(?:chrome|msedge|firefox|brave|vivaldi|chromium)\.exe$/i.test(win.exe);
198
+ }
199
+ function httpOrigin(value) {
200
+ try {
201
+ const url = new URL(value);
202
+ if (url.protocol === "http:" || url.protocol === "https:") return url.origin;
203
+ } catch {}
204
+ }
205
+ function isHarnessAddress(address, harnessUrl) {
206
+ const expected = httpOrigin(harnessUrl);
207
+ if (!address || !expected) return false;
208
+ const actual = httpOrigin(address.includes("://") ? address : new URL(expected).protocol + "//" + address);
209
+ if (!actual) return false;
210
+ if (actual === expected) return true;
211
+ const loopback = /* @__PURE__ */ new Set([
212
+ "localhost",
213
+ "127.0.0.1",
214
+ "[::1]"
215
+ ]);
216
+ const a = new URL(actual), b = new URL(expected);
217
+ return loopback.has(a.hostname) && loopback.has(b.hostname) && a.protocol === b.protocol && a.port === b.port;
218
+ }
219
+ async function readBrowserTab(helper, win) {
220
+ return await helper.call("browser_tab", {
221
+ hwnd: win.hwnd,
222
+ pid: win.pid
223
+ }, 2500).catch(() => null) ?? void 0;
224
+ }
225
+ //#endregion
195
226
  //#region lib/types/coords.js
196
227
  /**
197
228
  * The model only ever sees one coordinate space: pixels of the most recent
@@ -493,9 +524,19 @@ const ROLES = {
493
524
  文本: ["Text"],
494
525
  文字: ["Text"]
495
526
  };
496
- /** "按钮:保存" → Button named 保存; a colon that is not after a known role stays part of the name. */
527
+ /** "按钮:保存" → Button named 保存; a colon that is not after a known role stays part of the name.
528
+ * "id:NavTasksButton" / "#NavTasksButton" → match the UIA AutomationId instead of the name. */
497
529
  function parseTarget(target) {
498
530
  const text = target.trim();
531
+ if (text.startsWith("#") && text.length > 1) return {
532
+ automationId: text.slice(1).trim(),
533
+ name: text
534
+ };
535
+ const byId = /^(?:id|automationid|自动化id)\s*[::]\s*(.+)$/i.exec(text);
536
+ if (byId) return {
537
+ automationId: byId[1].trim(),
538
+ name: text
539
+ };
499
540
  const colon = text.search(/[::]/);
500
541
  if (colon > 0) {
501
542
  const roles = ROLES[text.slice(0, colon).trim().toLowerCase().replace(/[\s_-]/g, "")];
@@ -524,6 +565,19 @@ const center = (el) => `${Math.round(el.x + el.width / 2)},${Math.round(el.y + e
524
565
  */
525
566
  function matchTarget(elements, target) {
526
567
  const query = parseTarget(target);
568
+ if (query.automationId) {
569
+ const wantedId = query.automationId;
570
+ const exact = elements.filter((el) => (el.automationId ?? "") === wantedId);
571
+ const matches = exact.length > 0 ? exact : elements.filter((el) => (el.automationId ?? "").toLowerCase() === wantedId.toLowerCase());
572
+ if (matches.length === 1) return {
573
+ kind: "found",
574
+ element: matches[0]
575
+ };
576
+ if (matches.length > 1) return {
577
+ kind: "ambiguous",
578
+ candidates: matches.slice(0, 8)
579
+ };
580
+ }
527
581
  const wanted = normalizeName(query.name);
528
582
  if (wanted === "") return {
529
583
  kind: "missing",
@@ -916,17 +970,45 @@ var Computer = class Computer {
916
970
  if (!win) return "Foreground window: none (desktop).";
917
971
  return `Foreground window: ${win.exe} — "${win.title.slice(0, 80)}".`;
918
972
  }
919
- assertAllowed(call, win, verb) {
973
+ async assertAllowed(call, win, verb) {
920
974
  const s = this.settings();
921
975
  const reason = this.access.denial(call.session, win, s.accessMode, s.blockedApps, verb);
922
976
  if (reason) throw new Error(reason);
977
+ if (win && s.harnessUrl && isBrowser(win)) {
978
+ const tab = await readBrowserTab(this.helper, win);
979
+ if (isHarnessAddress(tab?.url, s.harnessUrl) || this.overlay.isRememberedWebWindow(win)) throw new Error("The DeepSeek Harness Web tab is protected. Use open_application with a URL to open a separate browser window.");
980
+ if (typeof tab?.url !== "string" || !tab.tab) throw new Error("Could not verify the active browser tab. Use open_application with a URL or switch to a browser window with a visible address bar.");
981
+ }
923
982
  }
924
983
  async checkPointer(call, point, verb) {
925
984
  const target = point ?? await this.cursor();
926
- this.assertAllowed(call, await this.windowAt(target), verb);
985
+ await this.assertAllowed(call, await this.windowAt(target), verb);
927
986
  }
928
987
  async checkKeyboard(call, verb) {
929
- this.assertAllowed(call, await this.foreground(), verb);
988
+ const window = await this.foreground();
989
+ await this.assertAllowed(call, window, verb);
990
+ return window;
991
+ }
992
+ async sendKeys(call, combos, holdMs) {
993
+ const window = await this.checkKeyboard(call, "send keys to");
994
+ const args = holdMs === void 0 ? {} : { holdMs };
995
+ if (!this.settings().harnessUrl || !window || !isBrowser(window) || combos.length < 2) {
996
+ await this.helper.call("keys", {
997
+ combos,
998
+ ...args
999
+ }, holdMs === void 0 ? void 0 : 2e4);
1000
+ return;
1001
+ }
1002
+ for (const [index, combo] of combos.entries()) {
1003
+ if (index > 0) {
1004
+ await setTimeout$1(100, void 0, { signal: call.signal });
1005
+ await this.checkNamed(call, window);
1006
+ }
1007
+ await this.helper.call("keys", {
1008
+ combos: [combo],
1009
+ ...args
1010
+ }, holdMs === void 0 ? void 0 : 2e4);
1011
+ }
930
1012
  }
931
1013
  /** Overlay status line for an action (Chinese, shown to the user). */
932
1014
  static statusOf(input) {
@@ -957,8 +1039,9 @@ var Computer = class Computer {
957
1039
  * own). They are read separately because scanning both costs a second or
958
1040
  * more on a file dialog, and the control is nearly always in the window.
959
1041
  */
960
- async elements(where = "window") {
1042
+ async elements(where = "window", hwnd) {
961
1043
  const result = await this.helper.call("ui", {
1044
+ ...hwnd === void 0 ? {} : { hwnd },
962
1045
  includeText: true,
963
1046
  maxNodes: 400,
964
1047
  ...where === "popups" ? { popupsOnly: true } : {}
@@ -966,11 +1049,11 @@ var Computer = class Computer {
966
1049
  return Array.isArray(result.elements) ? result.elements : [];
967
1050
  }
968
1051
  /** Look for a named control in the window, and only if it is not there in its popups. */
969
- async find(target) {
970
- const inWindow = await this.elements("window").catch(() => []);
1052
+ async find(target, hwnd) {
1053
+ const inWindow = await this.elements("window", hwnd).catch(() => []);
971
1054
  const match = matchTarget(inWindow, target);
972
1055
  if (match.kind !== "missing") return match;
973
- const inPopups = await this.elements("popups").catch(() => []);
1056
+ const inPopups = await this.elements("popups", hwnd).catch(() => []);
974
1057
  if (inPopups.length === 0) return match;
975
1058
  const second = matchTarget(inPopups, target);
976
1059
  return second.kind === "missing" ? matchTarget([...inWindow, ...inPopups], target) : second;
@@ -984,7 +1067,9 @@ var Computer = class Computer {
984
1067
  const started = Date.now();
985
1068
  for (;;) {
986
1069
  if (signal.aborted) throw new Error("Cancelled.");
987
- const match = await this.find(target);
1070
+ const window = await this.foreground();
1071
+ if (!window) throw new Error("No foreground window for the named target.");
1072
+ const match = await this.find(target, window.hwnd);
988
1073
  if (match.kind === "found") {
989
1074
  const el = match.element;
990
1075
  return {
@@ -992,7 +1077,8 @@ var Computer = class Computer {
992
1077
  x: Math.round(el.x + el.width / 2),
993
1078
  y: Math.round(el.y + el.height / 2)
994
1079
  },
995
- element: el
1080
+ element: el,
1081
+ window
996
1082
  };
997
1083
  }
998
1084
  if (match.kind === "ambiguous") {
@@ -1015,9 +1101,11 @@ var Computer = class Computer {
1015
1101
  /** The point an action aims at: a named control, a coordinate, or nothing (the cursor). */
1016
1102
  async aim(input, call) {
1017
1103
  if (typeof input.target === "string" && input.target.trim() !== "") {
1018
- const { point, element } = await this.locate(input.target, call.signal);
1104
+ const named = await this.locate(input.target, call.signal);
1105
+ const { point, element } = named;
1019
1106
  return {
1020
1107
  point,
1108
+ named,
1021
1109
  label: ` on ${element.role} "${element.name.slice(0, 60)}"`
1022
1110
  };
1023
1111
  }
@@ -1030,6 +1118,44 @@ var Computer = class Computer {
1030
1118
  label: " at the cursor"
1031
1119
  };
1032
1120
  }
1121
+ async checkNamed(call, win) {
1122
+ const current = await this.foreground();
1123
+ if (current?.hwnd !== win.hwnd || current.pid !== win.pid) throw new Error("The named target window changed. Look again before acting.");
1124
+ await this.assertAllowed(call, current, "act on");
1125
+ }
1126
+ async checkNamedPoint(call, point, window, element) {
1127
+ await this.checkNamed(call, window);
1128
+ const hit = await this.windowAt(point);
1129
+ if (!hit || hit.pid !== window.pid || hit.hwnd !== (element.windowHwnd ?? window.hwnd)) throw new Error("Another window covers the named target. Look again before acting.");
1130
+ if (hit.hwnd !== window.hwnd && !isBrowser(window)) await this.assertAllowed(call, hit, "click");
1131
+ return hit;
1132
+ }
1133
+ async semanticAction(call, named, action) {
1134
+ const { window, element, point } = named;
1135
+ const hit = await this.checkNamedPoint(call, point, window, element);
1136
+ if (!element.runtimeId || hit.hwnd !== window.hwnd) return false;
1137
+ if (call.signal.aborted) throw new Error("Cancelled.");
1138
+ const result = await this.helper.call("act", {
1139
+ hwnd: window.hwnd,
1140
+ pid: window.pid,
1141
+ ...point,
1142
+ runtimeId: element.runtimeId,
1143
+ action
1144
+ }, 4e3);
1145
+ if (result?.performed === true) return true;
1146
+ if (result?.performed !== false) throw new Error("UI Automation did not confirm whether the action ran. Look again before retrying.");
1147
+ return false;
1148
+ }
1149
+ async namedClickPoint(call, target, named) {
1150
+ if (!named.element.runtimeId) {
1151
+ await this.checkNamedPoint(call, named.point, named.window, named.element);
1152
+ return named.point;
1153
+ }
1154
+ const live = await this.locate(target, call.signal, 0);
1155
+ if (live.window.hwnd !== named.window.hwnd || live.window.pid !== named.window.pid || live.element.runtimeId !== named.element.runtimeId || live.element.windowHwnd !== named.element.windowHwnd) throw new Error("The named control changed. Look again before acting.");
1156
+ await this.checkNamedPoint(call, live.point, live.window, live.element);
1157
+ return live.point;
1158
+ }
1033
1159
  /** wait with `until`: done as soon as the window or control is there (or gone). */
1034
1160
  async waitUntil(input, signal) {
1035
1161
  const until = (input.until ?? "").trim();
@@ -1141,11 +1267,17 @@ var Computer = class Computer {
1141
1267
  case "middle_click":
1142
1268
  case "double_click":
1143
1269
  case "triple_click": {
1144
- const { point: p, label } = await this.aim(input, call);
1145
- await this.checkPointer(call, p, "click");
1270
+ const { point, label, named } = await this.aim(input, call);
1271
+ let p = point;
1272
+ if (!named) await this.checkPointer(call, p, "click");
1146
1273
  const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
1147
1274
  const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
1148
1275
  const modifiers = parseModifiers(input.modifiers ?? input.text);
1276
+ if (action === "left_click" && named && modifiers.length === 0) {
1277
+ const semantic = named.element.role === "Edit" || named.element.editable ? "focus" : "invoke";
1278
+ if (await this.semanticAction(call, named, semantic)) return { text: `${semantic === "focus" ? "Focused" : "Invoked"}${label}.` };
1279
+ }
1280
+ if (named) p = await this.namedClickPoint(call, input.target, named);
1149
1281
  await this.helper.call("click", {
1150
1282
  ...p ?? {},
1151
1283
  button,
@@ -1199,34 +1331,35 @@ var Computer = class Computer {
1199
1331
  if (text === "") throw new Error("type needs text.");
1200
1332
  let into = "";
1201
1333
  if (input.target || input.coordinate) {
1202
- const { point: p, label } = await this.aim(input, call);
1203
- await this.checkPointer(call, p, "click");
1204
- await this.helper.call("click", {
1205
- ...p ?? {},
1206
- button: "left",
1207
- count: 1,
1208
- modifiers: []
1209
- });
1334
+ const { point, label, named } = await this.aim(input, call);
1335
+ let p = point;
1336
+ const focused = named && await this.semanticAction(call, named, "focus");
1337
+ if (!focused) {
1338
+ if (named) p = await this.namedClickPoint(call, input.target, named);
1339
+ else await this.checkPointer(call, p, "click");
1340
+ await this.helper.call("click", {
1341
+ ...p ?? {},
1342
+ button: "left",
1343
+ count: 1,
1344
+ modifiers: []
1345
+ });
1346
+ }
1210
1347
  await setTimeout$1(120, void 0, { signal: call.signal });
1211
- into = ` (clicked${label} first)`;
1348
+ if (named) await this.checkNamed(call, named.window);
1349
+ into = ` (${focused ? "focused" : "clicked"}${label} first)`;
1212
1350
  }
1213
1351
  await this.checkKeyboard(call, "type into");
1214
1352
  return { text: `${await this.enterText(text, call)}${into}` };
1215
1353
  }
1216
1354
  case "key": {
1217
1355
  const combos = parseKeys(input.text ?? "");
1218
- await this.checkKeyboard(call, "send keys to");
1219
- await this.helper.call("keys", { combos });
1356
+ await this.sendKeys(call, combos);
1220
1357
  return { text: `Pressed ${input.text}.` };
1221
1358
  }
1222
1359
  case "hold_key": {
1223
1360
  const combos = parseKeys(input.text ?? "");
1224
1361
  const seconds = Math.min(10, Math.max(.05, input.duration ?? .5));
1225
- await this.checkKeyboard(call, "send keys to");
1226
- await this.helper.call("keys", {
1227
- combos,
1228
- holdMs: Math.round(seconds * 1e3)
1229
- }, 2e4);
1362
+ await this.sendKeys(call, combos, Math.round(seconds * 1e3));
1230
1363
  return { text: `Held ${input.text} for ${seconds}s.` };
1231
1364
  }
1232
1365
  }
@@ -1844,6 +1977,9 @@ var OverlayController = class {
1844
1977
  unusedTimer;
1845
1978
  otherTools = 0;
1846
1979
  hostWindows = [];
1980
+ returnTo;
1981
+ ending;
1982
+ starting;
1847
1983
  stopping = false;
1848
1984
  /** Progress card lines: the reply as it streams, and what the agent is doing. */
1849
1985
  streamAgent;
@@ -1914,6 +2050,8 @@ var OverlayController = class {
1914
2050
  }
1915
2051
  /** Called before every action: shows the overlay once and updates its status line. */
1916
2052
  async begin(agent, status) {
2053
+ await this.ending;
2054
+ await this.starting;
1917
2055
  if (agent) this.agent = agent;
1918
2056
  this.armIdle();
1919
2057
  this.armUnused();
@@ -1921,27 +2059,11 @@ var OverlayController = class {
1921
2059
  if (!this.visible) {
1922
2060
  this.visible = true;
1923
2061
  this.paused = false;
1924
- await this.onStart?.().catch((error) => this.log(`overlay start: ${String(error)}`));
1925
- await this.shrinkHost(settings.hostWindow);
1926
- const pet = settings.hostWindow === "pet";
1927
- if (settings.overlay || pet) {
1928
- if (this.streamAgent !== agent) {
1929
- this.text = "";
1930
- this.thinking = "";
1931
- }
1932
- this.steps = status ? [status] : [];
1933
- this.thinkingLatest = false;
1934
- await this.helper.call("overlay_show", {
1935
- label: pet ? `${settings.overlayLabel || "DeepSeek Harness"} 正在操控` : `${settings.overlayLabel || "DeepSeek Harness"} 正在操控你的电脑`,
1936
- status,
1937
- icon: this.iconPath,
1938
- iconLight: this.iconPath.replace(/deepseek-white\.png$/, "deepseek-black.png"),
1939
- idleMs: settings.userIdleMs,
1940
- glow: settings.overlay,
1941
- pet,
1942
- petOpacity: settings.cardOpacity,
1943
- text: this.text
1944
- }).catch((error) => this.log(`overlay: ${String(error)}`));
2062
+ this.starting = this.start(agent, status, settings);
2063
+ try {
2064
+ await this.starting;
2065
+ } finally {
2066
+ this.starting = void 0;
1945
2067
  }
1946
2068
  return;
1947
2069
  }
@@ -1952,6 +2074,31 @@ var OverlayController = class {
1952
2074
  }
1953
2075
  await this.status(status);
1954
2076
  }
2077
+ async start(agent, status, settings) {
2078
+ await this.rememberHost(settings.harnessUrl).catch((error) => this.log(`remember host: ${String(error)}`));
2079
+ await this.onStart?.().catch((error) => this.log(`overlay start: ${String(error)}`));
2080
+ await this.shrinkHost(settings.hostWindow);
2081
+ const pet = settings.hostWindow === "pet";
2082
+ if (settings.overlay || pet) {
2083
+ if (this.streamAgent !== agent) {
2084
+ this.text = "";
2085
+ this.thinking = "";
2086
+ }
2087
+ this.steps = status ? [status] : [];
2088
+ this.thinkingLatest = false;
2089
+ await this.helper.call("overlay_show", {
2090
+ label: pet ? `${settings.overlayLabel || "DeepSeek Harness"} 正在操控` : `${settings.overlayLabel || "DeepSeek Harness"} 正在操控你的电脑`,
2091
+ status,
2092
+ icon: this.iconPath,
2093
+ iconLight: this.iconPath.replace(/deepseek-white\.png$/, "deepseek-black.png"),
2094
+ idleMs: settings.userIdleMs,
2095
+ glow: settings.overlay,
2096
+ pet,
2097
+ petOpacity: settings.cardOpacity,
2098
+ text: this.text
2099
+ }).catch((error) => this.log(`overlay: ${String(error)}`));
2100
+ }
2101
+ }
1955
2102
  async status(status) {
1956
2103
  const settings = this.settings();
1957
2104
  if (!this.visible) return;
@@ -2027,6 +2174,7 @@ var OverlayController = class {
2027
2174
  }
2028
2175
  /** Agent finished (idle), was cancelled, or the plugin is stopping. */
2029
2176
  async end(agent) {
2177
+ if (this.starting) await this.starting;
2030
2178
  if (agent !== void 0 && this.agent !== void 0 && agent !== this.agent) return;
2031
2179
  if (this.idleTimer) clearTimeout(this.idleTimer);
2032
2180
  this.idleTimer = void 0;
@@ -2035,18 +2183,70 @@ var OverlayController = class {
2035
2183
  this.otherTools = 0;
2036
2184
  this.agent = void 0;
2037
2185
  this.paused = false;
2038
- if (!this.visible) return;
2186
+ if (!this.visible) return this.ending;
2039
2187
  this.visible = false;
2040
2188
  if (this.pushTimer) {
2041
2189
  clearTimeout(this.pushTimer);
2042
2190
  this.pushTimer = void 0;
2043
2191
  }
2044
- if (this.settings().hostWindow === "pet" && !this.stopping) await this.helper.call("pet_finish", {
2045
- text: this.text,
2046
- holdMs: FINISH_HOLD_MS
2047
- }).catch(() => {});
2048
- else await this.helper.call("overlay_hide").catch(() => {});
2049
- await this.restoreHost();
2192
+ this.ending = (async () => {
2193
+ if (this.settings().hostWindow === "pet" && !this.stopping) await this.helper.call("pet_finish", {
2194
+ text: this.text,
2195
+ holdMs: FINISH_HOLD_MS
2196
+ }).catch(() => {});
2197
+ else await this.helper.call("overlay_hide").catch(() => {});
2198
+ await this.restoreHost();
2199
+ await this.focusRememberedHost().catch((error) => this.log(`restore focus: ${String(error)}`));
2200
+ })();
2201
+ try {
2202
+ await this.ending;
2203
+ } finally {
2204
+ this.ending = void 0;
2205
+ }
2206
+ }
2207
+ isRememberedWebWindow(win) {
2208
+ const target = this.returnTo;
2209
+ return target?.web === true && target.window.hwnd === win.hwnd && target.window.pid === win.pid;
2210
+ }
2211
+ async rememberHost(harnessUrl) {
2212
+ const foreground = await this.helper.call("foreground");
2213
+ if (foreground?.hwnd && isHostWindow(foreground)) {
2214
+ this.returnTo = {
2215
+ window: foreground,
2216
+ web: false
2217
+ };
2218
+ return;
2219
+ }
2220
+ if (foreground?.hwnd && harnessUrl && isBrowser(foreground)) {
2221
+ const state = await readBrowserTab(this.helper, foreground);
2222
+ if (isHarnessAddress(state?.url, harnessUrl)) {
2223
+ this.returnTo = {
2224
+ window: foreground,
2225
+ web: true,
2226
+ tab: state?.tab
2227
+ };
2228
+ return;
2229
+ }
2230
+ }
2231
+ const desktop = (await this.helper.call("windows")).filter((win) => isHostWindow(win) && !win.minimized).sort((a, b) => b.width * b.height - a.width * a.height)[0];
2232
+ if (desktop) this.returnTo = {
2233
+ window: desktop,
2234
+ web: false
2235
+ };
2236
+ }
2237
+ async focusRememberedHost() {
2238
+ const target = this.returnTo;
2239
+ this.returnTo = void 0;
2240
+ if (!target) return;
2241
+ const { hwnd, pid } = target.window;
2242
+ if ((await this.helper.call("focus", {
2243
+ hwnd,
2244
+ pid
2245
+ }, 3e3))?.focused && target.web && target.tab) await this.helper.call("browser_tab", {
2246
+ hwnd,
2247
+ pid,
2248
+ select: target.tab
2249
+ }, 2500);
2050
2250
  }
2051
2251
  stop(reason) {
2052
2252
  if (this.stopping) return;
@@ -2096,7 +2296,8 @@ var OverlayController = class {
2096
2296
  });
2097
2297
  this.hostWindows = rows.map((row) => ({
2098
2298
  hwnd: row.hwnd,
2099
- mode: "minimize"
2299
+ mode: "minimize",
2300
+ maximized: row.maximized
2100
2301
  }));
2101
2302
  return;
2102
2303
  }
@@ -2148,7 +2349,7 @@ var OverlayController = class {
2148
2349
  }, 1200).unref();
2149
2350
  } else await this.helper.call("window_cmd", {
2150
2351
  hwnd: win.hwnd,
2151
- op: "restore"
2352
+ op: win.maximized ? "maximize" : "restore"
2152
2353
  }).catch(() => {});
2153
2354
  }
2154
2355
  };
@@ -2168,6 +2369,8 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
2168
2369
  - 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.
2169
2370
  - 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.
2170
2371
  - 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.
2372
+ - When two controls share a name, ui_elements reports automationId; use target "id:<AutomationId>" (or "#<AutomationId>") to pick the intended one.
2373
+ - Open HTTP(S) URLs with open_application so they use a new browser window. The DeepSeek Harness Web tab is protected just like the desktop chat window.
2171
2374
  - 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.
2172
2375
  - 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.
2173
2376
  - 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.
@@ -2407,6 +2610,7 @@ function resolveConfig(raw) {
2407
2610
  };
2408
2611
  const bool = (key) => typeof out[key] === "boolean" ? out[key] : DEFAULTS[key];
2409
2612
  return {
2613
+ harnessUrl: typeof out.harnessUrl === "string" ? httpOrigin(out.harnessUrl.trim()) : void 0,
2410
2614
  accessMode: out.accessMode === "allow-all" || out.accessMode === "per-app" ? out.accessMode : DEFAULTS.accessMode,
2411
2615
  overlay: bool("overlay"),
2412
2616
  overlayLabel: typeof out.overlayLabel === "string" && out.overlayLabel.trim() !== "" ? out.overlayLabel.trim().slice(0, 40) : DEFAULTS.overlayLabel,
@@ -8826,6 +9030,7 @@ function createTools(host) {
8826
9030
  await computer.overlay.yieldToUser(call.signal, false);
8827
9031
  const before = await computer.foreground();
8828
9032
  let how;
9033
+ let openedUrlWindow;
8829
9034
  const isUri = isUrl || /^[a-z][a-z0-9+.-]+:(?![\/])/i.test(name);
8830
9035
  const running = isUri || newInstance ? void 0 : (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
8831
9036
  const hidden = running || isUri || newInstance ? void 0 : (await computer.backgroundApps(false)).find((win) => !isHostWindow(win) && appMatches(name, win));
@@ -8839,12 +9044,22 @@ function createTools(host) {
8839
9044
  query: name,
8840
9045
  limit: 5
8841
9046
  }, 3e4))[0];
9047
+ const existing = isUrl ? new Set((await computer.windows()).map((win) => win.hwnd)) : void 0;
9048
+ const browser = isUrl ? await computer.helper.call("open_url", { url: name }) : void 0;
8842
9049
  if (app) await computer.helper.call("launch", { appId: app.id });
8843
- else await computer.helper.call("launch", { target: name });
8844
- how = app ? `Launched "${app.name}".` : isUrl ? `Opened ${name} in the default browser.` : `Started "${name}".`;
9050
+ else if (!isUrl) await computer.helper.call("launch", { target: name });
9051
+ how = app ? `Launched "${app.name}".` : isUrl ? `Requested a new browser window for ${name}.` : `Started "${name}".`;
8845
9052
  for (let i = 0; i < 80; i++) {
8846
9053
  await setTimeout$1(100, void 0, { signal: call.signal });
8847
9054
  const now = await computer.foreground();
9055
+ if (browser) {
9056
+ if (now?.exe.toLowerCase() === browser.exe && !existing.has(now.hwnd)) {
9057
+ openedUrlWindow = now;
9058
+ how = `Opened ${name} in a new browser window.`;
9059
+ break;
9060
+ }
9061
+ continue;
9062
+ }
8848
9063
  if (now && now.hwnd !== before?.hwnd && !isHostWindow(now) && !isTransientShell(now) && (now.exe.toLowerCase() !== "explorer.exe" || now.className === "CabinetWClass")) break;
8849
9064
  if (i >= 10 && i % 10 === 0 && !isUri) {
8850
9065
  const opened = (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
@@ -8856,7 +9071,7 @@ function createTools(host) {
8856
9071
  }
8857
9072
  }
8858
9073
  const fg = await computer.foreground();
8859
- if (fg && !isHostWindow(fg) && settings.accessMode === "per-app" && (computer.access.missing(call.session, [appName]).length === 0 || isUrl)) computer.access.grant(call.session, [fg.exe]);
9074
+ if (fg && !isHostWindow(fg) && settings.accessMode === "per-app" && (isUrl ? openedUrlWindow?.hwnd === fg.hwnd && openedUrlWindow.pid === fg.pid : computer.access.missing(call.session, [appName]).length === 0)) computer.access.grant(call.session, [fg.exe]);
8860
9075
  return `${how} ${await computer.describeForeground()}${skillNote(call.session, name, fg)}`;
8861
9076
  }
8862
9077
  }
@@ -8935,6 +9150,10 @@ function createTools(host) {
8935
9150
  if (denial && action !== "minimize") throw new Error(denial);
8936
9151
  await computer.overlay.begin(call.agent, `窗口 ${action}`);
8937
9152
  await computer.overlay.yieldToUser(call.signal, false);
9153
+ if (action === "close") {
9154
+ if (computer.overlay.isRememberedWebWindow(target)) throw new Error("This window contains the protected DeepSeek Harness Web tab.");
9155
+ await computer.assertAllowed(call, target, "close");
9156
+ }
8938
9157
  let text;
8939
9158
  if (action === "focus") text = (await computer.focus(target)).focused ? `Focused ${target.exe} ("${target.title.slice(0, 60)}").` : `Windows refused to focus ${target.exe}; try clicking it.`;
8940
9159
  else {
@@ -9176,6 +9395,10 @@ function createTools(host) {
9176
9395
  const name = "@copylee/dsh-computer-use";
9177
9396
  const inject = ["tools", "attachments"];
9178
9397
  const Config = z.object({
9398
+ harnessUrl: z.string().default("").volatile().i18n({
9399
+ "zh-CN": { $description: "DSH Web GUI 地址。留空时使用本地 Web 服务端口。反代或自定义域名请填写实际访问地址。" },
9400
+ "en-US": { $description: "DSH Web GUI URL. Leave blank to use the local Web server port. Set the actual URL when using a reverse proxy or custom domain." }
9401
+ }),
9179
9402
  accessMode: z.union([z.const("per-app").i18n({
9180
9403
  "zh-CN": { $description: "按应用授权(每个会话由你批准要操控的应用)" },
9181
9404
  "en-US": { $description: "Per app (approve the apps each session)" }
@@ -9282,7 +9505,12 @@ function apply(ctx, config = {}) {
9282
9505
  ctx.logger.warn("dsh-computer-use only supports Windows; no tools registered.");
9283
9506
  return;
9284
9507
  }
9285
- const settings = () => resolveConfig(config);
9508
+ const settings = () => {
9509
+ const resolved = resolveConfig(config);
9510
+ const port = ctx.get("webServer")?.port;
9511
+ if (!resolved.harnessUrl && port) resolved.harnessUrl = `http://127.0.0.1:${port}`;
9512
+ return resolved;
9513
+ };
9286
9514
  const log = (message) => ctx.logger.info(message);
9287
9515
  const helper = new NativeHelper(new HelperClient((message) => ctx.logger.warn(message)), (message) => ctx.logger.warn(message), () => settings().nativeHelper);
9288
9516
  const access = new AccessControl();
@@ -0,0 +1,15 @@
1
+ import type { HelperLike } from './helper-client.js';
2
+ interface BrowserWindow {
3
+ hwnd: number;
4
+ pid: number;
5
+ exe: string;
6
+ }
7
+ export interface BrowserTab {
8
+ url?: string;
9
+ tab?: string;
10
+ }
11
+ export declare function isBrowser(win: BrowserWindow): boolean;
12
+ export declare function httpOrigin(value: string): string | undefined;
13
+ export declare function isHarnessAddress(address: string | undefined, harnessUrl: string): boolean;
14
+ export declare function readBrowserTab(helper: HelperLike, win: BrowserWindow): Promise<BrowserTab | undefined>;
15
+ export {};
@@ -4,6 +4,8 @@ import type { HelperLike } from './helper-client.js';
4
4
  import { type UiElement } from './target.js';
5
5
  import type { CancellableAgent, HostWindowMode, OverlayController } from './overlay.js';
6
6
  export interface Settings {
7
+ /** Web GUI origin, inferred from the local web server unless configured. */
8
+ harnessUrl?: string | undefined;
7
9
  accessMode: AccessMode;
8
10
  blockedApps: string[];
9
11
  overlay: boolean;
@@ -155,9 +157,10 @@ export declare class Computer {
155
157
  cursor(): Promise<Point>;
156
158
  /** Short description of the frontmost window, for result text. */
157
159
  describeForeground(): Promise<string>;
158
- private assertAllowed;
160
+ assertAllowed(call: CallContext, win: WindowInfo | undefined, verb: string): Promise<void>;
159
161
  private checkPointer;
160
162
  private checkKeyboard;
163
+ private sendKeys;
161
164
  /** Overlay status line for an action (Chinese, shown to the user). */
162
165
  static statusOf(input: ActionInput): string;
163
166
  /**
@@ -166,7 +169,7 @@ export declare class Computer {
166
169
  * own). They are read separately because scanning both costs a second or
167
170
  * more on a file dialog, and the control is nearly always in the window.
168
171
  */
169
- elements(where?: 'window' | 'popups'): Promise<UiElement[]>;
172
+ elements(where?: 'window' | 'popups', hwnd?: number): Promise<UiElement[]>;
170
173
  /** Look for a named control in the window, and only if it is not there in its popups. */
171
174
  private find;
172
175
  /**
@@ -177,9 +180,14 @@ export declare class Computer {
177
180
  locate(target: string, signal: AbortSignal, waitMs?: number): Promise<{
178
181
  point: Point;
179
182
  element: UiElement;
183
+ window: WindowInfo;
180
184
  }>;
181
185
  /** The point an action aims at: a named control, a coordinate, or nothing (the cursor). */
182
186
  private aim;
187
+ private checkNamed;
188
+ private checkNamedPoint;
189
+ private semanticAction;
190
+ private namedClickPoint;
183
191
  /** wait with `until`: done as soon as the window or control is there (or gone). */
184
192
  private waitUntil;
185
193
  /** Run one action. Returns text plus an image for screenshot/zoom. */
@@ -7,6 +7,7 @@ export { DEFAULTS, ENTRY_ID, resolveConfig } from './settings.js';
7
7
  export declare const name = "@copylee/dsh-computer-use";
8
8
  export declare const inject: string[];
9
9
  export interface Config {
10
+ harnessUrl?: string;
10
11
  accessMode?: AccessMode;
11
12
  overlay?: boolean;
12
13
  overlayLabel?: string;
@@ -17,6 +17,7 @@ export interface StreamFrame {
17
17
  /** Markdown reduced to one plain line for the progress card. */
18
18
  export declare function plainLine(text: string): string;
19
19
  export interface OverlaySettings {
20
+ harnessUrl?: string | undefined;
20
21
  overlay: boolean;
21
22
  overlayLabel: string;
22
23
  hostWindow: HostWindowMode;
@@ -54,6 +55,9 @@ export declare class OverlayController {
54
55
  private unusedTimer;
55
56
  private otherTools;
56
57
  private hostWindows;
58
+ private returnTo;
59
+ private ending;
60
+ private starting;
57
61
  private stopping;
58
62
  /** Progress card lines: the reply as it streams, and what the agent is doing. */
59
63
  private streamAgent;
@@ -91,6 +95,7 @@ export declare class OverlayController {
91
95
  yieldToUser(signal: AbortSignal, waitForTyping: boolean): Promise<boolean>;
92
96
  /** Called before every action: shows the overlay once and updates its status line. */
93
97
  begin(agent: CancellableAgent | undefined, status: string): Promise<void>;
98
+ private start;
94
99
  status(status: string): Promise<void>;
95
100
  /** One more step on the card's timeline. */
96
101
  private step;
@@ -101,6 +106,12 @@ export declare class OverlayController {
101
106
  private schedulePush;
102
107
  /** Agent finished (idle), was cancelled, or the plugin is stopping. */
103
108
  end(agent?: CancellableAgent): Promise<void>;
109
+ isRememberedWebWindow(win: {
110
+ hwnd: number;
111
+ pid: number;
112
+ }): boolean;
113
+ private rememberHost;
114
+ private focusRememberedHost;
104
115
  private stop;
105
116
  /** Counted from the last computer action only: model output and other tools do not keep the overlay up. */
106
117
  private armUnused;
@@ -17,6 +17,9 @@ export interface UiElement {
17
17
  focusable?: boolean;
18
18
  /** True for web contenteditable composers (ProseMirror/tiptap/CodeMirror...). */
19
19
  editable?: boolean;
20
+ /** Internal UIA identity used to verify a live named target before dispatch. */
21
+ runtimeId?: string;
22
+ windowHwnd?: number;
20
23
  x: number;
21
24
  y: number;
22
25
  width: number;
@@ -26,6 +29,8 @@ export interface TargetQuery {
26
29
  /** UI Automation control type, when the target named one ("按钮:保存"). */
27
30
  role?: string;
28
31
  name: string;
32
+ /** Explicit AutomationId, when the target was "id:<AutomationId>" or "#<AutomationId>". */
33
+ automationId?: string;
29
34
  }
30
35
  export type TargetMatch = {
31
36
  kind: 'found';
@@ -37,7 +42,8 @@ export type TargetMatch = {
37
42
  kind: 'missing';
38
43
  suggestions: string[];
39
44
  };
40
- /** "按钮:保存" → Button named 保存; a colon that is not after a known role stays part of the name. */
45
+ /** "按钮:保存" → Button named 保存; a colon that is not after a known role stays part of the name.
46
+ * "id:NavTasksButton" / "#NavTasksButton" → match the UIA AutomationId instead of the name. */
41
47
  export declare function parseTarget(target: string): TargetQuery & {
42
48
  roles?: string[];
43
49
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.8.1",
3
+ "version": "0.8.2",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "type": "module",
6
6
  "author": "copylee",