@copylee/dsh-computer-use 0.7.6 → 0.8.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 CHANGED
@@ -36,7 +36,7 @@
36
36
  | 应用技能 | AI 对各个应用的操作笔记,每个应用一份 Markdown(`~/.dsh/computer-use-skills/`)。AI 摸索清楚一个不熟悉的应用后用 `app_skill` 自己记下来(只记操作规律,不记任务内容),以后 `open_application` 打开该应用时自动附带,不占系统提示。自带 Word、PowerPoint、Excel、Chrome、文件资源管理器、Obsidian、Typora、微信、QQ、记事本十份内置技能(含各应用的快捷键清单,PowerPoint 含原生公式和动画的做法);AI 在内置技能上追加的笔记单独保存,内置部分随插件更新;设置页“应用技能”里可以查看、修改、删除、新建,内置技能可覆盖和恢复 |
37
37
  | 打开应用 | `open_application` 同时搜索开始菜单和桌面快捷方式(含公共桌面),便携软件也能按名字打开。已经关到系统托盘的应用(QQ、微信等)会像人一样点托盘图标把窗口叫回来(必要时先展开“显示隐藏的图标”),不会再启动第二个实例、也不会重复登录;你明确要多开时(如微信双开)AI 会用 `new_instance` 另开一个。任务结束时 AI 会收拾现场:关掉自己打开、你不再需要的窗口,`windows tidy` 把原本最小化或在托盘里的应用重新最小化 |
38
38
  | 看不见图的模型 | `ui_elements` 用 Windows UI Automation 列出可点击元素和坐标,纯文本模型也能用 |
39
- | 零原生依赖 | 首次使用时用 Windows 自带的 .NET Framework `csc.exe` 编译一个小 helper(约 1 秒,之后缓存),不需要 node-gyp、不受 Electron ABI 影响 |
39
+ | 零原生依赖 | 截图、窗口查询和输入直接调用 DeepSeek Harness 自带的 koffi,不需要额外安装;浮层、UI Automation、剪贴板等由一个小 helper 负责,首次使用时用 Windows 自带的 .NET Framework `csc.exe` 编译(约 1 秒,之后缓存)。不需要 node-gyp,也不受 Electron ABI 影响。开启了智能应用控制(Smart App Control)时,helper 改为在系统自带的 PowerShell 里运行 |
40
40
 
41
41
  ## 安装
42
42
 
@@ -97,13 +97,14 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
97
97
  | 文字输入方式 | 流式 | 流式(长文本逐段出现)/ 逐字输入(最像打字,最慢)/ 一次粘贴(最快) |
98
98
  | 键盘静止多久后恢复 | 1500 ms | |
99
99
  | 禁止操控的应用 | 空 | 名称或 exe,如 `alipay` |
100
+ | 进程内截图与输入 | 开 | 截图、显示器和窗口查询,以及浮层未显示时的输入,改由 DSH 自带的 koffi 在进程内完成,启动更快,也少一次进程间往返。出问题时可以关掉,全部交给 helper |
100
101
  | 强调色 | 陶土橙 | 陶土橙 / 蓝色 / 黑色,决定设置页主按钮和开关的颜色,与 copylee 的其他插件共用同一个选择。操控时的橙色光晕不随它变化 |
101
102
 
102
103
  ## 数据与隐私
103
104
 
104
105
  - 截图只作为当前会话的图片附件发给你选择的模型,插件不上传、不保存到别处。
105
106
  - 截图附件存放在 `~/.dsh/attachments`,随会话历史保留(DSH 会校验附件,删掉仍被会话引用的截图会让该会话无法继续,所以插件不会动它们)。会话删除后留下的“孤儿”截图会在 DSH 启动几分钟后及之后每 12 小时自动清理;设置页“截图缓存”可查看占用并立即清理。
106
- - helper 源码 `helper/CuHelper.cs` 随包发布,可自行审阅;编译产物缓存在 `%LOCALAPPDATA%\dsh-computer-use\`。
107
+ - helper 源码 `helper/CuHelper.cs` 随包发布,可自行审阅;编译产物缓存在 `%LOCALAPPDATA%\dsh-computer-use\`。进程内的部分(`src/native/`)只加载 DSH 自带的 koffi.node 和 Windows 系统 DLL。
107
108
  - 以管理员身份运行的窗口、UAC 弹窗、锁屏无法被控制(Windows UIPI 限制),遇到时模型会请你手动处理。
108
109
  - 插件注入的系统提示要求模型不代填密码、支付信息、不处理验证码,遇到时交还给你。
109
110
 
@@ -112,7 +113,9 @@ dsh plugin --profile web add @copylee/dsh-computer-use@latest
112
113
  ```
113
114
  DSH Host (Electron, Node 模式)
114
115
  └─ lib/index.js 工具 / 审批 / 系统提示 / overlay 生命周期
115
- └─ cu-helper.exe(常驻,stdin/stdout 每行一个 JSON)
116
+ ├─ lib/native-worker.js(worker 线程,DSH 自带的 koffi)
117
+ │ 截图 · 显示器 / 窗口查询 · 浮层未显示时的鼠标键盘
118
+ └─ cu-helper.exe(常驻,stdin/stdout 每行一个 JSON;SAC 下在 powershell.exe 里加载)
116
119
  Per-Monitor-V2 DPI 感知 · GDI 截图 + 缩放 + JPEG · SendInput 鼠标键盘
117
120
  窗口枚举与前置 · shell:AppsFolder 启动应用 · 剪贴板 · UI Automation
118
121
  分层窗口 overlay(WDA_EXCLUDEFROMCAPTURE)· 低级键盘钩子(只认物理 Esc)
@@ -127,6 +130,7 @@ pnpm test # vitest(mock helper,跨平台)
127
130
  pnpm build # tsc → lib/types,tsdown → lib/index.js
128
131
  node scripts/helper-smoke.mjs # 本机实测:编译 helper、截图、overlay
129
132
  node scripts/helper-smoke.mjs --notepad # 另外用临时文件测试中文输入
133
+ node scripts/native-smoke.mjs --notepad # koffi 路径与 helper 对比;需在 DSH 运行时下跑或设 DSH_KOFFI_PATH
130
134
  pnpm pack:check
