offscreen-android 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,305 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * vdisplay —— 虚拟屏的 CLI 客户端。
4
+ *
5
+ * 它自己不建屏(那会被进程退出带走),只把命令发给常驻的 vdisplayd。
6
+ * 守护进程没在跑就自动拉起来一个。
7
+ *
8
+ * 这样任何 agent 都能用:Claude Code、opencode、Codex、Cursor,只要能跑 bash:
9
+ *
10
+ * vdisplay start
11
+ * vdisplay launch com.tencent.mm
12
+ * vdisplay shot --out /tmp/wx.jpg
13
+ * vdisplay input tap --nx 0.5 --ny 0.9
14
+ * vdisplay stop
15
+ *
16
+ * 加 --json 输出机器可读的完整结果。
17
+ */
18
+
19
+ import { readFile } from 'node:fs/promises';
20
+ import { spawn } from 'node:child_process';
21
+ import { homedir } from 'node:os';
22
+ import { join, dirname } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ const HERE = dirname(fileURLToPath(import.meta.url));
26
+ const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh');
27
+ const STATE_DIR = join(DSH_HOME, 'plugin-screen');
28
+ const STATE_FILE = join(STATE_DIR, 'cli-daemon.json');
29
+ const DAEMON = join(HERE, 'vdisplayd.mjs');
30
+
31
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
32
+
33
+ /** 把 --key value / --flag / 位置参数解析开。 */
34
+ function parseArgs(argv) {
35
+ const positional = [];
36
+ const flags = {};
37
+ for (let i = 0; i < argv.length; i += 1) {
38
+ const a = argv[i];
39
+ if (a.startsWith('--')) {
40
+ const key = a.slice(2);
41
+ const next = argv[i + 1];
42
+ if (next === undefined || next.startsWith('--')) flags[key] = true;
43
+ else { flags[key] = next; i += 1; }
44
+ } else {
45
+ positional.push(a);
46
+ }
47
+ }
48
+ return { positional, flags };
49
+ }
50
+
51
+ async function readDaemon() {
52
+ try {
53
+ const j = JSON.parse(await readFile(STATE_FILE, 'utf8'));
54
+ return Number(j?.port) > 0 ? j : null;
55
+ } catch { return null; }
56
+ }
57
+
58
+ async function ping(port) {
59
+ try {
60
+ const r = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1500) });
61
+ return r.ok;
62
+ } catch { return false; }
63
+ }
64
+
65
+ async function ensureDaemon() {
66
+ const st = await readDaemon();
67
+ if (st && await ping(st.port)) return st;
68
+
69
+ // 拉起来:detached + stdio ignore,父进程退出它也不死
70
+ const child = spawn(process.execPath, [DAEMON], {
71
+ detached: true,
72
+ stdio: 'ignore',
73
+ env: { ...process.env, DSH_HOME },
74
+ });
75
+ child.unref();
76
+
77
+ for (let i = 0; i < 40; i += 1) {
78
+ await sleep(250);
79
+ const s = await readDaemon();
80
+ if (s && await ping(s.port)) return s;
81
+ }
82
+ throw new Error('守护进程拉不起来。手动跑一下 vdisplayd.mjs 看报什么错。');
83
+ }
84
+
85
+ async function call(action, args = {}) {
86
+ const st = await ensureDaemon();
87
+ const r = await fetch(`http://127.0.0.1:${st.port}/cmd`, {
88
+ method: 'POST',
89
+ headers: { 'Content-Type': 'application/json' },
90
+ body: JSON.stringify({ action, args }),
91
+ signal: AbortSignal.timeout(180_000),
92
+ }).catch((e) => { throw new Error(`连不上守护进程:${e.message}`); });
93
+
94
+ const j = await r.json().catch(() => ({ ok: false, error: '守护进程返回的不是 JSON' }));
95
+ if (!j.ok) throw new Error(j.error || '命令失败');
96
+ return j.result;
97
+ }
98
+
99
+ const USAGE = `vdisplay —— 操作一块用户看不见的虚拟屏
100
+
101
+ 用法:
102
+ vdisplay start [--width 720] [--height 1280] [--dpi 320]
103
+ [--orientation landscape|portrait] [--hwc auto|on|off]
104
+ vdisplay stop [--forceStopApps]
105
+ vdisplay status
106
+ vdisplay launch <包名> [Activity]
107
+ vdisplay shot [--out 路径] [--width 540] [--format jpeg|png]
108
+ [--frames 9] [--interval 300] 九格连拍看运动
109
+ [--rx 0 --ry 1200 --rw 720 --rh 392] 只看一块并放大
110
+ vdisplay text [--minconf 0.45] [--maxlines 80] [--fresh]
111
+ 读屏文字(OCR),带 nx/ny 坐标,0 图片 token
112
+ vdisplay main-shot [--out 路径]
113
+ vdisplay input tap --x 100 --y 200 (或 --nx 0.5 --ny 0.5 归一化)
114
+ vdisplay input swipe --x1 100 --y1 200 --x2 300 --y2 400 [--ms 400]
115
+ vdisplay input text --text "要输入的字"
116
+ vdisplay input key --key KEYCODE_BACK
117
+ vdisplay input paste [--text "要粘的内容"]
118
+ vdisplay daemon stop
119
+
120
+ 通用参数:
121
+ --json 输出完整 JSON,而不是给人看的文本
122
+
123
+ 第一次调用会自动拉起守护进程,它会在闲置 10 分钟且没有虚拟屏时自己退出。
124
+ `;
125
+
126
+ function human(action, r) {
127
+ if (!r || typeof r !== 'object') return String(r ?? '');
128
+ const lines = [];
129
+
130
+ switch (action) {
131
+ case 'start':
132
+ if (r.ok === false) return `建屏失败:${r.hint || '未知原因'}`;
133
+ lines.push(`虚拟屏已就绪:displayId=${r.displayId}`);
134
+ lines.push(`SurfaceFlinger id: ${r.sfId || '(未取到)'}`);
135
+ lines.push(`能托管 App:${r.canHost ? '是' : '否'}`);
136
+ lines.push(`硬件合成(HWC):${r.hwc ? '已开启' : '未开启'}`);
137
+ return lines.join('\n');
138
+
139
+ case 'launch':
140
+ if (!r.displayId) return `投屏失败:${r.hint || '未知原因'}`;
141
+ lines.push(`已投到虚拟屏 display=${r.displayId}`);
142
+ if (r.landedOnVd !== undefined) lines.push(`落在虚拟屏上:${r.landedOnVd ? '是' : '否'}`);
143
+ if (r.hint) lines.push(r.hint);
144
+ return lines.join('\n');
145
+
146
+ case 'text': {
147
+ if (r.ok === false) return `识别失败:${r.hint || '未知原因'}`;
148
+ const pl = [`识别到 ${r.count} 行(${r.cached ? '缓存命中 0ms' : (r.elapsedMs + 'ms')})`];
149
+ const W = r.imageWidth || 720; const H = r.imageHeight || 1600;
150
+ for (const ln of (r.lines || [])) {
151
+ const nx = ((ln.x + ln.w / 2) / W).toFixed(3);
152
+ const ny = ((ln.y + ln.h / 2) / H).toFixed(3);
153
+ pl.push(` [${String(ln.conf).padEnd(4)}] ${ln.text} nx=${nx} ny=${ny}`);
154
+ }
155
+ return pl.join('\n');
156
+ }
157
+ case 'shot':
158
+ case 'mainShot':
159
+ if (r.ok === false || !r.path) return `截图失败:${r.hint || r.error || '未知原因'}`;
160
+ return `截图:${r.path}${r.width ? `(${r.width}px)` : ''}`
161
+ + (r.copyError ? `\n⚠️ ${r.copyError}` : '');
162
+
163
+ case 'status':
164
+ if (!r.running) return '虚拟屏没有在运行。';
165
+ lines.push(`虚拟屏在运行:displayId=${r.displayId}`);
166
+ if (r.focusedApp) lines.push(`上面跑着:${r.focusedApp}`);
167
+ if (r.mainFocus) lines.push(`主屏焦点:${r.mainFocus}`);
168
+ return lines.join('\n');
169
+
170
+ case 'stop':
171
+ lines.push('虚拟屏已销毁。');
172
+ if (r.stillRunning?.length) lines.push(`仍在后台运行:${r.stillRunning.join('、')}`);
173
+ return lines.join('\n');
174
+
175
+ case 'input':
176
+ if (r.ok === false) return `输入失败:${r.hint || r.reason || '未知原因'}`;
177
+ return r.hint || '已执行';
178
+
179
+ default:
180
+ return JSON.stringify(r, null, 2);
181
+ }
182
+ }
183
+
184
+ async function main() {
185
+ const { positional, flags } = parseArgs(process.argv.slice(2));
186
+ const wantJson = flags.json === true;
187
+
188
+ let cmd = positional[0];
189
+ let sub = positional[1];
190
+
191
+ if (!cmd || cmd === 'help' || cmd === '--help') {
192
+ process.stdout.write(USAGE);
193
+ return;
194
+ }
195
+
196
+ if (cmd === 'daemon') {
197
+ if (sub === 'stop') {
198
+ const st = await readDaemon();
199
+ if (!st) { console.error('守护进程没在跑。'); process.exit(1); }
200
+ // 必须断言:state 文件被写坏成负数时,process.kill(-1) 会给**整个进程组**发信号。
201
+ // 之前用 pkill 空模式杀掉用户 Shizuku 是同一种事故。
202
+ if (!Number.isInteger(st.pid) || st.pid <= 1) {
203
+ console.error(`状态文件里的 pid 不合法(${st.pid}),拒绝执行 kill。请删掉 ${STATE_FILE} 再试。`);
204
+ process.exit(1);
205
+ }
206
+ try { process.kill(st.pid, 'SIGTERM'); } catch { /* 已经死了 */ }
207
+ console.log(`已让守护进程(pid ${st.pid})退出。`);
208
+ return;
209
+ }
210
+ const st = await readDaemon();
211
+ const alive = st ? await ping(st.port) : false;
212
+ console.log(alive ? `守护进程在跑:pid ${st.pid},端口 ${st.port}` : '守护进程没在跑。');
213
+ return;
214
+ }
215
+
216
+ let action = cmd;
217
+ let args = {};
218
+
219
+ // 数字参数必须校验。以前 `Number(true)` = 1、`Number('abc')` = NaN,
220
+ // 用户漏写一个值就会静默点错坐标或按默认尺寸建屏,没有任何提示。
221
+ const num = (k) => {
222
+ const v = flags[k];
223
+ if (v === undefined) return undefined;
224
+ if (v === true) { console.error(`参数 --${k} 缺少值。`); process.exit(1); }
225
+ const n = Number(v);
226
+ if (!Number.isFinite(n)) { console.error(`参数 --${k} 不是合法数字:「${v}」。`); process.exit(1); }
227
+ return n;
228
+ };
229
+ const str = (k) => (flags[k] === undefined || flags[k] === true ? undefined : String(flags[k]));
230
+
231
+ if (cmd === 'start') {
232
+ args = {
233
+ width: num('width'), height: num('height'), dpi: num('dpi'),
234
+ orientation: str('orientation'), hwc: str('hwc'),
235
+ systemDecorations: flags.systemDecorations === true,
236
+ };
237
+ } else if (cmd === 'stop') {
238
+ args = { forceStopApps: flags.forceStopApps === true };
239
+ } else if (cmd === 'launch') {
240
+ if (!sub) { console.error('需要包名:vdisplay launch <pkg> [activity]'); process.exit(1); }
241
+ args = { pkg: sub, activity: positional[2] };
242
+ } else if (cmd === 'shot' || cmd === 'main-shot') {
243
+ action = cmd === 'shot' ? 'shot' : 'mainShot';
244
+ // region 用四个 flag 给:--rx --ry --rw --rh,四个都有才算有效局部
245
+ const rx = num('rx'); const ry = num('ry'); const rw = num('rw'); const rh = num('rh');
246
+ const region = (rx !== undefined && ry !== undefined && rw !== undefined && rh !== undefined)
247
+ ? { x: rx, y: ry, w: rw, h: rh } : undefined;
248
+ args = {
249
+ out: str('out'), dir: str('out') ? dirname(str('out')) : undefined,
250
+ width: num('width'), format: str('format'),
251
+ frames: num('frames'), // >1 走九格连拍
252
+ intervalMs: num('interval'), // 采样上限间隔
253
+ region,
254
+ };
255
+ } else if (cmd === 'text') {
256
+ // 读屏文字(OCR)。CLI 以前没这个命令,导致插件有、命令行没有。
257
+ action = 'text';
258
+ args = { minConf: num('minconf'), maxLines: num('maxlines'), fresh: flags.fresh === true };
259
+ } else if (cmd === 'input') {
260
+ if (!sub) { console.error('需要输入类型:tap / swipe / hold / text / key / paste'); process.exit(1); }
261
+ action = 'input';
262
+ args = {
263
+ kind: sub,
264
+ x: num('x'), y: num('y'), nx: num('nx'), ny: num('ny'),
265
+ x1: num('x1'), y1: num('y1'), x2: num('x2'), y2: num('y2'),
266
+ ms: num('ms'), text: str('text'), key: str('key'),
267
+ };
268
+ } else if (cmd === 'status') {
269
+ action = 'status';
270
+ } else {
271
+ console.error(`不认识的命令「${cmd}」。跑 vdisplay help 看用法。`);
272
+ process.exit(1);
273
+ }
274
+
275
+ // 截图输出路径:--out 指定的文件名要精确,不能只给目录
276
+ if ((action === 'shot' || action === 'mainShot') && str('out')) {
277
+ args.wantPath = str('out');
278
+ }
279
+
280
+ const result = await call(action, args);
281
+
282
+ if (wantJson) {
283
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
284
+ return;
285
+ }
286
+
287
+ // shot 支持精确输出路径:守护进程按 dir 存,这里再搬一次
288
+ if ((action === 'shot' || action === 'mainShot') && str('out') && result?.path) {
289
+ const { copyFile } = await import('node:fs/promises');
290
+ try {
291
+ await copyFile(result.path, str('out'));
292
+ result.path = str('out');
293
+ } catch (e) {
294
+ // 以前这里静默吞掉,用户会去 --out 找文件却找不到。必须说出来。
295
+ result.copyError = `拷贝到 ${str('out')} 失败:${e.message}(截图实际在 ${result.path})`;
296
+ }
297
+ }
298
+
299
+ process.stdout.write(`${human(action, result)}\n`);
300
+ }
301
+
302
+ main().catch((e) => {
303
+ console.error(`出错了:${e?.message || e}`);
304
+ process.exit(1);
305
+ });