@limrun/api 0.76.0 → 0.77.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +26 -1
  3. package/client.d.mts +3 -0
  4. package/client.d.mts.map +1 -1
  5. package/client.d.ts +3 -0
  6. package/client.d.ts.map +1 -1
  7. package/client.js +3 -0
  8. package/client.js.map +1 -1
  9. package/client.mjs +3 -0
  10. package/client.mjs.map +1 -1
  11. package/index.d.mts +1 -0
  12. package/index.d.mts.map +1 -1
  13. package/index.d.ts +1 -0
  14. package/index.d.ts.map +1 -1
  15. package/index.js +5 -2
  16. package/index.js.map +1 -1
  17. package/index.mjs +1 -0
  18. package/index.mjs.map +1 -1
  19. package/ios-argent.d.mts +63 -0
  20. package/ios-argent.d.mts.map +1 -0
  21. package/ios-argent.d.ts +63 -0
  22. package/ios-argent.d.ts.map +1 -0
  23. package/ios-argent.js +690 -0
  24. package/ios-argent.js.map +1 -0
  25. package/ios-argent.mjs +683 -0
  26. package/ios-argent.mjs.map +1 -0
  27. package/package.json +11 -1
  28. package/resources/analytics.d.mts +22 -2
  29. package/resources/analytics.d.mts.map +1 -1
  30. package/resources/analytics.d.ts +22 -2
  31. package/resources/analytics.d.ts.map +1 -1
  32. package/resources/analytics.js.map +1 -1
  33. package/resources/analytics.mjs.map +1 -1
  34. package/resources/index.d.mts +1 -0
  35. package/resources/index.d.mts.map +1 -1
  36. package/resources/index.d.ts +1 -0
  37. package/resources/index.d.ts.map +1 -1
  38. package/resources/index.js +3 -1
  39. package/resources/index.js.map +1 -1
  40. package/resources/index.mjs +1 -0
  41. package/resources/index.mjs.map +1 -1
  42. package/resources/macos-instances.d.mts +224 -0
  43. package/resources/macos-instances.d.mts.map +1 -0
  44. package/resources/macos-instances.d.ts +224 -0
  45. package/resources/macos-instances.d.ts.map +1 -0
  46. package/resources/macos-instances.js +51 -0
  47. package/resources/macos-instances.js.map +1 -0
  48. package/resources/macos-instances.mjs +47 -0
  49. package/resources/macos-instances.mjs.map +1 -0
  50. package/src/client.ts +19 -0
  51. package/src/index.ts +7 -0
  52. package/src/ios-argent.ts +789 -0
  53. package/src/resources/analytics.ts +22 -2
  54. package/src/resources/index.ts +8 -0
  55. package/src/resources/macos-instances.ts +296 -0
  56. package/src/version.ts +1 -1
  57. package/version.d.mts +1 -1
  58. package/version.d.ts +1 -1
  59. package/version.js +1 -1
  60. package/version.mjs +1 -1
