dsh-foxy-game 0.0.0-stage → 0.1.30

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kun-Fox
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # dsh-foxy-game
2
+
3
+ 让 Foxy 陪你玩游戏。不是“让模型看一张截图然后祈祷它能操作”,而是把**感知、决策、操作、交流**拆成可替换的适配器,先跑通一个可控的小闭环,再逐个游戏加适配。
4
+
5
+ > 当前是 `0.1.29` 开发预览版。默认关闭所有自动操作;不会主动碰带反作弊的网游。
6
+
7
+ ### 开发进度(2026-11-25 05:00)
8
+
9
+ - 新增“屏幕陪伴”:只截图、看画面、和 Foxy 聊天,不执行键鼠动作;按 `watchIntervalMs` 定时观察,画面没变化时跳过,避免连续烧 token。
10
+ - 新增 GPT-SoVITS TTS:`ttsProvider:'gpt-sovits'`,直接 POST 本地 `api_v2.py` 的 `/tts`,播放返回的 WAV;失败可按 `ttsFallback` 回退 DSH Speech 或 Windows SAPI。实测用 Foxy e14 GPT + e8 SoVITS 返回 197,164 B 并成功播放。
11
+
12
+ - 已跑通 DSH 侧栏、窗口枚举、窗口截图、SHA-256 跳帧、视觉模型 JSON 决策、后台动作接口、自测游戏 HTTP 闭环。
13
+ - 变化区域裁剪(实验,默认关闭):ffmpeg 对比上一帧,只把变化块送视觉模型;原生测试窗实测 440×300(5.4 KB)→ 112×104(1.5 KB),鼠标坐标会按裁剪区域自动映射回整窗。
14
+ - 浏览器/Edge 游戏截图已验证:对 Edge 里的 7×7 测试游戏 `PrintWindow` 得到 900×548 JPEG(约 27.8 KB),画面内容完整,不是黑屏。
15
+ - 浏览器游戏代理动作已验证:截图 → mock 视觉返回 `D` → 通过自测游戏 HTTP 桥执行,玩家从 (0,0) 走到 (1,0);说明“浏览器画面 + 外部状态/动作桥”是可行的,绕开了 Edge 忽略后台键鼠消息的问题。
16
+ - 混合感知已验证:Edge 小花园截图 + 自测游戏 HTTP 状态一起送视觉模型,prompt 同时包含 900×726 JPEG 与 `grid/player/steps` 结构化状态;模型返回 `D` 后玩家从 (0,0) 走到 (1,0)。
17
+ - `npm test`:19/19 通过(设置/脱敏/裁剪参数/键位/视觉解析/策略/自测游戏/memory/插件路由/坐标映射/人设/对话/静音门限/麦克风解析/显式清空 Key/内存写入默认拦截)。
18
+ - 真实 DSH `foxy-test` profile:已并入 Foxy 统一控制台的「游戏」标签页,`/api/dsh-foxy-game/status` 返回 200。
19
+ - 真实窗口截图:`captureWindow` 对系统设置窗口返回 640×379 JPEG(约 15 KB);mock 视觉接口收到图片并返回决策。`0.1.12` 起可选 `auto`/`printwindow`/`screen`:`auto` 在 PrintWindow 返回全黑时自动改用屏幕区域,系统设置窗口实测 `printwindow` 14,981 B、`screen` 14,333 B;全黑测试窗 `auto` 正确回退到 `screen`。
20
+ - 自测游戏 memory 闭环:观察 → BFS 决策 → HTTP 动作 → 状态更新,已验证。
21
+ - 进程内存(实验):`scripts/memory.ps1` 支持按 PID/进程名、模块基址+偏移或绝对地址读取 `int32/uint32/int64/float/double`,并支持逗号分隔的指针链偏移;用测试进程验证“基址→指针→+0x10”读到 `424242`。写入默认关闭,必须手动勾选 `memoryWriteEnabled` 并点“写入”,只写当前地址;已在测试进程验证 `424242 → 777`,再读回 `777`,没有自动扫描或反作弊绕过。按进程名匹配到多个 PID 时现在会直接报错并列出 PID,避免误写同名进程。写入是“直接改当前地址”,如果把指针本身写坏,游戏会崩溃;务必先读确认地址和类型,再手动写入。
22
+ - 悬浮字幕可独立于语音运行:即使 `voiceEnabled:false`,只要 `overlayEnabled:true`,视觉模型的 `say` 也会显示在置顶字幕里,不强制开麦。已实测 overlay 进程启动、无热键进程。
23
+ - 自动循环:能启动、按截图间隔跳帧、停止;画面未变化时只记 `skip` 日志。
24
+ - `F12` 全局紧急停止:已用 `keybd_event` 注入 F12 实测,能写入停止标志;启动时自动拉起隐藏热键进程,停止时清理。
25
+ - 语音录音停止改为给 ffmpeg 发 `q` 正常收尾,避免直接 kill 留下损坏 WAV;真实麦克风录音仍待验证。
26
+ - 麦克风设备改为从 `ffmpeg -list_devices` 枚举,UI 下拉选择;本机实测列出 UGREEN、Steam Streaming、VoiceMeeter、AMD 阵列、MEGATRON 五个音频输入,避免手填 dshow 名称。
27
+ - 角色预设接入:UI 可从 `~/.dsh/foxy/presets` 选择 `personaPresetId`,视觉决策与按住说话的回复都会读取该 YAML 的 `persona` 块;实际读取 `foxy3` 得到 3,966 字人设,视觉提示仍以“只输出 JSON”收尾。
28
+ - 语音对话上下文:按住说话的回复会带上当前游戏窗口标题、上一轮画面分析、最近 8 轮对话,避免 Foxy 每句话都从零开始;回复仍限制两句话并走字幕/TTS。
29
+ - PTT 静音门限:录音结束后先用 ffmpeg `volumedetect` 测平均音量,低于 `pttMinVolumeDb`(默认 -45 dB)直接丢弃,避免把环境噪声转成“嗯”。用 1 秒虚拟麦克风录音(31,662 B,-91 dB)和 SAPI 语音 WAV(-26.3 dB)验证了门限两侧。
30
+ - PTT 空录音保护:注入 F8 短暂按下 120 ms 时 ffmpeg 会留下 0 字节 WAV;现在录制时长 <250 ms 或文件 <1 KB 直接跳过,不再把 EOFError 抛到 STT。实测 120 ms 快速按一下不报错、不转写;按住 1.5 秒虚拟静音被 -91 dB 门限丢弃。
31
+ - 文字对 Foxy 说:新增 `POST /api/dsh-foxy-game/say`,走与 PTT 相同的 `onVoiceTranscript` 流程(人设、当前窗口、上一轮画面、最近对话),并新增 `ttsProvider:'none'`(仅字幕)。用 mock LLM 实测返回「我在,先往右走,别撞墙。」,日志同时出现 voice/say 两条,且没有触发 SAPI。
32
+ - 语音独立启动:以前只有开始自动循环才启动 F8/字幕;现在保存设置时只要 `voiceEnabled` 或 `overlayEnabled` 为真就会启动,插件加载时也会恢复。实测 `running:false`、`voiceEnabled:true` 时 `voice.running:true`,不必先开自动操作。`overlayEnabled` 默认改为 false。测试 19/19。
33
+ - 文字对 Foxy 说 UI:在“语音与悬浮字幕”里直接输入文字发送,回复显示在输入框下方,同时写入实时日志。无 API Key 时会返回“我听到了:…”,用于验证上下文/UI 链路;实际模型回复需要填视觉 API Key。
34
+ - 游戏插件自己的 STT 链路已用 16 kHz 单声道 WAV 验证:`GameVoice.transcribe()` → `scripts/stt.py` → SenseVoice 输出 `你好,我是foxy。今天我们一起打游戏吧。`。这不是麦克风实录,PTT 录音仍需真实按键验证。
35
+ - 后台输入:`SendMessage` 对原生 WinForms 测试窗实测成功(`D` 使玩家 x+1),且不抢前台;后台鼠标也实测成功:`0.5,0.5` 点击被窗口记录为 `click:212,130`、`clicks:1`。Edge 会忽略合成消息,真实游戏兼容性必须逐个测。
36
+ - 完整屏幕闭环:原生 WinForms 测试窗 `hwnd 122882056` 截图 640×436(8.5 KB)→ mock 视觉返回 `{type:'key',key:'d'}` → 后台 `SendMessage`,玩家 x 从 0 变为 1,前台未切换。
37
+ - TTS 真实调用:`GameVoice.speak('测试语音。', { ttsProvider: 'sapi', overlayEnabled: false })` 返回 `{ok:true,provider:'sapi'}`,耗时约 2.5 秒;这是 SAPI 播放路径,不是虚拟麦克风。
38
+
39
+ ## 设计原则
40
+
41
+ 1. **先适配,再通用**:屏幕、内存、游戏 API 都只是“观测源”;键鼠、后台消息、内存写入都只是“动作端”。
42
+ 2. **默认低成本**:截图先做窗口裁剪、缩放、JPEG 压缩,再按哈希跳帧;不是每帧都发给视觉模型。
43
+ 3. **默认不抢前台**:优先后台 `SendMessage`(同步调用,可能被不处理消息的游戏卡住),前台 `SendInput` 作为兼容回退;MAA 的 `AnchoredTouch` 说明“合成输入不移动真实光标”是可行的,但需要游戏窗口支持。
44
+ 4. **语音是本地回路**:按住快捷键说话 → 本地 STT → 模型 → 悬浮字幕 + TTS;不依赖游戏内聊天框。
45
+ 5. **危险能力显式开启**:读内存、写内存、自动点击都默认关闭,并在 UI 里单独警告。
46
+
47
+ ## 三条感知路线
48
+
49
+ | 模式 | 原理 | 适合 | 风险/限制 |
50
+ | --- | --- | --- | --- |
51
+ | `screen` | 窗口截图 → 视觉模型 → 动作 | 解密、视觉小说、回合制、慢节奏策略 | 延迟高、token 贵、精确坐标难 |
52
+ | `memory` | 读游戏进程/游戏 API 的结构化状态 | 本地小游戏、模拟器、带 API 的游戏 | 需要偏移/结构;反作弊风险;版本一变就坏 |
53
+ | `hybrid` | 内存给数值,屏幕给空间/文字 | 大多数可组合场景 | 两套适配器都要维护 |
54
+
55
+ 当前版本实现了 `screen`、`hybrid` 和 `memory` 的骨架;`memory` 支持受控 HTTP 状态源(自测游戏)和进程内存(PID/进程名 + 模块偏移/绝对地址 + 数值类型 + 指针链)。读取默认可用;写入必须手动打开 `memoryWriteEnabled`,只写当前地址,**没有**自动偏移扫描或反作弊绕过。
56
+
57
+ ## 已实现(开发预览)
58
+
59
+ > `0.1.28` 起不再单独占用左侧栏;入口在 **Foxy → 游戏**。
60
+
61
+ - Foxy 控制台「游戏」标签页:窗口选择、截图间隔、跳帧、视觉模型配置、动作模式、自动循环开关、实时日志。
62
+ - `capture.ps1`:枚举窗口,`PrintWindow`/屏幕回退截图,缩放 + JPEG,返回 base64;Node 侧做 SHA-256 跳帧。
63
+ - 安全:自动循环运行时可用 `F12` 全局紧急停止;默认 `enabled:false`,不会自行启动。
64
+ - `vision.js`:OpenAI 兼容的视觉请求,严格 JSON 输出(`analysis/action/say/confidence`);解析失败会保留原文并报错。
65
+ - `actions.js` + `input.ps1`:键盘按下/抬起/点按、鼠标移动/点击、文本;支持 `background`(SendMessage)和 `foreground`(SendInput)。
66
+ - `test-game/`:一个本地小游戏 + HTTP 状态/动作 API,用来在没有视觉模型时验证“观测→决策→动作→记忆”闭环。
67
+ - 语音/悬浮字幕:`voice.js`、`overlay.ps1`、`hotkey.ps1` 的本地回路骨架(默认关闭,需要麦克风设备名)。悬浮字幕已实测:原生长文本会自动扩高到 760×208,并保持置顶。
68
+ - `scripts/stt.py`:本地 SenseVoice 转写后备;TTS 优先 DSH Speech,回退 Windows SAPI。
69
+
70
+ ## 调研结论
71
+
72
+ - **Neuro-sama** 不是纯屏幕 AI:游戏通过 [Neuro API](https://github.com/o9nn/neuro-sama) 这类游戏侧 SDK 暴露状态/动作,AI 与语音是独立管线。结论:能给游戏加 API 时,API 永远优于截图。
73
+ - **ARC-AGI 多模态 Agent** 常用“每步截图 → 视觉模型分析 → 动作 → 累计规则/历史”,但会把图缩到很小(如 128×128)来控制成本。结论:全量每帧视觉不可持续,必须跳帧 + 变化检测 + 结构化缓存。
74
+ - **MAA Win32** 的输入分层:`Seize`(SendInput,兼容性最好但抢鼠标)、`Message/Post`(后台消息,部分游戏屏蔽)、`AnchoredTouch`(`InjectSyntheticPointerInput`,不移动真实光标/不切前台,MaaFramework v5.13.0)。参考 [MAA Win32 控制器](https://deepwiki.com/MaaXYZ/MaaFramework/4.2-win32)、[MAA PR #18341](https://github.com/MaaAssistantArknights/MaaAssistantArknights/pull/18341)。结论:默认后台,失败再回退前台;不要默认抢鼠标。
75
+ - **LLM 游戏 Agent** 的共同点是“观察→行动→结果→短期记忆”的循环,而不是一次性长提示。参考 [Human Strategy Meets AI Execution](https://dl.acm.org/doi/pdf/10.1145/3715014.3724375)。
76
+
77
+ ## 快速开始
78
+
79
+ ```powershell
80
+ # 在 DSH 工作区
81
+ cd D:\Documents\deepseek-harness\default-workspace\dsh-foxy-game
82
+ npm test
83
+
84
+ # 启动自测游戏(另一个终端)
85
+ npm run test-game
86
+ # 浏览器打开 http://127.0.0.1:8787
87
+
88
+ # 或者启动原生 WinForms 测试窗,专门测后台输入
89
+ powershell -ExecutionPolicy Bypass -File test-game/win.ps1
90
+ # 状态文件:%TEMP%\foxy-win-game.json
91
+ ```
92
+
93
+ 安装到 DSH(开发时):
94
+
95
+ ```powershell
96
+ dsh plugin --profile desktop add file:D:\Documents\deepseek-harness\default-workspace\dsh-foxy-game
97
+ ```
98
+
99
+ 然后在侧栏打开 `Foxy Game`:
100
+
101
+ 1. 点“刷新窗口”,选择游戏窗口;
102
+ 2. 配置视觉模型(OpenAI 兼容 `/chat/completions`,模型必须支持图片输入);
103
+ 3. 先点“观察一次”,看日志里的分析/动作;
104
+ 4. 确认动作模式(建议先 `background`)再开“自动循环”。
105
+
106
+ ## 配置
107
+
108
+ 设置保存在 `~/.dsh/foxy-game/settings.json`。关键字段:
109
+
110
+ ```jsonc
111
+ {
112
+ "enabled": false,
113
+ "mode": "screen", // screen | hybrid | memory
114
+ "windowHwnd": 0,
115
+ "windowTitle": "",
116
+ "captureIntervalMs": 1500,
117
+ "skipUnchanged": true,
118
+ "maxWidth": 1280,
119
+ "jpegQuality": 65,
120
+ "visionBaseUrl": "https://api.deepseek.com",
121
+ "visionApiKey": "",
122
+ "visionModel": "deepseek-chat",
123
+ "actionMode": "background", // background | foreground | none
124
+ "autoPlay": false,
125
+ "maxStepsPerMinute": 20,
126
+ "memorySource": "none", // none | test-http | process
127
+ "memoryUrl": "http://127.0.0.1:8787",
128
+ "memoryProcess": "",
129
+ "memoryPid": 0,
130
+ "memoryModule": "",
131
+ "memoryAddress": "",
132
+ "memoryOffset": "",
133
+ "memoryPointerOffsets": "", // 逗号分隔,如 0x10,0x20
134
+ "memoryType": "int32", // int32 | uint32 | int64 | float | double
135
+ "voiceEnabled": false,
136
+ "pttKey": "F8",
137
+ "micDevice": "",
138
+ "ttsProvider": "sapi", // sapi | dsh
139
+ "overlayEnabled": true
140
+ }
141
+ ```
142
+
143
+ ## 目录
144
+
145
+ ```
146
+ lib/ DSH 服务端插件、截图、视觉、动作、语音
147
+ scripts/ PowerShell 窗口/截图/输入/悬浮窗/热键,Python STT
148
+ test-game/ 本地自测游戏 + HTTP API
149
+ test/ Node 内置测试
150
+ ```
151
+
152
+ ## 已知问题 / 下一步
153
+
154
+ - [ ] 真实游戏窗口的 `PrintWindow` 在部分 DirectX 游戏返回黑屏;`captureMethod:'screen'` 已能按窗口矩形截桌面,适合无边框/窗口化 DirectX,但独占全屏仍需要 `Windows.Graphics.Capture` 或 `ffmpeg gdigrab`。Edge/Chromium 内容实测可截,但不是所有 GPU 加速窗口都行。
155
+ - [ ] 后台合成消息在 Edge 窗口实测无效(浏览器忽略);原生 WinForms 测试窗用 `SendMessage` 已通过。真实游戏是否接受需逐个验证,不接受时只能回退前台 `SendInput` 或做 `AnchoredTouch`。
156
+ - [x] 变化区域裁剪(实验,默认关闭):ffmpeg diff 找 bbox,裁剪后只送变化块;鼠标坐标自动映射回整窗。只裁剪会丢失画面上下文,复杂游戏建议关闭或配合完整帧使用。
157
+ - [ ] 视觉模型的动作坐标是归一化坐标,未做窗口 DPI 校正;高 DPI 需要实测。
158
+ - [ ] 内存适配器目前支持单值读取(绝对地址或模块基址+偏移,可带指针链);写入需手动开启并填值,没有结构体/数组读取、自动扫描或反作弊绕过。
159
+ - [x] 悬浮字幕已单独验证;按住说话热键已用 `keybd_event` 注入 F8 验证(按下写入 `ptt.down`、松开删除)。
160
+ - [x] Windows SAPI 播报已用 `speak.ps1` 实测退出码 0。
161
+ - [ ] 麦克风录音/STT 还需要真实麦克风端到端验证,当前默认关闭。
162
+ - [x] 自动循环支持 `F12` 全局紧急停止(`scripts/stop-hotkey.ps1`);默认仍不自动启动。
163
+ - [ ] 没有做反作弊检测/规避;这是有意为之,不提供绕过能力。
164
+
165
+ ## License
166
+
167
+ MIT
168
+
2
169
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,21 @@
1
+ # dsh-foxy-game bundle patch.
2
+ # Install with:
3
+ # dsh plugin --profile desktop add file:D:\...\dsh-foxy-game
4
+ #
5
+ # Runtime settings are written to ~/.dsh/foxy-game/settings.json by the
6
+ # sidebar. These values are only first-run defaults.
7
+ - insert:
8
+ - id: foxy-game
9
+ name: dsh-foxy-game
10
+ config:
11
+ enabled: false
12
+ mode: screen
13
+ windowHwnd: 0
14
+ captureIntervalMs: 1500
15
+ skipUnchanged: true
16
+ maxWidth: 1280
17
+ jpegQuality: 65
18
+ actionMode: background
19
+ autoPlay: false
20
+ voiceEnabled: false
21
+ overlayEnabled: true
package/lib/actions.js ADDED
@@ -0,0 +1,94 @@
1
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { mapRegionPoint, runPowerShell } from './capture.js'
5
+
6
+ const VK = {
7
+ backspace: 8, tab: 9, enter: 13, return: 13, shift: 16, ctrl: 17, control: 17, alt: 18,
8
+ pause: 19, capslock: 20, escape: 27, esc: 27, space: 32, pageup: 33, pagedown: 34,
9
+ end: 35, home: 36, left: 37, up: 38, right: 39, down: 40, insert: 45, delete: 46,
10
+ '0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57,
11
+ a: 65, b: 66, c: 67, d: 68, e: 69, f: 70, g: 71, h: 72, i: 73, j: 74, k: 75, l: 76, m: 77,
12
+ n: 78, o: 79, p: 80, q: 81, r: 82, s: 83, t: 84, u: 85, v: 86, w: 87, x: 88, y: 89, z: 90,
13
+ f1: 112, f2: 113, f3: 114, f4: 115, f5: 116, f6: 117, f7: 118, f8: 119, f9: 120, f10: 121, f11: 122, f12: 123,
14
+ }
15
+
16
+ export function keyToVk(key) {
17
+ const text = String(key || '').trim()
18
+ if (!text) throw new Error('key is empty')
19
+ const lower = text.toLowerCase()
20
+ if (VK[lower] !== undefined) return VK[lower]
21
+ if (/^[a-z]$/i.test(text)) return text.toUpperCase().charCodeAt(0)
22
+ if (/^[0-9]$/.test(text)) return text.charCodeAt(0)
23
+ throw new Error(`unsupported key: ${text}`)
24
+ }
25
+
26
+ export function normalizeAction(input) {
27
+ if (!input || typeof input !== 'object') return { type: 'none' }
28
+ const type = String(input.type || '').toLowerCase()
29
+ if (type === 'none' || type === 'wait') {
30
+ return { type: 'wait', ms: Math.min(5000, Math.max(0, Number(input.ms) || 0)) }
31
+ }
32
+ if (type === 'key') {
33
+ const action = ['press', 'down', 'up'].includes(input.action) ? input.action : 'press'
34
+ const modifiers = Array.isArray(input.modifiers)
35
+ ? input.modifiers.slice(0, 4).map(keyToVk)
36
+ : []
37
+ return {
38
+ type: 'key',
39
+ vk: keyToVk(input.key),
40
+ key: String(input.key),
41
+ action,
42
+ durationMs: Math.min(3000, Math.max(20, Number(input.durationMs) || 80)),
43
+ modifiers,
44
+ }
45
+ }
46
+ if (type === 'mouse') {
47
+ const x = Math.min(1, Math.max(0, Number(input.x)))
48
+ const y = Math.min(1, Math.max(0, Number(input.y)))
49
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('mouse x/y must be numbers')
50
+ return {
51
+ type: 'mouse',
52
+ x,
53
+ y,
54
+ button: ['left', 'right', 'middle'].includes(input.button) ? input.button : 'left',
55
+ action: ['click', 'down', 'up', 'move'].includes(input.action) ? input.action : 'click',
56
+ }
57
+ }
58
+ if (type === 'text') {
59
+ const text = String(input.text || '').slice(0, 500)
60
+ if (!text) return { type: 'none' }
61
+ return { type: 'text', text }
62
+ }
63
+ throw new Error(`unsupported action type: ${type}`)
64
+ }
65
+
66
+ export async function executeAction(settings, input, { hwnd, mode, region } = {}) {
67
+ const actionMode = mode || settings.actionMode || 'background'
68
+ if (actionMode === 'none') return { ok: true, skipped: true, reason: 'actionMode=none' }
69
+ const action = normalizeAction(input)
70
+ if (action.type === 'none') return { ok: true, skipped: true }
71
+ if (action.type === 'wait') {
72
+ await new Promise((resolve) => setTimeout(resolve, action.ms))
73
+ return { ok: true, action }
74
+ }
75
+ if (action.type === 'mouse' && region) {
76
+ const mapped = mapRegionPoint(region, action.x, action.y)
77
+ action.x = mapped.x
78
+ action.y = mapped.y
79
+ }
80
+ const target = Number(hwnd || settings.windowHwnd) || 0
81
+ if (!target && actionMode === 'background') throw new Error('background input needs a selected window handle')
82
+ if (action.type === 'text' && actionMode !== 'background') throw new Error('text input requires background mode')
83
+ const dir = await mkdtemp(join(tmpdir(), 'foxy-game-'))
84
+ const file = join(dir, 'action.json')
85
+ try {
86
+ await writeFile(file, JSON.stringify(action), 'utf8')
87
+ await runPowerShell('input.ps1', ['-JsonPath', file, '-Hwnd', String(target), '-Mode', actionMode], { timeoutMs: 15000 })
88
+ return { ok: true, action }
89
+ } finally {
90
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
91
+ }
92
+ }
93
+
94
+ export const internals = { VK }
package/lib/capture.js ADDED
@@ -0,0 +1,224 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { execFile } from 'node:child_process'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { dirname, join } from 'node:path'
5
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
6
+ import { tmpdir } from 'node:os'
7
+ import { promisify } from 'node:util'
8
+ import { parseRegion } from './settings.js'
9
+
10
+ const execFileAsync = promisify(execFile)
11
+ const here = dirname(fileURLToPath(import.meta.url))
12
+ const scripts = join(here, '..', 'scripts')
13
+ const DEFAULT_FFMPEG = 'F:\\kunfox\\ffmpeg-8.1.2-essentials_build\\bin\\ffmpeg.exe'
14
+
15
+ let lastHash = ''
16
+
17
+ export function scriptsDir() {
18
+ return scripts
19
+ }
20
+
21
+ function parseJsonOutput(stdout) {
22
+ const text = String(stdout || '').trim()
23
+ try {
24
+ return JSON.parse(text)
25
+ } catch {}
26
+ const line = text.split(/\r?\n/).reverse().find((entry) => {
27
+ const trimmed = entry.trim()
28
+ return trimmed.startsWith('{') || trimmed.startsWith('[')
29
+ })
30
+ if (!line) throw new Error(`PowerShell returned no JSON: ${text.slice(-400)}`)
31
+ return JSON.parse(line)
32
+ }
33
+
34
+ export async function runPowerShell(script, args = [], { timeoutMs = 30000 } = {}) {
35
+ const path = join(scripts, script)
36
+ const { stdout, stderr } = await execFileAsync(
37
+ 'powershell.exe',
38
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', path, ...args],
39
+ { timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, windowsHide: true },
40
+ )
41
+ if (stderr?.trim()) {
42
+ // PowerShell writes non-fatal Add-Type chatter to stderr on some hosts.
43
+ const meaningful = stderr.trim().split(/\r?\n/).filter((line) => !/^CategoryInfo|^FullyQualifiedErrorId|^\+/.test(line))
44
+ if (meaningful.length && !stdout?.trim()) throw new Error(meaningful.join('\n'))
45
+ }
46
+ return stdout
47
+ }
48
+
49
+ export async function listWindows() {
50
+ const stdout = await runPowerShell('windows.ps1', [], { timeoutMs: 20000 })
51
+ const parsed = parseJsonOutput(stdout)
52
+ const list = Array.isArray(parsed) ? parsed : parsed ? [parsed] : []
53
+ return list.filter((item) => item && item.hwnd && item.width > 0 && item.height > 0)
54
+ }
55
+
56
+ export function ffmpegPath(settings = {}) {
57
+ return String(settings.ffmpegPath || process.env.FFMPEG_PATH || '').trim() || DEFAULT_FFMPEG
58
+ }
59
+
60
+ function parseBBox(stderr) {
61
+ const text = String(stderr || '')
62
+ const match = text.match(/x1:(\d+)\s+x2:(\d+)\s+y1:(\d+)\s+y2:(\d+)\s+w:(\d+)\s+h:(\d+)/)
63
+ if (!match) return null
64
+ const [, x1, x2, y1, y2, w, h] = match.map(Number)
65
+ if (![x1, x2, y1, y2, w, h].every(Number.isFinite)) return null
66
+ return { x: x1, y: y1, w, h, x2, y2 }
67
+ }
68
+
69
+ async function runFfmpeg(settings, args, timeoutMs = 20000) {
70
+ const { stderr } = await execFileAsync(ffmpegPath(settings), ['-hide_banner', '-loglevel', 'info', ...args], {
71
+ timeout: timeoutMs,
72
+ maxBuffer: 16 * 1024 * 1024,
73
+ windowsHide: true,
74
+ })
75
+ return stderr
76
+ }
77
+
78
+ export async function diffBBox(settings, previousPath, currentBuffer) {
79
+ const dir = await mkdtemp(join(tmpdir(), 'foxy-diff-'))
80
+ const currentPath = join(dir, 'current.jpg')
81
+ try {
82
+ await writeFile(currentPath, currentBuffer)
83
+ const stderr = await runFfmpeg(settings, [
84
+ '-i', previousPath,
85
+ '-i', currentPath,
86
+ '-filter_complex', '[0:v][1:v]blend=all_mode=difference,bbox',
87
+ '-f', 'null',
88
+ '-',
89
+ ])
90
+ return parseBBox(stderr)
91
+ } finally {
92
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
93
+ }
94
+ }
95
+
96
+ export async function cropJpeg(settings, buffer, box, quality = 65) {
97
+ const dir = await mkdtemp(join(tmpdir(), 'foxy-crop-'))
98
+ const inPath = join(dir, 'in.jpg')
99
+ const outPath = join(dir, 'out.jpg')
100
+ try {
101
+ await writeFile(inPath, buffer)
102
+ const q = String(Math.max(2, Math.min(31, Math.round(31 - (Number(quality) || 65) / 3.2))))
103
+ await runFfmpeg(settings, [
104
+ '-i', inPath,
105
+ '-vf', `crop=${box.w}:${box.h}:${box.x}:${box.y}`,
106
+ '-q:v', q,
107
+ '-y', outPath,
108
+ ])
109
+ return await readFile(outPath)
110
+ } finally {
111
+ await rm(dir, { recursive: true, force: true }).catch(() => {})
112
+ }
113
+ }
114
+
115
+ export function padBox(box, totalWidth, totalHeight, padding = 24) {
116
+ if (!box) return null
117
+ const x = Math.max(0, box.x - padding)
118
+ const y = Math.max(0, box.y - padding)
119
+ const right = Math.min(totalWidth, box.x + box.w + padding)
120
+ const bottom = Math.min(totalHeight, box.y + box.h + padding)
121
+ return {
122
+ x,
123
+ y,
124
+ w: Math.max(2, right - x),
125
+ h: Math.max(2, bottom - y),
126
+ }
127
+ }
128
+
129
+ export async function captureWindow(settings = {}, { force = false, previousPath = '' } = {}) {
130
+ const hwnd = Number(settings.windowHwnd) || 0
131
+ const region = parseRegion(settings.captureRegion)
132
+ const args = [
133
+ '-Hwnd', String(hwnd),
134
+ '-MaxWidth', String(Number(settings.maxWidth) || 1280),
135
+ '-Quality', String(Number(settings.jpegQuality) || 65),
136
+ '-Format', 'jpeg',
137
+ '-Method', String(settings.captureMethod || 'auto'),
138
+ ]
139
+ if (region) args.push('-Region', `${region.x},${region.y},${region.w},${region.h}`)
140
+ const stdout = await runPowerShell('capture.ps1', args, { timeoutMs: 20000 })
141
+ const parsed = parseJsonOutput(stdout)
142
+ if (!parsed?.ok || !parsed.base64) throw new Error(parsed?.error || 'capture failed')
143
+ const full = Buffer.from(parsed.base64, 'base64')
144
+ const hash = createHash('sha256').update(parsed.base64).digest('hex')
145
+ const changed = hash !== lastHash
146
+ if (settings.skipUnchanged !== false && !force && !changed) {
147
+ return {
148
+ ok: true,
149
+ changed: false,
150
+ skipped: true,
151
+ hash,
152
+ width: parsed.width,
153
+ height: parsed.height,
154
+ bytes: parsed.bytes,
155
+ mime: `image/${parsed.format || 'jpeg'}`,
156
+ captureMethod: parsed.method || '',
157
+ }
158
+ }
159
+ lastHash = hash
160
+
161
+ let output = full
162
+ let width = Number(parsed.width) || 0
163
+ let height = Number(parsed.height) || 0
164
+ let crop = null
165
+ if (previousPath && settings.cropChanges && !region) {
166
+ const previous = await readFile(previousPath).catch(() => null)
167
+ if (previous) {
168
+ try {
169
+ const rawBox = await diffBBox(settings, previousPath, full)
170
+ const box = padBox(rawBox, width, height, Number(settings.changePadding) || 24)
171
+ const ratio = box ? (box.w * box.h) / Math.max(1, width * height) : 1
172
+ if (box && ratio >= 0.002 && ratio <= 0.92) {
173
+ output = await cropJpeg(settings, full, box, settings.jpegQuality)
174
+ width = box.w
175
+ height = box.h
176
+ crop = {
177
+ x: box.x,
178
+ y: box.y,
179
+ w: box.w,
180
+ h: box.h,
181
+ totalWidth: Number(parsed.width) || width,
182
+ totalHeight: Number(parsed.height) || height,
183
+ }
184
+ }
185
+ } catch {
186
+ // Diff/crop is an optimization; never turn it into a capture failure.
187
+ }
188
+ }
189
+ await writeFile(previousPath, full).catch(() => {})
190
+ }
191
+
192
+ return {
193
+ ok: true,
194
+ changed: true,
195
+ skipped: false,
196
+ hash,
197
+ width,
198
+ height,
199
+ bytes: output.length,
200
+ format: 'jpeg',
201
+ mime: 'image/jpeg',
202
+ captureMethod: parsed.method || '',
203
+ base64: output.toString('base64'),
204
+ region: crop,
205
+ fullWidth: Number(parsed.width) || width,
206
+ fullHeight: Number(parsed.height) || height,
207
+ }
208
+ }
209
+
210
+ export function resetCaptureCache() {
211
+ lastHash = ''
212
+ }
213
+
214
+ export function mapRegionPoint(region, x, y) {
215
+ if (!region) return { x, y }
216
+ const totalWidth = Number(region.totalWidth) || Number(region.w) || 1
217
+ const totalHeight = Number(region.totalHeight) || Number(region.h) || 1
218
+ return {
219
+ x: Math.min(1, Math.max(0, (Number(region.x) + Number(x) * Number(region.w)) / totalWidth)),
220
+ y: Math.min(1, Math.max(0, (Number(region.y) + Number(y) * Number(region.h)) / totalHeight)),
221
+ }
222
+ }
223
+
224
+ export const internals = { parseJsonOutput, parseBBox }