@jian-ai/remote-control 0.7.1 → 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.
@@ -0,0 +1,479 @@
1
+ /**
2
+ * macOS computer-use: primary-display screenshots, coord mapping, Jian overlay helper.
3
+ * English-only messages. Imported by jian-remote.mjs on darwin.
4
+ */
5
+ import { spawn, spawnSync } from 'node:child_process';
6
+ import { createHash } from 'node:crypto';
7
+ import { existsSync } from 'node:fs';
8
+ import { chmod, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
9
+ import { homedir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ export const COMPUTER_CAPABILITY = 'computer-macos-v1';
14
+ const IDLE_MS = 30_000;
15
+ const HELPER_NAME = 'computer-helper';
16
+
17
+ /** Map screenshot image pixels → display points (primary). Half-pixel centers the click. */
18
+ export function imagePixelToPoint(x, y, geometry) {
19
+ const { originX, originY, pointWidth, pointHeight, widthPx, heightPx } = geometry;
20
+ if (!(widthPx > 0 && heightPx > 0 && pointWidth > 0 && pointHeight > 0)) {
21
+ throw new Error('Invalid screenshot geometry for coordinate mapping');
22
+ }
23
+ return {
24
+ pointX: originX + (x + 0.5) * (pointWidth / widthPx),
25
+ pointY: originY + (y + 0.5) * (pointHeight / heightPx),
26
+ };
27
+ }
28
+
29
+ export function scaleFromGeometry(geometry) {
30
+ return {
31
+ imageToPointX: geometry.pointWidth / geometry.widthPx,
32
+ imageToPointY: geometry.pointHeight / geometry.heightPx,
33
+ };
34
+ }
35
+
36
+ /** Capture primary display and compress like the gateway’s former screenshotCommand. */
37
+ export function capturePrimaryScreenshotBase64() {
38
+ const script = [
39
+ 'tmp=$(mktemp /tmp/jian-shot.XXXXXX.jpg);',
40
+ 'screencapture -x -t jpg -D 1 "$tmp" || { rm -f "$tmp"; exit 1; };',
41
+ 'sips -Z 1920 -s format jpeg -s formatOptions 50 "$tmp" >/dev/null 2>&1 || true;',
42
+ 'size=$(wc -c < "$tmp" | tr -d " ");',
43
+ 'if [ "$size" -gt 280000 ]; then sips -Z 1440 -s format jpeg -s formatOptions 40 "$tmp" >/dev/null 2>&1 || true; fi;',
44
+ 'size=$(wc -c < "$tmp" | tr -d " ");',
45
+ 'if [ "$size" -gt 280000 ]; then sips -Z 1280 -s format jpeg -s formatOptions 35 "$tmp" >/dev/null 2>&1 || true; fi;',
46
+ 'w=$(sips -g pixelWidth "$tmp" 2>/dev/null | awk "/pixelWidth/{print \\$2}");',
47
+ 'h=$(sips -g pixelHeight "$tmp" 2>/dev/null | awk "/pixelHeight/{print \\$2}");',
48
+ 'echo "$w $h";',
49
+ 'base64 < "$tmp";',
50
+ 'rm -f "$tmp"',
51
+ ].join(' ');
52
+ const result = spawnSync('/bin/sh', ['-lc', script], {
53
+ encoding: 'utf8',
54
+ maxBuffer: 600_000,
55
+ });
56
+ if (result.status !== 0) {
57
+ const err = (result.stderr || result.stdout || 'Screenshot failed').trim();
58
+ throw new Error(
59
+ /not authorized|capture/i.test(err)
60
+ ? 'Jian Remote needs Screen Recording permission in System Settings.'
61
+ : err || 'Screenshot failed',
62
+ );
63
+ }
64
+ const out = result.stdout || '';
65
+ const nl = out.indexOf('\n');
66
+ if (nl < 0) throw new Error('Screenshot produced no image data.');
67
+ const [wRaw, hRaw] = out.slice(0, nl).trim().split(/\s+/);
68
+ const widthPx = Number(wRaw);
69
+ const heightPx = Number(hRaw);
70
+ const base64 = out.slice(nl + 1).replace(/\s+/g, '');
71
+ if (!Number.isFinite(widthPx) || !Number.isFinite(heightPx) || widthPx < 1 || heightPx < 1) {
72
+ throw new Error('Could not read screenshot dimensions.');
73
+ }
74
+ if (!base64) throw new Error('Screenshot produced no image data.');
75
+ return { base64, widthPx, heightPx };
76
+ }
77
+
78
+ function helperPaths() {
79
+ const support = join(homedir(), 'Library', 'Application Support', 'Jian Remote');
80
+ return {
81
+ support,
82
+ source: join(support, `${HELPER_NAME}.swift`),
83
+ binary: join(support, HELPER_NAME),
84
+ };
85
+ }
86
+
87
+ function packageSwiftPath() {
88
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'macos', `${HELPER_NAME}.swift`);
89
+ }
90
+
91
+ async function ensureHelperBinary() {
92
+ const paths = helperPaths();
93
+ await mkdir(paths.support, { recursive: true, mode: 0o755 });
94
+ let sourceText;
95
+ try {
96
+ sourceText = await readFile(packageSwiftPath(), 'utf8');
97
+ } catch {
98
+ try {
99
+ sourceText = await readFile(paths.source, 'utf8');
100
+ } catch {
101
+ throw new Error(
102
+ 'Computer-use helper source is missing. Reinstall or update @jian-ai/remote-control.',
103
+ );
104
+ }
105
+ }
106
+ const hash = createHash('sha256').update(sourceText).digest('hex').slice(0, 16);
107
+ const stamp = join(paths.support, `${HELPER_NAME}.sha256`);
108
+ let previous = '';
109
+ try {
110
+ previous = (await readFile(stamp, 'utf8')).trim();
111
+ } catch {
112
+ previous = '';
113
+ }
114
+ const needsBuild = previous !== hash || !existsSync(paths.binary);
115
+ await writeFile(paths.source, sourceText, { mode: 0o644 });
116
+ if (needsBuild) {
117
+ const compiled = spawnSync(
118
+ 'swiftc',
119
+ ['-O', '-framework', 'AppKit', '-framework', 'Carbon', '-o', paths.binary, paths.source],
120
+ { encoding: 'utf8' },
121
+ );
122
+ if (compiled.status !== 0) {
123
+ throw new Error(
124
+ (compiled.stderr || compiled.stdout || 'swiftc failed').trim() ||
125
+ 'Could not build the Jian computer-use helper. Install Xcode Command Line Tools.',
126
+ );
127
+ }
128
+ await chmod(paths.binary, 0o755);
129
+ await writeFile(stamp, `${hash}\n`, { mode: 0o644 });
130
+ }
131
+ return paths.binary;
132
+ }
133
+
134
+ /** Copy Swift sources next to the installed worker when present in the npm package. */
135
+ export async function materializeComputerHelperSources(configDir) {
136
+ if (process.platform !== 'darwin') return;
137
+ try {
138
+ const from = packageSwiftPath();
139
+ if (!existsSync(from)) return;
140
+ const support = join(homedir(), 'Library', 'Application Support', 'Jian Remote');
141
+ await mkdir(support, { recursive: true, mode: 0o755 });
142
+ await copyFile(from, join(support, `${HELPER_NAME}.swift`));
143
+ const localMacos = join(configDir, 'macos');
144
+ await mkdir(localMacos, { recursive: true, mode: 0o755 });
145
+ await copyFile(from, join(localMacos, `${HELPER_NAME}.swift`));
146
+ } catch {
147
+ // Best-effort on install; computer session will surface a clear error.
148
+ }
149
+ }
150
+
151
+ export class MacComputerSession {
152
+ constructor() {
153
+ this.child = null;
154
+ this.buffer = '';
155
+ this.pending = [];
156
+ this.geometry = null;
157
+ this.shotGeometry = null;
158
+ this.idleTimer = null;
159
+ this.active = false;
160
+ }
161
+
162
+ async ensure() {
163
+ if (this.child && !this.child.killed) {
164
+ await this.send({ cmd: 'ensureSession' });
165
+ this.active = true;
166
+ this.bumpIdle();
167
+ return;
168
+ }
169
+ const binary = await ensureHelperBinary();
170
+ this.child = spawn(binary, [], {
171
+ stdio: ['pipe', 'pipe', 'pipe'],
172
+ });
173
+ this.buffer = '';
174
+ this.child.stdout.setEncoding('utf8');
175
+ this.child.stdout.on('data', (chunk) => this.onData(chunk));
176
+ this.child.stderr.on('data', (chunk) => {
177
+ const text = chunk.toString('utf8').trim();
178
+ if (text) console.error(text);
179
+ });
180
+ this.child.on('exit', () => {
181
+ this.failAll('Computer-use helper exited unexpectedly.');
182
+ this.child = null;
183
+ this.active = false;
184
+ });
185
+ const ping = await this.send({ cmd: 'ping' });
186
+ if (!ping.ok) throw new Error(ping.error || 'Computer-use helper did not respond.');
187
+ const geo = await this.send({ cmd: 'geometry' });
188
+ if (!geo.ok) throw new Error(geo.error || 'Could not read display geometry.');
189
+ this.geometry = {
190
+ originX: Number(geo.originX) || 0,
191
+ originY: Number(geo.originY) || 0,
192
+ pointWidth: Number(geo.pointWidth),
193
+ pointHeight: Number(geo.pointHeight),
194
+ pixelWidth: Number(geo.pixelWidth),
195
+ pixelHeight: Number(geo.pixelHeight),
196
+ scaleFactor: Number(geo.scaleFactor) || 1,
197
+ };
198
+ await this.send({ cmd: 'ensureSession' });
199
+ this.active = true;
200
+ this.bumpIdle();
201
+ }
202
+
203
+ bumpIdle() {
204
+ if (this.idleTimer) clearTimeout(this.idleTimer);
205
+ this.idleTimer = setTimeout(() => {
206
+ if (!this.active || !this.child) return;
207
+ void this.send({ cmd: 'setIdle' }).catch(() => {});
208
+ }, IDLE_MS);
209
+ this.idleTimer.unref?.();
210
+ }
211
+
212
+ onData(chunk) {
213
+ this.buffer += chunk;
214
+ for (;;) {
215
+ const idx = this.buffer.indexOf('\n');
216
+ if (idx < 0) break;
217
+ const line = this.buffer.slice(0, idx).trim();
218
+ this.buffer = this.buffer.slice(idx + 1);
219
+ if (!line) continue;
220
+ let parsed;
221
+ try {
222
+ parsed = JSON.parse(line);
223
+ } catch {
224
+ this.failNext('Computer-use helper returned invalid JSON.');
225
+ continue;
226
+ }
227
+ const next = this.pending.shift();
228
+ if (next) next.resolve(parsed);
229
+ }
230
+ }
231
+
232
+ failNext(message) {
233
+ const next = this.pending.shift();
234
+ if (next) next.reject(new Error(message));
235
+ }
236
+
237
+ failAll(message) {
238
+ while (this.pending.length) {
239
+ this.pending.shift().reject(new Error(message));
240
+ }
241
+ }
242
+
243
+ send(payload) {
244
+ return new Promise((resolve, reject) => {
245
+ if (!this.child?.stdin) {
246
+ reject(new Error('Computer-use helper is not running.'));
247
+ return;
248
+ }
249
+ this.pending.push({ resolve, reject });
250
+ this.child.stdin.write(`${JSON.stringify(payload)}\n`, (error) => {
251
+ if (error) {
252
+ this.pending.pop();
253
+ reject(error);
254
+ }
255
+ });
256
+ });
257
+ }
258
+
259
+ requireShotGeometry() {
260
+ if (!this.shotGeometry) {
261
+ throw new Error('Take a screenshot before using screen coordinates.');
262
+ }
263
+ return this.shotGeometry;
264
+ }
265
+
266
+ mapCoordinate(coordinate) {
267
+ const [x, y] = coordinate;
268
+ const shot = this.requireShotGeometry();
269
+ if (x < 0 || y < 0 || x >= shot.widthPx || y >= shot.heightPx) {
270
+ throw new Error(
271
+ `Coordinate (${x}, ${y}) is outside the last screenshot (${shot.widthPx}×${shot.heightPx}).`,
272
+ );
273
+ }
274
+ return imagePixelToPoint(x, y, shot);
275
+ }
276
+
277
+ async end() {
278
+ if (this.idleTimer) clearTimeout(this.idleTimer);
279
+ this.idleTimer = null;
280
+ if (this.child) {
281
+ try {
282
+ await this.send({ cmd: 'endSession' });
283
+ } catch {
284
+ // ignore
285
+ }
286
+ this.child.kill('SIGTERM');
287
+ this.child = null;
288
+ }
289
+ this.active = false;
290
+ this.shotGeometry = null;
291
+ this.geometry = null;
292
+ }
293
+
294
+ async runAction(computer) {
295
+ const { action } = computer;
296
+ if (action === 'end_session') {
297
+ await this.end();
298
+ return {
299
+ exitCode: 0,
300
+ stdout: '',
301
+ stderr: '',
302
+ timedOut: false,
303
+ computer: { ok: true },
304
+ };
305
+ }
306
+
307
+ if (action === 'wait') {
308
+ const ms = Math.round((computer.duration ?? 0.5) * 1000);
309
+ await new Promise((r) => setTimeout(r, ms));
310
+ if (this.active) this.bumpIdle();
311
+ return {
312
+ exitCode: 0,
313
+ stdout: '',
314
+ stderr: '',
315
+ timedOut: false,
316
+ computer: { ok: true },
317
+ };
318
+ }
319
+
320
+ if (action === 'screenshot') {
321
+ await this.ensure();
322
+ const shot = capturePrimaryScreenshotBase64();
323
+ if (!this.geometry) throw new Error('Display geometry unavailable.');
324
+ this.shotGeometry = {
325
+ ...this.geometry,
326
+ widthPx: shot.widthPx,
327
+ heightPx: shot.heightPx,
328
+ };
329
+ this.bumpIdle();
330
+ return {
331
+ exitCode: 0,
332
+ stdout: shot.base64,
333
+ stderr: '',
334
+ timedOut: false,
335
+ computer: {
336
+ ok: true,
337
+ widthPx: shot.widthPx,
338
+ heightPx: shot.heightPx,
339
+ scale: scaleFromGeometry(this.shotGeometry),
340
+ },
341
+ };
342
+ }
343
+
344
+ await this.ensure();
345
+
346
+ try {
347
+ if (
348
+ action === 'mouse_move' ||
349
+ action === 'left_click' ||
350
+ action === 'right_click' ||
351
+ action === 'double_click'
352
+ ) {
353
+ if (!computer.coordinate) throw new Error('coordinate is required for this action.');
354
+ const { pointX, pointY } = this.mapCoordinate(computer.coordinate);
355
+ const moved = await this.send({ cmd: 'move', pointX, pointY });
356
+ if (!moved.ok) throw new Error(moved.error || 'Move failed.');
357
+ if (action !== 'mouse_move') {
358
+ const button = action === 'right_click' ? 'right' : 'left';
359
+ const count = action === 'double_click' ? 2 : 1;
360
+ const clicked = await this.send({ cmd: 'click', button, count });
361
+ if (!clicked.ok) throw new Error(clicked.error || 'Click failed.');
362
+ }
363
+ } else if (action === 'left_click_drag') {
364
+ if (!computer.startCoordinate || !computer.coordinate) {
365
+ throw new Error('startCoordinate and coordinate are required for drag.');
366
+ }
367
+ const from = this.mapCoordinate(computer.startCoordinate);
368
+ const to = this.mapCoordinate(computer.coordinate);
369
+ const dragged = await this.send({
370
+ cmd: 'drag',
371
+ fromX: from.pointX,
372
+ fromY: from.pointY,
373
+ toX: to.pointX,
374
+ toY: to.pointY,
375
+ });
376
+ if (!dragged.ok) throw new Error(dragged.error || 'Drag failed.');
377
+ } else if (action === 'type') {
378
+ if (!computer.text) throw new Error('text is required for type.');
379
+ const typed = await this.send({ cmd: 'type', text: computer.text });
380
+ if (!typed.ok) throw new Error(typed.error || 'Type failed.');
381
+ } else if (action === 'key') {
382
+ if (!computer.key) throw new Error('key is required for key.');
383
+ const keyed = await this.send({ cmd: 'key', key: computer.key });
384
+ if (!keyed.ok) throw new Error(keyed.error || 'Key failed.');
385
+ } else if (action === 'scroll') {
386
+ if (!computer.coordinate) throw new Error('coordinate is required for scroll.');
387
+ if (!computer.scrollDirection) throw new Error('scrollDirection is required for scroll.');
388
+ const { pointX, pointY } = this.mapCoordinate(computer.coordinate);
389
+ const scrolled = await this.send({
390
+ cmd: 'scroll',
391
+ pointX,
392
+ pointY,
393
+ direction: computer.scrollDirection,
394
+ amount: computer.scrollAmount ?? 3,
395
+ });
396
+ if (!scrolled.ok) throw new Error(scrolled.error || 'Scroll failed.');
397
+ } else {
398
+ throw new Error(`Unsupported computer action: ${action}`);
399
+ }
400
+ } catch (error) {
401
+ const message = error instanceof Error ? error.message : String(error);
402
+ const tcc = /accessib|not permitted|not authorized/i.test(message)
403
+ ? ' Jian Remote needs Accessibility (and Screen Recording for screenshots) in System Settings.'
404
+ : '';
405
+ return {
406
+ exitCode: 1,
407
+ stdout: '',
408
+ stderr: `${message}${tcc}`,
409
+ timedOut: false,
410
+ computer: { ok: false, error: `${message}${tcc}`.trim() },
411
+ };
412
+ }
413
+
414
+ this.bumpIdle();
415
+ return {
416
+ exitCode: 0,
417
+ stdout: '',
418
+ stderr: '',
419
+ timedOut: false,
420
+ computer: { ok: true },
421
+ };
422
+ }
423
+ }
424
+
425
+ let sharedSession = null;
426
+
427
+ export function computerSession() {
428
+ if (!sharedSession) sharedSession = new MacComputerSession();
429
+ return sharedSession;
430
+ }
431
+
432
+ export async function executeComputerTask(task) {
433
+ const session = computerSession();
434
+ const computer = task.computer;
435
+ if (!computer?.action) {
436
+ return {
437
+ taskId: task.id,
438
+ exitCode: 1,
439
+ stdout: '',
440
+ stderr: 'Computer task missing action.',
441
+ timedOut: false,
442
+ computer: { ok: false, error: 'Computer task missing action.' },
443
+ };
444
+ }
445
+ const timeoutMs = task.timeoutMs || 30_000;
446
+ let timedOut = false;
447
+ const result = await Promise.race([
448
+ session.runAction(computer),
449
+ new Promise((resolve) => {
450
+ setTimeout(() => {
451
+ timedOut = true;
452
+ resolve({
453
+ exitCode: null,
454
+ stdout: '',
455
+ stderr: 'Computer action timed out',
456
+ timedOut: true,
457
+ computer: { ok: false, error: 'Computer action timed out' },
458
+ });
459
+ }, timeoutMs);
460
+ }),
461
+ ]);
462
+ return { taskId: task.id, ...result, timedOut: timedOut || Boolean(result.timedOut) };
463
+ }
464
+
465
+ /** Probe whether this Mac can advertise computer-use (helper builds). */
466
+ export async function probeComputerCapability() {
467
+ if (process.platform !== 'darwin') return false;
468
+ try {
469
+ await ensureHelperBinary();
470
+ return true;
471
+ } catch {
472
+ // Still advertise: screenshot-only path can work; input fails with TCC guidance.
473
+ // Prefer advertising when swiftc exists so gateway can send jobs after first grant.
474
+ return (
475
+ Boolean(spawnSync('which', ['swiftc'], { encoding: 'utf8' }).stdout?.trim()) ||
476
+ existsSync(helperPaths().binary)
477
+ );
478
+ }
479
+ }