@phren/cli 0.3.57 → 0.3.59
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 +1 -1
- package/dist/bridge/account-add.d.ts +30 -0
- package/dist/bridge/account-add.js +125 -19
- package/dist/bridge/account-failover.d.ts +9 -2
- package/dist/bridge/account-failover.js +1 -1
- package/dist/bridge/account-policy.d.ts +44 -0
- package/dist/bridge/account-policy.js +103 -0
- package/dist/bridge/account-pools.d.ts +35 -0
- package/dist/bridge/account-pools.js +171 -0
- package/dist/bridge/account-usage.d.ts +18 -0
- package/dist/bridge/account-usage.js +57 -1
- package/dist/bridge/agent-hook-callback.d.ts +6 -0
- package/dist/bridge/agent-hook-callback.js +10 -2
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +13 -0
- package/dist/bridge/agent-hooks.d.ts +12 -2
- package/dist/bridge/agent-hooks.js +41 -4
- package/dist/bridge/claude-account-setup.d.ts +16 -0
- package/dist/bridge/claude-account-setup.js +46 -2
- package/dist/bridge/claude-accounts.d.ts +9 -0
- package/dist/bridge/claude-accounts.js +53 -15
- package/dist/bridge/claude-credits.d.ts +5 -1
- package/dist/bridge/claude-credits.js +37 -29
- package/dist/bridge/command.js +12 -3
- package/dist/bridge/computer-identity.d.ts +4 -2
- package/dist/bridge/computer-identity.js +7 -3
- package/dist/bridge/conductor-group.d.ts +1 -1
- package/dist/bridge/conductor-group.js +2 -2
- package/dist/bridge/conductor-sets.d.ts +6 -0
- package/dist/bridge/conductor-sets.js +8 -2
- package/dist/bridge/dispatch-command.js +22 -0
- package/dist/bridge/dispatch-returns.d.ts +23 -0
- package/dist/bridge/dispatch-returns.js +57 -0
- package/dist/bridge/dispatch.d.ts +26 -4
- package/dist/bridge/dispatch.js +100 -11
- package/dist/bridge/git-host-gitlab.js +2 -1
- package/dist/bridge/hand-off-queue.d.ts +71 -0
- package/dist/bridge/hand-off-queue.js +38 -0
- package/dist/bridge/harnesses.d.ts +12 -0
- package/dist/bridge/harnesses.js +20 -4
- package/dist/bridge/helper.d.ts +54 -0
- package/dist/bridge/helper.js +186 -0
- package/dist/bridge/herdr.js +6 -2
- package/dist/bridge/hook-fast.d.ts +3 -0
- package/dist/bridge/hook-fast.js +10 -2
- package/dist/bridge/move-computers.d.ts +15 -1
- package/dist/bridge/move-computers.js +123 -26
- package/dist/bridge/prompt-deliveries.d.ts +29 -1
- package/dist/bridge/prompt-deliveries.js +146 -10
- package/dist/bridge/schedule-watch.js +17 -3
- package/dist/bridge/server-routes.d.ts +4 -0
- package/dist/bridge/server-routes.js +66 -6
- package/dist/bridge/server.js +8 -2
- package/dist/bridge/session-move.d.ts +59 -1
- package/dist/bridge/session-move.js +266 -18
- package/dist/bridge/simulator-stream.d.ts +118 -0
- package/dist/bridge/simulator-stream.js +284 -0
- package/dist/bridge/simulators.d.ts +31 -0
- package/dist/bridge/simulators.js +126 -40
- package/dist/bridge/speech-live.js +132 -22
- package/dist/bridge/task-routes.d.ts +16 -16
- package/dist/bridge/terminal-herdr.js +6 -1
- package/dist/bridge/terminal-tmux.js +9 -5
- package/dist/bridge/terminal.d.ts +9 -2
- package/dist/bridge/transcript-claude.d.ts +3 -0
- package/dist/bridge/transcript-claude.js +175 -29
- package/dist/bridge/transcript-preview.d.ts +11 -2
- package/dist/bridge/transcript-preview.js +90 -8
- package/dist/bridge/turn-records.d.ts +19 -0
- package/dist/bridge/turn-records.js +78 -3
- package/dist/bridge-hook.mjs +12129 -10324
- package/dist/cli-registry.js +2 -2
- package/dist/content/citation.d.ts +4 -0
- package/dist/content/citation.js +21 -21
- package/dist/data/task-contract.d.ts +4 -4
- package/dist/governance/policy.js +5 -2
- package/dist/index.js +1 -1
- package/dist/modules/registry.js +4 -4
- package/dist/project-config.d.ts +14 -0
- package/dist/project-config.js +40 -1
- package/dist/tools/helper.d.ts +3 -0
- package/dist/tools/helper.js +44 -0
- package/package.json +1 -1
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { spawn as spawnChild } from "node:child_process";
|
|
2
|
+
import { BridgeError } from "./protocol.js";
|
|
3
|
+
import { bootedSimulators, SIMULATOR_UDID, verifiedHelper } from "./simulators.js";
|
|
4
|
+
/**
|
|
5
|
+
* `WS /v1/simulators/stream?udid=&fps=&size=&quality=`: one booted
|
|
6
|
+
* simulator's screen, live. The native helper (native/simcast.swift) reads the
|
|
7
|
+
* device's framebuffer through CoreSimulator, as `simctl io` does, and writes
|
|
8
|
+
* each changed frame as a length-prefixed JPEG; this side forwards them.
|
|
9
|
+
*
|
|
10
|
+
* Why JPEG frames from the framebuffer, not the alternatives:
|
|
11
|
+
* - `simctl io screenshot` took about 1.1 s a shot (Xcode 27.1, M1 Max),
|
|
12
|
+
* which is today's 1 fps poll and no more.
|
|
13
|
+
* - `simctl io recordVideo` writes a QuickTime movie that is only readable
|
|
14
|
+
* once finalized, so it cannot feed a live socket.
|
|
15
|
+
* - ScreenCaptureKit on the Simulator window needs a Screen Recording grant
|
|
16
|
+
* (which macOS re-asks for monthly), captures the window chrome, and stops
|
|
17
|
+
* when the window is minimized; the framebuffer needs no grant.
|
|
18
|
+
* - H.264 halves the bytes but ties frames together: a dropped frame corrupts
|
|
19
|
+
* the picture until the next keyframe, so "always the latest frame" would
|
|
20
|
+
* need keyframe requests across the socket. Every JPEG stands alone, so a
|
|
21
|
+
* frame the phone can't take yet is simply replaced by the next one.
|
|
22
|
+
* - The helper sends only frames whose framebuffer changed (its IOSurface
|
|
23
|
+
* seed moved): a still screen costs nothing on the wire.
|
|
24
|
+
*
|
|
25
|
+
* Frames: a text `{ type: "start", format: "jpeg", fps, size, quality, ack }`,
|
|
26
|
+
* then one binary message per frame, each a whole JPEG. A phone that asks
|
|
27
|
+
* with `ack=1` sends `{ type: "ack" }` for each frame it receives, and at
|
|
28
|
+
* most two frames are unacknowledged: the SSH channel and TCP buffers between
|
|
29
|
+
* here and the phone then never hold more than that, so what the phone shows
|
|
30
|
+
* is at most two frames old however slow the link. Without it, a frame is
|
|
31
|
+
* done once written to the gateway's socket. When the stream
|
|
32
|
+
* ends, the socket closes with the reason (1008 for a bad request, 1011 when
|
|
33
|
+
* capture failed); the phone then falls back to `/v1/simulators/screenshot`.
|
|
34
|
+
* Closing the socket stops the helper. Taps and keys stay on
|
|
35
|
+
* `/v1/simulators/action`.
|
|
36
|
+
*/
|
|
37
|
+
/** A JPEG larger than this is a broken helper, not a frame. */
|
|
38
|
+
export const MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
39
|
+
/** The wire budget: about 24 Mbit/s, so animations at full rate on Wi-Fi, and
|
|
40
|
+
* the phone asks for a smaller `size` on a slower link. */
|
|
41
|
+
export const STREAM_BYTES_PER_SECOND = 3 * 1024 * 1024;
|
|
42
|
+
/** Each stream runs its own helper; a few phones may watch at once. */
|
|
43
|
+
export const MAX_STREAMS = 4;
|
|
44
|
+
const OPEN = 1;
|
|
45
|
+
/** Frames in flight when the phone acknowledges them: one decoding on the
|
|
46
|
+
* phone while the next crosses the network. */
|
|
47
|
+
export const ACK_WINDOW = 2;
|
|
48
|
+
/** The query, validated before anything runs. */
|
|
49
|
+
export function streamOptions(query) {
|
|
50
|
+
const udid = query.get("udid") ?? "";
|
|
51
|
+
if (!SIMULATOR_UDID.test(udid))
|
|
52
|
+
throw new BridgeError(400, "Invalid simulator identifier.");
|
|
53
|
+
const int = (name, fallback, min, max) => {
|
|
54
|
+
const raw = query.get(name);
|
|
55
|
+
if (raw === null)
|
|
56
|
+
return fallback;
|
|
57
|
+
if (!/^\d{1,5}$/.test(raw) || Number(raw) < min || Number(raw) > max)
|
|
58
|
+
throw new BridgeError(400, `${name} must be a whole number from ${min} to ${max}.`);
|
|
59
|
+
return Number(raw);
|
|
60
|
+
};
|
|
61
|
+
// size is the longest side in pixels; quality is the JPEG quality in percent.
|
|
62
|
+
const ack = query.get("ack");
|
|
63
|
+
if (ack !== null && ack !== "1" && ack !== "0")
|
|
64
|
+
throw new BridgeError(400, "ack must be 1 or 0.");
|
|
65
|
+
return { udid: udid.toUpperCase(), fps: int("fps", 24, 1, 30), size: int("size", 1280, 240, 1600), quality: int("quality", 60, 30, 90), ack: ack === "1" };
|
|
66
|
+
}
|
|
67
|
+
/** Splits the helper's stdout into frames: a 4-byte big-endian length, then
|
|
68
|
+
* that many bytes. Pipes deliver arbitrary chunks, so a frame may span many. */
|
|
69
|
+
export class FrameReader {
|
|
70
|
+
buffered = [];
|
|
71
|
+
bytes = 0;
|
|
72
|
+
push(chunk) {
|
|
73
|
+
this.buffered.push(chunk);
|
|
74
|
+
this.bytes += chunk.length;
|
|
75
|
+
const frames = [];
|
|
76
|
+
while (this.bytes >= 4) {
|
|
77
|
+
const head = this.buffered[0].length >= 4 ? this.buffered[0] : Buffer.concat(this.buffered);
|
|
78
|
+
const length = head.readUInt32BE(0);
|
|
79
|
+
if (length === 0 || length > MAX_FRAME_BYTES)
|
|
80
|
+
throw new Error(`frame of ${length} bytes`);
|
|
81
|
+
if (this.bytes < 4 + length)
|
|
82
|
+
break;
|
|
83
|
+
const all = this.buffered.length === 1 ? this.buffered[0] : Buffer.concat(this.buffered);
|
|
84
|
+
frames.push(all.subarray(4, 4 + length));
|
|
85
|
+
const rest = all.subarray(4 + length);
|
|
86
|
+
this.buffered = rest.length ? [rest] : [];
|
|
87
|
+
this.bytes = rest.length;
|
|
88
|
+
}
|
|
89
|
+
return frames;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Sends the newest frame only. At most `window` frames are in flight (until
|
|
93
|
+
* written, or until acknowledged when `acked`); frames that arrive meanwhile
|
|
94
|
+
* replace the one waiting, so a slow link sees fewer frames, never older
|
|
95
|
+
* ones. A byte budget, refilled continuously with one second of burst, bounds
|
|
96
|
+
* the bitrate the same way. */
|
|
97
|
+
export class LatestFrame {
|
|
98
|
+
send;
|
|
99
|
+
options;
|
|
100
|
+
now;
|
|
101
|
+
waiting;
|
|
102
|
+
inFlight = 0;
|
|
103
|
+
tokens;
|
|
104
|
+
refilled;
|
|
105
|
+
timer;
|
|
106
|
+
closed = false;
|
|
107
|
+
sent = 0;
|
|
108
|
+
dropped = 0;
|
|
109
|
+
constructor(send, options = {}, now = Date.now) {
|
|
110
|
+
this.send = send;
|
|
111
|
+
this.options = options;
|
|
112
|
+
this.now = now;
|
|
113
|
+
this.tokens = this.bytesPerSecond;
|
|
114
|
+
this.refilled = now();
|
|
115
|
+
}
|
|
116
|
+
offer(frame) {
|
|
117
|
+
if (this.closed)
|
|
118
|
+
return;
|
|
119
|
+
if (this.waiting)
|
|
120
|
+
this.dropped++;
|
|
121
|
+
this.waiting = frame;
|
|
122
|
+
this.pump();
|
|
123
|
+
}
|
|
124
|
+
/** The phone has a frame; an acknowledgement it owes nothing for is ignored. */
|
|
125
|
+
ack() {
|
|
126
|
+
if (!this.options.acked || this.inFlight === 0)
|
|
127
|
+
return;
|
|
128
|
+
this.inFlight--;
|
|
129
|
+
this.pump();
|
|
130
|
+
}
|
|
131
|
+
close() { this.closed = true; this.waiting = undefined; clearTimeout(this.timer); }
|
|
132
|
+
get bytesPerSecond() { return this.options.bytesPerSecond ?? STREAM_BYTES_PER_SECOND; }
|
|
133
|
+
pump() {
|
|
134
|
+
if (this.closed || this.inFlight >= (this.options.window ?? 1) || !this.waiting || this.timer)
|
|
135
|
+
return;
|
|
136
|
+
const now = this.now();
|
|
137
|
+
this.tokens = Math.min(this.bytesPerSecond, this.tokens + (now - this.refilled) * this.bytesPerSecond / 1000);
|
|
138
|
+
this.refilled = now;
|
|
139
|
+
if (this.tokens < 0) {
|
|
140
|
+
// Over budget: the frame waits (and may be replaced) until it refills.
|
|
141
|
+
this.timer = setTimeout(() => { this.timer = undefined; this.pump(); }, Math.ceil(-this.tokens * 1000 / this.bytesPerSecond));
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const frame = this.waiting;
|
|
145
|
+
this.waiting = undefined;
|
|
146
|
+
this.inFlight++;
|
|
147
|
+
this.tokens -= frame.length;
|
|
148
|
+
this.send(frame, error => {
|
|
149
|
+
if (error) {
|
|
150
|
+
this.close();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
this.sent++;
|
|
154
|
+
if (this.options.acked)
|
|
155
|
+
return;
|
|
156
|
+
this.inFlight--;
|
|
157
|
+
this.pump();
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const defaultDeps = {
|
|
162
|
+
booted: bootedSimulators,
|
|
163
|
+
helper: () => verifiedHelper("simcast"),
|
|
164
|
+
spawn: (binary, args) => spawnChild(binary, args, { stdio: ["ignore", "pipe", "pipe"] }),
|
|
165
|
+
platform: () => process.platform,
|
|
166
|
+
};
|
|
167
|
+
let active = 0;
|
|
168
|
+
/** Streams running now, for tests and health. */
|
|
169
|
+
export function activeSimulatorStreams() { return active; }
|
|
170
|
+
/** WebSocket close reasons are at most 123 bytes. */
|
|
171
|
+
function reason(text) { return Buffer.from(text).subarray(0, 120).toString("utf8").replace(/�+$/, ""); }
|
|
172
|
+
export async function streamSimulator(client, query, deps = defaultDeps) {
|
|
173
|
+
let options;
|
|
174
|
+
try {
|
|
175
|
+
options = streamOptions(query);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
client.close(1008, reason(error.message));
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (deps.platform() !== "darwin") {
|
|
182
|
+
client.close(1008, "Simulators run on macOS only.");
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (active >= MAX_STREAMS) {
|
|
186
|
+
client.close(1013, "Too many simulator streams; try again.");
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
// The slot is held until the work it pays for is over: discovery and the
|
|
190
|
+
// build still running after the socket closed, and a helper that takes up
|
|
191
|
+
// to 2 s to exit. Releasing it on close would let connect-close cycles pile
|
|
192
|
+
// up simctl and helper processes past MAX_STREAMS.
|
|
193
|
+
active++;
|
|
194
|
+
let released = false;
|
|
195
|
+
const release = () => { if (!released) {
|
|
196
|
+
released = true;
|
|
197
|
+
active--;
|
|
198
|
+
} };
|
|
199
|
+
let ended = false, child, killer;
|
|
200
|
+
const latest = new LatestFrame((frame, done) => {
|
|
201
|
+
if (client.readyState !== OPEN) {
|
|
202
|
+
done(new Error("closed"));
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
client.send(frame, { binary: true }, done);
|
|
206
|
+
}, { bytesPerSecond: deps.bytesPerSecond, window: options.ack ? ACK_WINDOW : 1, acked: options.ack });
|
|
207
|
+
client.on("message", (data, isBinary) => {
|
|
208
|
+
if (isBinary || data.length > 64)
|
|
209
|
+
return;
|
|
210
|
+
try {
|
|
211
|
+
if (JSON.parse(data.toString("utf8")).type === "ack")
|
|
212
|
+
latest.ack();
|
|
213
|
+
}
|
|
214
|
+
catch { /* not ours */ }
|
|
215
|
+
});
|
|
216
|
+
const end = (code, why) => {
|
|
217
|
+
if (ended)
|
|
218
|
+
return;
|
|
219
|
+
ended = true;
|
|
220
|
+
latest.close();
|
|
221
|
+
if (child) {
|
|
222
|
+
const running = child;
|
|
223
|
+
running.kill("SIGTERM");
|
|
224
|
+
// A helper stuck in CoreSimulator still goes.
|
|
225
|
+
killer = setTimeout(() => running.kill("SIGKILL"), 2_000);
|
|
226
|
+
killer.unref?.();
|
|
227
|
+
running.once("exit", () => clearTimeout(killer));
|
|
228
|
+
}
|
|
229
|
+
if (code !== undefined && client.readyState === OPEN)
|
|
230
|
+
client.close(code, reason(why ?? "Simulator stream ended."));
|
|
231
|
+
};
|
|
232
|
+
client.once("close", () => end());
|
|
233
|
+
client.once("error", () => end());
|
|
234
|
+
try {
|
|
235
|
+
if (!(await deps.booted()).some(device => device.udid === options.udid)) {
|
|
236
|
+
end(1008, "That simulator is not booted.");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
// A socket that closed during discovery doesn't go on to build the helper.
|
|
240
|
+
if (ended || client.readyState !== OPEN) {
|
|
241
|
+
end();
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
const binary = await deps.helper();
|
|
245
|
+
if (ended || client.readyState !== OPEN) {
|
|
246
|
+
end();
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
child = deps.spawn(binary, [options.udid, String(options.fps), String(options.size), (options.quality / 100).toFixed(2)]);
|
|
250
|
+
child.once("exit", release);
|
|
251
|
+
child.once("error", release);
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
end(1011, error instanceof BridgeError ? error.message : "Couldn't start the simulator stream.");
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
if (!child)
|
|
259
|
+
release();
|
|
260
|
+
}
|
|
261
|
+
const reader = new FrameReader();
|
|
262
|
+
let stderr = "";
|
|
263
|
+
child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString("utf8")).slice(-400); });
|
|
264
|
+
child.stdout?.on("data", (chunk) => {
|
|
265
|
+
if (ended)
|
|
266
|
+
return;
|
|
267
|
+
let frames;
|
|
268
|
+
try {
|
|
269
|
+
frames = reader.push(chunk);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
end(1011, "The simulator stream sent a broken frame.");
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
for (const frame of frames)
|
|
276
|
+
latest.offer(frame);
|
|
277
|
+
});
|
|
278
|
+
child.once("error", () => end(1011, "Couldn't start the simulator stream."));
|
|
279
|
+
child.once("exit", () => {
|
|
280
|
+
const last = stderr.trim().split("\n").at(-1);
|
|
281
|
+
end(1011, last ? `Simulator stream ended: ${last}` : "Simulator stream ended.");
|
|
282
|
+
});
|
|
283
|
+
client.send(JSON.stringify({ type: "start", format: "jpeg", fps: options.fps, size: options.size, quality: options.quality, ack: options.ack }), { binary: false });
|
|
284
|
+
}
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import { type Json } from "./protocol.js";
|
|
2
|
+
export declare const SIMULATOR_UDID: RegExp;
|
|
2
3
|
/** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */
|
|
3
4
|
export declare function bootedSimulators(): Promise<Json[]>;
|
|
5
|
+
/** Most devices `GET /v1/simulators?all=1` lists. */
|
|
6
|
+
export declare const SIMULATOR_DEVICE_LIMIT = 64;
|
|
7
|
+
/**
|
|
8
|
+
* Every iOS simulator this Mac can run (`simctl list devices available`), booted or not, with its `state`
|
|
9
|
+
* (`Booted`, `Shutdown`, `Booting`, `Shutting Down`): booted ones first, then the newest runtime, then by
|
|
10
|
+
* name, at most SIMULATOR_DEVICE_LIMIT. For the phone's device picker, which boots one from here.
|
|
11
|
+
*/
|
|
12
|
+
export declare function simulatorDevices(): Promise<Json[]>;
|
|
4
13
|
/** A PNG of one booted simulator's screen. */
|
|
5
14
|
export declare function simulatorScreenshot(udid: string): Promise<Buffer>;
|
|
6
15
|
/** What the phone may ask a simulator to do. Boot, shutdown, launch and
|
|
@@ -18,11 +27,33 @@ export type SimulatorAction = {
|
|
|
18
27
|
action: "tap";
|
|
19
28
|
x: number;
|
|
20
29
|
y: number;
|
|
30
|
+
}
|
|
31
|
+
/** A swipe or scroll: press at (x1, y1), move to (x2, y2) over `durationMs` (default 300), release. */
|
|
32
|
+
| {
|
|
33
|
+
action: "drag";
|
|
34
|
+
x1: number;
|
|
35
|
+
y1: number;
|
|
36
|
+
x2: number;
|
|
37
|
+
y2: number;
|
|
38
|
+
durationMs?: number;
|
|
21
39
|
} | {
|
|
22
40
|
action: "type";
|
|
23
41
|
text: string;
|
|
24
42
|
submit?: boolean;
|
|
25
43
|
};
|
|
44
|
+
/** A drag's duration bounds, in ms. */
|
|
45
|
+
export declare const DRAG_DEFAULT_MS = 300, DRAG_MIN_MS = 50, DRAG_MAX_MS = 5000;
|
|
46
|
+
/** The native helpers, compiled once per Hook version with swiftc, which any
|
|
47
|
+
* Mac with the simulators has. simtap (native/simtap.swift) finds the
|
|
48
|
+
* Simulator window through the Accessibility API and posts touches and keys
|
|
49
|
+
* with CGEvent. AppleScript would need Automation consent, which a launchd
|
|
50
|
+
* agent can never be prompted for; the helper needs one Accessibility grant.
|
|
51
|
+
* Its `prompt` command puts it in the Accessibility list and shows the system
|
|
52
|
+
* dialog. simcast (native/simcast.swift) streams a simulator's framebuffer
|
|
53
|
+
* for simulator-stream.ts and needs no grant. */
|
|
54
|
+
export type NativeHelper = "simtap" | "simcast";
|
|
55
|
+
/** A helper, hashed again right before it runs. */
|
|
56
|
+
export declare function verifiedHelper(name?: NativeHelper): Promise<string>;
|
|
26
57
|
/** The steps for the Accessibility grant, for the 403 and the docs. */
|
|
27
58
|
export declare function accessibilityHelp(binary: string): string;
|
|
28
59
|
export declare function simulatorAct(udid: string, request: SimulatorAction): Promise<Json>;
|
|
@@ -5,26 +5,37 @@ import path from "node:path";
|
|
|
5
5
|
import { createHash, randomUUID } from "node:crypto";
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
7
|
import { BridgeError, bridgeRoot } from "./protocol.js";
|
|
8
|
-
const
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
/** Every simulator child is killed outright at its timeout. SIGTERM, the
|
|
10
|
+
* default, let one that ignored it hold its promise, and with it a stream's
|
|
11
|
+
* slot, for good. */
|
|
12
|
+
const exec = (file, args, options) => execFileAsync(file, args, { ...options, killSignal: "SIGKILL", encoding: "utf8" });
|
|
13
|
+
export const SIMULATOR_UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
14
|
+
/** `simctl list devices [filter] -j`, parsed (every device without a filter); undefined when simctl failed, timed
|
|
15
|
+
* out or answered nonsense. */
|
|
16
|
+
async function listDevices(filter) {
|
|
17
|
+
const listed = await exec("/usr/bin/xcrun", ["simctl", "list", "devices", ...(filter ? [filter] : []), "-j"], { timeout: 8_000, maxBuffer: 8_388_608 }).catch(() => undefined);
|
|
18
|
+
if (!listed)
|
|
19
|
+
return undefined;
|
|
16
20
|
try {
|
|
17
|
-
|
|
21
|
+
return JSON.parse(listed.stdout);
|
|
18
22
|
}
|
|
19
23
|
catch {
|
|
20
|
-
return
|
|
24
|
+
return undefined;
|
|
21
25
|
}
|
|
26
|
+
}
|
|
27
|
+
/** com.apple.CoreSimulator.SimRuntime.iOS-26-1 → iOS 26.1 */
|
|
28
|
+
const runtimeName = (runtimeID) => runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
|
|
29
|
+
/** The iOS simulators booted on this Mac, from `simctl`; none elsewhere. */
|
|
30
|
+
export async function bootedSimulators() {
|
|
31
|
+
if (process.platform !== "darwin")
|
|
32
|
+
return [];
|
|
33
|
+
const parsed = await listDevices("booted") ?? {};
|
|
22
34
|
const list = [];
|
|
23
35
|
for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
|
|
24
|
-
|
|
25
|
-
const runtime = runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
|
|
36
|
+
const runtime = runtimeName(runtimeID);
|
|
26
37
|
for (const device of devices ?? []) {
|
|
27
|
-
if (device.state !== "Booted" || !device.udid || !
|
|
38
|
+
if (device.state !== "Booted" || !device.udid || !SIMULATOR_UDID.test(device.udid))
|
|
28
39
|
continue;
|
|
29
40
|
list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime });
|
|
30
41
|
if (list.length >= 16)
|
|
@@ -33,9 +44,49 @@ export async function bootedSimulators() {
|
|
|
33
44
|
}
|
|
34
45
|
return list;
|
|
35
46
|
}
|
|
47
|
+
/** Most devices `GET /v1/simulators?all=1` lists. */
|
|
48
|
+
export const SIMULATOR_DEVICE_LIMIT = 64;
|
|
49
|
+
/**
|
|
50
|
+
* Every iOS simulator this Mac can run (`simctl list devices available`), booted or not, with its `state`
|
|
51
|
+
* (`Booted`, `Shutdown`, `Booting`, `Shutting Down`): booted ones first, then the newest runtime, then by
|
|
52
|
+
* name, at most SIMULATOR_DEVICE_LIMIT. For the phone's device picker, which boots one from here.
|
|
53
|
+
*/
|
|
54
|
+
export async function simulatorDevices() {
|
|
55
|
+
if (process.platform !== "darwin")
|
|
56
|
+
return [];
|
|
57
|
+
const parsed = await listDevices("available") ?? {};
|
|
58
|
+
const list = [];
|
|
59
|
+
for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
|
|
60
|
+
if (!/SimRuntime\.iOS-/.test(runtimeID))
|
|
61
|
+
continue;
|
|
62
|
+
const version = (/iOS-(\d+)-(\d+)/.exec(runtimeID) ?? []).slice(1).map(Number);
|
|
63
|
+
for (const device of devices ?? []) {
|
|
64
|
+
if (device.isAvailable === false || !device.udid || !SIMULATOR_UDID.test(device.udid))
|
|
65
|
+
continue;
|
|
66
|
+
const state = typeof device.state === "string" && /^[A-Za-z ]{1,32}$/.test(device.state) ? device.state : "Unknown";
|
|
67
|
+
list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime: runtimeName(runtimeID), state, version });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const newer = (a, b) => (b[0] ?? 0) - (a[0] ?? 0) || (b[1] ?? 0) - (a[1] ?? 0);
|
|
71
|
+
return list.sort((a, b) => Number(b.state === "Booted") - Number(a.state === "Booted") || newer(a.version, b.version) || a.name.localeCompare(b.name))
|
|
72
|
+
.slice(0, SIMULATOR_DEVICE_LIMIT).map(({ version: _version, ...device }) => device);
|
|
73
|
+
}
|
|
74
|
+
/** A simulator's state as `simctl` reports it now, from every device it has (a booted device whose runtime is no
|
|
75
|
+
* longer available still shuts down): `missing` when simctl lists no such device, undefined when it couldn't say. */
|
|
76
|
+
async function deviceState(udid) {
|
|
77
|
+
const listed = await listDevices();
|
|
78
|
+
if (!listed)
|
|
79
|
+
return undefined;
|
|
80
|
+
for (const devices of Object.values(listed.devices ?? {})) {
|
|
81
|
+
const device = devices?.find(d => d.udid?.toUpperCase() === udid.toUpperCase());
|
|
82
|
+
if (device)
|
|
83
|
+
return String(device.state ?? "");
|
|
84
|
+
}
|
|
85
|
+
return "missing";
|
|
86
|
+
}
|
|
36
87
|
/** A PNG of one booted simulator's screen. */
|
|
37
88
|
export async function simulatorScreenshot(udid) {
|
|
38
|
-
if (!
|
|
89
|
+
if (!SIMULATOR_UDID.test(udid))
|
|
39
90
|
throw new BridgeError(400, "Invalid simulator identifier.");
|
|
40
91
|
if (process.platform !== "darwin")
|
|
41
92
|
throw new BridgeError(404, "Simulators run on macOS only.");
|
|
@@ -53,22 +104,26 @@ export async function simulatorScreenshot(udid) {
|
|
|
53
104
|
await unlink(file).catch(() => undefined);
|
|
54
105
|
}
|
|
55
106
|
}
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
return
|
|
67
|
-
}
|
|
68
|
-
async function
|
|
107
|
+
/** A drag's duration bounds, in ms. */
|
|
108
|
+
export const DRAG_DEFAULT_MS = 300, DRAG_MIN_MS = 50, DRAG_MAX_MS = 5_000;
|
|
109
|
+
const HELPER_LABEL = { simtap: "simulator input helper", simcast: "simulator stream helper" };
|
|
110
|
+
const building = new Map();
|
|
111
|
+
function helper(name) {
|
|
112
|
+
let build = building.get(name);
|
|
113
|
+
if (!build) {
|
|
114
|
+
build = buildHelper(name).finally(() => building.delete(name));
|
|
115
|
+
building.set(name, build);
|
|
116
|
+
}
|
|
117
|
+
return build;
|
|
118
|
+
}
|
|
119
|
+
async function helperSource(name) {
|
|
120
|
+
const bundled = name === "simtap" ? (typeof SIMTAP_SOURCE === "string" ? SIMTAP_SOURCE : undefined) : (typeof SIMCAST_SOURCE === "string" ? SIMCAST_SOURCE : undefined);
|
|
121
|
+
return bundled ?? await readFile(new URL(`./native/${name}.swift`, import.meta.url), "utf8");
|
|
122
|
+
}
|
|
123
|
+
async function buildHelper(name) {
|
|
69
124
|
const dir = path.join(bridgeRoot(), "native");
|
|
70
|
-
const binary = path.join(dir,
|
|
71
|
-
const code =
|
|
125
|
+
const binary = path.join(dir, name);
|
|
126
|
+
const code = await helperSource(name);
|
|
72
127
|
const digest = createHash("sha256").update(code).digest("hex");
|
|
73
128
|
// Rebuilt only when the source changes: the Accessibility grant is tied
|
|
74
129
|
// to this binary, and a needless rebuild would make macOS ask again.
|
|
@@ -76,12 +131,12 @@ async function buildHelper() {
|
|
|
76
131
|
if (await stat(binary).catch(() => undefined) && saved?.sourceSha === digest)
|
|
77
132
|
return binary;
|
|
78
133
|
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
79
|
-
const temporary = path.join(dir,
|
|
134
|
+
const temporary = path.join(dir, `${name}.${randomUUID()}`), source = temporary + ".swift";
|
|
80
135
|
const sidecar = temporary + ".sha256";
|
|
81
136
|
try {
|
|
82
137
|
await writeFile(source, code, { mode: 0o600, flag: "wx" });
|
|
83
138
|
await exec("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 180_000 }).catch(() => {
|
|
84
|
-
throw new BridgeError(409,
|
|
139
|
+
throw new BridgeError(409, `Couldn't build the ${HELPER_LABEL[name]} (needs Xcode's swiftc).`);
|
|
85
140
|
});
|
|
86
141
|
await chmod(temporary, 0o700);
|
|
87
142
|
const binarySha = createHash("sha256").update(await readFile(temporary)).digest("hex");
|
|
@@ -100,13 +155,13 @@ function simtap(name, ...args) {
|
|
|
100
155
|
inputQueue = task;
|
|
101
156
|
return task;
|
|
102
157
|
}
|
|
103
|
-
/**
|
|
104
|
-
async function verifiedHelper() {
|
|
105
|
-
const binary = await helper();
|
|
158
|
+
/** A helper, hashed again right before it runs. */
|
|
159
|
+
export async function verifiedHelper(name = "simtap") {
|
|
160
|
+
const binary = await helper(name);
|
|
106
161
|
const saved = await readFile(binary + ".sha256", "utf8").then(JSON.parse).catch(() => undefined);
|
|
107
162
|
const binarySha = createHash("sha256").update(await readFile(binary)).digest("hex");
|
|
108
163
|
if (!saved || saved.binarySha !== binarySha)
|
|
109
|
-
throw new BridgeError(409,
|
|
164
|
+
throw new BridgeError(409, `${HELPER_LABEL[name][0].toUpperCase()}${HELPER_LABEL[name].slice(1)} integrity check failed.`);
|
|
110
165
|
return binary;
|
|
111
166
|
}
|
|
112
167
|
async function executeSimtap(name, ...args) {
|
|
@@ -148,19 +203,39 @@ const ACCESSIBILITY_PANE = "x-apple.systempreferences:com.apple.preference.secur
|
|
|
148
203
|
// macOS virtual key codes.
|
|
149
204
|
const KEY_H = "4", KEY_L = "37";
|
|
150
205
|
export async function simulatorAct(udid, request) {
|
|
151
|
-
if (!
|
|
206
|
+
if (!SIMULATOR_UDID.test(udid))
|
|
152
207
|
throw new BridgeError(400, "Invalid simulator identifier.");
|
|
153
|
-
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request.action))
|
|
208
|
+
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "drag", "screenshot-ready", "accessibility-settings"].includes(request.action))
|
|
154
209
|
throw new BridgeError(400, "Unknown simulator action.");
|
|
155
210
|
if (process.platform !== "darwin")
|
|
156
211
|
throw new BridgeError(404, "Simulators run on macOS only.");
|
|
157
212
|
const simctl = (...args) => exec("/usr/bin/xcrun", ["simctl", ...args], { timeout: 30_000 }).catch(() => { throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`); });
|
|
213
|
+
// Boot and shutdown take any device, booted or not, and a device already in (or on its way to) the asked-for
|
|
214
|
+
// state is not a failure: the phone's picker may be a moment behind. A list that failed (simctl slow to start)
|
|
215
|
+
// is no reason to refuse; simctl itself then says.
|
|
216
|
+
const settle = async (verb, done) => {
|
|
217
|
+
const state = await deviceState(udid);
|
|
218
|
+
if (state === "missing")
|
|
219
|
+
throw new BridgeError(404, "No such simulator on this Mac.");
|
|
220
|
+
if (state !== undefined && done.includes(state))
|
|
221
|
+
return;
|
|
222
|
+
try {
|
|
223
|
+
await simctl(verb, udid);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
const now = await deviceState(udid);
|
|
227
|
+
if (now === undefined || !done.includes(now))
|
|
228
|
+
throw error;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
158
231
|
switch (request.action) {
|
|
159
232
|
case "boot":
|
|
160
|
-
await
|
|
233
|
+
await settle("boot", ["Booted", "Booting"]);
|
|
234
|
+
// Taps, drags and keys go to the device's window in the Simulator app, which booting alone doesn't open.
|
|
235
|
+
await exec("/usr/bin/open", ["-a", "Simulator", "--args", "-CurrentDeviceUDID", udid.toUpperCase()], { timeout: 15_000 }).catch(() => undefined);
|
|
161
236
|
break;
|
|
162
237
|
case "shutdown":
|
|
163
|
-
await
|
|
238
|
+
await settle("shutdown", ["Shutdown", "Shutting Down"]);
|
|
164
239
|
break;
|
|
165
240
|
case "launch":
|
|
166
241
|
if (typeof request.bundleId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9.-]{2,199}$/.test(request.bundleId))
|
|
@@ -193,6 +268,17 @@ export async function simulatorAct(udid, request) {
|
|
|
193
268
|
await simtap(await deviceName(udid), "tap", String(x), String(y));
|
|
194
269
|
break;
|
|
195
270
|
}
|
|
271
|
+
case "drag": {
|
|
272
|
+
// From and to are fractions of the screenshot, as a tap's are.
|
|
273
|
+
const { x1, y1, x2, y2 } = request, durationMs = request.durationMs ?? DRAG_DEFAULT_MS;
|
|
274
|
+
if (![x1, y1, x2, y2].every(v => typeof v === "number" && v >= 0 && v <= 1))
|
|
275
|
+
throw new BridgeError(400, "Drag outside the screen.");
|
|
276
|
+
if (typeof durationMs !== "number" || !Number.isInteger(durationMs) || durationMs < DRAG_MIN_MS || durationMs > DRAG_MAX_MS) {
|
|
277
|
+
throw new BridgeError(400, `A drag takes ${DRAG_MIN_MS} to ${DRAG_MAX_MS} ms.`);
|
|
278
|
+
}
|
|
279
|
+
await simtap(await deviceName(udid), "drag", String(x1), String(y1), String(x2), String(y2), String(durationMs));
|
|
280
|
+
break;
|
|
281
|
+
}
|
|
196
282
|
case "screenshot-ready": break;
|
|
197
283
|
case "accessibility-settings": {
|
|
198
284
|
// The phone's "Open Accessibility settings": ask for the grant again and
|
|
@@ -216,7 +302,7 @@ async function deviceName(udid) {
|
|
|
216
302
|
}
|
|
217
303
|
/** The apps a simulator has, for the launcher. */
|
|
218
304
|
export async function simulatorApps(udid) {
|
|
219
|
-
if (!
|
|
305
|
+
if (!SIMULATOR_UDID.test(udid))
|
|
220
306
|
throw new BridgeError(400, "Invalid simulator identifier.");
|
|
221
307
|
if (process.platform !== "darwin")
|
|
222
308
|
return [];
|