@@ -0,0 +1,789 @@
1
+ import fs from 'fs';
2
+ import http, { type IncomingMessage, type ServerResponse } from 'http';
3
+ import os from 'os';
4
+ import path from 'path';
5
+ import { WebSocketServer } from 'ws';
6
+
7
+ import type { DeviceInfo, ElementTree, ElementTreeNode, InstanceClient, PerformAction } from './ios-client';
8
+
9
+ /**
10
+ * Mechanisms the provider descriptor grants Argent on the simulator. Each one
11
+ * is served by the bridge instead of a process on a local Mac.
12
+ */
13
+ export const ARGENT_PROVIDER_CAPABILITIES = ['simulator-server', 'simctl', 'ax-service'] as const;
14
+
15
+ export type ArgentBridgeClient = Pick<
16
+ InstanceClient,
17
+ | 'deviceInfo'
18
+ | 'getDeviceInfo'
19
+ | 'listApps'
20
+ | 'simctl'
21
+ | 'syncApp'
22
+ | 'screenshot'
23
+ | 'elementTree'
24
+ | 'performActions'
25
+ | 'setOrientation'
26
+ | 'setElementValue'
27
+ >;
28
+
29
+ export type ArgentBridge = {
30
+ /** The id Argent lists the simulator under; pass it as `--udid` to Argent tools. */
31
+ deviceId: string;
32
+ /** The provider descriptor Argent discovers the simulator from. */
33
+ descriptorPath: string;
34
+ /** Environment overrides for the Argent tool-server process; merge over process.env. */
35
+ env: Record<string, string>;
36
+ /** Stops the bridge and withdraws the simulator from Argent. */
37
+ close: () => Promise<void>;
38
+ };
39
+
40
+ export type ArgentBridgeOptions = {
41
+ /** Directory Argent scans for provider descriptors. Defaults to `~/.argent/providers`. */
42
+ providersDir?: string;
43
+ };
44
+
45
+ /**
46
+ * Offer this instance's simulator to a locally installed Argent through its
47
+ * device-provider contract.
48
+ *
49
+ * Argent expects a simulator on the same Mac: it runs `xcrun simctl`, attaches
50
+ * to a local simulator-server for input and screenshots, and spawns an
51
+ * accessibility daemon inside the simulator. The bridge stands in for all
52
+ * three, so an unmodified Argent drives the remote simulator:
53
+ *
54
+ * - a provider descriptor points Argent at a local HTTP and WebSocket server
55
+ * that speaks the simulator-server protocol,
56
+ * - an `xcrun` executable for PATH forwards simctl calls for this simulator,
57
+ * - the same executable answers the accessibility daemon's requests when
58
+ * Argent spawns it.
59
+ *
60
+ * The Argent tool-server must start with the returned `env`, because it
61
+ * resolves `xcrun` from its own PATH.
62
+ */
63
+ export async function startArgentBridge(
64
+ client: ArgentBridgeClient,
65
+ options: ArgentBridgeOptions = {},
66
+ ): Promise<ArgentBridge> {
67
+ const udid = client.deviceInfo.udid;
68
+ const providerId = `limrun-${udid.slice(0, 8).toLowerCase()}`;
69
+ const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'limrun-argent-'));
70
+ const mediaDir = path.join(workDir, 'media');
71
+ fs.mkdirSync(mediaDir);
72
+
73
+ const session = new BridgeSession(client, mediaDir);
74
+ const server = http.createServer((req, res) => void session.handleHttp(req, res));
75
+ const sockets = new WebSocketServer({ server, path: '/ws' });
76
+ sockets.on('connection', (socket) => {
77
+ socket.on('message', (raw) => {
78
+ void session.handleCommand(raw.toString()).then((reply) => socket.send(JSON.stringify(reply)));
79
+ });
80
+ });
81
+
82
+ const cleanup = async (descriptorPath?: string) => {
83
+ if (descriptorPath) fs.rmSync(descriptorPath, { force: true });
84
+ sockets.close();
85
+ await new Promise<void>((resolve) => server.close(() => resolve()));
86
+ fs.rmSync(workDir, { recursive: true, force: true });
87
+ };
88
+
89
+ try {
90
+ await new Promise<void>((resolve, reject) => {
91
+ server.once('error', reject);
92
+ server.listen(0, '127.0.0.1', () => {
93
+ server.off('error', reject);
94
+ resolve();
95
+ });
96
+ });
97
+ const address = server.address();
98
+ if (!address || typeof address === 'string') {
99
+ throw new Error('Failed to start the Argent bridge server.');
100
+ }
101
+ const baseUrl = `http://127.0.0.1:${address.port}`;
102
+ session.baseUrl = baseUrl;
103
+
104
+ const shimDir = path.join(workDir, 'bin');
105
+ fs.mkdirSync(shimDir);
106
+ const shimPath = path.join(shimDir, 'xcrun');
107
+ fs.writeFileSync(shimPath, xcrunShimSource({ baseUrl, device: simctlDevice(client.deviceInfo) }), 'utf8');
108
+ fs.chmodSync(shimPath, 0o755);
109
+
110
+ const providersDir = options.providersDir ?? path.join(os.homedir(), '.argent', 'providers');
111
+ fs.mkdirSync(providersDir, { recursive: true });
112
+ const descriptorPath = path.join(providersDir, `${providerId}.json`);
113
+ fs.writeFileSync(
114
+ descriptorPath,
115
+ JSON.stringify(
116
+ {
117
+ schemaVersion: 1,
118
+ id: providerId,
119
+ name: 'Limrun',
120
+ // Lets `argent providers prune` drop the descriptor if this process dies.
121
+ pid: process.pid,
122
+ supportUrl: 'https://docs.limrun.com',
123
+ devices: [
124
+ {
125
+ nativeId: udid,
126
+ platform: 'ios',
127
+ kind: 'simulator',
128
+ name: client.deviceInfo.model,
129
+ state: 'Booted',
130
+ capabilities: ARGENT_PROVIDER_CAPABILITIES,
131
+ // The contract requires streamUrl. The bridge serves no video stream.
132
+ simulatorServer: { apiUrl: baseUrl, streamUrl: `${baseUrl}/stream.mjpeg` },
133
+ },
134
+ ],
135
+ },
136
+ null,
137
+ 2,
138
+ ),
139
+ 'utf8',
140
+ );
141
+
142
+ return {
143
+ deviceId: `ext:${providerId}:${udid}`,
144
+ descriptorPath,
145
+ env: { PATH: `${shimDir}${path.delimiter}${process.env['PATH'] ?? ''}` },
146
+ close: () => cleanup(descriptorPath),
147
+ };
148
+ } catch (error) {
149
+ await cleanup();
150
+ throw error;
151
+ }
152
+ }
153
+
154
+ type CommandReply = { id?: string; status: 'ok' | 'error'; message?: string };
155
+ type SimctlResult = { code: number; stdout: string; stderr: string };
156
+
157
+ /** Keeps this many screenshots on disk; Argent reads each one right after the call. */
158
+ const MEDIA_FILES_KEPT = 32;
159
+
160
+ class BridgeSession {
161
+ baseUrl = '';
162
+ private info: DeviceInfo;
163
+ private gesture: { actions: PerformAction[]; last: number } | undefined;
164
+ private queue: QueuedInput[] = [];
165
+ private draining: Promise<void> | undefined;
166
+ private deferredError: Error | undefined;
167
+ private mediaFiles: string[] = [];
168
+
169
+ constructor(
170
+ private client: ArgentBridgeClient,
171
+ private mediaDir: string,
172
+ ) {
173
+ this.info = client.deviceInfo;
174
+ }
175
+
176
+ // ---- input ---------------------------------------------------------------
177
+
178
+ /**
179
+ * Runs actions in arrival order. Actions that arrive while a batch is on the
180
+ * wire go out together in the next one, so a typed word costs a few round
181
+ * trips instead of two per character.
182
+ */
183
+ private enqueue(actions: PerformAction[]): Promise<void> {
184
+ const done = new Promise<void>((resolve, reject) => this.queue.push({ actions, resolve, reject }));
185
+ this.draining ??= this.drain();
186
+ return done;
187
+ }
188
+
189
+ private async drain(): Promise<void> {
190
+ while (this.queue.length > 0) {
191
+ const batch = this.queue.splice(0);
192
+ try {
193
+ await this.client.performActions(batch.flatMap((entry) => entry.actions));
194
+ batch.forEach((entry) => entry.resolve());
195
+ } catch (error) {
196
+ batch.forEach((entry) => entry.reject(asError(error)));
197
+ }
198
+ }
199
+ this.draining = undefined;
200
+ }
201
+
202
+ /**
203
+ * Keys and buttons are acknowledged before they reach the simulator, to keep
204
+ * Argent's own typing pace. A failure is reported on the next call instead.
205
+ */
206
+ private enqueueUnacknowledged(actions: PerformAction[]): void {
207
+ this.enqueue(actions).catch((error: Error) => {
208
+ this.deferredError = error;
209
+ });
210
+ }
211
+
212
+ /** Reads wait for pending input, so a screenshot never overtakes a tap. */
213
+ private async settled(): Promise<void> {
214
+ while (this.draining) await this.draining;
215
+ const error = this.deferredError;
216
+ this.deferredError = undefined;
217
+ if (error) throw error;
218
+ }
219
+
220
+ private screen(): { width: number; height: number } {
221
+ return {
222
+ width: this.info.displayWidth ?? this.info.screenWidth,
223
+ height: this.info.displayHeight ?? this.info.screenHeight,
224
+ };
225
+ }
226
+
227
+ private touch(type: 'touchDown' | 'touchMove' | 'touchUp', cmd: Record<string, unknown>): PerformAction {
228
+ const { width, height } = this.screen();
229
+ const action = { type, x: Number(cmd['x']) * width, y: Number(cmd['y']) * height };
230
+ const secondX = cmd['second_x'];
231
+ const secondY = cmd['second_y'];
232
+ if (typeof secondX === 'number' && typeof secondY === 'number') {
233
+ return { ...action, x2: secondX * width, y2: secondY * height };
234
+ }
235
+ return action;
236
+ }
237
+
238
+ /** One simulator-server WebSocket command. Argent sends coordinates as 0..1 fractions. */
239
+ async handleCommand(raw: string): Promise<CommandReply> {
240
+ let cmd: Record<string, unknown>;
241
+ try {
242
+ cmd = JSON.parse(raw) as Record<string, unknown>;
243
+ } catch {
244
+ return { status: 'error', message: 'parse error: invalid JSON' };
245
+ }
246
+ try {
247
+ await this.runCommand(cmd);
248
+ return { id: String(cmd['id']), status: 'ok' };
249
+ } catch (error) {
250
+ // simulator-server omits the id on a rejected command, and Argent matches on that.
251
+ return { status: 'error', message: asError(error).message };
252
+ }
253
+ }
254
+
255
+ private async runCommand(cmd: Record<string, unknown>): Promise<void> {
256
+ const pressed = cmd['direction'] === 'Down';
257
+ switch (cmd['cmd']) {
258
+ case 'touch':
259
+ case 'edgeTouch': {
260
+ const now = Date.now();
261
+ if (cmd['type'] === 'Down') {
262
+ this.gesture = { actions: [this.touch('touchDown', cmd)], last: now };
263
+ return;
264
+ }
265
+ const gesture = this.gesture;
266
+ if (!gesture) throw new Error(`touch ${String(cmd['type'])} arrived without a Down`);
267
+ // Argent paces a gesture by when it sends each event; replay that pace.
268
+ if (now > gesture.last) gesture.actions.push({ type: 'wait', durationMs: now - gesture.last });
269
+ gesture.last = now;
270
+ if (cmd['type'] === 'Move') {
271
+ gesture.actions.push(this.touch('touchMove', cmd));
272
+ return;
273
+ }
274
+ gesture.actions.push(this.touch('touchUp', cmd));
275
+ this.gesture = undefined;
276
+ // The whole gesture goes out as one batch, and only its Up waits for it.
277
+ await this.enqueue(gesture.actions);
278
+ return;
279
+ }
280
+ case 'key':
281
+ // Argent sends USB HID keyboard usages, which is HID usage page 7.
282
+ this.enqueueUnacknowledged([
283
+ { type: pressed ? 'usageDown' : 'usageUp', usagePage: 7, usage: Number(cmd['code']) },
284
+ ]);
285
+ return;
286
+ case 'button': {
287
+ const button = ARGENT_BUTTONS[String(cmd['button'])];
288
+ if (!button) throw new Error(`button ${String(cmd['button'])} is not supported on Limrun simulators`);
289
+ this.enqueueUnacknowledged([{ type: pressed ? 'buttonDown' : 'buttonUp', button }]);
290
+ return;
291
+ }
292
+ case 'rotate':
293
+ await this.settled();
294
+ await this.client.setOrientation(cmd['direction'] as Parameters<InstanceClient['setOrientation']>[0]);
295
+ this.info = await this.client.getDeviceInfo();
296
+ return;
297
+ case 'capture_on_demand':
298
+ return;
299
+ default:
300
+ throw new Error(`parse error: unknown variant \`${String(cmd['cmd'])}\``);
301
+ }
302
+ }
303
+
304
+ // ---- http ----------------------------------------------------------------
305
+
306
+ async handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {
307
+ const url = req.url ?? '/';
308
+ try {
309
+ if (req.method === 'GET' && url.startsWith('/media/')) {
310
+ // Serve only screenshots this bridge wrote and still keeps; anything
311
+ // else, a deleted screenshot included, is not found.
312
+ const name = url.slice('/media/'.length);
313
+ const file = this.mediaFiles.find((kept) => path.basename(kept) === name);
314
+ let image: Buffer;
315
+ try {
316
+ if (!file) throw new Error('not kept');
317
+ image = await fs.promises.readFile(file);
318
+ } catch {
319
+ return sendJson(res, 404, { error: 'not found' });
320
+ }
321
+ res.writeHead(200, { 'content-type': 'image/png', 'content-length': image.length });
322
+ res.end(image);
323
+ return;
324
+ }
325
+ // Argent probes apiUrl to check that the provider is alive.
326
+ if (req.method === 'GET' && url === '/') return sendJson(res, 200, { status: 'ok' });
327
+ if (req.method !== 'POST') return sendJson(res, 404, { error: 'not found' });
328
+
329
+ const body = (await readJson(req)) as Record<string, unknown>;
330
+ if (url === '/api/screenshot') return sendJson(res, 200, await this.screenshot(body));
331
+ if (url === '/api/pointer') return sendJson(res, 200, { status: 'ok' });
332
+ if (url === '/api/clipboard/text') {
333
+ await this.settled();
334
+ const copied = await this.client
335
+ .simctl(['pbcopy', this.info.udid], { stdin: String(body['text'] ?? '') })
336
+ .wait();
337
+ return sendJson(res, 200, copied.code === 0 ? { status: 'ok' } : { error: copied.stderr });
338
+ }
339
+ if (url === '/xcrun') return sendJson(res, 200, await this.simctl((body['args'] as string[]) ?? []));
340
+ if (url === '/ax') {
341
+ return sendJson(res, 200, await this.accessibilityReply(String(body['command']), body['params']));
342
+ }
343
+ return sendJson(res, 404, { error: 'not found' });
344
+ } catch (error) {
345
+ const message = asError(error).message;
346
+ // One body serves both callers: Argent reads `error`, the xcrun shim reads the rest.
347
+ sendJson(res, 200, { error: message, code: 1, stdout: '', stderr: `limrun: ${message}\n` });
348
+ }
349
+ }
350
+
351
+ private async screenshot(body: Record<string, unknown>): Promise<{ url: string; path: string }> {
352
+ await this.settled();
353
+ // Argent omits `scale` only when it wants native pixels. Every smaller
354
+ // scale gets the point-sized image, the nearest size the simulator serves.
355
+ const data = await this.client.screenshot({
356
+ format: 'png',
357
+ size: body['scale'] === undefined ? 'full' : 'scaled',
358
+ });
359
+ const name = `screenshot-${Date.now()}-${this.mediaFiles.length}.png`;
360
+ const file = path.join(this.mediaDir, name);
361
+ fs.writeFileSync(file, Buffer.from(data.base64, 'base64'));
362
+ this.mediaFiles.push(file);
363
+ while (this.mediaFiles.length > MEDIA_FILES_KEPT) {
364
+ fs.rmSync(this.mediaFiles.shift()!, { force: true });
365
+ }
366
+ return { url: `${this.baseUrl}/media/${name}`, path: file };
367
+ }
368
+
369
+ // ---- simctl --------------------------------------------------------------
370
+
371
+ /** A simctl call for this simulator, as the xcrun shim forwards it (without `xcrun simctl`). */
372
+ private async simctl(args: string[]): Promise<SimctlResult> {
373
+ const udid = this.info.udid;
374
+ const command = args[0];
375
+ const rest = args.slice(args.indexOf(udid) + 1);
376
+
377
+ if (command === 'spawn') {
378
+ // Argent reads this flag to decide whether accessibility is degraded. It
379
+ // describes Argent's own daemon, which does not run here.
380
+ if (rest.join(' ') === 'defaults read com.apple.Accessibility IgnoreAXServerEntitlements') {
381
+ return { code: 0, stdout: '1\n', stderr: '' };
382
+ }
383
+ if (rest[0] === 'launchctl' && rest[1] === 'list') {
384
+ // Argent parses running apps out of `launchctl list`, which the
385
+ // simulator does not let callers run.
386
+ const running = (await this.client.listApps()).filter((app) => app.pid !== undefined);
387
+ const lines = running.map(
388
+ (app) => `${app.pid}\t0\tUIKitApplication:${app.bundleId}[0000][rb-legacy]`,
389
+ );
390
+ return { code: 0, stdout: ['PID\tStatus\tLabel', ...lines].join('\n') + '\n', stderr: '' };
391
+ }
392
+ }
393
+ await this.settled();
394
+ if (command === 'bootstatus') return { code: 0, stdout: '', stderr: '' };
395
+ if (command === 'install') {
396
+ const appPath = rest[0];
397
+ if (!appPath) return { code: 64, stdout: '', stderr: 'simctl install requires a local .app path.\n' };
398
+ await this.client.syncApp(appPath, { install: true, launchMode: 'None', watch: false });
399
+ return { code: 0, stdout: '', stderr: '' };
400
+ }
401
+ return await this.client.simctl(args).wait();
402
+ }
403
+
404
+ // ---- accessibility -------------------------------------------------------
405
+
406
+ /** The reply to one accessibility daemon request, as `{result}` or `{error}`. */
407
+ private async accessibilityReply(
408
+ command: string,
409
+ params: unknown,
410
+ ): Promise<{ result: unknown } | { error: string }> {
411
+ try {
412
+ await this.settled();
413
+ return { result: await this.accessibility(command, (params ?? {}) as Record<string, unknown>) };
414
+ } catch (error) {
415
+ return { error: asError(error).message };
416
+ }
417
+ }
418
+
419
+ private async accessibility(command: string, params: Record<string, unknown>): Promise<unknown> {
420
+ if (command === 'ping') return { status: 'ok' };
421
+ if (command === 'live_panel') return { displayId: null };
422
+ if (command === 'orientation') {
423
+ this.info = await this.client.getDeviceInfo();
424
+ return { interfaceOrientation: this.info.orientation ?? 'portrait', screenFrame: this.screen() };
425
+ }
426
+ if (command === 'fill' && params['check'] !== true) {
427
+ // Without a selector the simulator resolves the focused field itself.
428
+ try {
429
+ await this.client.setElementValue(String(params['text'] ?? ''));
430
+ } catch {
431
+ throw new Error('no_focused_field');
432
+ }
433
+ return { verified: true };
434
+ }
435
+
436
+ if (!TREE_COMMANDS.has(command)) {
437
+ // Argent treats this code as "the daemon predates the command" and
438
+ // probes with it, so answer before reading the tree.
439
+ throw new Error('unknown_command');
440
+ }
441
+ const tree = await this.client.elementTree(undefined, { visibleOnly: true });
442
+ const screen = this.screen();
443
+ const base = {
444
+ alertVisible: someNode(tree, (node) => node.type === 'Alert' || node.type === 'Sheet'),
445
+ screenFrame: screen,
446
+ interfaceOrientation: this.info.orientation ?? 'portrait',
447
+ };
448
+ switch (command) {
449
+ case 'alert_check':
450
+ return { alertVisible: base.alertVisible };
451
+ case 'fill':
452
+ return { verified: someNode(tree, (node) => node.AXValue === params['text']) };
453
+ case 'foreground_app':
454
+ return { alertVisible: base.alertVisible, ...(await this.foregroundApp(tree)) };
455
+ case 'describe':
456
+ return { ...base, elements: toArgentElements(tree, screen) };
457
+ case 'tree': {
458
+ const app = await this.foregroundApp(tree);
459
+ return {
460
+ ...base,
461
+ nodes: toArgentTreeNodes(tree, screen, app.bundleId),
462
+ truncated: false,
463
+ ...(app.bundleId ? { foregroundApp: app.bundleId } : {}),
464
+ treeVersion: 1,
465
+ };
466
+ }
467
+ default:
468
+ throw new Error('unknown_command');
469
+ }
470
+ }
471
+
472
+ private async foregroundApp(tree: ElementTree): Promise<{ bundleId?: string; name?: string }> {
473
+ const root = tree[0];
474
+ if (!root) return {};
475
+ const apps = await this.client.listApps();
476
+ const app = apps.find((candidate) => candidate.pid === root.pid);
477
+ const name = root.AXLabel ?? app?.name;
478
+ return { ...(app ? { bundleId: app.bundleId } : {}), ...(name ? { name } : {}) };
479
+ }
480
+ }
481
+
482
+ /** The accessibility commands answered from the element tree. */
483
+ const TREE_COMMANDS = new Set(['alert_check', 'fill', 'foreground_app', 'describe', 'tree']);
484
+
485
+ type QueuedInput = { actions: PerformAction[]; resolve: () => void; reject: (error: Error) => void };
486
+
487
+ const ARGENT_BUTTONS: Record<string, string> = {
488
+ home: 'home',
489
+ power: 'lock',
490
+ volumeUp: 'volumeUp',
491
+ volumeDown: 'volumeDown',
492
+ };
493
+
494
+ // Argent derives an element's role from these trait names.
495
+ const TRAIT_BY_TYPE: Record<string, string> = {
496
+ Button: 'button',
497
+ Cell: 'button',
498
+ Switch: 'button',
499
+ StaticText: 'staticText',
500
+ Heading: 'header',
501
+ Link: 'link',
502
+ Image: 'image',
503
+ TextField: 'textEntry',
504
+ SecureTextField: 'textEntry',
505
+ TextView: 'textEntry',
506
+ SearchField: 'searchField',
507
+ TabBar: 'tabBar',
508
+ Slider: 'adjustable',
509
+ };
510
+
511
+ const CONTAINER_TYPES = new Set([
512
+ 'Application',
513
+ 'Window',
514
+ 'Group',
515
+ 'Other',
516
+ 'ScrollView',
517
+ 'Table',
518
+ 'CollectionView',
519
+ ]);
520
+
521
+ type ArgentElement = {
522
+ label?: string;
523
+ hint?: string;
524
+ frame: { x: number; y: number; width: number; height: number };
525
+ traits: string[];
526
+ value?: string;
527
+ identifier?: string;
528
+ };
529
+
530
+ type Screen = { width: number; height: number };
531
+
532
+ /** The node's fields in Argent's shape, with the frame left out when it is empty. */
533
+ function toArgentFields(
534
+ node: ElementTreeNode,
535
+ screen: Screen,
536
+ ): Omit<ArgentElement, 'frame'> & {
537
+ frame?: ArgentElement['frame'];
538
+ } {
539
+ const { x, y, width, height } = node.frame;
540
+ const traits = new Set(node.traits.map((trait) => trait.charAt(0).toLowerCase() + trait.slice(1)));
541
+ const fromType = TRAIT_BY_TYPE[node.type];
542
+ if (fromType) traits.add(fromType);
543
+ if (!node.enabled) traits.add('notEnabled');
544
+ const label = node.AXLabel ?? node.title;
545
+ return {
546
+ ...(label ? { label } : {}),
547
+ ...(node.help ? { hint: node.help } : {}),
548
+ // Argent expects frames as fractions of the screen. It treats a node without
549
+ // a frame as unframed, but hides a 0x0 frame together with its subtree.
550
+ ...(width > 0 && height > 0 ?
551
+ {
552
+ frame: {
553
+ x: x / screen.width,
554
+ y: y / screen.height,
555
+ width: width / screen.width,
556
+ height: height / screen.height,
557
+ },
558
+ }
559
+ : {}),
560
+ traits: [...traits],
561
+ ...(node.AXValue ? { value: node.AXValue } : {}),
562
+ ...(node.AXUniqueId ? { identifier: node.AXUniqueId } : {}),
563
+ };
564
+ }
565
+
566
+ /** One `describe` element; describe has no use for an element without a frame. */
567
+ function toArgentElement(node: ElementTreeNode, screen: Screen): ArgentElement | undefined {
568
+ const fields = toArgentFields(node, screen);
569
+ return fields.frame ? { ...fields, frame: fields.frame } : undefined;
570
+ }
571
+
572
+ /** The flat element list behind Argent's `describe`: every node except unnamed containers. */
573
+ export function toArgentElements(tree: ElementTree, screen: Screen): ArgentElement[] {
574
+ const elements: ArgentElement[] = [];
575
+ const visit = (nodes: ElementTreeNode[]) => {
576
+ for (const node of nodes) {
577
+ const named = node.AXLabel || node.AXValue || node.title || node.AXUniqueId;
578
+ const element = CONTAINER_TYPES.has(node.type) && !named ? undefined : toArgentElement(node, screen);
579
+ if (element) elements.push(element);
580
+ visit(node.children ?? []);
581
+ }
582
+ };
583
+ visit(tree);
584
+ return elements;
585
+ }
586
+
587
+ /** The nested tree behind Argent's `ui-tree`, in document order with parent links. */
588
+ export function toArgentTreeNodes(
589
+ tree: ElementTree,
590
+ screen: Screen,
591
+ rootBundleId: string | undefined,
592
+ ): Array<Record<string, unknown>> {
593
+ const nodes: Array<Record<string, unknown>> = [];
594
+ const visit = (children: ElementTreeNode[], parentIndex: number | undefined) => {
595
+ for (const node of children) {
596
+ const index = nodes.length;
597
+ nodes.push({
598
+ index,
599
+ ...(parentIndex === undefined ?
600
+ rootBundleId ? { bundleId: rootBundleId }
601
+ : {}
602
+ : { parentIndex }),
603
+ ...toArgentFields(node, screen),
604
+ roleDescription: node.role_description,
605
+ });
606
+ visit(node.children ?? [], index);
607
+ }
608
+ };
609
+ visit(tree, undefined);
610
+ return nodes;
611
+ }
612
+
613
+ function someNode(tree: ElementTreeNode[], matches: (node: ElementTreeNode) => boolean): boolean {
614
+ return tree.some((node) => matches(node) || someNode(node.children ?? [], matches));
615
+ }
616
+
617
+ type SimctlDevice = { runtime: string; entry: Record<string, unknown> };
618
+
619
+ /** This simulator as an entry of `xcrun simctl list devices --json`. */
620
+ function simctlDevice(info: DeviceInfo): SimctlDevice {
621
+ const version = (info.osVersion ?? '26.0').replace(/\./g, '-');
622
+ return {
623
+ runtime: `com.apple.CoreSimulator.SimRuntime.iOS-${version}`,
624
+ entry: {
625
+ udid: info.udid,
626
+ name: info.model,
627
+ state: 'Booted',
628
+ isAvailable: true,
629
+ deviceTypeIdentifier: `com.apple.CoreSimulator.SimDeviceType.${info.model.replace(
630
+ /[^A-Za-z0-9]+/g,
631
+ '-',
632
+ )}`,
633
+ },
634
+ };
635
+ }
636
+
637
+ // Argent execs this for every simctl call. It handles this simulator and hands
638
+ // every other call to the real xcrun, so local simulators and devices keep
639
+ // working beside the remote one. The Go SDK embeds the same script as
640
+ // websocket/ios/shim/argent-xcrun.js; keep the two identical.
641
+ const ARGENT_XCRUN_SHIM = `#!/usr/bin/env node
642
+ const fs = require('node:fs');
643
+ const http = require('node:http');
644
+ const net = require('node:net');
645
+ const { spawnSync } = require('node:child_process');
646
+
647
+ const bridgeUrl = process.env.LIMRUN_ARGENT_BRIDGE_URL;
648
+ const device = JSON.parse(process.env.LIMRUN_ARGENT_DEVICE || 'null');
649
+ const udid = device.entry.udid;
650
+ const realXcrun = process.env.LIMRUN_REAL_XCRUN || '/usr/bin/xcrun';
651
+ const hasRealXcrun = fs.existsSync(realXcrun);
652
+ const args = process.argv.slice(2);
653
+
654
+ function delegate() {
655
+ if (!hasRealXcrun) {
656
+ process.stderr.write('limrun xcrun shim: unsupported without Xcode: xcrun ' + args.join(' ') + '\\n');
657
+ process.exit(127);
658
+ }
659
+ const result = spawnSync(realXcrun, args, { stdio: 'inherit' });
660
+ process.exit(result.status ?? 1);
661
+ }
662
+
663
+ function post(route, body) {
664
+ return new Promise((resolve, reject) => {
665
+ const payload = JSON.stringify(body);
666
+ const req = http.request(bridgeUrl + route, {
667
+ method: 'POST',
668
+ headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(payload) },
669
+ }, (res) => {
670
+ const chunks = [];
671
+ res.on('data', (chunk) => chunks.push(chunk));
672
+ res.on('end', () => {
673
+ try {
674
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
675
+ } catch (error) {
676
+ reject(error);
677
+ }
678
+ });
679
+ });
680
+ req.on('error', reject);
681
+ req.end(payload);
682
+ });
683
+ }
684
+
685
+ // \\\`simctl list devices --json\\\`: the local simulators plus the remote one.
686
+ function listDevices() {
687
+ let listing = { devices: {} };
688
+ if (hasRealXcrun) {
689
+ const real = spawnSync(realXcrun, args, { encoding: 'utf8' });
690
+ try {
691
+ listing = JSON.parse(real.stdout);
692
+ } catch {}
693
+ }
694
+ listing.devices = listing.devices || {};
695
+ listing.devices[device.runtime] = [...(listing.devices[device.runtime] || []), device.entry];
696
+ process.stdout.write(JSON.stringify(listing) + '\\n');
697
+ process.exit(0);
698
+ }
699
+
700
+ // Argent listens on a socket and spawns its accessibility daemon, which dials
701
+ // in. This process takes the daemon's place and answers from the bridge.
702
+ function accessibilityDaemon(endpoint) {
703
+ const socket = net.connect(endpoint);
704
+ let buffered = '';
705
+ socket.on('data', (chunk) => {
706
+ buffered += chunk.toString('utf8');
707
+ let end;
708
+ while ((end = buffered.indexOf('\\n')) >= 0) {
709
+ const line = buffered.slice(0, end).trim();
710
+ buffered = buffered.slice(end + 1);
711
+ if (!line) continue;
712
+ const { id, command, params } = JSON.parse(line);
713
+ post('/ax', { command, params })
714
+ .catch((error) => ({ error: String(error.message || error) }))
715
+ .then((reply) => socket.write(JSON.stringify({ id, ...reply }) + '\\n'));
716
+ }
717
+ });
718
+ socket.on('close', () => process.exit(0));
719
+ socket.on('error', (error) => {
720
+ process.stderr.write('limrun xcrun shim: ' + error.message + '\\n');
721
+ process.exit(1);
722
+ });
723
+ }
724
+
725
+ function main() {
726
+ if (args[0] !== 'simctl') return delegate();
727
+ // Argent scopes simctl to a device set; the remote simulator has none here.
728
+ const simctlArgs = args[1] === '--set' ? args.slice(3) : args.slice(1);
729
+ const command = simctlArgs[0];
730
+ const wantsJson = simctlArgs.includes('--json') || simctlArgs.includes('-j');
731
+ if (command === 'list' && simctlArgs[1] === 'devices' && wantsJson) return listDevices();
732
+ if (!simctlArgs.includes(udid)) return delegate();
733
+
734
+ if (command === 'spawn' && /(^|\\/)ax-service$/.test(simctlArgs[2] || '')) {
735
+ const socketAt = simctlArgs.indexOf('--socket');
736
+ const portAt = simctlArgs.indexOf('--port');
737
+ if (socketAt > 0) return accessibilityDaemon({ path: simctlArgs[socketAt + 1] });
738
+ if (portAt > 0) return accessibilityDaemon({ host: '127.0.0.1', port: Number(simctlArgs[portAt + 1]) });
739
+ }
740
+ post('/xcrun', { args: simctlArgs }).then((result) => {
741
+ if (result.stdout) process.stdout.write(result.stdout);
742
+ if (result.stderr) process.stderr.write(result.stderr);
743
+ process.exit(typeof result.code === 'number' ? result.code : 1);
744
+ }, (error) => {
745
+ process.stderr.write('limrun xcrun shim: ' + error.message + '\\n');
746
+ process.exit(1);
747
+ });
748
+ }
749
+
750
+ main();
751
+ `;
752
+
753
+ function xcrunShimSource(options: { baseUrl: string; device: SimctlDevice }): string {
754
+ return ARGENT_XCRUN_SHIM.replace(
755
+ 'const bridgeUrl = process.env.LIMRUN_ARGENT_BRIDGE_URL;',
756
+ `const bridgeUrl = ${JSON.stringify(options.baseUrl)};`,
757
+ ).replace(
758
+ "const device = JSON.parse(process.env.LIMRUN_ARGENT_DEVICE || 'null');",
759
+ `const device = ${JSON.stringify(options.device)};`,
760
+ );
761
+ }
762
+
763
+ function asError(error: unknown): Error {
764
+ return error instanceof Error ? error : new Error(String(error));
765
+ }
766
+
767
+ function readJson(req: IncomingMessage): Promise<unknown> {
768
+ return new Promise((resolve, reject) => {
769
+ const chunks: Buffer[] = [];
770
+ req.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
771
+ req.on('end', () => {
772
+ try {
773
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'));
774
+ } catch (error) {
775
+ reject(error);
776
+ }
777
+ });
778
+ req.on('error', reject);
779
+ });
780
+ }
781
+
782
+ function sendJson(res: ServerResponse, statusCode: number, payload: unknown): void {
783
+ const body = JSON.stringify(payload);
784
+ res.writeHead(statusCode, {
785
+ 'content-type': 'application/json',
786
+ 'content-length': Buffer.byteLength(body),
787
+ });
788
+ res.end(body);
789
+ }