@copylee/dsh-computer-use 0.5.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -15
- package/helper/CuHelper.cs +150 -5
- package/lib/client.js +139 -7
- package/lib/index.js +373 -47
- package/lib/types/client/accent.d.ts +39 -0
- package/lib/types/client/select.d.ts +1 -1
- package/lib/types/computer.d.ts +30 -1
- package/lib/types/target.d.ts +49 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,18 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-computer-use
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/@copylee/dsh-computer-use)
|
|
4
4
|
|
|
5
5
|
让 DeepSeek Harness 直接操控你的 Windows 电脑:看屏幕、点鼠标、敲键盘,打开应用、切换窗口、读写剪贴板。控制期间屏幕四周会泛起**橙色光晕**,顶部出现“**DeepSeek Harness 正在操控你的电脑**”提示条,DeepSeek Harness 自己最小化,右下角换成一张**迷你进度卡片**,两行滚动显示 AI 的回复正文和思考 / 工具调用,让你同时看清操作过程和 AI 在想什么。按 **Esc** 暂停 / 继续,点“停止”结束本轮。
|
|
6
6
|
|
|
7
|
+
仅支持 Windows。
|
|
8
|
+
|
|
9
|
+
## 功能
|
|
10
|
+
|
|
7
11
|
| 功能 | 说明 |
|
|
8
12
|
|---|---|
|
|
9
13
|
| 截图即坐标系 | 模型只用最近一张截图的像素坐标,DPI、缩放、多显示器偏移全部由插件换算,高分屏(200% 缩放)也点得准 |
|
|
10
14
|
| 动作后自动回传截图 | 点击 / 输入 / 按键 / 滚动后,**等画面不再变化**(页面加载、动画结束,最多约 2.5 秒)再截图;`wait` 也直接带回截图,“等一下再看”只需一步,而且画面一静止就提前结束,不会死等满时长;画面与上一张截图完全相同时不再发图,只告诉模型“没有可见变化”,省 token |
|
|
11
15
|
| 批量动作 | `computer_batch` 一次执行“点输入框 → 输入 → 回车”等多步,最后只截一张图 |
|
|
16
|
+
| 按名称点控件 | 动作里用 `target`(控件的可见名称,如 `"保存"`、`"按钮:确定"`)代替坐标。上一张截图里还没出现的控件也能点,比如上一步才打开的菜单项、才弹出的对话框按钮;最多等 3 秒它出现。重名时不猜,直接把候选和坐标告诉模型 |
|
|
17
|
+
| 等条件而不是等时间 | `wait` 加 `until`(`"window:另存为"`、`"target:保存"`):窗口或控件一出现(或一消失)就继续,超时才报错。配合 `target`,“按 Ctrl+S → 等另存为 → 填文件名 → 点保存”可以写进同一个批量调用 |
|
|
18
|
+
| 把窗口读成文本 | `ui_elements` 加 `text: true` 直接读出文档、网页、聊天回复或日志的文字(默认取末尾 4000 字),比滚动加放大截图快,也能逐字引用;批量调用加 `finish: "text"` 可以用文字代替结尾的截图 |
|
|
12
19
|
| 按应用授权 | 先 `request_access` 列出要操控的应用,经 DSH 原生审批后才能操作;也可改为“全部允许” |
|
|
13
20
|
| 不会操作自己 | 永远拒绝向 DeepSeek Harness 自身窗口输入;常见密码管理器默认禁止,可再自定义禁用列表 |
|
|
14
21
|
| 正在控制的提示 | 橙色光晕 + 胶囊提示条(显示当前动作),**不会出现在截图里** |
|
|
15
|
-
| 迷你进度卡片(默认) | 操控期间 DeepSeek Harness 最小化,右下角显示一张半透明小卡片:标题行有 DeepSeek
|
|
22
|
+
| 迷你进度卡片(默认) | 操控期间 DeepSeek Harness 最小化,右下角显示一张半透明小卡片:标题行有 DeepSeek 图标和“输入”“展开”“暂停”“停止”四个圆形按钮;第一行滚动显示回复正文(实时流式),第二行显示思考过程,或最近几步的小时间线(已完成的步骤打勾,如“打开 Word › 输入正文 › 另存为”)。点“展开”变成长卡片:多行回复、思考、最近 5 步时间线。点“输入”在卡片下方弹出输入框,AI 自动暂停,输入指令按 Enter 发送(与在 DSH 里插话一样,AI 下一步就会看到),Esc 取消。任务结束时卡片显示“已完成”几秒再消失(鼠标停在上面会一直保留)。卡片可拖动、跟随系统深浅色,AI 的截图里看不到它,点击也会穿透它。操控中你把 DSH 窗口打开,它会自动变成下面的半透明悬浮卡片,不会挡住 AI |
|
|
16
23
|
| 悬浮卡片 | 操控期间 DeepSeek Harness 窗口缩成右下角置顶卡片,结束后自动恢复原尺寸、位置和最大化 / 最小化状态(也可选最小化或不动)。卡片只给你看:AI 的截图里看到的是卡片下面的内容(通过 Windows 放大镜接口截图时把卡片排除在外,不闪烁;该接口不可用时退回为截图瞬间让卡片透明约 20 毫秒),点击和滚动也直接穿透卡片,卡片不会挪位置。卡片默认 80% 不透明,可以透过它看清下面的操作过程;鼠标在卡片上停一下就变回不透明,方便阅读和点击(透明度可在设置里调) |
|
|
17
24
|
| 暂停与停止 | 你亲手按 **Esc** 暂停(AI 停在下一步之前),再按 Esc 或点“继续”恢复,对话不会被中断;点“停止”才结束本轮。插件自己发出的 Esc 不会误触发 |
|
|
18
25
|
| 你随时可以插手 | 你用键盘打字时 AI 自动暂停,停手 1.5 秒后继续(单按 Shift / Ctrl 等修饰键不算);你切换或打开了别的窗口,AI 下一步不会盲目执行,而是先看新截图再决定。你只是点进 DSH 卡片看对话时不算切换,AI 的按键会自动回到它正在操作的窗口。鼠标移动不会触发,避免误触 |
|
|
@@ -37,7 +44,7 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
|
|
|
37
44
|
|
|
38
45
|
> 如果之前装过其他 computer-use 插件或 skill(例如 `dsh-computer-use-win`、Hermes 的 computer-use skill),建议先停用,避免工具和说明互相冲突。
|
|
39
46
|
|
|
40
|
-
##
|
|
47
|
+
## 使用
|
|
41
48
|
|
|
42
49
|
直接说要做什么就行,例如:
|
|
43
50
|
|
|
@@ -54,11 +61,11 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
|
|
|
54
61
|
| 工具 | 作用 |
|
|
55
62
|
|---|---|
|
|
56
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 动作命名,模型上手即会) |
|
|
57
|
-
| `computer_batch` |
|
|
64
|
+
| `computer_batch` | 顺序执行多个动作,遇错即停,最后回传一张截图;最后一步可以是 `zoom`(回传放大区域),`finish` 可选 `screenshot` / `text` / `none` |
|
|
58
65
|
| `app_skill` | 应用技能:`list` 列出、`read` 读取、`append` 追加、`write` 重写某个应用的操作笔记(单份上限 4000 字) |
|
|
59
66
|
| `open_application` | 按名称(“Chrome”“记事本”“微信”)、exe 路径或网址打开应用;已运行则切到前台,在托盘里则从托盘图标恢复 |
|
|
60
67
|
| `windows` | 列出窗口(含进程 exe 名)、聚焦 / 最小化 / 最大化 / 还原 / 关闭 |
|
|
61
|
-
| `ui_elements` |
|
|
68
|
+
| `ui_elements` | 前台窗口(含已打开的菜单)的 UI Automation 元素列表,坐标已换算到截图坐标系;`text: true` 改为读出窗口的文字内容 |
|
|
62
69
|
| `clipboard` | 读 / 写剪贴板文本 |
|
|
63
70
|
| `switch_display` | 多显示器时切换截图所在屏幕 |
|
|
64
71
|
| `request_access` / `list_granted_applications` | 按应用授权 |
|
|
@@ -81,6 +88,7 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
|
|
|
81
88
|
| 文字输入方式 | 流式 | 流式(长文本逐段出现)/ 逐字输入(最像打字,最慢)/ 一次粘贴(最快) |
|
|
82
89
|
| 键盘静止多久后恢复 | 1500 ms | |
|
|
83
90
|
| 禁止操控的应用 | 空 | 名称或 exe,如 `alipay` |
|
|
91
|
+
| 强调色 | 陶土橙 | 陶土橙 / 蓝色 / 黑色,决定设置页主按钮和开关的颜色,与 copylee 的其他插件共用同一个选择。操控时的橙色光晕不随它变化 |
|
|
84
92
|
|
|
85
93
|
## 数据与隐私
|
|
86
94
|
|
|
@@ -115,15 +123,6 @@ pnpm pack:check
|
|
|
115
123
|
|
|
116
124
|
本地联调:DSH 桌面版“添加插件”里填本仓库目录路径即可(以 link 方式安装),改完 `pnpm build` 后重启 DSH 生效。
|
|
117
125
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
推送版本 tag 后,GitHub Actions(`.github/workflows/publish.yml`)通过 npm Trusted Publishing 自动发布并附带 provenance:
|
|
121
|
-
|
|
122
|
-
```bash
|
|
123
|
-
# 先把 package.json 的 version 改成新版本并合并到 main
|
|
124
|
-
git tag v0.1.1 && git push origin v0.1.1
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
## License
|
|
126
|
+
## 许可证
|
|
128
127
|
|
|
129
128
|
MIT
|
package/helper/CuHelper.cs
CHANGED
|
@@ -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
|
-
|
|
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 =
|
|
1687
|
-
|
|
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
|
@@ -74,6 +74,137 @@ window.__ModuleLoader__.load({
|
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
76
|
//#endregion
|
|
77
|
+
//#region lib/types/client/accent.js
|
|
78
|
+
/**
|
|
79
|
+
* The accent colour shared by the copylee DSH plugins (docs/ui-spec.md).
|
|
80
|
+
*
|
|
81
|
+
* One choice — terracotta orange by default, blue or black — is kept in the
|
|
82
|
+
* browser under a key every plugin reads, and painted as two CSS variables on
|
|
83
|
+
* `<body>`, where the Host keeps its own theme variables. A plugin's styles
|
|
84
|
+
* only ever write `var(--cl-accent)` / `var(--cl-accent-ink)`, so changing the
|
|
85
|
+
* colour in any plugin's settings recolours all of them at once.
|
|
86
|
+
*
|
|
87
|
+
* This file is identical in every plugin; change it in all of them together.
|
|
88
|
+
*/
|
|
89
|
+
const ACCENTS = {
|
|
90
|
+
orange: {
|
|
91
|
+
name: "陶土橙",
|
|
92
|
+
accent: "#D97757",
|
|
93
|
+
ink: "#FFFFFF"
|
|
94
|
+
},
|
|
95
|
+
blue: {
|
|
96
|
+
name: "蓝色",
|
|
97
|
+
accent: "#3D63E6",
|
|
98
|
+
ink: "#FFFFFF"
|
|
99
|
+
},
|
|
100
|
+
black: {
|
|
101
|
+
name: "黑色",
|
|
102
|
+
accent: "var(--dsw-alias-label-primary, #1F1E1D)",
|
|
103
|
+
ink: "var(--dsw-alias-bg-base, #FFFFFF)"
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
const ACCENT_IDS = Object.keys(ACCENTS);
|
|
107
|
+
const DEFAULT_ACCENT = "orange";
|
|
108
|
+
/** Use these in styles; the fallbacks cover the moment before the first paint. */
|
|
109
|
+
const ACCENT = `var(--cl-accent, ${ACCENTS[DEFAULT_ACCENT].accent})`;
|
|
110
|
+
const ACCENT_INK = `var(--cl-accent-ink, ${ACCENTS[DEFAULT_ACCENT].ink})`;
|
|
111
|
+
const KEY = "copylee.dsh.accent";
|
|
112
|
+
const EVENT = "copylee-dsh-accent";
|
|
113
|
+
function isAccent(value) {
|
|
114
|
+
return typeof value === "string" && Object.hasOwn(ACCENTS, value);
|
|
115
|
+
}
|
|
116
|
+
/** The choice made in this browser, or null while none has been made. */
|
|
117
|
+
function storedAccent() {
|
|
118
|
+
try {
|
|
119
|
+
const stored = localStorage.getItem(KEY);
|
|
120
|
+
return isAccent(stored) ? stored : null;
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function readAccent() {
|
|
126
|
+
return storedAccent() ?? "orange";
|
|
127
|
+
}
|
|
128
|
+
function paint() {
|
|
129
|
+
const colors = ACCENTS[readAccent()];
|
|
130
|
+
document.body?.style.setProperty("--cl-accent", colors.accent);
|
|
131
|
+
document.body?.style.setProperty("--cl-accent-ink", colors.ink);
|
|
132
|
+
}
|
|
133
|
+
/** Choose the accent for every plugin. */
|
|
134
|
+
function writeAccent(accent) {
|
|
135
|
+
try {
|
|
136
|
+
localStorage.setItem(KEY, accent);
|
|
137
|
+
} catch {}
|
|
138
|
+
paint();
|
|
139
|
+
window.dispatchEvent(new Event(EVENT));
|
|
140
|
+
}
|
|
141
|
+
/** Paint the current accent and keep it current. Returns the undo for plugin disposal. */
|
|
142
|
+
function installAccent() {
|
|
143
|
+
if (typeof document === "undefined") return () => {};
|
|
144
|
+
paint();
|
|
145
|
+
if (document.body === null) document.addEventListener("DOMContentLoaded", paint, { once: true });
|
|
146
|
+
window.addEventListener(EVENT, paint);
|
|
147
|
+
window.addEventListener("storage", paint);
|
|
148
|
+
return () => {
|
|
149
|
+
window.removeEventListener(EVENT, paint);
|
|
150
|
+
window.removeEventListener("storage", paint);
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function useAccent() {
|
|
154
|
+
const [accent, setAccent] = react.useState(readAccent);
|
|
155
|
+
react.useEffect(() => {
|
|
156
|
+
const sync = () => setAccent(readAccent());
|
|
157
|
+
window.addEventListener(EVENT, sync);
|
|
158
|
+
window.addEventListener("storage", sync);
|
|
159
|
+
return () => {
|
|
160
|
+
window.removeEventListener(EVENT, sync);
|
|
161
|
+
window.removeEventListener("storage", sync);
|
|
162
|
+
};
|
|
163
|
+
}, []);
|
|
164
|
+
return [accent, writeAccent];
|
|
165
|
+
}
|
|
166
|
+
/** A row of round swatches: one of them is always chosen. */
|
|
167
|
+
function AccentPicker({ label = "强调色", hint = "对 copylee 的全部插件生效", names }) {
|
|
168
|
+
const [accent, choose] = useAccent();
|
|
169
|
+
const h = react.createElement;
|
|
170
|
+
const name = (id) => names?.[id] ?? ACCENTS[id].name;
|
|
171
|
+
return h("div", { style: {
|
|
172
|
+
display: "flex",
|
|
173
|
+
alignItems: "center",
|
|
174
|
+
gap: 10,
|
|
175
|
+
fontSize: 13,
|
|
176
|
+
flexWrap: "wrap"
|
|
177
|
+
} }, h("span", { style: { fontWeight: 500 } }, label), h("span", {
|
|
178
|
+
role: "radiogroup",
|
|
179
|
+
"aria-label": label,
|
|
180
|
+
style: {
|
|
181
|
+
display: "inline-flex",
|
|
182
|
+
gap: 8
|
|
183
|
+
}
|
|
184
|
+
}, ...ACCENT_IDS.map((id) => h("button", {
|
|
185
|
+
key: id,
|
|
186
|
+
type: "button",
|
|
187
|
+
role: "radio",
|
|
188
|
+
"aria-checked": accent === id,
|
|
189
|
+
"aria-label": name(id),
|
|
190
|
+
title: name(id),
|
|
191
|
+
onClick: () => choose(id),
|
|
192
|
+
style: {
|
|
193
|
+
width: 18,
|
|
194
|
+
height: 18,
|
|
195
|
+
padding: 0,
|
|
196
|
+
borderRadius: "50%",
|
|
197
|
+
cursor: "pointer",
|
|
198
|
+
background: ACCENTS[id].accent,
|
|
199
|
+
border: "2px solid var(--dsw-alias-bg-base, #fff)",
|
|
200
|
+
boxShadow: accent === id ? "0 0 0 2px var(--dsw-alias-label-primary, #1F1E1D)" : "0 0 0 1px var(--dsw-alias-border-l2, rgba(127,127,127,.35))"
|
|
201
|
+
}
|
|
202
|
+
}))), h("span", { style: {
|
|
203
|
+
fontSize: 12,
|
|
204
|
+
color: "var(--dsw-alias-label-tertiary, #888)"
|
|
205
|
+
} }, `${name(accent)} · ${hint}`));
|
|
206
|
+
}
|
|
207
|
+
//#endregion
|
|
77
208
|
//#region lib/types/client/nav-icon.js
|
|
78
209
|
/**
|
|
79
210
|
* Give the "电脑控制" row in the DSH settings navigation a mouse-pointer icon
|
|
@@ -140,7 +271,7 @@ window.__ModuleLoader__.load({
|
|
|
140
271
|
const selectCss = `
|
|
141
272
|
.dshcu-select{box-sizing:border-box;width:100%;height:36px;padding:0 12px;display:flex;align-items:center;gap:8px;text-align:left;border:1px solid var(--dsw-alias-border-l4,rgba(127,127,127,.3));border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-3,transparent);color:inherit;font:inherit;font-size:13px;cursor:pointer}
|
|
142
273
|
.dshcu-select:hover{border-color:var(--dsw-alias-border-l3,#888)}
|
|
143
|
-
.dshcu-select:focus-visible,.dshcu-select[aria-expanded=true]{outline:2px solid var(--
|
|
274
|
+
.dshcu-select:focus-visible,.dshcu-select[aria-expanded=true]{outline:2px solid var(--cl-accent,#D97757);outline-offset:2px}
|
|
144
275
|
.dshcu-select:disabled{opacity:.5;cursor:default}
|
|
145
276
|
.dshcu-menu{position:fixed;z-index:1100;box-sizing:border-box;padding:4px;overflow-y:auto;overscroll-behavior:contain;border-radius:var(--dsw-radius-lg,12px);background:var(--dsw-menu-surface-fill,var(--dsw-alias-bg-layer-1,#fff));color:var(--dsw-alias-label-primary,#222);backdrop-filter:var(--dsw-menu-backdrop-filter,none);box-shadow:var(--dsw-elevation-prominent,0 10px 32px rgba(0,0,0,.16),0 0 0 .5px rgba(0,0,0,.1))}
|
|
146
277
|
.dshcu-option{display:flex;align-items:center;gap:8px;min-height:34px;padding:6px 8px;box-sizing:border-box;border-radius:var(--dsw-radius-md,8px);font-size:13px;line-height:20px;cursor:pointer;user-select:none}
|
|
@@ -690,9 +821,9 @@ window.__ModuleLoader__.load({
|
|
|
690
821
|
padding: "7px 16px",
|
|
691
822
|
fontSize: 13,
|
|
692
823
|
borderRadius: "var(--dsw-radius-md, 8px)",
|
|
693
|
-
border:
|
|
694
|
-
background:
|
|
695
|
-
color:
|
|
824
|
+
border: `1px solid ${ACCENT}`,
|
|
825
|
+
background: ACCENT,
|
|
826
|
+
color: ACCENT_INK,
|
|
696
827
|
cursor: "pointer"
|
|
697
828
|
},
|
|
698
829
|
secondary: {
|
|
@@ -733,7 +864,7 @@ window.__ModuleLoader__.load({
|
|
|
733
864
|
border: "none",
|
|
734
865
|
padding: 2,
|
|
735
866
|
cursor: disabled ? "default" : "pointer",
|
|
736
|
-
background: checked ?
|
|
867
|
+
background: checked ? ACCENT : "var(--dsw-alias-border-l3, rgba(127,127,127,.35))",
|
|
737
868
|
opacity: disabled ? .5 : 1,
|
|
738
869
|
transition: "background .15s"
|
|
739
870
|
}
|
|
@@ -742,7 +873,7 @@ window.__ModuleLoader__.load({
|
|
|
742
873
|
width: 18,
|
|
743
874
|
height: 18,
|
|
744
875
|
borderRadius: 9,
|
|
745
|
-
background: "#fff",
|
|
876
|
+
background: checked ? ACCENT_INK : "#fff",
|
|
746
877
|
transform: checked ? "translateX(18px)" : "none",
|
|
747
878
|
transition: "transform .15s"
|
|
748
879
|
} }));
|
|
@@ -1160,7 +1291,7 @@ window.__ModuleLoader__.load({
|
|
|
1160
1291
|
setDirty(true);
|
|
1161
1292
|
setMessage(null);
|
|
1162
1293
|
}
|
|
1163
|
-
}, "恢复默认"), dirty ? h("span", { style: S.hint }, "有未保存的修改") : null, message === null ? null : h("span", { style: message.kind === "ok" ? S.ok : S.error }, message.text)));
|
|
1294
|
+
}, "恢复默认"), dirty ? h("span", { style: S.hint }, "有未保存的修改") : null, message === null ? null : h("span", { style: message.kind === "ok" ? S.ok : S.error }, message.text)), h(AccentPicker, null));
|
|
1164
1295
|
}
|
|
1165
1296
|
const inject = [
|
|
1166
1297
|
"slots",
|
|
@@ -1168,6 +1299,7 @@ window.__ModuleLoader__.load({
|
|
|
1168
1299
|
"remote.settings"
|
|
1169
1300
|
];
|
|
1170
1301
|
function apply(ctx) {
|
|
1302
|
+
ctx.effect(() => installAccent(), "computer-use: accent colour");
|
|
1171
1303
|
ctx.effect(() => registerNavIcon("电脑控制"), "computer-use: settings nav icon");
|
|
1172
1304
|
ctx.slots.inject("settings.section", () => ctx.slots.register({
|
|
1173
1305
|
name: "settings.section",
|
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
|
|
@@ -554,6 +682,10 @@ const KEYBOARD = /* @__PURE__ */ new Set([
|
|
|
554
682
|
const UNCHANGED_DIFF = 5e-4;
|
|
555
683
|
/** Text returned instead of an identical screenshot. */
|
|
556
684
|
const UNCHANGED_TEXT = "The screen looks exactly as in your previous screenshot: the action had no visible effect.";
|
|
685
|
+
/** How long a named control may take to appear before the action gives up. */
|
|
686
|
+
const TARGET_WAIT_MS = 3e3;
|
|
687
|
+
/** Pause between looks while waiting for a control or a window. */
|
|
688
|
+
const POLL_MS = 200;
|
|
557
689
|
var Computer = class Computer {
|
|
558
690
|
helper;
|
|
559
691
|
access;
|
|
@@ -610,7 +742,7 @@ var Computer = class Computer {
|
|
|
610
742
|
const display = await this.display();
|
|
611
743
|
return {
|
|
612
744
|
...toScreenshot(point, display, this.shotSize(display)),
|
|
613
|
-
offscreen: !contains(display, point)
|
|
745
|
+
offscreen: !contains$1(display, point)
|
|
614
746
|
};
|
|
615
747
|
}
|
|
616
748
|
async screenshot() {
|
|
@@ -766,8 +898,8 @@ var Computer = class Computer {
|
|
|
766
898
|
return was && !win.minimized ? "minimized" : void 0;
|
|
767
899
|
}
|
|
768
900
|
/** 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(() => []);
|
|
901
|
+
async backgroundApps(tray = true) {
|
|
902
|
+
const rows = await this.helper.call("background", { tray }, 15e3).catch(() => []);
|
|
771
903
|
return Array.isArray(rows) ? rows : [];
|
|
772
904
|
}
|
|
773
905
|
async cursor() {
|
|
@@ -794,7 +926,7 @@ var Computer = class Computer {
|
|
|
794
926
|
}
|
|
795
927
|
/** Overlay status line for an action (Chinese, shown to the user). */
|
|
796
928
|
static statusOf(input) {
|
|
797
|
-
const at = input.coordinate ? ` (${input.coordinate.join(", ")})` : "";
|
|
929
|
+
const at = input.target ? ` “${input.target.slice(0, 20)}”` : input.coordinate ? ` (${input.coordinate.join(", ")})` : "";
|
|
798
930
|
switch (input.action) {
|
|
799
931
|
case "screenshot": return "查看屏幕";
|
|
800
932
|
case "zoom": return "放大查看";
|
|
@@ -811,10 +943,130 @@ var Computer = class Computer {
|
|
|
811
943
|
case "type": return `输入 “${(input.text ?? "").slice(0, 16)}${(input.text ?? "").length > 16 ? "…" : ""}”`;
|
|
812
944
|
case "key": return `按键 ${input.text ?? ""}`;
|
|
813
945
|
case "hold_key": return `按住 ${input.text ?? ""}`;
|
|
814
|
-
case "wait": return "等待";
|
|
946
|
+
case "wait": return input.until ? `等待 ${input.until.slice(0, 24)}${input.gone ? " 消失" : ""}` : "等待";
|
|
815
947
|
case "cursor_position": return "读取光标位置";
|
|
816
948
|
}
|
|
817
949
|
}
|
|
950
|
+
/**
|
|
951
|
+
* Controls of the foreground window, in physical pixels. `where` picks the
|
|
952
|
+
* window itself or its popups (open menus and flyouts are windows of their
|
|
953
|
+
* own). They are read separately because scanning both costs a second or
|
|
954
|
+
* more on a file dialog, and the control is nearly always in the window.
|
|
955
|
+
*/
|
|
956
|
+
async elements(where = "window") {
|
|
957
|
+
const result = await this.helper.call("ui", {
|
|
958
|
+
includeText: true,
|
|
959
|
+
maxNodes: 400,
|
|
960
|
+
...where === "popups" ? { popupsOnly: true } : {}
|
|
961
|
+
}, 2e4);
|
|
962
|
+
return Array.isArray(result.elements) ? result.elements : [];
|
|
963
|
+
}
|
|
964
|
+
/** Look for a named control in the window, and only if it is not there in its popups. */
|
|
965
|
+
async find(target) {
|
|
966
|
+
const inWindow = await this.elements("window").catch(() => []);
|
|
967
|
+
const match = matchTarget(inWindow, target);
|
|
968
|
+
if (match.kind !== "missing") return match;
|
|
969
|
+
const inPopups = await this.elements("popups").catch(() => []);
|
|
970
|
+
if (inPopups.length === 0) return match;
|
|
971
|
+
const second = matchTarget(inPopups, target);
|
|
972
|
+
return second.kind === "missing" ? matchTarget([...inWindow, ...inPopups], target) : second;
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Where a named control is. It may still be appearing (the menu just
|
|
976
|
+
* opened), so look again for a few seconds before giving up; an ambiguous
|
|
977
|
+
* name fails at once, with the candidates, rather than clicking a guess.
|
|
978
|
+
*/
|
|
979
|
+
async locate(target, signal, waitMs = TARGET_WAIT_MS) {
|
|
980
|
+
const started = Date.now();
|
|
981
|
+
for (;;) {
|
|
982
|
+
if (signal.aborted) throw new Error("Cancelled.");
|
|
983
|
+
const match = await this.find(target);
|
|
984
|
+
if (match.kind === "found") {
|
|
985
|
+
const el = match.element;
|
|
986
|
+
return {
|
|
987
|
+
point: {
|
|
988
|
+
x: Math.round(el.x + el.width / 2),
|
|
989
|
+
y: Math.round(el.y + el.height / 2)
|
|
990
|
+
},
|
|
991
|
+
element: el
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
if (match.kind === "ambiguous") {
|
|
995
|
+
const list = await Promise.all(match.candidates.map(async (el) => {
|
|
996
|
+
const at = await this.toModel({
|
|
997
|
+
x: el.x + el.width / 2,
|
|
998
|
+
y: el.y + el.height / 2
|
|
999
|
+
});
|
|
1000
|
+
return `${el.role} "${el.name}" @ (${at.x}, ${at.y})`;
|
|
1001
|
+
}));
|
|
1002
|
+
throw new Error(`target "${target}" matches ${match.candidates.length} controls: ${list.join("; ")}. Use one of these coordinates, or a more specific name.`);
|
|
1003
|
+
}
|
|
1004
|
+
if (Date.now() - started >= waitMs) {
|
|
1005
|
+
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.";
|
|
1006
|
+
throw new Error(`No control named "${target}" in the foreground window.${near}`);
|
|
1007
|
+
}
|
|
1008
|
+
await setTimeout$1(POLL_MS, void 0, { signal });
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
/** The point an action aims at: a named control, a coordinate, or nothing (the cursor). */
|
|
1012
|
+
async aim(input, call) {
|
|
1013
|
+
if (typeof input.target === "string" && input.target.trim() !== "") {
|
|
1014
|
+
const { point, element } = await this.locate(input.target, call.signal);
|
|
1015
|
+
return {
|
|
1016
|
+
point,
|
|
1017
|
+
label: ` on ${element.role} "${element.name.slice(0, 60)}"`
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
if (input.coordinate) return {
|
|
1021
|
+
point: await this.point(input.coordinate),
|
|
1022
|
+
label: ` at (${input.coordinate.join(", ")})`
|
|
1023
|
+
};
|
|
1024
|
+
return {
|
|
1025
|
+
point: void 0,
|
|
1026
|
+
label: " at the cursor"
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
/** wait with `until`: done as soon as the window or control is there (or gone). */
|
|
1030
|
+
async waitUntil(input, signal) {
|
|
1031
|
+
const until = (input.until ?? "").trim();
|
|
1032
|
+
const split = until.search(/[::]/);
|
|
1033
|
+
const prefix = split > 0 ? until.slice(0, split).trim().toLowerCase() : "";
|
|
1034
|
+
const kind = prefix === "window" ? "window" : "target";
|
|
1035
|
+
const subject = (prefix === "window" || prefix === "target" ? until.slice(split + 1) : until).trim();
|
|
1036
|
+
if (subject === "") throw new Error("wait until needs \"window:<title or exe>\" or \"target:<control name>\".");
|
|
1037
|
+
const gone = input.gone === true;
|
|
1038
|
+
const timeout = Math.min(60, Math.max(.2, Number(input.duration ?? 10) || 10)) * 1e3;
|
|
1039
|
+
const needle = subject.toLowerCase();
|
|
1040
|
+
let suggestions = [];
|
|
1041
|
+
let firstSeen;
|
|
1042
|
+
const present = async () => {
|
|
1043
|
+
if (kind === "window") {
|
|
1044
|
+
const matches = (win) => win.title.toLowerCase().includes(needle) || win.exe.toLowerCase().includes(needle) || appMatches(subject, win);
|
|
1045
|
+
const fg = await this.foreground().catch(() => void 0);
|
|
1046
|
+
if (fg && matches(fg)) return true;
|
|
1047
|
+
const rows = await this.windows().catch(() => []);
|
|
1048
|
+
const found = (Array.isArray(rows) ? rows : []).filter((win) => !win.minimized && matches(win));
|
|
1049
|
+
if (gone || found.length === 0) return found.length > 0;
|
|
1050
|
+
if (found.some((win) => win.foreground === true)) return true;
|
|
1051
|
+
if (fg && found.some((win) => win.hwnd === fg.hwnd || win.pid === fg.pid)) return true;
|
|
1052
|
+
firstSeen ??= Date.now();
|
|
1053
|
+
return Date.now() - firstSeen > 1500;
|
|
1054
|
+
}
|
|
1055
|
+
const match = await this.find(subject);
|
|
1056
|
+
if (match.kind === "missing") suggestions = match.suggestions;
|
|
1057
|
+
return match.kind !== "missing";
|
|
1058
|
+
};
|
|
1059
|
+
const started = Date.now();
|
|
1060
|
+
for (;;) {
|
|
1061
|
+
if (signal.aborted) throw new Error("Cancelled.");
|
|
1062
|
+
if (await present() !== gone) return `${kind === "window" ? "Window" : "Control"} "${subject}" ${gone ? "is gone" : "is there"} after ${((Date.now() - started) / 1e3).toFixed(1)}s.`;
|
|
1063
|
+
if (Date.now() - started >= timeout) {
|
|
1064
|
+
const near = !gone && kind === "target" && suggestions.length ? ` Controls there now: ${suggestions.map((name) => `"${name.slice(0, 40)}"`).join(", ")}.` : "";
|
|
1065
|
+
throw new Error(`Timed out after ${Math.round(timeout / 1e3)}s waiting for ${kind === "window" ? "window" : "control"} "${subject}" to ${gone ? "disappear" : "appear"}.${near}`);
|
|
1066
|
+
}
|
|
1067
|
+
await setTimeout$1(POLL_MS, void 0, { signal });
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
818
1070
|
/** Run one action. Returns text plus an image for screenshot/zoom. */
|
|
819
1071
|
async run(input, call) {
|
|
820
1072
|
if (call.signal.aborted) throw new Error("Cancelled.");
|
|
@@ -865,21 +1117,23 @@ var Computer = class Computer {
|
|
|
865
1117
|
return { text: `Cursor at (${p.x}, ${p.y})${p.offscreen ? " — on another display" : ""}.` };
|
|
866
1118
|
}
|
|
867
1119
|
case "wait": {
|
|
1120
|
+
if (input.until) return { text: await this.waitUntil(input, call.signal) };
|
|
868
1121
|
const seconds = Math.min(30, Math.max(0, Number(input.duration ?? 1) || 0));
|
|
869
1122
|
const waited = await this.waitForQuiet(seconds * 1e3, call.signal);
|
|
870
1123
|
return { text: waited < seconds * 1e3 - 200 ? `Waited ${(waited / 1e3).toFixed(1)}s (the screen settled early).` : `Waited ${seconds}s.` };
|
|
871
1124
|
}
|
|
872
1125
|
case "mouse_move": {
|
|
873
|
-
const p = await this.
|
|
1126
|
+
const { point: p, label } = await this.aim(input, call);
|
|
1127
|
+
if (!p) throw new Error("mouse_move needs coordinate or target.");
|
|
874
1128
|
await this.helper.call("move", { ...p });
|
|
875
|
-
return { text: `Moved the mouse
|
|
1129
|
+
return { text: `Moved the mouse${label.replace(/^ (at|on)/, " to")}.` };
|
|
876
1130
|
}
|
|
877
1131
|
case "left_click":
|
|
878
1132
|
case "right_click":
|
|
879
1133
|
case "middle_click":
|
|
880
1134
|
case "double_click":
|
|
881
1135
|
case "triple_click": {
|
|
882
|
-
const p
|
|
1136
|
+
const { point: p, label } = await this.aim(input, call);
|
|
883
1137
|
await this.checkPointer(call, p, "click");
|
|
884
1138
|
const button = action === "right_click" ? "right" : action === "middle_click" ? "middle" : "left";
|
|
885
1139
|
const count = action === "double_click" ? 2 : action === "triple_click" ? 3 : 1;
|
|
@@ -890,7 +1144,7 @@ var Computer = class Computer {
|
|
|
890
1144
|
count,
|
|
891
1145
|
modifiers
|
|
892
1146
|
});
|
|
893
|
-
return { text: `${action.replace("_", " ")}${
|
|
1147
|
+
return { text: `${action.replace("_", " ")}${label}${modifiers.length ? ` holding ${input.modifiers ?? input.text}` : ""}.` };
|
|
894
1148
|
}
|
|
895
1149
|
case "left_click_drag": {
|
|
896
1150
|
const from = await this.point(input.start_coordinate, "start_coordinate");
|
|
@@ -918,7 +1172,7 @@ var Computer = class Computer {
|
|
|
918
1172
|
return { text: `Left button ${action === "left_mouse_down" ? "down" : "up"}.` };
|
|
919
1173
|
}
|
|
920
1174
|
case "scroll": {
|
|
921
|
-
const p =
|
|
1175
|
+
const { point: p } = await this.aim(input, call);
|
|
922
1176
|
await this.checkPointer(call, p, "scroll");
|
|
923
1177
|
const amount = Math.max(1, Math.min(30, Math.round(input.scroll_amount ?? 3)));
|
|
924
1178
|
const direction = input.scroll_direction ?? "down";
|
|
@@ -935,8 +1189,21 @@ var Computer = class Computer {
|
|
|
935
1189
|
case "type": {
|
|
936
1190
|
const text = input.text ?? "";
|
|
937
1191
|
if (text === "") throw new Error("type needs text.");
|
|
1192
|
+
let into = "";
|
|
1193
|
+
if (input.target || input.coordinate) {
|
|
1194
|
+
const { point: p, label } = await this.aim(input, call);
|
|
1195
|
+
await this.checkPointer(call, p, "click");
|
|
1196
|
+
await this.helper.call("click", {
|
|
1197
|
+
...p ?? {},
|
|
1198
|
+
button: "left",
|
|
1199
|
+
count: 1,
|
|
1200
|
+
modifiers: []
|
|
1201
|
+
});
|
|
1202
|
+
await setTimeout$1(120, void 0, { signal: call.signal });
|
|
1203
|
+
into = ` (clicked${label} first)`;
|
|
1204
|
+
}
|
|
938
1205
|
await this.checkKeyboard(call, "type into");
|
|
939
|
-
return { text: await this.enterText(text, call) };
|
|
1206
|
+
return { text: `${await this.enterText(text, call)}${into}` };
|
|
940
1207
|
}
|
|
941
1208
|
case "key": {
|
|
942
1209
|
const combos = parseKeys(input.text ?? "");
|
|
@@ -1627,7 +1894,7 @@ ${mode === "per-app" ? "- Before acting on an app, call request_access once with
|
|
|
1627
1894
|
- 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
1895
|
- 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
1896
|
- 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
|
|
1897
|
+
- 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 screenshot: its result already is the settled screen. 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
1898
|
- 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
1899
|
- 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
1900
|
- 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.
|
|
@@ -7979,6 +8246,16 @@ const coordinate = {
|
|
|
7979
8246
|
items: { type: "number" },
|
|
7980
8247
|
description: "[x, y] in pixels of the latest screenshot."
|
|
7981
8248
|
};
|
|
8249
|
+
/** Reads what a window says through UI Automation: exact text, no image. */
|
|
8250
|
+
async function windowText(computer, hwnd, tail) {
|
|
8251
|
+
const result = await computer.helper.call("text", {
|
|
8252
|
+
...hwnd === void 0 ? {} : { hwnd },
|
|
8253
|
+
tail: Math.min(2e4, Math.max(200, Math.round(tail ?? 4e3)))
|
|
8254
|
+
}, 2e4);
|
|
8255
|
+
const head = `${result.exe} — "${String(result.title ?? "").slice(0, 80)}"`;
|
|
8256
|
+
if (!result.text || result.source === "none") return `${head}: this window exposes no readable text; use a screenshot.`;
|
|
8257
|
+
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}`;
|
|
8258
|
+
}
|
|
7982
8259
|
const actionProperties = {
|
|
7983
8260
|
action: {
|
|
7984
8261
|
type: "string",
|
|
@@ -8014,7 +8291,19 @@ const actionProperties = {
|
|
|
8014
8291
|
},
|
|
8015
8292
|
duration: {
|
|
8016
8293
|
type: "number",
|
|
8017
|
-
description: "Seconds for wait / hold_key."
|
|
8294
|
+
description: "Seconds for wait / hold_key (with until: the timeout, default 10)."
|
|
8295
|
+
},
|
|
8296
|
+
target: {
|
|
8297
|
+
type: "string",
|
|
8298
|
+
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."
|
|
8299
|
+
},
|
|
8300
|
+
until: {
|
|
8301
|
+
type: "string",
|
|
8302
|
+
description: "wait: return as soon as this is there, \"window:<title or exe part>\" or \"target:<control name>\", instead of waiting a fixed time."
|
|
8303
|
+
},
|
|
8304
|
+
gone: {
|
|
8305
|
+
type: "boolean",
|
|
8306
|
+
description: "wait until: wait for it to disappear instead."
|
|
8018
8307
|
},
|
|
8019
8308
|
region: {
|
|
8020
8309
|
type: "array",
|
|
@@ -8022,7 +8311,7 @@ const actionProperties = {
|
|
|
8022
8311
|
description: "zoom: [x1, y1, x2, y2] in screenshot pixels."
|
|
8023
8312
|
}
|
|
8024
8313
|
};
|
|
8025
|
-
const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot"
|
|
8314
|
+
const BATCH_ACTIONS = ACTIONS.filter((action) => action !== "screenshot");
|
|
8026
8315
|
function createTools(host) {
|
|
8027
8316
|
const { computer } = host;
|
|
8028
8317
|
const tools = [];
|
|
@@ -8049,40 +8338,55 @@ function createTools(host) {
|
|
|
8049
8338
|
}));
|
|
8050
8339
|
tools.push(defineTool({
|
|
8051
8340
|
name: "computer_batch",
|
|
8052
|
-
description: "Run several computer actions in order in one call (
|
|
8053
|
-
parameters: {
|
|
8054
|
-
|
|
8055
|
-
|
|
8056
|
-
|
|
8057
|
-
|
|
8058
|
-
|
|
8059
|
-
|
|
8060
|
-
|
|
8061
|
-
|
|
8062
|
-
|
|
8063
|
-
|
|
8064
|
-
|
|
8341
|
+
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 \"保存\"].",
|
|
8342
|
+
parameters: {
|
|
8343
|
+
actions: {
|
|
8344
|
+
type: "array",
|
|
8345
|
+
required: true,
|
|
8346
|
+
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).",
|
|
8347
|
+
items: {
|
|
8348
|
+
type: "object",
|
|
8349
|
+
additionalProperties: false,
|
|
8350
|
+
properties: {
|
|
8351
|
+
...actionProperties,
|
|
8352
|
+
action: {
|
|
8353
|
+
...actionProperties.action,
|
|
8354
|
+
enum: BATCH_ACTIONS
|
|
8355
|
+
}
|
|
8065
8356
|
}
|
|
8066
8357
|
}
|
|
8358
|
+
},
|
|
8359
|
+
finish: {
|
|
8360
|
+
type: "string",
|
|
8361
|
+
enum: [
|
|
8362
|
+
"screenshot",
|
|
8363
|
+
"text",
|
|
8364
|
+
"none"
|
|
8365
|
+
],
|
|
8366
|
+
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
8367
|
}
|
|
8068
|
-
}
|
|
8368
|
+
},
|
|
8069
8369
|
output,
|
|
8070
8370
|
timeoutMs: 18e5,
|
|
8071
8371
|
async execute(args, exec) {
|
|
8072
8372
|
const call = await host.context(exec);
|
|
8073
8373
|
const actions = args.actions;
|
|
8374
|
+
const finish = args.finish ?? "screenshot";
|
|
8375
|
+
let zoomed;
|
|
8074
8376
|
if (!Array.isArray(actions) || actions.length === 0) throw new Error("actions must be a non-empty array.");
|
|
8075
8377
|
if (actions.length > 30) throw new Error("At most 30 actions per batch.");
|
|
8076
8378
|
const lines = [];
|
|
8077
8379
|
let failure;
|
|
8078
8380
|
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.`;
|
|
8381
|
+
if (input.action === "screenshot" || input.action === "zoom" && index !== actions.length - 1) {
|
|
8382
|
+
failure = `#${index + 1} ${input.action}: ${input.action === "zoom" ? "only allowed as the last action of a batch" : "not allowed in a batch"}.`;
|
|
8081
8383
|
break;
|
|
8082
8384
|
}
|
|
8083
8385
|
try {
|
|
8084
8386
|
const stepStart = Date.now();
|
|
8387
|
+
if (input.action === "zoom" && index > 0) await computer.settle(call.signal);
|
|
8085
8388
|
const outcome = await computer.run(input, call);
|
|
8389
|
+
if (input.action === "zoom") zoomed = outcome.image;
|
|
8086
8390
|
if (outcome.skipped) {
|
|
8087
8391
|
failure = `#${index + 1} ${input.action} skipped: the user was typing on the keyboard. Re-check the screen before continuing.`;
|
|
8088
8392
|
break;
|
|
@@ -8103,8 +8407,15 @@ function createTools(host) {
|
|
|
8103
8407
|
}
|
|
8104
8408
|
}
|
|
8105
8409
|
const done = lines.join("\n");
|
|
8106
|
-
const shot = call.vision && computer.settings().autoScreenshot ? await computer.settle(call.signal).then(() => computer.freshShot()) : void 0;
|
|
8107
8410
|
const summary = failure === void 0 ? `All ${actions.length} actions done.\n${done}` : `Stopped: ${failure}${done ? `\nCompleted before it:\n${done}` : ""}\nRemaining actions were skipped.`;
|
|
8411
|
+
if (zoomed !== void 0 && failure === void 0) return withShot(host, summary, zoomed, call);
|
|
8412
|
+
if (failure === void 0 && finish === "none") return { text: `${summary}\n${await computer.describeForeground()}` };
|
|
8413
|
+
if (failure === void 0 && finish === "text") {
|
|
8414
|
+
await computer.settle(call.signal);
|
|
8415
|
+
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)}`)}` };
|
|
8416
|
+
}
|
|
8417
|
+
const waited = failure === void 0 && actions[actions.length - 1]?.action === "wait";
|
|
8418
|
+
const shot = call.vision && computer.settings().autoScreenshot ? await (waited ? Promise.resolve() : computer.settle(call.signal)).then(() => computer.freshShot()) : void 0;
|
|
8108
8419
|
return withShot(host, shot === void 0 ? `${summary}\n${await computer.describeForeground()}` : summary, shot, call);
|
|
8109
8420
|
},
|
|
8110
8421
|
presentCall: (args) => card(`电脑操作 · 批量 ${args.actions?.length ?? 0} 步`)
|
|
@@ -8127,14 +8438,22 @@ function createTools(host) {
|
|
|
8127
8438
|
timeoutMs: 18e5,
|
|
8128
8439
|
async execute(args, exec) {
|
|
8129
8440
|
const call = await host.context(exec);
|
|
8130
|
-
const
|
|
8131
|
-
|
|
8441
|
+
const text = await openApp(String(args.name ?? ""), args.new_instance === true, call);
|
|
8442
|
+
await computer.settle(call.signal);
|
|
8443
|
+
return withShot(host, text, call.vision ? await computer.screenshot() : void 0, call);
|
|
8444
|
+
},
|
|
8445
|
+
presentCall: (args) => card(`打开应用 · ${args.name ?? ""}`)
|
|
8446
|
+
}));
|
|
8447
|
+
/** Open an app or bring it forward; returns what happened, the foreground window and the app's skill notes. */
|
|
8448
|
+
async function openApp(rawName, newInstance, call) {
|
|
8449
|
+
{
|
|
8450
|
+
const name = rawName.trim();
|
|
8132
8451
|
if (name === "") throw new Error("name is required.");
|
|
8133
8452
|
const settings = computer.settings();
|
|
8134
8453
|
const isUrl = /^https?:\/\//i.test(name);
|
|
8135
8454
|
const appName = /^ms-settings:/i.test(name) ? "设置" : name;
|
|
8136
8455
|
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));
|
|
8456
|
+
const running = (await computer.windows()).find((win) => appMatches(appName, win)) ?? (await computer.backgroundApps(false)).find((win) => appMatches(appName, win));
|
|
8138
8457
|
if (!running || !computer.access.isGranted(call.session, running)) throw new Error(`"${appName}" is not granted for this session. Call request_access with ["${appName}"] first.`);
|
|
8139
8458
|
}
|
|
8140
8459
|
await computer.overlay.begin(call.agent, `打开 ${name}`);
|
|
@@ -8143,7 +8462,7 @@ function createTools(host) {
|
|
|
8143
8462
|
let how;
|
|
8144
8463
|
const isUri = isUrl || /^[a-z][a-z0-9+.-]+:(?![\/])/i.test(name);
|
|
8145
8464
|
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));
|
|
8465
|
+
const hidden = running || isUri || newInstance ? void 0 : (await computer.backgroundApps(false)).find((win) => !isHostWindow(win) && appMatches(name, win));
|
|
8147
8466
|
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
8467
|
else if (hidden) {
|
|
8149
8468
|
const restored = await computer.helper.call("tray_restore", { exe: hidden.exe }, 2e4);
|
|
@@ -8157,11 +8476,11 @@ function createTools(host) {
|
|
|
8157
8476
|
if (app) await computer.helper.call("launch", { appId: app.id });
|
|
8158
8477
|
else await computer.helper.call("launch", { target: name });
|
|
8159
8478
|
how = app ? `Launched "${app.name}".` : isUrl ? `Opened ${name} in the default browser.` : `Started "${name}".`;
|
|
8160
|
-
for (let i = 0; i <
|
|
8161
|
-
await setTimeout$1(
|
|
8479
|
+
for (let i = 0; i < 80; i++) {
|
|
8480
|
+
await setTimeout$1(100, void 0, { signal: call.signal });
|
|
8162
8481
|
const now = await computer.foreground();
|
|
8163
8482
|
if (now && now.hwnd !== before?.hwnd && !isHostWindow(now) && !isTransientShell(now) && (now.exe.toLowerCase() !== "explorer.exe" || now.className === "CabinetWClass")) break;
|
|
8164
|
-
if (i >=
|
|
8483
|
+
if (i >= 10 && i % 10 === 0 && !isUri) {
|
|
8165
8484
|
const opened = (await computer.windows()).find((win) => !isHostWindow(win) && appMatches(name, win));
|
|
8166
8485
|
if (opened) {
|
|
8167
8486
|
await computer.focus(opened).catch(() => void 0);
|
|
@@ -8172,12 +8491,9 @@ function createTools(host) {
|
|
|
8172
8491
|
}
|
|
8173
8492
|
const fg = await computer.foreground();
|
|
8174
8493
|
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.
|
|
8176
|
-
|
|
8177
|
-
|
|
8178
|
-
},
|
|
8179
|
-
presentCall: (args) => card(`打开应用 · ${args.name ?? ""}`)
|
|
8180
|
-
}));
|
|
8494
|
+
return `${how} ${await computer.describeForeground()}${skillNote(call.session, name, fg)}`;
|
|
8495
|
+
}
|
|
8496
|
+
}
|
|
8181
8497
|
/** Skills already handed to a session, so each is attached once. */
|
|
8182
8498
|
const told = /* @__PURE__ */ new Map();
|
|
8183
8499
|
/** The app's skill, appended to open_application's result the first time in a session. */
|
|
@@ -8269,12 +8585,20 @@ function createTools(host) {
|
|
|
8269
8585
|
}));
|
|
8270
8586
|
tools.push(defineTool({
|
|
8271
8587
|
name: "ui_elements",
|
|
8272
|
-
description: "
|
|
8588
|
+
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
8589
|
parameters: {
|
|
8274
8590
|
hwnd: {
|
|
8275
8591
|
type: "integer",
|
|
8276
8592
|
description: "Window handle; default foreground window."
|
|
8277
8593
|
},
|
|
8594
|
+
text: {
|
|
8595
|
+
type: "boolean",
|
|
8596
|
+
description: "Return the window's text content instead of the element list."
|
|
8597
|
+
},
|
|
8598
|
+
tail: {
|
|
8599
|
+
type: "integer",
|
|
8600
|
+
description: "text: how many characters from the end to return (default 4000, max 20000); new content is usually at the end."
|
|
8601
|
+
},
|
|
8278
8602
|
include_text: {
|
|
8279
8603
|
type: "boolean",
|
|
8280
8604
|
description: "Also list static text elements."
|
|
@@ -8288,10 +8612,12 @@ function createTools(host) {
|
|
|
8288
8612
|
timeoutMs: 3e4,
|
|
8289
8613
|
isConcurrencySafe: () => true,
|
|
8290
8614
|
async execute(args) {
|
|
8291
|
-
const { hwnd, include_text: includeText, max } = args;
|
|
8615
|
+
const { hwnd, include_text: includeText, max, text, tail } = args;
|
|
8616
|
+
if (text === true) return { text: await windowText(computer, hwnd, tail) };
|
|
8292
8617
|
const result = await computer.helper.call("ui", {
|
|
8293
8618
|
...hwnd === void 0 ? {} : { hwnd },
|
|
8294
8619
|
includeText: includeText === true,
|
|
8620
|
+
popups: true,
|
|
8295
8621
|
maxNodes: Math.min(400, Math.max(10, max ?? 120))
|
|
8296
8622
|
}, 2e4);
|
|
8297
8623
|
const lines = [];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The accent colour shared by the copylee DSH plugins (docs/ui-spec.md).
|
|
3
|
+
*
|
|
4
|
+
* One choice — terracotta orange by default, blue or black — is kept in the
|
|
5
|
+
* browser under a key every plugin reads, and painted as two CSS variables on
|
|
6
|
+
* `<body>`, where the Host keeps its own theme variables. A plugin's styles
|
|
7
|
+
* only ever write `var(--cl-accent)` / `var(--cl-accent-ink)`, so changing the
|
|
8
|
+
* colour in any plugin's settings recolours all of them at once.
|
|
9
|
+
*
|
|
10
|
+
* This file is identical in every plugin; change it in all of them together.
|
|
11
|
+
*/
|
|
12
|
+
import * as React from 'react';
|
|
13
|
+
export type Accent = 'orange' | 'blue' | 'black';
|
|
14
|
+
export declare const ACCENTS: Record<Accent, {
|
|
15
|
+
name: string;
|
|
16
|
+
accent: string;
|
|
17
|
+
ink: string;
|
|
18
|
+
}>;
|
|
19
|
+
export declare const ACCENT_IDS: Accent[];
|
|
20
|
+
export declare const DEFAULT_ACCENT: Accent;
|
|
21
|
+
/** Use these in styles; the fallbacks cover the moment before the first paint. */
|
|
22
|
+
export declare const ACCENT: string;
|
|
23
|
+
export declare const ACCENT_INK: string;
|
|
24
|
+
export declare function isAccent(value: unknown): value is Accent;
|
|
25
|
+
/** The choice made in this browser, or null while none has been made. */
|
|
26
|
+
export declare function storedAccent(): Accent | null;
|
|
27
|
+
export declare function readAccent(): Accent;
|
|
28
|
+
/** Choose the accent for every plugin. */
|
|
29
|
+
export declare function writeAccent(accent: Accent): void;
|
|
30
|
+
/** Paint the current accent and keep it current. Returns the undo for plugin disposal. */
|
|
31
|
+
export declare function installAccent(): () => void;
|
|
32
|
+
export declare function useAccent(): [Accent, (accent: Accent) => void];
|
|
33
|
+
/** A row of round swatches: one of them is always chosen. */
|
|
34
|
+
export declare function AccentPicker({ label, hint, names }: {
|
|
35
|
+
label?: string;
|
|
36
|
+
hint?: string;
|
|
37
|
+
/** Colour names in the page's language; the built-in ones are Chinese. */
|
|
38
|
+
names?: Partial<Record<Accent, string>>;
|
|
39
|
+
}): React.ReactElement;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
2
|
/** Menu appearance and fixed-position behavior follow dsh-free-search / dsh-proxy. */
|
|
3
|
-
export declare const selectCss = "\n.dshcu-select{box-sizing:border-box;width:100%;height:36px;padding:0 12px;display:flex;align-items:center;gap:8px;text-align:left;border:1px solid var(--dsw-alias-border-l4,rgba(127,127,127,.3));border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-3,transparent);color:inherit;font:inherit;font-size:13px;cursor:pointer}\n.dshcu-select:hover{border-color:var(--dsw-alias-border-l3,#888)}\n.dshcu-select:focus-visible,.dshcu-select[aria-expanded=true]{outline:2px solid var(--
|
|
3
|
+
export declare const selectCss = "\n.dshcu-select{box-sizing:border-box;width:100%;height:36px;padding:0 12px;display:flex;align-items:center;gap:8px;text-align:left;border:1px solid var(--dsw-alias-border-l4,rgba(127,127,127,.3));border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-3,transparent);color:inherit;font:inherit;font-size:13px;cursor:pointer}\n.dshcu-select:hover{border-color:var(--dsw-alias-border-l3,#888)}\n.dshcu-select:focus-visible,.dshcu-select[aria-expanded=true]{outline:2px solid var(--cl-accent,#D97757);outline-offset:2px}\n.dshcu-select:disabled{opacity:.5;cursor:default}\n.dshcu-menu{position:fixed;z-index:1100;box-sizing:border-box;padding:4px;overflow-y:auto;overscroll-behavior:contain;border-radius:var(--dsw-radius-lg,12px);background:var(--dsw-menu-surface-fill,var(--dsw-alias-bg-layer-1,#fff));color:var(--dsw-alias-label-primary,#222);backdrop-filter:var(--dsw-menu-backdrop-filter,none);box-shadow:var(--dsw-elevation-prominent,0 10px 32px rgba(0,0,0,.16),0 0 0 .5px rgba(0,0,0,.1))}\n.dshcu-option{display:flex;align-items:center;gap:8px;min-height:34px;padding:6px 8px;box-sizing:border-box;border-radius:var(--dsw-radius-md,8px);font-size:13px;line-height:20px;cursor:pointer;user-select:none}\n.dshcu-option[data-active=true]{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.12))}\n";
|
|
4
4
|
export declare function Select<V extends string>({ options, value, disabled, label, onChange }: {
|
|
5
5
|
options: {
|
|
6
6
|
value: V;
|
package/lib/types/computer.d.ts
CHANGED
|
@@ -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;
|
|
@@ -61,6 +62,12 @@ export interface ActionInput {
|
|
|
61
62
|
scroll_amount?: number;
|
|
62
63
|
duration?: number;
|
|
63
64
|
region?: number[];
|
|
65
|
+
/** A control named by what it says, instead of a coordinate. */
|
|
66
|
+
target?: string;
|
|
67
|
+
/** wait: what to wait for ("window:记事本", "target:保存"). */
|
|
68
|
+
until?: string;
|
|
69
|
+
/** wait: wait for it to disappear instead. */
|
|
70
|
+
gone?: boolean;
|
|
64
71
|
}
|
|
65
72
|
export interface ActionOutcome {
|
|
66
73
|
text: string;
|
|
@@ -136,7 +143,7 @@ export declare class Computer {
|
|
|
136
143
|
/** How a window relates to the layout before the task: opened by the agent, or restored from minimized / tray. */
|
|
137
144
|
origin(win: WindowInfo): 'opened' | 'minimized' | 'tray' | undefined;
|
|
138
145
|
/** Programs running without any visible window (closed to the system tray); `tray` = has a tray icon. */
|
|
139
|
-
backgroundApps(): Promise<Array<WindowInfo & {
|
|
146
|
+
backgroundApps(tray?: boolean): Promise<Array<WindowInfo & {
|
|
140
147
|
tray: boolean;
|
|
141
148
|
}>>;
|
|
142
149
|
cursor(): Promise<Point>;
|
|
@@ -147,6 +154,28 @@ export declare class Computer {
|
|
|
147
154
|
private checkKeyboard;
|
|
148
155
|
/** Overlay status line for an action (Chinese, shown to the user). */
|
|
149
156
|
static statusOf(input: ActionInput): string;
|
|
157
|
+
/**
|
|
158
|
+
* Controls of the foreground window, in physical pixels. `where` picks the
|
|
159
|
+
* window itself or its popups (open menus and flyouts are windows of their
|
|
160
|
+
* own). They are read separately because scanning both costs a second or
|
|
161
|
+
* more on a file dialog, and the control is nearly always in the window.
|
|
162
|
+
*/
|
|
163
|
+
elements(where?: 'window' | 'popups'): Promise<UiElement[]>;
|
|
164
|
+
/** Look for a named control in the window, and only if it is not there in its popups. */
|
|
165
|
+
private find;
|
|
166
|
+
/**
|
|
167
|
+
* Where a named control is. It may still be appearing (the menu just
|
|
168
|
+
* opened), so look again for a few seconds before giving up; an ambiguous
|
|
169
|
+
* name fails at once, with the candidates, rather than clicking a guess.
|
|
170
|
+
*/
|
|
171
|
+
locate(target: string, signal: AbortSignal, waitMs?: number): Promise<{
|
|
172
|
+
point: Point;
|
|
173
|
+
element: UiElement;
|
|
174
|
+
}>;
|
|
175
|
+
/** The point an action aims at: a named control, a coordinate, or nothing (the cursor). */
|
|
176
|
+
private aim;
|
|
177
|
+
/** wait with `until`: done as soon as the window or control is there (or gone). */
|
|
178
|
+
private waitUntil;
|
|
150
179
|
/** Run one action. Returns text plus an image for screenshot/zoom. */
|
|
151
180
|
run(input: ActionInput, call: CallContext): Promise<ActionOutcome>;
|
|
152
181
|
/**
|
|
@@ -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;
|
package/package.json
CHANGED