131
135
  ```
132
136
 
@@ -0,0 +1,10 @@
1
+ # Runs the compiled helper inside the signed powershell.exe, for machines where
2
+ # Smart App Control (or another code-integrity policy) refuses to start the
3
+ # unsigned cu-helper.exe. Loading the assembly from bytes maps no executable
4
+ # image, so the policy has nothing to check. stdin / stdout stay the helper's
5
+ # JSON pipes: nothing here may write to stdout.
6
+ param([Parameter(Mandatory = $true)][string]$HelperExe)
7
+ $ErrorActionPreference = 'Stop'
8
+ $assembly = [Reflection.Assembly]::Load([IO.File]::ReadAllBytes($HelperExe))
9
+ $code = $assembly.EntryPoint.Invoke($null, [object[]]@(, [string[]]@()))
10
+ exit [int]$code
package/lib/client.js CHANGED
@@ -46,7 +46,8 @@ window.__ModuleLoader__.load({
46
46
  pauseOnUserInput: true,
47
47
  userIdleMs: 1500,
48
48
  typingMode: "stream",
49
- quickSteps: false
49
+ quickSteps: false,
50
+ nativeHelper: true
50
51
  };
51
52
  /** Unwrap `.volatile()` refs (`{ get() }`) and fall back to defaults for bad values. */
52
53
  function resolveConfig(raw) {
@@ -71,6 +72,7 @@ window.__ModuleLoader__.load({
71
72
  pauseOnUserInput: bool("pauseOnUserInput"),
72
73
  userIdleMs: num("userIdleMs", 300, 1e4),
73
74
  quickSteps: bool("quickSteps"),
75
+ nativeHelper: bool("nativeHelper"),
74
76
  typingMode: out.typingMode === "stream" || out.typingMode === "type" || out.typingMode === "paste" ? out.typingMode : DEFAULTS.typingMode,
75
77
  blockedApps: Array.isArray(out.blockedApps) ? out.blockedApps.filter((item) => typeof item === "string" && item.trim() !== "") : []
76
78
  };
package/lib/index.js CHANGED
@@ -6,8 +6,9 @@ import { execFile, spawn } from "node:child_process";
6
6
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { chmod, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
8
  import { homedir, tmpdir } from "node:os";
9
- import { join } from "node:path";
9
+ import { dirname, join } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
+ import { Worker } from "node:worker_threads";
11
12
  import * as zlib from "node:zlib";
12
13
  import { Context, Service } from "@deepseek-ai/cordis";
13
14
  //#region lib/types/access.js
@@ -1403,6 +1404,24 @@ async function ensureHelperExe(source = helperSourcePath()) {
1403
1404
  throw error;
1404
1405
  }
1405
1406
  }
1407
+ /**
1408
+ * Set once the unsigned exe has been refused: Smart App Control blocks it with
1409
+ * ERROR_ACCESS_DISABLED_BY_POLICY, which libuv reports as UNKNOWN. From then on
1410
+ * the same assembly runs inside the signed powershell.exe (helper/host.ps1).
1411
+ */
1412
+ let hostedHelper = false;
1413
+ const POLICY_CODES = /* @__PURE__ */ new Set([
1414
+ "UNKNOWN",
1415
+ "EACCES",
1416
+ "EPERM"
1417
+ ]);
1418
+ function isPolicyBlock(error) {
1419
+ return POLICY_CODES.has(String(error?.code)) && error.syscall?.startsWith("spawn") === true;
1420
+ }
1421
+ function powershellPath() {
1422
+ const windir = process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows";
1423
+ return join(windir, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
1424
+ }
1406
1425
  var HelperClient = class {
1407
1426
  log;
1408
1427
  child;
@@ -1469,7 +1488,30 @@ var HelperClient = class {
1469
1488
  }
1470
1489
  async start() {
1471
1490
  const exe = await ensureHelperExe();
1472
- const child = spawn(exe, [], {
1491
+ if (!hostedHelper) try {
1492
+ return await this.launch(exe, []);
1493
+ } catch (error) {
1494
+ if (!isPolicyBlock(error)) throw error;
1495
+ this.log(`starting cu-helper.exe was refused (${error.code ?? "unknown"}); running it inside powershell.exe instead`);
1496
+ hostedHelper = true;
1497
+ }
1498
+ try {
1499
+ return await this.launch(powershellPath(), [
1500
+ "-NoProfile",
1501
+ "-NonInteractive",
1502
+ "-STA",
1503
+ "-ExecutionPolicy",
1504
+ "Bypass",
1505
+ "-File",
1506
+ helperAssetPath("host.ps1"),
1507
+ exe
1508
+ ]);
1509
+ } catch (error) {
1510
+ throw new Error(`The computer-use helper could not be started (${error instanceof Error ? error.message : String(error)}). Windows refused to run the helper this plugin compiles (cu-helper.exe), and running it inside powershell.exe failed too. Smart App Control or another application control policy is the usual cause: see Event Viewer > Applications and Services Logs > Microsoft > Windows > CodeIntegrity > Operational.`);
1511
+ }
1512
+ }
1513
+ async launch(command, args) {
1514
+ const child = spawn(command, args, {
1473
1515
  stdio: [
1474
1516
  "pipe",
1475
1517
  "pipe",
@@ -1540,6 +1582,195 @@ var HelperClient = class {
1540
1582
  }
1541
1583
  };
1542
1584
  //#endregion
1585
+ //#region lib/types/native/koffi-path.js
1586
+ /**
1587
+ * Finds the koffi.node that DSH ships. It is signed by DeepSeek, so Smart App
1588
+ * Control lets it load where our own compiled cu-helper.exe is refused; a koffi
1589
+ * installed from npm would be unsigned and no better than the exe.
1590
+ */
1591
+ const RELATIVE = join("app.asar.unpacked", "dsh", "node_modules", "@koromix", "koffi-win32-x64", "win32_x64", "koffi.node");
1592
+ const IN_NODE_MODULES = join("node_modules", "@koromix", "koffi-win32-x64", "win32_x64", "koffi.node");
1593
+ /** node_modules/@koromix/... in the folders above the host's entry script, nearest first. */
1594
+ function besideHost(script) {
1595
+ if (!script) return [];
1596
+ const found = [];
1597
+ for (let dir = dirname(script);; dir = dirname(dir)) {
1598
+ found.push(join(dir, IN_NODE_MODULES));
1599
+ if (dirname(dir) === dir) return found;
1600
+ }
1601
+ }
1602
+ function koffiCandidates(env = process.env, script = process.argv[1]) {
1603
+ const resources = process.resourcesPath;
1604
+ return [
1605
+ env.DSH_KOFFI_PATH,
1606
+ resources && join(resources, RELATIVE),
1607
+ join(dirname(process.execPath), "resources", RELATIVE),
1608
+ env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs", "DeepSeek Harness", "resources", RELATIVE),
1609
+ ...besideHost(script)
1610
+ ].filter((path) => Boolean(path));
1611
+ }
1612
+ function findKoffi(env = process.env) {
1613
+ return koffiCandidates(env).find((path) => existsSync(path));
1614
+ }
1615
+ //#endregion
1616
+ //#region lib/types/native/native-helper.js
1617
+ /**
1618
+ * A HelperLike that runs some commands in-process through the koffi.node DSH
1619
+ * ships (see worker.ts) and hands everything else to the C# helper.
1620
+ *
1621
+ * What may go native depends on what the C# helper has on screen:
1622
+ * - displays / cursor / foreground: always.
1623
+ * - screenshot: unless a window card is up (the C# side captures under it).
1624
+ * - move / click / keys / drag / scroll / type: only while no overlay is
1625
+ * shown, since the C# side dodges the pill, lets input through its cards
1626
+ * and waits for the instruction box around every pointer or key action.
1627
+ * - windows / window_at: likewise, since the C# side leaves its own overlay
1628
+ * windows and the DSH card out of them.
1629
+ * If the worker fails to start, every command goes to the C# helper.
1630
+ */
1631
+ const ALWAYS = /* @__PURE__ */ new Set([
1632
+ "displays",
1633
+ "cursor",
1634
+ "foreground"
1635
+ ]);
1636
+ const NO_CARD = /* @__PURE__ */ new Set(["screenshot"]);
1637
+ const NO_OVERLAY = /* @__PURE__ */ new Set([
1638
+ "move",
1639
+ "click",
1640
+ "keys",
1641
+ "drag",
1642
+ "scroll",
1643
+ "type",
1644
+ "windows",
1645
+ "window_at"
1646
+ ]);
1647
+ /** The worker next to this module: lib/native-worker.js when bundled, lib/types/native/worker.js otherwise. */
1648
+ function workerPath() {
1649
+ const candidates = ["./native-worker.js", "./worker.js"].map((rel) => fileURLToPath(new URL(rel, import.meta.url)));
1650
+ return candidates.find((path) => existsSync(path)) ?? candidates[1];
1651
+ }
1652
+ var NativeHelper = class {
1653
+ fallback;
1654
+ log;
1655
+ enabled;
1656
+ koffiPath;
1657
+ worker;
1658
+ ready;
1659
+ pending = /* @__PURE__ */ new Map();
1660
+ nextId = 0;
1661
+ broken = false;
1662
+ overlay = false;
1663
+ cards = /* @__PURE__ */ new Set();
1664
+ constructor(fallback, log = () => {}, enabled = () => true, koffiPath = findKoffi() ?? null) {
1665
+ this.fallback = fallback;
1666
+ this.log = log;
1667
+ this.enabled = enabled;
1668
+ this.koffiPath = koffiPath;
1669
+ }
1670
+ get available() {
1671
+ return this.koffiPath !== null && !this.broken && this.enabled();
1672
+ }
1673
+ /** Whether a command would run through koffi right now. */
1674
+ routesNative(cmd) {
1675
+ if (!this.available) return false;
1676
+ if (ALWAYS.has(cmd)) return true;
1677
+ if (NO_CARD.has(cmd)) return this.cards.size === 0;
1678
+ if (NO_OVERLAY.has(cmd)) return !this.overlay && this.cards.size === 0;
1679
+ return false;
1680
+ }
1681
+ async call(cmd, args = {}, timeoutMs = 2e4) {
1682
+ if (!this.routesNative(cmd)) {
1683
+ this.shows(cmd, args);
1684
+ const result = await this.fallback.call(cmd, args, timeoutMs);
1685
+ this.hides(cmd, args);
1686
+ return result;
1687
+ }
1688
+ let worker;
1689
+ try {
1690
+ worker = await this.ensure();
1691
+ } catch (error) {
1692
+ this.broken = true;
1693
+ this.log(`koffi helper unavailable, using the C# helper only: ${error instanceof Error ? error.message : String(error)}`);
1694
+ return this.fallback.call(cmd, args, timeoutMs);
1695
+ }
1696
+ return new Promise((resolve, reject) => {
1697
+ const id = ++this.nextId;
1698
+ const timer = setTimeout(() => {
1699
+ this.pending.delete(id);
1700
+ reject(/* @__PURE__ */ new Error(`computer-use helper timed out on "${cmd}"`));
1701
+ }, timeoutMs);
1702
+ this.pending.set(id, {
1703
+ resolve,
1704
+ reject,
1705
+ timer
1706
+ });
1707
+ worker.postMessage({
1708
+ id,
1709
+ cmd,
1710
+ args
1711
+ });
1712
+ });
1713
+ }
1714
+ onEvent(listener) {
1715
+ return this.fallback.onEvent(listener);
1716
+ }
1717
+ dispose() {
1718
+ this.worker?.terminate();
1719
+ this.worker = void 0;
1720
+ this.ready = void 0;
1721
+ this.fallback.dispose();
1722
+ }
1723
+ /** Follow what the C# helper shows: count it as shown from the request on, hidden once it is done. */
1724
+ shows(cmd, args) {
1725
+ if (cmd === "overlay_show") this.overlay = true;
1726
+ else if (cmd === "window_card") this.cards.add(String(args.hwnd));
1727
+ }
1728
+ hides(cmd, args) {
1729
+ if (cmd === "overlay_hide") {
1730
+ this.overlay = false;
1731
+ this.cards.clear();
1732
+ } else if (cmd === "window_uncard") this.cards.delete(String(args.hwnd));
1733
+ }
1734
+ ensure() {
1735
+ this.ready ??= new Promise((resolve, reject) => {
1736
+ const worker = new Worker(workerPath(), { workerData: { koffiPath: this.koffiPath } });
1737
+ worker.unref();
1738
+ worker.on("message", (message) => {
1739
+ if (message.event === "ready") {
1740
+ this.worker = worker;
1741
+ this.log(`computer-use: koffi helper ready (${String(this.koffiPath)})`);
1742
+ resolve(worker);
1743
+ return;
1744
+ }
1745
+ if (typeof message.id !== "number") return;
1746
+ const entry = this.pending.get(message.id);
1747
+ if (!entry) return;
1748
+ this.pending.delete(message.id);
1749
+ clearTimeout(entry.timer);
1750
+ if (message.ok) entry.resolve(message.result ?? null);
1751
+ else entry.reject(new Error(message.error ?? "helper error"));
1752
+ });
1753
+ worker.on("error", (error) => {
1754
+ this.worker = void 0;
1755
+ this.ready = void 0;
1756
+ reject(error);
1757
+ for (const [id, entry] of this.pending) {
1758
+ clearTimeout(entry.timer);
1759
+ entry.reject(error);
1760
+ this.pending.delete(id);
1761
+ }
1762
+ });
1763
+ worker.on("exit", () => {
1764
+ if (this.worker === worker) {
1765
+ this.worker = void 0;
1766
+ this.ready = void 0;
1767
+ }
1768
+ });
1769
+ });
1770
+ return this.ready;
1771
+ }
1772
+ };
1773
+ //#endregion
1543
1774
  //#region lib/types/overlay.js
1544
1775
  /**
1545
1776
  * The "AI is controlling your computer" indicator and the user's controls:
@@ -2163,7 +2394,8 @@ const DEFAULTS = {
2163
2394
  pauseOnUserInput: true,
2164
2395
  userIdleMs: 1500,
2165
2396
  typingMode: "stream",
2166
- quickSteps: false
2397
+ quickSteps: false,
2398
+ nativeHelper: true
2167
2399
  };
2168
2400
  /** Unwrap `.volatile()` refs (`{ get() }`) and fall back to defaults for bad values. */
2169
2401
  function resolveConfig(raw) {
@@ -2188,6 +2420,7 @@ function resolveConfig(raw) {
2188
2420
  pauseOnUserInput: bool("pauseOnUserInput"),
2189
2421
  userIdleMs: num("userIdleMs", 300, 1e4),
2190
2422
  quickSteps: bool("quickSteps"),
2423
+ nativeHelper: bool("nativeHelper"),
2191
2424
  typingMode: out.typingMode === "stream" || out.typingMode === "type" || out.typingMode === "paste" ? out.typingMode : DEFAULTS.typingMode,
2192
2425
  blockedApps: Array.isArray(out.blockedApps) ? out.blockedApps.filter((item) => typeof item === "string" && item.trim() !== "") : []
2193
2426
  };
@@ -9032,6 +9265,10 @@ const Config = z.object({
9032
9265
  "zh-CN": { $description: "键盘停止多少毫秒后恢复操作" },
9033
9266
  "en-US": { $description: "Milliseconds of keyboard quiet before resuming" }
9034
9267
  }),
9268
+ nativeHelper: z.boolean().default(true).volatile().i18n({
9269
+ "zh-CN": { $description: "截图、显示器与窗口查询、无浮层时的输入改由 DeepSeek Harness 自带的 koffi 在进程内完成(更快,也不受智能应用控制拦截);关闭则全部交给 C# 辅助程序" },
9270
+ "en-US": { $description: "Take screenshots, display and window queries, and input while no overlay is shown in-process through the koffi that DeepSeek Harness ships (faster, and not blocked by Smart App Control); off sends everything to the C# helper" }
9271
+ }),
9035
9272
  blockedApps: z.array(z.string()).default([]).volatile().i18n({
9036
9273
  "zh-CN": { $description: "禁止操控的应用(名称或 exe,如 “alipay”)。常见密码管理器默认已禁止。" },
9037
9274
  "en-US": { $description: "Apps that may never be controlled (names or exe). Common password managers are always blocked." }
@@ -9044,7 +9281,7 @@ function apply(ctx, config = {}) {
9044
9281
  }
9045
9282
  const settings = () => resolveConfig(config);
9046
9283
  const log = (message) => ctx.logger.info(message);
9047
- const helper = new HelperClient((message) => ctx.logger.warn(message));
9284
+ const helper = new NativeHelper(new HelperClient((message) => ctx.logger.warn(message)), (message) => ctx.logger.warn(message), () => settings().nativeHelper);
9048
9285
  const access = new AccessControl();
9049
9286
  const iconPath = helperAssetPath("deepseek-white.png");
9050
9287
  const overlay = new OverlayController(helper, settings, log, iconPath);
@@ -0,0 +1,695 @@
1
+ import { createRequire } from "node:module";
2
+ import { win32 } from "node:path";
3
+ import { parentPort, workerData } from "node:worker_threads";
4
+ //#region lib/types/native/worker.js
5
+ /**
6
+ * Spike: part of the helper's command set done in-process through koffi, on a
7
+ * worker thread so that Sleep-style pauses and GDI work never block the host's
8
+ * event loop. Replies use the same shapes as helper/CuHelper.cs.
9
+ */
10
+ const koffi = createRequire(import.meta.url)(workerData.koffiPath);
11
+ const user32 = koffi.load("user32.dll");
12
+ const gdi32 = koffi.load("gdi32.dll");
13
+ const shcore = koffi.load("shcore.dll");
14
+ const gdiplus = koffi.load("gdiplus.dll");
15
+ const ole32 = koffi.load("ole32.dll");
16
+ const kernel32 = koffi.load("kernel32.dll");
17
+ const dwmapi = koffi.load("dwmapi.dll");
18
+ const RECT = koffi.struct("RECT", {
19
+ left: "int32_t",
20
+ top: "int32_t",
21
+ right: "int32_t",
22
+ bottom: "int32_t"
23
+ });
24
+ koffi.struct("POINT", {
25
+ x: "int32_t",
26
+ y: "int32_t"
27
+ });
28
+ const MONITORINFOEXW = koffi.struct("MONITORINFOEXW", {
29
+ cbSize: "uint32_t",
30
+ rcMonitor: RECT,
31
+ rcWork: RECT,
32
+ dwFlags: "uint32_t",
33
+ szDevice: koffi.array("char16_t", 32, "String")
34
+ });
35
+ koffi.struct("BITMAPINFOHEADER", {
36
+ biSize: "uint32_t",
37
+ biWidth: "int32_t",
38
+ biHeight: "int32_t",
39
+ biPlanes: "uint16_t",
40
+ biBitCount: "uint16_t",
41
+ biCompression: "uint32_t",
42
+ biSizeImage: "uint32_t",
43
+ biXPelsPerMeter: "int32_t",
44
+ biYPelsPerMeter: "int32_t",
45
+ biClrUsed: "uint32_t",
46
+ biClrImportant: "uint32_t"
47
+ });
48
+ const GUID = koffi.struct("GUID", {
49
+ Data1: "uint32_t",
50
+ Data2: "uint16_t",
51
+ Data3: "uint16_t",
52
+ Data4: koffi.array("uint8_t", 8, "Array")
53
+ });
54
+ const EncoderParameter = koffi.struct("EncoderParameter", {
55
+ Guid: GUID,
56
+ NumberOfValues: "uint32_t",
57
+ Type: "uint32_t",
58
+ Value: "void *"
59
+ });
60
+ koffi.struct("EncoderParameters", {
61
+ Count: "uint32_t",
62
+ Parameter: koffi.array(EncoderParameter, 1)
63
+ });
64
+ koffi.struct("GdiplusStartupInput", {
65
+ GdiplusVersion: "uint32_t",
66
+ DebugEventCallback: "void *",
67
+ SuppressBackgroundThread: "int",
68
+ SuppressExternalCodecs: "int"
69
+ });
70
+ const MonitorEnumProc = koffi.proto("int __stdcall MonitorEnumProc(void *monitor, void *hdc, RECT *rect, intptr_t data)");
71
+ const ReleaseProc = koffi.proto("uint32_t __stdcall ReleaseProc(void *self)");
72
+ const EnumWindowsProc = koffi.proto("int __stdcall EnumWindowsProc(void *hwnd, intptr_t data)");
73
+ const SetThreadDpiAwarenessContext = user32.func("intptr_t __stdcall SetThreadDpiAwarenessContext(intptr_t context)");
74
+ const EnumDisplayMonitors = user32.func("int __stdcall EnumDisplayMonitors(void *hdc, RECT *clip, MonitorEnumProc *proc, intptr_t data)");
75
+ const GetMonitorInfoW = user32.func("int __stdcall GetMonitorInfoW(void *monitor, _Inout_ MONITORINFOEXW *info)");
76
+ const GetCursorPos = user32.func("int __stdcall GetCursorPos(_Out_ POINT *point)");
77
+ const SetCursorPos = user32.func("int __stdcall SetCursorPos(int x, int y)");
78
+ const SendInput = user32.func("uint32_t __stdcall SendInput(uint32_t count, void *inputs, int size)");
79
+ const MapVirtualKeyW = user32.func("uint32_t __stdcall MapVirtualKeyW(uint32_t code, uint32_t type)");
80
+ const GetDC = user32.func("void * __stdcall GetDC(void *hwnd)");
81
+ const ReleaseDC = user32.func("int __stdcall ReleaseDC(void *hwnd, void *hdc)");
82
+ const GetLastError = kernel32.func("uint32_t __stdcall GetLastError()");
83
+ const GetForegroundWindow = user32.func("void * __stdcall GetForegroundWindow()");
84
+ const IsWindow = user32.func("int __stdcall IsWindow(void *hwnd)");
85
+ const IsWindowVisible = user32.func("int __stdcall IsWindowVisible(void *hwnd)");
86
+ const IsIconic = user32.func("int __stdcall IsIconic(void *hwnd)");
87
+ const IsZoomed = user32.func("int __stdcall IsZoomed(void *hwnd)");
88
+ const GetWindow = user32.func("void * __stdcall GetWindow(void *hwnd, uint32_t cmd)");
89
+ const GetAncestor = user32.func("void * __stdcall GetAncestor(void *hwnd, uint32_t flags)");
90
+ const WindowFromPoint = user32.func("void * __stdcall WindowFromPoint(POINT point)");
91
+ const GetWindowLongW = user32.func("int32_t __stdcall GetWindowLongW(void *hwnd, int index)");
92
+ const GetWindowTextLengthW = user32.func("int __stdcall GetWindowTextLengthW(void *hwnd)");
93
+ const GetWindowTextW = user32.func("int __stdcall GetWindowTextW(void *hwnd, void *text, int max)");
94
+ const GetClassNameW = user32.func("int __stdcall GetClassNameW(void *hwnd, void *name, int max)");
95
+ const GetWindowRect = user32.func("int __stdcall GetWindowRect(void *hwnd, _Out_ RECT *rect)");
96
+ const GetWindowThreadProcessId = user32.func("uint32_t __stdcall GetWindowThreadProcessId(void *hwnd, _Out_ uint32_t *pid)");
97
+ const EnumWindows = user32.func("int __stdcall EnumWindows(EnumWindowsProc *proc, intptr_t data)");
98
+ const DwmGetWindowAttribute = dwmapi.func("int32_t __stdcall DwmGetWindowAttribute(void *hwnd, uint32_t attribute, void *value, uint32_t size)");
99
+ const OpenProcess = kernel32.func("void * __stdcall OpenProcess(uint32_t access, int inherit, uint32_t pid)");
100
+ const QueryFullProcessImageNameW = kernel32.func("int __stdcall QueryFullProcessImageNameW(void *process, uint32_t flags, void *name, _Inout_ uint32_t *size)");
101
+ const CloseHandle = kernel32.func("int __stdcall CloseHandle(void *handle)");
102
+ const GetDpiForMonitor = shcore.func("int32_t __stdcall GetDpiForMonitor(void *monitor, int type, _Out_ uint32_t *x, _Out_ uint32_t *y)");
103
+ const CreateCompatibleDC = gdi32.func("void * __stdcall CreateCompatibleDC(void *hdc)");
104
+ const CreateDIBSection = gdi32.func("void * __stdcall CreateDIBSection(void *hdc, BITMAPINFOHEADER *info, uint32_t usage, _Out_ void **bits, void *section, uint32_t offset)");
105
+ const SelectObject = gdi32.func("void * __stdcall SelectObject(void *hdc, void *object)");
106
+ const BitBlt = gdi32.func("int __stdcall BitBlt(void *dst, int x, int y, int w, int h, void *src, int sx, int sy, uint32_t rop)");
107
+ const DeleteObject = gdi32.func("int __stdcall DeleteObject(void *object)");
108
+ const DeleteDC = gdi32.func("int __stdcall DeleteDC(void *hdc)");
109
+ const GdiFlush = gdi32.func("int __stdcall GdiFlush()");
110
+ const GdiplusStartup = gdiplus.func("int __stdcall GdiplusStartup(_Out_ uintptr_t *token, GdiplusStartupInput *input, void *output)");
111
+ const GdipCreateBitmapFromScan0 = gdiplus.func("int __stdcall GdipCreateBitmapFromScan0(int w, int h, int stride, int format, void *scan0, _Out_ void **bitmap)");
112
+ const GdipGetImageGraphicsContext = gdiplus.func("int __stdcall GdipGetImageGraphicsContext(void *image, _Out_ void **graphics)");
113
+ const GdipSetInterpolationMode = gdiplus.func("int __stdcall GdipSetInterpolationMode(void *graphics, int mode)");
114
+ const GdipSetPixelOffsetMode = gdiplus.func("int __stdcall GdipSetPixelOffsetMode(void *graphics, int mode)");
115
+ const GdipSetCompositingQuality = gdiplus.func("int __stdcall GdipSetCompositingQuality(void *graphics, int quality)");
116
+ const GdipCreateImageAttributes = gdiplus.func("int __stdcall GdipCreateImageAttributes(_Out_ void **attrs)");
117
+ const GdipSetImageAttributesWrapMode = gdiplus.func("int __stdcall GdipSetImageAttributesWrapMode(void *attrs, int wrap, uint32_t argb, int clamp)");
118
+ const GdipDrawImageRectRectI = gdiplus.func("int __stdcall GdipDrawImageRectRectI(void *graphics, void *image, int dx, int dy, int dw, int dh, int sx, int sy, int sw, int sh, int unit, void *attrs, void *callback, void *data)");
119
+ const GdipSaveImageToStream = gdiplus.func("int __stdcall GdipSaveImageToStream(void *image, void *stream, GUID *clsid, EncoderParameters *params)");
120
+ const GdipDisposeImage = gdiplus.func("int __stdcall GdipDisposeImage(void *image)");
121
+ const GdipDeleteGraphics = gdiplus.func("int __stdcall GdipDeleteGraphics(void *graphics)");
122
+ const GdipDisposeImageAttributes = gdiplus.func("int __stdcall GdipDisposeImageAttributes(void *attrs)");
123
+ const CreateStreamOnHGlobal = ole32.func("int32_t __stdcall CreateStreamOnHGlobal(void *global, int deleteOnRelease, _Out_ void **stream)");
124
+ const GetHGlobalFromStream = ole32.func("int32_t __stdcall GetHGlobalFromStream(void *stream, _Out_ void **global)");
125
+ const GlobalSize = kernel32.func("size_t __stdcall GlobalSize(void *global)");
126
+ const GlobalLock = kernel32.func("void * __stdcall GlobalLock(void *global)");
127
+ const GlobalUnlock = kernel32.func("int __stdcall GlobalUnlock(void *global)");
128
+ SetThreadDpiAwarenessContext(-4);
129
+ const MARKER = 1146308675n;
130
+ const INPUT_SIZE = 40;
131
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
132
+ function sleep(ms) {
133
+ if (ms > 0) Atomics.wait(sleeper, 0, 0, ms);
134
+ }
135
+ function int(args, key, fallback) {
136
+ const value = args[key];
137
+ return typeof value === "number" ? Math.trunc(value) : fallback;
138
+ }
139
+ function displays() {
140
+ const list = [];
141
+ const callback = koffi.register((monitor) => {
142
+ const info = { cbSize: MONITORINFOEXW.size };
143
+ GetMonitorInfoW(monitor, info);
144
+ const dx = [96];
145
+ GetDpiForMonitor(monitor, 0, dx, [96]);
146
+ const m = info.rcMonitor, w = info.rcWork;
147
+ list.push({
148
+ x: m.left,
149
+ y: m.top,
150
+ width: m.right - m.left,
151
+ height: m.bottom - m.top,
152
+ workX: w.left,
153
+ workY: w.top,
154
+ workWidth: w.right - w.left,
155
+ workHeight: w.bottom - w.top,
156
+ primary: (info.dwFlags & 1) !== 0,
157
+ dpi: dx[0],
158
+ name: info.szDevice
159
+ });
160
+ return 1;
161
+ }, koffi.pointer(MonitorEnumProc));
162
+ try {
163
+ EnumDisplayMonitors(null, null, callback, 0);
164
+ } finally {
165
+ koffi.unregister(callback);
166
+ }
167
+ return list;
168
+ }
169
+ function cursor() {
170
+ const point = {};
171
+ GetCursorPos(point);
172
+ return {
173
+ x: point.x,
174
+ y: point.y
175
+ };
176
+ }
177
+ const EXTENDED = /* @__PURE__ */ new Set([
178
+ 33,
179
+ 34,
180
+ 35,
181
+ 36,
182
+ 37,
183
+ 38,
184
+ 39,
185
+ 40,
186
+ 44,
187
+ 45,
188
+ 46,
189
+ 91,
190
+ 92,
191
+ 93,
192
+ 111,
193
+ 144,
194
+ 163,
195
+ 165
196
+ ]);
197
+ /** One INPUT (x64 layout, 40 bytes) for a mouse event. */
198
+ function mouse(flags, data = 0) {
199
+ const b = Buffer.alloc(INPUT_SIZE);
200
+ b.writeUInt32LE(0, 0);
201
+ b.writeUInt32LE(data >>> 0, 16);
202
+ b.writeUInt32LE(flags, 20);
203
+ b.writeBigUInt64LE(MARKER, 32);
204
+ return b;
205
+ }
206
+ function key(vk, up) {
207
+ const b = Buffer.alloc(INPUT_SIZE);
208
+ b.writeUInt32LE(1, 0);
209
+ b.writeUInt16LE(vk, 8);
210
+ b.writeUInt16LE(MapVirtualKeyW(vk, 0), 10);
211
+ b.writeUInt32LE((up ? 2 : 0) | (EXTENDED.has(vk) ? 1 : 0), 12);
212
+ b.writeBigUInt64LE(MARKER, 24);
213
+ return b;
214
+ }
215
+ function send(inputs) {
216
+ if (inputs.length === 0) return;
217
+ if (SendInput(inputs.length, Buffer.concat(inputs), INPUT_SIZE) !== inputs.length) throw new Error(`SendInput was blocked (error ${String(GetLastError())}). The target may be running elevated (as administrator) or the secure desktop (UAC / lock screen) is active.`);
218
+ }
219
+ function move(x, y) {
220
+ SetCursorPos(x, y);
221
+ send([mouse(1)]);
222
+ }
223
+ function buttonFlags(button) {
224
+ if (button === "right") return [8, 16];
225
+ if (button === "middle") return [32, 64];
226
+ return [2, 4];
227
+ }
228
+ function vkList(value) {
229
+ return Array.isArray(value) ? value.filter((v) => typeof v === "number") : [];
230
+ }
231
+ function click(args) {
232
+ if (typeof args.x === "number") {
233
+ move(int(args, "x", 0), int(args, "y", 0));
234
+ sleep(30);
235
+ }
236
+ const [down, up] = buttonFlags(args.button);
237
+ const count = Math.max(1, Math.min(3, int(args, "count", 1)));
238
+ const mods = vkList(args.modifiers);
239
+ send(mods.map((vk) => key(vk, false)));
240
+ try {
241
+ for (let i = 0; i < count; i++) {
242
+ send([mouse(down)]);
243
+ sleep(20);
244
+ send([mouse(up)]);
245
+ if (i < count - 1) sleep(40);
246
+ }
247
+ } finally {
248
+ send([...mods].reverse().map((vk) => key(vk, true)));
249
+ }
250
+ return null;
251
+ }
252
+ function keys(args) {
253
+ const combos = Array.isArray(args.combos) ? args.combos.map(vkList) : [];
254
+ const hold = int(args, "holdMs", 0);
255
+ for (const combo of combos) {
256
+ send(combo.map((vk) => key(vk, false)));
257
+ sleep(hold > 0 ? hold : 25);
258
+ send([...combo].reverse().map((vk) => key(vk, true)));
259
+ sleep(30);
260
+ }
261
+ return null;
262
+ }
263
+ function drag(args) {
264
+ const x1 = int(args, "x1", 0), y1 = int(args, "y1", 0), x2 = int(args, "x2", 0), y2 = int(args, "y2", 0);
265
+ const [down, up] = buttonFlags(args.button);
266
+ move(x1, y1);
267
+ sleep(40);
268
+ send([mouse(down)]);
269
+ try {
270
+ sleep(60);
271
+ const steps = Math.max(8, Math.min(40, Math.trunc(Math.hypot(x2 - x1, y2 - y1) / 20)));
272
+ for (let i = 1; i <= steps; i++) {
273
+ move(x1 + Math.trunc((x2 - x1) * i / steps), y1 + Math.trunc((y2 - y1) * i / steps));
274
+ sleep(12);
275
+ }
276
+ sleep(60);
277
+ } finally {
278
+ send([mouse(up)]);
279
+ }
280
+ return null;
281
+ }
282
+ function scroll(args) {
283
+ if (typeof args.x === "number") {
284
+ move(int(args, "x", 0), int(args, "y", 0));
285
+ sleep(30);
286
+ }
287
+ const dx = int(args, "dx", 0), dy = int(args, "dy", 0);
288
+ const mods = vkList(args.modifiers);
289
+ send(mods.map((vk) => key(vk, false)));
290
+ try {
291
+ for (let i = 0; i < Math.abs(dy); i++) {
292
+ send([mouse(2048, dy > 0 ? -120 : 120)]);
293
+ sleep(15);
294
+ }
295
+ for (let i = 0; i < Math.abs(dx); i++) {
296
+ send([mouse(4096, dx > 0 ? 120 : -120)]);
297
+ sleep(15);
298
+ }
299
+ } finally {
300
+ send([...mods].reverse().map((vk) => key(vk, true)));
301
+ }
302
+ return null;
303
+ }
304
+ function unicode(unit, up) {
305
+ const b = Buffer.alloc(INPUT_SIZE);
306
+ b.writeUInt32LE(1, 0);
307
+ b.writeUInt16LE(unit, 10);
308
+ b.writeUInt32LE(4 | (up ? 2 : 0), 12);
309
+ b.writeBigUInt64LE(MARKER, 24);
310
+ return b;
311
+ }
312
+ /** charDelay > 0: one character at a time, like a person typing; otherwise fast batches. */
313
+ function typeText(args) {
314
+ const text = typeof args.text === "string" ? args.text : "";
315
+ const charDelay = int(args, "charDelay", 0), pause = charDelay > 0 ? charDelay : int(args, "chunkDelay", 8);
316
+ let batch = [];
317
+ const flush = () => {
318
+ if (batch.length === 0) return;
319
+ send(batch);
320
+ batch = [];
321
+ if (pause > 0) sleep(pause);
322
+ };
323
+ for (let i = 0; i < text.length; i++) {
324
+ let c = text.charCodeAt(i);
325
+ if (c === 13) {
326
+ if (text.charCodeAt(i + 1) === 10) continue;
327
+ c = 10;
328
+ }
329
+ if (c === 10) {
330
+ flush();
331
+ batch.push(key(13, false), key(13, true));
332
+ flush();
333
+ continue;
334
+ }
335
+ if (c === 9) {
336
+ batch.push(key(9, false), key(9, true));
337
+ continue;
338
+ }
339
+ batch.push(unicode(c, false), unicode(c, true));
340
+ if (c >= 55296 && c <= 56319) continue;
341
+ if (charDelay > 0 || batch.length >= 40) flush();
342
+ }
343
+ flush();
344
+ return null;
345
+ }
346
+ function hwndOf(value) {
347
+ if (typeof value === "bigint") return value;
348
+ if (typeof value === "number") return BigInt(Math.trunc(value));
349
+ return 0n;
350
+ }
351
+ function utf16(read, max) {
352
+ const buffer = Buffer.alloc(max * 2);
353
+ const n = read(buffer, max);
354
+ return n > 0 ? buffer.toString("utf16le", 0, n * 2) : "";
355
+ }
356
+ function exePath(pid) {
357
+ const handle = OpenProcess(4096, 0, pid);
358
+ if (!handle) return "";
359
+ try {
360
+ const size = [1024];
361
+ const name = Buffer.alloc(2048);
362
+ return QueryFullProcessImageNameW(handle, 0, name, size) ? name.toString("utf16le", 0, size[0] * 2) : "";
363
+ } finally {
364
+ CloseHandle(handle);
365
+ }
366
+ }
367
+ function processOf(hwnd) {
368
+ const pid = [0];
369
+ GetWindowThreadProcessId(hwnd, pid);
370
+ return pid[0];
371
+ }
372
+ function cloaked(hwnd) {
373
+ const value = Buffer.alloc(4);
374
+ return DwmGetWindowAttribute(hwnd, 14, value, 4) === 0 && value.readInt32LE(0) !== 0;
375
+ }
376
+ function windowRect(hwnd) {
377
+ const rect = {};
378
+ GetWindowRect(hwnd, rect);
379
+ return rect;
380
+ }
381
+ /** The visible frame (without the invisible resize border), else the window rectangle. */
382
+ function bounds(hwnd) {
383
+ const frame = Buffer.alloc(16);
384
+ if (DwmGetWindowAttribute(hwnd, 9, frame, 16) !== 0) return windowRect(hwnd);
385
+ return {
386
+ left: frame.readInt32LE(0),
387
+ top: frame.readInt32LE(4),
388
+ right: frame.readInt32LE(8),
389
+ bottom: frame.readInt32LE(12)
390
+ };
391
+ }
392
+ /** Same fields as Windows.Describe in the C# helper; {} for no window. */
393
+ function describe(hwnd) {
394
+ if (!hwnd || !IsWindow(hwnd)) return {};
395
+ const pid = processOf(hwnd);
396
+ const length = GetWindowTextLengthW(hwnd);
397
+ const title = utf16((b, max) => GetWindowTextW(hwnd, b, max), Math.max(length + 1, 2));
398
+ const className = utf16((b, max) => GetClassNameW(hwnd, b, max), 256);
399
+ const rc = bounds(hwnd);
400
+ const path = exePath(pid);
401
+ return {
402
+ hwnd: Number(hwnd),
403
+ title,
404
+ className,
405
+ pid,
406
+ exe: path ? win32.basename(path) : "",
407
+ path,
408
+ x: rc.left,
409
+ y: rc.top,
410
+ width: rc.right - rc.left,
411
+ height: rc.bottom - rc.top,
412
+ minimized: Boolean(IsIconic(hwnd)),
413
+ maximized: Boolean(IsZoomed(hwnd))
414
+ };
415
+ }
416
+ function enumWindows(visit) {
417
+ const callback = koffi.register((hwnd) => visit(hwndOf(hwnd)) ? 1 : 0, koffi.pointer(EnumWindowsProc));
418
+ try {
419
+ EnumWindows(callback, 0);
420
+ } finally {
421
+ koffi.unregister(callback);
422
+ }
423
+ }
424
+ function foreground() {
425
+ return describe(hwndOf(GetForegroundWindow()));
426
+ }
427
+ /** Top-level app windows, as Windows.List in the C# helper. */
428
+ function windows() {
429
+ const list = [];
430
+ const fg = hwndOf(GetForegroundWindow());
431
+ enumWindows((h) => {
432
+ if (!IsWindowVisible(h) || GetWindowTextLengthW(h) === 0) return true;
433
+ if (hwndOf(GetWindow(h, 4))) return true;
434
+ const ex = GetWindowLongW(h, -20);
435
+ if ((ex & 128) !== 0 && (ex & 262144) === 0) return true;
436
+ if (cloaked(h)) return true;
437
+ list.push({
438
+ ...describe(h),
439
+ foreground: h === fg
440
+ });
441
+ return true;
442
+ });
443
+ return list;
444
+ }
445
+ /** Full-screen overlays that never take input themselves (NVIDIA / Xbox Game Bar...). */
446
+ const SEE_THROUGH = [
447
+ "nvidia overlay.exe",
448
+ "nvsphelper64.exe",
449
+ "gamebar.exe",
450
+ "gamebarftserver.exe"
451
+ ];
452
+ function seeThrough(pid) {
453
+ return pid !== 0 && SEE_THROUGH.includes(win32.basename(exePath(pid)).toLowerCase());
454
+ }
455
+ /** The top-level window under a point, as Windows.At in the C# helper. */
456
+ function windowAt(args) {
457
+ const x = int(args, "x", 0), y = int(args, "y", 0);
458
+ let h = hwndOf(WindowFromPoint({
459
+ x,
460
+ y
461
+ }));
462
+ if (h) h = hwndOf(GetAncestor(h, 2));
463
+ if (!h || seeThrough(processOf(h))) {
464
+ let found = 0n;
465
+ enumWindows((w) => {
466
+ if (!IsWindowVisible(w) || seeThrough(processOf(w))) return true;
467
+ if ((GetWindowLongW(w, -20) & 32) !== 0) return true;
468
+ if (IsIconic(w) || cloaked(w)) return true;
469
+ const rc = windowRect(w);
470
+ if (x >= rc.left && x < rc.right && y >= rc.top && y < rc.bottom) {
471
+ found = w;
472
+ return false;
473
+ }
474
+ return true;
475
+ });
476
+ h = found;
477
+ }
478
+ return describe(h);
479
+ }
480
+ let gdiplusReady = false;
481
+ const JPEG = {
482
+ Data1: 1434252289,
483
+ Data2: 6660,
484
+ Data3: 4563,
485
+ Data4: [
486
+ 154,
487
+ 115,
488
+ 0,
489
+ 0,
490
+ 248,
491
+ 30,
492
+ 243,
493
+ 46
494
+ ]
495
+ };
496
+ const QUALITY = {
497
+ Data1: 492561589,
498
+ Data2: 64074,
499
+ Data3: 17709,
500
+ Data4: [
501
+ 156,
502
+ 221,
503
+ 93,
504
+ 179,
505
+ 81,
506
+ 5,
507
+ 231,
508
+ 235
509
+ ]
510
+ };
511
+ function check(status, what) {
512
+ if (status !== 0) throw new Error(`${what} failed (GDI+ status ${String(status)})`);
513
+ }
514
+ function startGdiplus() {
515
+ if (gdiplusReady) return;
516
+ check(GdiplusStartup([0n], {
517
+ GdiplusVersion: 1,
518
+ DebugEventCallback: null,
519
+ SuppressBackgroundThread: 0,
520
+ SuppressExternalCodecs: 0
521
+ }, null), "GdiplusStartup");
522
+ gdiplusReady = true;
523
+ }
524
+ /**
525
+ * Copy native memory into a Buffer. Not koffi.view(): Electron (the DSH host
526
+ * runtime) forbids external ArrayBuffers and aborts the process on one.
527
+ */
528
+ function copy(pointer, offset, length) {
529
+ return koffi.decode(pointer, offset, koffi.array("uint8_t", length, "Buffer"));
530
+ }
531
+ /** Every 8th pixel of every 8th row, as BGR bytes (same sample the C# helper takes). */
532
+ function sample(bits, w, h) {
533
+ const sx = Math.ceil(w / 8), sy = Math.ceil(h / 8);
534
+ const out = new Uint8Array(sx * sy * 3);
535
+ let k = 0;
536
+ for (let j = 0; j < sy; j++) {
537
+ const row = copy(bits, j * 8 * w * 4, w * 4);
538
+ for (let i = 0; i < sx; i++) {
539
+ const o = i * 32;
540
+ out[k++] = row[o];
541
+ out[k++] = row[o + 1];
542
+ out[k++] = row[o + 2];
543
+ }
544
+ }
545
+ return out;
546
+ }
547
+ function changed(a, b) {
548
+ let diff = 0;
549
+ for (let i = 0; i < a.length; i += 3) if (Math.abs(a[i] - b[i]) + Math.abs(a[i + 1] - b[i + 1]) + Math.abs(a[i + 2] - b[i + 2]) > 30) diff++;
550
+ return a.length === 0 ? 0 : diff / (a.length / 3);
551
+ }
552
+ let marked;
553
+ let markedRect = "";
554
+ /** Encode a GDI+ image to JPEG in memory and return the bytes. */
555
+ function encodeJpeg(image, quality) {
556
+ const value = koffi.alloc("uint32_t", 1);
557
+ koffi.encode(value, "uint32_t", quality);
558
+ const params = {
559
+ Count: 1,
560
+ Parameter: [{
561
+ Guid: QUALITY,
562
+ NumberOfValues: 1,
563
+ Type: 4,
564
+ Value: value
565
+ }]
566
+ };
567
+ const stream = [0n];
568
+ check(CreateStreamOnHGlobal(null, 1, stream), "CreateStreamOnHGlobal");
569
+ try {
570
+ check(GdipSaveImageToStream(image, stream[0], JPEG, params), "GdipSaveImageToStream");
571
+ const global = [0n];
572
+ check(GetHGlobalFromStream(stream[0], global), "GetHGlobalFromStream");
573
+ const size = Number(GlobalSize(global[0]));
574
+ const data = GlobalLock(global[0]);
575
+ try {
576
+ return copy(data, 0, size);
577
+ } finally {
578
+ GlobalUnlock(global[0]);
579
+ }
580
+ } finally {
581
+ const vtable = koffi.decode(stream[0], "void *");
582
+ koffi.call(koffi.decode(vtable, 16, "void *"), ReleaseProc, stream[0]);
583
+ koffi.free(value);
584
+ }
585
+ }
586
+ function screenshot(args) {
587
+ const x = int(args, "x", 0), y = int(args, "y", 0), w = int(args, "width", 0), h = int(args, "height", 0);
588
+ const ow = int(args, "outWidth", w), oh = int(args, "outHeight", h), quality = int(args, "quality", 80);
589
+ if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Error("invalid capture size");
590
+ startGdiplus();
591
+ const screen = GetDC(null);
592
+ const memory = CreateCompatibleDC(screen);
593
+ const bits = [0n];
594
+ const dib = CreateDIBSection(memory, {
595
+ biSize: 40,
596
+ biWidth: w,
597
+ biHeight: -h,
598
+ biPlanes: 1,
599
+ biBitCount: 32,
600
+ biCompression: 0,
601
+ biSizeImage: 0,
602
+ biXPelsPerMeter: 0,
603
+ biYPelsPerMeter: 0,
604
+ biClrUsed: 0,
605
+ biClrImportant: 0
606
+ }, 0, bits, null, 0);
607
+ const previous = SelectObject(memory, dib);
608
+ const images = [];
609
+ let graphics = 0n, attrs = 0n;
610
+ try {
611
+ if (!BitBlt(memory, 0, 0, w, h, screen, x, y, 1087111200)) throw new Error(`BitBlt failed (error ${String(GetLastError())})`);
612
+ GdiFlush();
613
+ const compare = args.compare === true;
614
+ if (args.mark === true || compare) {
615
+ const key = `${x},${y},${w},${h}`;
616
+ const now = sample(bits[0], w, h);
617
+ const threshold = typeof args.threshold === "number" ? args.threshold : 5e-4;
618
+ if (compare && marked && markedRect === key && changed(marked, now) < threshold) return { unchanged: true };
619
+ marked = now;
620
+ markedRect = key;
621
+ }
622
+ const source = [0n];
623
+ check(GdipCreateBitmapFromScan0(w, h, w * 4, 139273, bits[0], source), "GdipCreateBitmapFromScan0");
624
+ images.push(source[0]);
625
+ let output = source[0];
626
+ if (ow !== w || oh !== h) {
627
+ const scaled = [0n];
628
+ check(GdipCreateBitmapFromScan0(ow, oh, 0, 137224, null, scaled), "GdipCreateBitmapFromScan0");
629
+ images.push(scaled[0]);
630
+ const g = [0n], a = [0n];
631
+ check(GdipGetImageGraphicsContext(scaled[0], g), "GdipGetImageGraphicsContext");
632
+ graphics = g[0];
633
+ GdipSetInterpolationMode(graphics, 7);
634
+ GdipSetPixelOffsetMode(graphics, 2);
635
+ GdipSetCompositingQuality(graphics, 2);
636
+ check(GdipCreateImageAttributes(a), "GdipCreateImageAttributes");
637
+ attrs = a[0];
638
+ GdipSetImageAttributesWrapMode(attrs, 3, 0, 0);
639
+ check(GdipDrawImageRectRectI(graphics, source[0], 0, 0, ow, oh, 0, 0, w, h, 2, attrs, null, null), "GdipDrawImageRectRectI");
640
+ output = scaled[0];
641
+ }
642
+ return {
643
+ data: encodeJpeg(output, quality).toString("base64"),
644
+ via: "blt",
645
+ width: ow,
646
+ height: oh
647
+ };
648
+ } finally {
649
+ if (attrs) GdipDisposeImageAttributes(attrs);
650
+ if (graphics) GdipDeleteGraphics(graphics);
651
+ for (const image of images) GdipDisposeImage(image);
652
+ SelectObject(memory, previous);
653
+ DeleteObject(dib);
654
+ DeleteDC(memory);
655
+ ReleaseDC(null, screen);
656
+ }
657
+ }
658
+ const COMMANDS = {
659
+ ping: () => ({ version: "koffi-spike" }),
660
+ displays,
661
+ cursor,
662
+ move: (args) => {
663
+ move(int(args, "x", 0), int(args, "y", 0));
664
+ return null;
665
+ },
666
+ click,
667
+ keys,
668
+ drag,
669
+ scroll,
670
+ type: typeText,
671
+ foreground,
672
+ windows,
673
+ window_at: windowAt,
674
+ screenshot
675
+ };
676
+ parentPort?.on("message", (message) => {
677
+ try {
678
+ const run = COMMANDS[message.cmd];
679
+ if (!run) throw new Error(`unknown command "${message.cmd}"`);
680
+ parentPort.postMessage({
681
+ id: message.id,
682
+ ok: true,
683
+ result: run(message.args) ?? null
684
+ });
685
+ } catch (error) {
686
+ parentPort.postMessage({
687
+ id: message.id,
688
+ ok: false,
689
+ error: error instanceof Error ? error.message : String(error)
690
+ });
691
+ }
692
+ });
693
+ parentPort?.postMessage({ event: "ready" });
694
+ //#endregion
695
+ export {};
@@ -24,6 +24,8 @@ export interface Settings {
24
24
  typingMode: TypingMode;
25
25
  /** Run the model at its lowest reasoning effort for the requests in the middle of operating the computer. */
26
26
  quickSteps: boolean;
27
+ /** Run screenshots, display / window queries and idle input in-process through DSH's koffi instead of the C# helper. */
28
+ nativeHelper: boolean;
27
29
  }
28
30
  export type TypingMode = 'stream' | 'type' | 'paste';
29
31
  export interface WindowInfo extends WindowLike {
@@ -12,6 +12,8 @@ export declare function helperAssetPath(name: string): string;
12
12
  export declare function helperSourcePath(): string;
13
13
  /** Compile the helper if this source version has no cached exe yet; returns the exe path. */
14
14
  export declare function ensureHelperExe(source?: string): Promise<string>;
15
+ /** For the smoke script: run the helper inside powershell.exe from the start. */
16
+ export declare function useHostedHelper(on?: boolean): void;
15
17
  export declare class HelperClient implements HelperLike {
16
18
  private readonly log;
17
19
  private child;
@@ -27,5 +29,6 @@ export declare class HelperClient implements HelperLike {
27
29
  private kill;
28
30
  private ensure;
29
31
  private start;
32
+ private launch;
30
33
  private handle;
31
34
  }
@@ -24,6 +24,7 @@ export interface Config {
24
24
  userIdleMs?: number;
25
25
  typingMode?: TypingMode;
26
26
  quickSteps?: boolean;
27
+ nativeHelper?: boolean;
27
28
  }
28
29
  export declare const Config: z<Config>;
29
30
  export declare function apply(ctx: Context, config?: Config): void;
@@ -0,0 +1,2 @@
1
+ export declare function koffiCandidates(env?: NodeJS.ProcessEnv, script?: string | undefined): string[];
2
+ export declare function findKoffi(env?: NodeJS.ProcessEnv): string | undefined;
@@ -0,0 +1,31 @@
1
+ import type { HelperEvent, HelperLike } from '../helper-client.js';
2
+ export declare class NativeHelper implements HelperLike {
3
+ private readonly fallback;
4
+ private readonly log;
5
+ /** The nativeHelper setting, read on every call. */
6
+ private readonly enabled;
7
+ /** null: no koffi.node, every command goes to the C# helper. */
8
+ private readonly koffiPath;
9
+ private worker;
10
+ private ready;
11
+ private readonly pending;
12
+ private nextId;
13
+ private broken;
14
+ private overlay;
15
+ private readonly cards;
16
+ constructor(fallback: HelperLike, log?: (message: string) => void,
17
+ /** The nativeHelper setting, read on every call. */
18
+ enabled?: () => boolean,
19
+ /** null: no koffi.node, every command goes to the C# helper. */
20
+ koffiPath?: string | null);
21
+ get available(): boolean;
22
+ /** Whether a command would run through koffi right now. */
23
+ routesNative(cmd: string): boolean;
24
+ call<T = unknown>(cmd: string, args?: Record<string, unknown>, timeoutMs?: number): Promise<T>;
25
+ onEvent(listener: (event: HelperEvent) => void): () => void;
26
+ dispose(): void;
27
+ /** Follow what the C# helper shows: count it as shown from the request on, hidden once it is done. */
28
+ private shows;
29
+ private hides;
30
+ private ensure;
31
+ }
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@copylee/dsh-computer-use",
3
- "version": "0.7.6",
3
+ "version": "0.8.0",
4
4
  "description": "DeepSeek Harness Computer Use 插件(Windows):让 AI 看屏幕、点鼠标、敲键盘操控电脑;控制时屏幕泛起橙色光晕并显示“DeepSeek Harness 正在操控你的电脑”,按 Esc 暂停 / 继续。",
5
5
  "type": "module",
6
6
  "author": "copylee",
@@ -27,9 +27,11 @@
27
27
  },
28
28
  "files": [
29
29
  "lib/index.js",
30
+ "lib/native-worker.js",
30
31
  "lib/client.js",
31
32
  "lib/types/**/*.d.ts",
32
33
  "helper/CuHelper.cs",
34
+ "helper/host.ps1",
33
35
  "helper/deepseek-white.png",
34
36
  "helper/deepseek-black.png",
35
37
  "helper/skills/*.md",
@@ -111,6 +113,7 @@
111
113
  "@deepseek-ai/schemastery": "3.18.4",
112
114
  "@types/node": "^22.20.0",
113
115
  "@types/react": "~18.3.31",
116
+ "koffi": "3.1.1",
114
117
  "react": "^18.3.1",
115
118
  "tsdown": "^0.22.2",
116
119
  "typescript": "^6.0.3",