@0perator/operator 0.1.360-next.1 → 0.2.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.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/dist/autonomy/delegate-mode.js +159 -0
  3. package/dist/autonomy/delegate.js +1 -1
  4. package/dist/autonomy/session-factory.js +8 -2
  5. package/dist/background/index.js +26 -2
  6. package/dist/background/resume.js +125 -0
  7. package/dist/browser/engine.js +163 -0
  8. package/dist/browser/session.js +172 -134
  9. package/dist/cli.js +261 -70
  10. package/dist/config/settings.js +28 -7
  11. package/dist/config/skills-index.js +4 -0
  12. package/dist/engine/agent.js +1 -1
  13. package/dist/engine/aurora.js +22 -13
  14. package/dist/engine/compaction.js +1 -1
  15. package/dist/engine/moa.js +2 -1
  16. package/dist/engine/selfheal.js +1 -1
  17. package/dist/engine/speed-compaction.js +37 -0
  18. package/dist/engine/toolcalls.js +6 -6
  19. package/dist/gateway-cli.js +14 -5
  20. package/dist/index.js +3 -0
  21. package/dist/mcp/phone-server.js +30 -0
  22. package/dist/permissions/index.js +33 -17
  23. package/dist/permissions/signature.js +5 -0
  24. package/dist/phone-cli.js +65 -0
  25. package/dist/remote/host.js +31 -2
  26. package/dist/router/models.js +49 -25
  27. package/dist/selfimprove/index.js +1 -1
  28. package/dist/services/preflight.js +31 -8
  29. package/dist/session.js +96 -14
  30. package/dist/tools/deferred.js +1 -0
  31. package/dist/tools/device/android.js +227 -0
  32. package/dist/tools/device/classify.js +127 -0
  33. package/dist/tools/device/deps.js +69 -0
  34. package/dist/tools/device/desktop.js +82 -0
  35. package/dist/tools/device/harness.js +262 -0
  36. package/dist/tools/device/iphone.js +206 -0
  37. package/dist/tools/device/mirroring-jxa.js +146 -0
  38. package/dist/tools/device/setup.js +90 -0
  39. package/dist/tools/device/tools.js +70 -0
  40. package/dist/tools/device/types.js +19 -0
  41. package/dist/tools/registry.js +242 -48
  42. package/dist/tools/vision-media.js +162 -0
  43. package/dist/ui/App.js +4 -3
  44. package/dist/ui/ApprovalPrompt.js +10 -4
  45. package/dist/ui/BgPanel.js +2 -2
  46. package/dist/ui/UpdatePrompt.js +40 -0
  47. package/dist/ui/modelPicker.js +26 -8
  48. package/dist/ui/slashCommands.js +1 -0
  49. package/dist/update-check.js +134 -0
  50. package/dist/update.js +82 -13
  51. package/dist/util/slash.js +2 -2
  52. package/package.json +4 -2
  53. package/src/tools/device/NOTICE +37 -0
  54. package/dist/browser/cdp.js +0 -271
@@ -0,0 +1,262 @@
1
+ // The shared half of the device harness: which backend a call goes to, coordinate checks against the screenshot the
2
+ // model saw, the observe → act → verify loop (a fresh screenshot after every action), the one-shot grant a classed
3
+ // phone action needs, and an audit line per action. Backends (android.ts, iphone.ts, desktop.ts) never see a tool
4
+ // argument that has not been checked here.
5
+ import { operatorPath } from "../../config/home.js";
6
+ import { redactSecrets } from "../../engine/redact.js";
7
+ import { AndroidBackend } from "./android.js";
8
+ import { deviceOf, observe, phoneLine, PHONE_LINE_WHAT, setPhonePreview, takeGrant } from "./classify.js";
9
+ import { deviceDeps } from "./deps.js";
10
+ import { DesktopBackend } from "./desktop.js";
11
+ import { IphoneBackend } from "./iphone.js";
12
+ import { DEVICE_KEYS, NeedsOwner, Unsupported } from "./types.js";
13
+ const backends = new Map();
14
+ const shots = new Map();
15
+ const reads = new Map();
16
+ export function resetHarness() { backends.clear(); shots.clear(); reads.clear(); }
17
+ function iphoneDriver() {
18
+ const v = (process.env.KODE_PHONE_IPHONE_DRIVER ?? "").toLowerCase();
19
+ return v === "chauffeur" || v === "builtin" ? v : "auto";
20
+ }
21
+ function backendFor(id) {
22
+ let b = backends.get(id);
23
+ if (!b) {
24
+ b = id === "desktop" ? new DesktopBackend() : id === "iphone" ? new IphoneBackend(iphoneDriver()) : id === "android" ? new AndroidBackend() : new AndroidBackend(id);
25
+ backends.set(id, b);
26
+ }
27
+ return b;
28
+ }
29
+ /** Every backend this machine has, with its state — what phone_status and `operator phone setup` report. */
30
+ export async function scanDevices() {
31
+ const settle = async (id) => {
32
+ const b = backendFor(id);
33
+ try {
34
+ return await b.status();
35
+ }
36
+ catch (e) {
37
+ return { kind: b.kind, backend: id, state: "unreachable", detail: e instanceof Error ? e.message : String(e) };
38
+ }
39
+ };
40
+ return Promise.all(["android", "iphone", "desktop"].map(settle));
41
+ }
42
+ /** The backend a call goes to. `device` names one ("iphone", "android", "desktop", or an adb serial); without it,
43
+ * KODE_PHONE_DEVICE, else the one phone that is ready. The desktop is never picked for a phone without being named. */
44
+ export async function resolveDevice(device) {
45
+ const key = deviceOf({ device });
46
+ const named = typeof device === "string" && device.trim() ? device.trim() : process.env.KODE_PHONE_DEVICE?.trim();
47
+ if (named)
48
+ return { key, id: named, backend: backendFor(named) };
49
+ const [android, iphone] = await Promise.all([backendFor("android").status().catch(() => null), backendFor("iphone").status().catch(() => null)]);
50
+ const ready = [android, iphone].filter((s) => s?.state === "ready");
51
+ if (ready.length === 1)
52
+ return { key, id: ready[0].kind, backend: backendFor(ready[0].kind) };
53
+ if (ready.length > 1)
54
+ throw new NeedsOwner("an Android phone and an iPhone are both ready", 'pass device: "android" or device: "iphone"');
55
+ const why = [android, iphone].filter(Boolean).map((s) => `${s.kind}: ${s.detail}${s.fix ? ` — ${s.fix}` : ""}`).join("; ");
56
+ throw new NeedsOwner(`no phone is ready (${why || "nothing found"})`, "run `operator phone setup` for the checklist");
57
+ }
58
+ // ── Audit: one JSON line per phone action, whatever the permission mode ────────────────────────────────────────────
59
+ export function auditPath() { return process.env.KODE_DEVICE_AUDIT || operatorPath("audit", "device.jsonl"); }
60
+ /** The args as the trail keeps them: typed text by length only (it can be a password), everything else redacted. */
61
+ export function auditArgs(args) {
62
+ const out = {};
63
+ for (const [k, v] of Object.entries(args)) {
64
+ if (k === "text" && typeof v === "string")
65
+ out.text_chars = v.length;
66
+ else
67
+ out[k] = typeof v === "string" ? redactSecrets(v).slice(0, 200) : v;
68
+ }
69
+ return out;
70
+ }
71
+ async function audit(e) {
72
+ const d = deviceDeps();
73
+ const line = JSON.stringify({ ts: new Date(d.now()).toISOString(), ...e, args: auditArgs(e.args), detail: redactSecrets(e.detail).slice(0, 300) });
74
+ await d.appendFile(auditPath(), line + "\n").catch(() => { });
75
+ }
76
+ // ── Observe ─────────────────────────────────────────────────────────────────────────────────────────────────────────
77
+ async function capture(key, backend) {
78
+ const shot = await backend.screenshot();
79
+ shots.set(key, shot);
80
+ reads.delete(key);
81
+ return shot;
82
+ }
83
+ async function readScreen(key, backend, shot) {
84
+ const r = await backend.read(shot);
85
+ reads.set(key, r);
86
+ const app = backend.currentApp ? await backend.currentApp().catch(() => undefined) : undefined;
87
+ observe(key, { items: r.items, ...(app ? { app } : {}) });
88
+ return r;
89
+ }
90
+ const fmtItems = (items, cap = 120) => items.slice(0, cap).map((t) => `${JSON.stringify(t.text)} @ (${t.x}, ${t.y})`).join("\n") + (items.length > cap ? `\n… ${items.length - cap} more` : "");
91
+ async function describe(path, question) {
92
+ return deviceDeps().vision(path, question || "This is a phone or computer screen. Say which app is open, what the screen shows, and list every button and text field with its rough position.");
93
+ }
94
+ /** The check every coordinate goes through: inside the screenshot the model looked at. */
95
+ export function checkPoint(x, y, shot) {
96
+ const nx = Number(x), ny = Number(y);
97
+ if (!Number.isFinite(nx) || !Number.isFinite(ny))
98
+ throw new Unsupported("x and y must be numbers (pixels in the latest screenshot)");
99
+ if (nx < 0 || ny < 0 || nx >= shot.width || ny >= shot.height) {
100
+ throw new Unsupported(`(${nx}, ${ny}) is outside the latest screenshot (${shot.width}×${shot.height} px); coordinates are pixels in that image — take phone_screenshot and read them off it`);
101
+ }
102
+ return { x: Math.round(nx), y: Math.round(ny) };
103
+ }
104
+ /** Best on-screen match for `text`: exact (case-insensitive), then starts-with, then contains; the smallest box wins. */
105
+ export function findText(items, text) {
106
+ const want = text.trim().toLowerCase();
107
+ const by = (f) => items.filter((t) => f(t.text.trim().toLowerCase())).sort((a, b) => a.w * a.h - b.w * b.h)[0];
108
+ return by((s) => s === want) ?? by((s) => s.startsWith(want)) ?? by((s) => s.includes(want));
109
+ }
110
+ const errText = (e) => {
111
+ if (e instanceof NeedsOwner)
112
+ return `error: ${e.message}${e.fix ? `. Next: ${e.fix}` : ""}`;
113
+ if (e instanceof Unsupported)
114
+ return `error: not supported: ${e.message}`;
115
+ return `error: ${e instanceof Error ? e.message : String(e)}`;
116
+ };
117
+ // ── Tool bodies ─────────────────────────────────────────────────────────────────────────────────────────────────────
118
+ export async function phoneScreenshot(args) {
119
+ try {
120
+ const { key, id, backend } = await resolveDevice(args.device);
121
+ const shot = await capture(key, backend);
122
+ const lines = [`screenshot (${id}) → ${shot.path} (${shot.width}×${shot.height} px; tap coordinates are pixels in this image)`];
123
+ if (args.describe === true)
124
+ lines.push(`--- what it shows ---\n${await describe(shot.path, typeof args.question === "string" ? args.question : undefined)}`);
125
+ return lines.join("\n");
126
+ }
127
+ catch (e) {
128
+ return errText(e);
129
+ }
130
+ }
131
+ export async function phoneRead(args) {
132
+ try {
133
+ const { key, id, backend } = await resolveDevice(args.device);
134
+ const shot = await capture(key, backend);
135
+ const r = await readScreen(key, backend, shot);
136
+ if (r.items.length)
137
+ return `screen text (${id}, ${r.source}; pixels in ${shot.path}, ${shot.width}×${shot.height}):\n${fmtItems(r.items)}`;
138
+ if (r.note && r.source === "accessibility")
139
+ return `screen (${id}, accessibility):\n${r.note}`;
140
+ if (args.vision === false)
141
+ return `no text could be read (${r.note ?? r.source}); screenshot: ${shot.path}`;
142
+ return `no text via ${r.source}${r.note ? ` (${r.note})` : ""}; vision read of ${shot.path}:\n${await describe(shot.path, "Transcribe every piece of text on this screen, top to bottom, one per line, with its rough position.")}`;
143
+ }
144
+ catch (e) {
145
+ return errText(e);
146
+ }
147
+ }
148
+ async function act(name, args, body) {
149
+ const line = phoneLine(name, args);
150
+ let device = typeof args.device === "string" ? args.device : "auto";
151
+ if (line && !takeGrant(name, args)) {
152
+ const msg = `Permission denied: "${name}" is a ${line} step (${PHONE_LINE_WHAT[line]}) and the owner has not approved it. ` +
153
+ "Only the owner can approve it, call by call, in an interactive Operator session (it is never covered by a plan or \"allow always\"). Do not retry it another way.";
154
+ await audit({ tool: name, device, line, outcome: "refused", detail: "no owner approval", args });
155
+ return msg;
156
+ }
157
+ try {
158
+ const r = await resolveDevice(args.device);
159
+ device = r.id;
160
+ const shot = async () => shots.get(r.key) ?? capture(r.key, r.backend);
161
+ const before = shots.get(r.key)?.path;
162
+ const did = await body({ ...r, shot });
163
+ let after;
164
+ if (args.verify !== false)
165
+ after = await capture(r.key, r.backend).catch(() => undefined);
166
+ if (r.backend.currentApp)
167
+ observe(r.key, { app: await r.backend.currentApp().catch(() => undefined) });
168
+ await audit({ tool: name, device, line, outcome: "ok", detail: did, args, before, after: after?.path });
169
+ const tail = after ? `\nafter → ${after.path} (${after.width}×${after.height}) — look at it before the next step` : "";
170
+ const seen = after && args.describe === true ? `\n--- what it shows now ---\n${await describe(after.path)}` : "";
171
+ return did + tail + seen;
172
+ }
173
+ catch (e) {
174
+ const msg = errText(e);
175
+ await audit({ tool: name, device, line, outcome: "error", detail: msg, args });
176
+ return msg;
177
+ }
178
+ }
179
+ export const phoneTap = (args) => act("phone_tap", args, async ({ key, id, backend, shot }) => {
180
+ if (typeof args.text === "string" && args.text.trim()) {
181
+ const s = await capture(key, backend);
182
+ const r = await readScreen(key, backend, s);
183
+ const hit = findText(r.items, args.text);
184
+ if (!hit) {
185
+ if (backend instanceof DesktopBackend) {
186
+ await backend.tapElement(args.text);
187
+ return `tapped element "${args.text}" (${id})`;
188
+ }
189
+ throw new Error(`"${args.text}" is not on the screen (${r.source} read ${r.items.length} items). Read it with phone_read, or tap by x, y`);
190
+ }
191
+ await backend.tap(hit.x, hit.y, s);
192
+ return `tapped "${hit.text}" at (${hit.x}, ${hit.y}) (${id})`;
193
+ }
194
+ const s = await shot();
195
+ const p = checkPoint(args.x, args.y, s);
196
+ await backend.tap(p.x, p.y, s);
197
+ return `tapped (${p.x}, ${p.y}) (${id})`;
198
+ });
199
+ export const phoneType = (args) => act("phone_type", args, async ({ id, backend }) => {
200
+ const text = typeof args.text === "string" ? args.text : "";
201
+ if (!text)
202
+ throw new Unsupported("text is required");
203
+ if (args.keystrokes === true && backend instanceof IphoneBackend)
204
+ await backend.keystrokes(text);
205
+ else
206
+ await backend.type(text);
207
+ if (args.submit === true)
208
+ await backend.key("enter");
209
+ return `typed ${text.length} characters${args.submit === true ? " and pressed enter" : ""} (${id}) — a field that had no focus drops text silently, so check the after screenshot`;
210
+ });
211
+ const DIRS = ["up", "down", "left", "right"];
212
+ export const phoneSwipe = (args) => act("phone_swipe", args, async ({ id, backend, shot }) => {
213
+ const s = await shot();
214
+ const ms = Number.isFinite(Number(args.duration_ms)) ? Number(args.duration_ms) : 300;
215
+ if (args.x1 !== undefined || args.x2 !== undefined) {
216
+ const a = checkPoint(args.x1, args.y1, s), b = checkPoint(args.x2, args.y2, s);
217
+ await backend.swipe(a, b, s, ms);
218
+ return `swiped (${a.x}, ${a.y}) → (${b.x}, ${b.y}) (${id})`;
219
+ }
220
+ const dir = String(args.direction ?? "");
221
+ if (!DIRS.includes(dir))
222
+ throw new Unsupported('give direction ("up" | "down" | "left" | "right") or x1, y1, x2, y2');
223
+ if (backend instanceof IphoneBackend) {
224
+ await backend.scroll(dir, s);
225
+ return `swiped ${dir} (${id}, scroll gesture)`;
226
+ }
227
+ if (backend instanceof DesktopBackend)
228
+ throw new Unsupported("on the desktop give x1, y1, x2, y2 (a drag); scroll with phone_key up/down");
229
+ const cx = s.width / 2, cy = s.height / 2, dx = s.width * 0.3, dy = s.height * 0.3;
230
+ const from = { x: dir === "left" ? cx + dx : dir === "right" ? cx - dx : cx, y: dir === "up" ? cy + dy : dir === "down" ? cy - dy : cy };
231
+ const to = { x: dir === "left" ? cx - dx : dir === "right" ? cx + dx : cx, y: dir === "up" ? cy - dy : dir === "down" ? cy + dy : cy };
232
+ await backend.swipe(from, to, s, ms);
233
+ return `swiped ${dir} (${id})`;
234
+ });
235
+ export const phoneKey = (args) => act("phone_key", args, async ({ id, backend }) => {
236
+ const k = String(args.key ?? "");
237
+ if (!DEVICE_KEYS.includes(k))
238
+ throw new Unsupported(`key must be one of: ${DEVICE_KEYS.join(", ")}`);
239
+ await backend.key(k);
240
+ return `pressed ${k} (${id})`;
241
+ });
242
+ export const phoneOpenApp = (args) => act("phone_open_app", args, async ({ key, id, backend }) => {
243
+ const name = typeof args.name === "string" ? args.name.trim() : "";
244
+ if (!name || name.length > 100 || /[\n\r\0]/.test(name))
245
+ throw new Unsupported("name is required: the app's name (\"Settings\") or, on Android, its package id");
246
+ const opened = await backend.openApp(name);
247
+ observe(key, { app: opened });
248
+ return `opened ${opened} (${id})`;
249
+ });
250
+ // ── The approval prompt's preview ───────────────────────────────────────────────────────────────────────────────────
251
+ setPhonePreview(async (name, args) => {
252
+ const { key, backend } = await resolveDevice(args.device);
253
+ const shot = await capture(key, backend);
254
+ let target = name.replace(/^phone_/, "");
255
+ if (name === "phone_tap")
256
+ target = typeof args.text === "string" ? `tap "${args.text}"` : `tap (${args.x}, ${args.y})`;
257
+ else if (name === "phone_type")
258
+ target = `type ${String(args.text ?? "").length} characters${args.submit === true ? " and press enter" : ""}`;
259
+ else if (name === "phone_key")
260
+ target = `press ${String(args.key)}`;
261
+ return { screenshot: shot.path, target };
262
+ });
@@ -0,0 +1,206 @@
1
+ // iPhone through the Mac's iPhone Mirroring window (macOS 15+, iOS 18+): nothing is installed on the phone. Ported
2
+ // from phone-harness's ios.py / mirror.py / ocr.py (MIT, see ./NOTICE). Two drivers behind one backend:
3
+ // - Chauffeur, when it is installed: taps and drags go to the window in the background (the owner keeps the screen).
4
+ // - The built-in driver (mirroring-jxa.ts, the system's own osascript), for every Mac without Chauffeur: CGEvents,
5
+ // after bringing the window to the front.
6
+ // Keys and text always use the built-in driver: Mirroring forwards raw HID keycodes to iOS, so a modifier has to be a
7
+ // key held down, which is what that driver does. What Mirroring cannot do is reported, never emulated: no Back key,
8
+ // no app inventory, no accessibility tree inside the phone image (text comes from Vision OCR of the window).
9
+ import { deviceDeps, pngSize } from "./deps.js";
10
+ import { MIRRORING_APP, MIRRORING_JXA, NAMED_KEYCODES, keycodesFor } from "./mirroring-jxa.js";
11
+ import { NeedsOwner, Unsupported } from "./types.js";
12
+ const T_JXA = 15_000;
13
+ const T_CAPTURE = 15_000;
14
+ /** The app macOS asks about for a permission: the outermost app that runs Operator, not node itself. */
15
+ export function hostAppName(env = process.env) {
16
+ const t = env.TERM_PROGRAM ?? "";
17
+ const known = { Apple_Terminal: "Terminal", "iTerm.app": "iTerm", vscode: "Visual Studio Code", ghostty: "Ghostty", WarpTerminal: "Warp", WezTerm: "WezTerm", tmux: "the terminal app running tmux" };
18
+ return known[t] ?? (t ? t : "the app that runs Operator (your terminal)");
19
+ }
20
+ export const PERMISSION_FIX = {
21
+ accessibility: (app) => `System Settings > Privacy & Security > Accessibility: switch on "${app}" (takes effect at once)`,
22
+ screenRecording: (app) => `System Settings > Privacy & Security > Screen & System Audio Recording: switch on "${app}", then quit and reopen it`,
23
+ };
24
+ export function macMajor(version) { return Number(version.trim().split(".")[0]) || 0; }
25
+ export class IphoneBackend {
26
+ prefer;
27
+ kind = "iphone";
28
+ chauffeurCall;
29
+ constructor(prefer = "auto") {
30
+ this.prefer = prefer;
31
+ }
32
+ async jxa(...args) {
33
+ const r = await deviceDeps().run("osascript", ["-l", "JavaScript", "-e", MIRRORING_JXA, ...args], { timeoutMs: T_JXA });
34
+ if (r.missing)
35
+ throw new Unsupported("osascript is missing — this is not a standard macOS install");
36
+ if (r.timedOut)
37
+ throw new Error(`the iPhone Mirroring driver did not answer in ${T_JXA / 1000} s (${args[0]})`);
38
+ if (r.code !== 0)
39
+ throw new Error(`iPhone Mirroring: ${(r.stderr || r.stdout).replace(/^.*execution error: /s, "").trim().slice(0, 300)}`);
40
+ return JSON.parse(r.stdout.trim() || "{}");
41
+ }
42
+ /** The driver for pointer input: Chauffeur when it answers (and is not switched off), else the built-in one. */
43
+ async driver() {
44
+ if (this.prefer === "builtin")
45
+ return "builtin";
46
+ if (this.chauffeurCall === undefined)
47
+ this.chauffeurCall = await deviceDeps().chauffeur().catch(() => null);
48
+ if (this.chauffeurCall)
49
+ return "chauffeur";
50
+ if (this.prefer === "chauffeur")
51
+ throw new NeedsOwner("Chauffeur was asked for but is not installed", "install Chauffeur, or let Operator pick the iPhone driver itself");
52
+ return "builtin";
53
+ }
54
+ async status() {
55
+ const d = deviceDeps();
56
+ const base = { kind: "iphone", backend: "iphone-mirroring" };
57
+ if (d.platform !== "darwin")
58
+ return { ...base, state: "unsupported", detail: `iPhone Mirroring is a macOS app; this computer runs ${d.platform}`, fix: "drive an iPhone from a Mac (macOS 15+), or use an Android phone over adb here" };
59
+ const ver = await d.run("sw_vers", ["-productVersion"], { timeoutMs: 5000 });
60
+ const major = macMajor(ver.stdout);
61
+ if (major && major < 15)
62
+ return { ...base, state: "unsupported", detail: `macOS ${ver.stdout.trim()} has no iPhone Mirroring`, fix: "update to macOS 15 Sequoia or later (Apple menu > System Settings > General > Software Update)" };
63
+ const present = await d.run("osascript", ["-l", "JavaScript", "-e", `ObjC.import('Foundation'); $.NSFileManager.defaultManager.fileExistsAtPath(${JSON.stringify(MIRRORING_APP)}) ? 'yes' : 'no'`], { timeoutMs: T_JXA });
64
+ if (present.missing)
65
+ return { ...base, state: "unsupported", detail: "osascript is missing" };
66
+ if (present.stdout.trim() === "no")
67
+ return { ...base, state: "missing-tool", detail: "the iPhone Mirroring app is not on this Mac", fix: "iPhone Mirroring ships with macOS 15+; it is unavailable in some regions (EU) and on managed Macs that disable it" };
68
+ const perms = await this.jxa("perms");
69
+ const host = hostAppName();
70
+ if (!perms.accessibility)
71
+ return { ...base, state: "permission", detail: `Accessibility is off for ${host} (needed for taps and typing)`, fix: PERMISSION_FIX.accessibility(host) };
72
+ if (!perms.screenRecording)
73
+ return { ...base, state: "permission", detail: `Screen Recording is off for ${host} (needed to see the phone)`, fix: PERMISSION_FIX.screenRecording(host) };
74
+ const w = await this.jxa("window");
75
+ if (!w.running)
76
+ return { ...base, state: "not-running", detail: "iPhone Mirroring is not open", fix: "open iPhone Mirroring (Applications) with your iPhone nearby and locked" };
77
+ if (!w.window)
78
+ return { ...base, state: "not-paired", detail: "iPhone Mirroring is open but shows no phone", fix: "finish pairing in the iPhone Mirroring window (the phone must be in your hand once, signed in to the same Apple Account)" };
79
+ const said = [...(w.ax?.texts ?? []), ...(w.ax?.buttons ?? []).map((b) => `[${b}]`)].join(" ").slice(0, 200);
80
+ if (w.ax?.ok && said)
81
+ return { ...base, state: "blocked", detail: `the mirroring window shows: ${said}`, fix: /in use/i.test(said) ? "lock the iPhone (mirroring pauses while it is unlocked)" : "clear the message in the iPhone Mirroring window (Connect / Try Again)", name: "iPhone Mirroring" };
82
+ return { ...base, state: "ready", detail: `iPhone Mirroring window ${Math.round(w.window.w)}×${Math.round(w.window.h)}${w.ax?.ok ? "" : " (session state unverified: no accessibility read)"}`, name: "iPhone Mirroring" };
83
+ }
84
+ async window() {
85
+ const w = await this.jxa("window");
86
+ if (!w.running)
87
+ throw new NeedsOwner("iPhone Mirroring is not open", "open iPhone Mirroring with your iPhone nearby and locked");
88
+ if (!w.window)
89
+ throw new NeedsOwner("iPhone Mirroring shows no phone window", "finish pairing in the iPhone Mirroring window");
90
+ const said = [...(w.ax?.texts ?? []), ...(w.ax?.buttons ?? [])].join(" ");
91
+ if (w.ax?.ok && said)
92
+ throw new NeedsOwner(`the mirroring window shows: ${said.slice(0, 200)}`, "lock the iPhone, or press Connect in the window — nothing was sent");
93
+ return w.window;
94
+ }
95
+ async screenshot() {
96
+ const d = deviceDeps();
97
+ const win = await this.window();
98
+ const path = await d.tempFile("iphone", "png");
99
+ let r = await d.run("screencapture", ["-x", "-o", "-l", String(win.id), path], { timeoutMs: T_CAPTURE });
100
+ let bytes = r.code === 0 ? await d.readFile(path).catch(() => new Uint8Array()) : new Uint8Array();
101
+ if (bytes.length < 1000) {
102
+ // Not composited (another Space, covered while backing is purged): bring it up and capture its rect instead.
103
+ await this.jxa("activate");
104
+ const w2 = await this.window();
105
+ r = await d.run("screencapture", ["-x", "-R", `${Math.round(w2.x)},${Math.round(w2.y)},${Math.round(w2.w)},${Math.round(w2.h)}`, path], { timeoutMs: T_CAPTURE });
106
+ bytes = r.code === 0 ? await d.readFile(path).catch(() => new Uint8Array()) : new Uint8Array();
107
+ }
108
+ const size = pngSize(bytes);
109
+ if (!size)
110
+ throw new Error(`capturing the iPhone Mirroring window failed: ${(r.stderr || "empty capture").trim()} (Screen Recording must be on for ${hostAppName()})`);
111
+ return { path, ...size };
112
+ }
113
+ /** Vision OCR of the window (the phone image is opaque to accessibility). Boxes come back normalized with a
114
+ * bottom-left origin; flipped here into top-left screenshot pixels. */
115
+ async read(shot) {
116
+ const r = await this.jxa("ocr", shot.path);
117
+ const items = r.items.filter((o) => o.confidence >= 0.3).map((o) => ({
118
+ text: o.text,
119
+ x: Math.round((o.x + o.w / 2) * shot.width),
120
+ y: Math.round((1 - o.y - o.h / 2) * shot.height),
121
+ w: Math.round(o.w * shot.width),
122
+ h: Math.round(o.h * shot.height),
123
+ }));
124
+ return { source: "ocr", items };
125
+ }
126
+ /** Screenshot pixels → global screen points, against the window as it is now (it may have moved). */
127
+ async toScreen(x, y, shot) {
128
+ const win = await this.window();
129
+ const lx = (x * win.w) / shot.width, ly = (y * win.h) / shot.height;
130
+ return { win, lx, ly, sx: win.x + lx, sy: win.y + ly };
131
+ }
132
+ async tap(x, y, shot) {
133
+ const p = await this.toScreen(x, y, shot);
134
+ if ((await this.driver()) === "chauffeur") {
135
+ const pid = (await this.jxa("window")).pid;
136
+ const r = await this.chauffeurCall("click", { pid, window_id: p.win.id, x: Math.round(p.lx), y: Math.round(p.ly) });
137
+ if (/^error|"error"/i.test(r))
138
+ throw new Error(`Chauffeur click: ${r.slice(0, 200)}`);
139
+ return;
140
+ }
141
+ await this.jxa("tap", String(p.sx), String(p.sy));
142
+ }
143
+ async swipe(from, to, shot, durationMs) {
144
+ const a = await this.toScreen(from.x, from.y, shot);
145
+ const b = await this.toScreen(to.x, to.y, shot);
146
+ if ((await this.driver()) === "chauffeur") {
147
+ const pid = (await this.jxa("window")).pid;
148
+ const r = await this.chauffeurCall("drag", { pid, window_id: a.win.id, from_x: Math.round(a.lx), from_y: Math.round(a.ly), to_x: Math.round(b.lx), to_y: Math.round(b.ly) });
149
+ if (/^error|"error"/i.test(r))
150
+ throw new Error(`Chauffeur drag: ${r.slice(0, 200)}`);
151
+ return;
152
+ }
153
+ await this.jxa("drag", String(a.sx), String(a.sy), String(b.sx), String(b.sy), String(Math.min(Math.max(durationMs, 100), 3000) / 1000));
154
+ }
155
+ /** A content scroll (what most "swipe up" requests mean): scroll-wheel events at the window centre. A slow drag
156
+ * barely registers on iOS, the wheel always does (phone-harness, measured). */
157
+ async scroll(dir, shot) {
158
+ const c = await this.toScreen(shot.width / 2, shot.height / 2, shot);
159
+ const amount = Math.round(c.win.h * 0.6);
160
+ const dy = dir === "up" ? amount : dir === "down" ? -amount : 0; // swipe up = reveal content further down
161
+ const dx = dir === "left" ? amount : dir === "right" ? -amount : 0;
162
+ await this.jxa("scroll", String(c.sx), String(c.sy), String(dy), String(dx));
163
+ }
164
+ async type(text) {
165
+ await this.window();
166
+ if (!text)
167
+ return;
168
+ await this.jxa("paste", text);
169
+ }
170
+ /** Real keystrokes, for fields that refuse paste. Subject to iOS autocorrect; US layout only. */
171
+ async keystrokes(text) {
172
+ const codes = keycodesFor(text);
173
+ if (!codes)
174
+ throw new Unsupported("this text has characters with no US-layout key (emoji, accents); type it without keystrokes: true to paste it");
175
+ await this.window();
176
+ await this.jxa("keycodes", JSON.stringify(codes));
177
+ }
178
+ async key(key) {
179
+ const combos = {
180
+ home: ["cmd+1", NAMED_KEYCODES["1"]], recents: ["cmd+2", NAMED_KEYCODES["2"]], search: ["cmd+3", NAMED_KEYCODES["3"]],
181
+ enter: ["return", 36], delete: ["delete", 51], tab: ["tab", 48], space: ["space", 49], escape: ["escape", 53],
182
+ up: ["up", 126], down: ["down", 125], left: ["left", 123], right: ["right", 124],
183
+ };
184
+ if (key === "back")
185
+ throw new Unsupported("iOS has no system Back button: tap the app's own back control (top left), or swipe right from the left edge with phone_swipe");
186
+ const c = combos[key];
187
+ if (!c)
188
+ throw new Unsupported(`iPhone Mirroring cannot press ${key} (no hardware buttons are forwarded)`);
189
+ await this.window();
190
+ await this.jxa("key", c[0], String(c[1]));
191
+ }
192
+ /** Spotlight (Cmd+3), type the name, Return — what a person does. */
193
+ async openApp(name) {
194
+ const codes = keycodesFor(name);
195
+ await this.window();
196
+ await this.jxa("key", "cmd+3", String(NAMED_KEYCODES["3"]));
197
+ await deviceDeps().sleep(900);
198
+ if (codes)
199
+ await this.jxa("keycodes", JSON.stringify(codes));
200
+ else
201
+ await this.jxa("paste", name);
202
+ await deviceDeps().sleep(1200);
203
+ await this.jxa("key", "return", "36");
204
+ return name;
205
+ }
206
+ }
@@ -0,0 +1,146 @@
1
+ // The iPhone Mirroring driver for a Mac without Chauffeur: one JavaScript-for-Automation program run by the system's
2
+ // own `osascript -l JavaScript` (on every Mac — nothing to install), reaching CoreGraphics, AppKit, Accessibility and
3
+ // Vision through the ObjC bridge. It is a port of phone-harness's mirror.py and ocr.py (MIT, see ./NOTICE). The
4
+ // program is fixed text; every value (coordinates, the text to paste, the image path) arrives as an argv word and is
5
+ // read as data, so nothing the model sends is ever evaluated. It never asks macOS for a permission: AXIsProcessTrusted
6
+ // and CGPreflightScreenCaptureAccess only read the grant, they raise no dialog.
7
+ //
8
+ // What phone-harness learned the hard way and this keeps: windows are matched by the owner pid of the
9
+ // com.apple.ScreenContinuity process, never the (localized) app name; iPhone Mirroring forwards raw HID keycodes to iOS
10
+ // and drops the CGEvent flag mask, so a modifier is a key held down, not a flag set; text goes in by paste (immune to
11
+ // autocorrect and keyboard layout), keystrokes only on request; the live phone image is a video stream accessibility
12
+ // cannot see into, so a window with accessible labels or buttons is an interstitial (paused, iPhone in Use, Connect).
13
+ export const MIRRORING_BUNDLE = "com.apple.ScreenContinuity";
14
+ export const MIRRORING_APP = "/System/Applications/iPhone Mirroring.app";
15
+ export const MIRRORING_JXA = `
16
+ ObjC.import('AppKit'); ObjC.import('CoreGraphics'); ObjC.import('ApplicationServices');
17
+ var BUNDLE = 'com.apple.ScreenContinuity';
18
+ function out(o) { return JSON.stringify(o); }
19
+ function app() { var a = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(BUNDLE); return a.count > 0 ? a.objectAtIndex(0) : null; }
20
+ function win(pid) {
21
+ var list = ObjC.deepUnwrap(ObjC.castRefToObject($.CGWindowListCopyWindowInfo(1, 0))) || [];
22
+ for (var i = 0; i < list.length; i++) {
23
+ var w = list[i];
24
+ if (w.kCGWindowOwnerPID === pid && (w.kCGWindowLayer || 0) === 0) {
25
+ var b = w.kCGWindowBounds; return { x: b.X, y: b.Y, w: b.Width, h: b.Height, id: w.kCGWindowNumber };
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+ function front(pid) { var f = $.NSWorkspace.sharedWorkspace.frontmostApplication; return !!f && f.processIdentifier === pid; }
31
+ function activate() {
32
+ var a = app(); if (!a) throw new Error('iPhone Mirroring is not running');
33
+ for (var i = 0; i < 25 && !front(a.processIdentifier); i++) { a.activateWithOptions(2); delay(0.08); }
34
+ if (!front(a.processIdentifier)) throw new Error('could not bring iPhone Mirroring to the front, so nothing was sent');
35
+ return a;
36
+ }
37
+ function mouse(type, x, y) { $.CGEventPost(0, $.CGEventCreateMouseEvent($(), type, { x: x, y: y }, 0)); }
38
+ var MODS = { cmd: [55, 0x100000], shift: [56, 0x20000], alt: [58, 0x80000], option: [58, 0x80000], ctrl: [59, 0x40000] };
39
+ function keyEv(code, down, flags) { var e = $.CGEventCreateKeyboardEvent($(), code, down); if (flags) $.CGEventSetFlags(e, flags); $.CGEventPost(0, e); }
40
+ function chord(mods, code) {
41
+ var acc = 0;
42
+ mods.forEach(function (m) { acc |= MODS[m][1]; keyEv(MODS[m][0], true, acc); delay(0.01); });
43
+ try { keyEv(code, true, acc); delay(0.03); keyEv(code, false, acc); delay(0.03); }
44
+ finally { mods.slice().reverse().forEach(function (m) { acc &= ~MODS[m][1]; keyEv(MODS[m][0], false, acc); delay(0.01); }); }
45
+ }
46
+ function axTexts(pid) {
47
+ var texts = [], buttons = [];
48
+ function attr(el, name) { var r = Ref(); return $.AXUIElementCopyAttributeValue(el, $(name), r) === 0 ? ObjC.castRefToObject(r[0]) : null; }
49
+ function str(v) { try { return v ? ObjC.unwrap(v) : ''; } catch (e) { return ''; } }
50
+ function walk(el, depth) {
51
+ if (depth > 8) return;
52
+ var role = str(attr(el, 'AXRole')), label = str(attr(el, 'AXValue')) || str(attr(el, 'AXTitle')) || str(attr(el, 'AXDescription'));
53
+ if (typeof label === 'string' && label.trim()) { if (role === 'AXButton') buttons.push(label.trim()); else if (role === 'AXStaticText') texts.push(label.trim()); }
54
+ var kids = attr(el, 'AXChildren'); if (!kids) return;
55
+ for (var i = 0; i < kids.count; i++) walk(kids.objectAtIndex(i), depth + 1);
56
+ }
57
+ var wins = attr($.AXUIElementCreateApplication(pid), 'AXWindows');
58
+ if (!wins || wins.count === 0) return { ok: false };
59
+ walk(wins.objectAtIndex(0), 0);
60
+ return { ok: true, texts: texts, buttons: buttons };
61
+ }
62
+ function run(argv) {
63
+ var verb = argv[0], n = function (i) { var v = Number(argv[i]); if (!isFinite(v)) throw new Error('bad number: ' + argv[i]); return v; };
64
+ if (verb === 'perms') { ObjC.bindFunction('CGPreflightScreenCaptureAccess', ['bool', []]); return out({ accessibility: !!$.AXIsProcessTrusted(), screenRecording: !!$.CGPreflightScreenCaptureAccess() }); }
65
+ if (verb === 'window') {
66
+ var a = app(); if (!a) return out({ running: false });
67
+ var pid = a.processIdentifier, ax = null;
68
+ if ($.AXIsProcessTrusted()) { try { ax = axTexts(pid); } catch (e) { ax = { ok: false }; } }
69
+ return out({ running: true, pid: pid, window: win(pid), front: front(pid), ax: ax });
70
+ }
71
+ if (verb === 'activate') { activate(); return out({ ok: true }); }
72
+ if (verb === 'tap') {
73
+ activate(); var x = n(1), y = n(2), hold = argv[3] ? n(3) : 0.06;
74
+ mouse(5, x, y); delay(0.1); mouse(1, x, y); delay(hold); mouse(2, x, y); return out({ ok: true });
75
+ }
76
+ if (verb === 'drag') {
77
+ activate(); var x1 = n(1), y1 = n(2), x2 = n(3), y2 = n(4), secs = n(5), steps = 14;
78
+ mouse(5, x1, y1); delay(0.1); mouse(1, x1, y1);
79
+ for (var i = 1; i <= steps; i++) { var t = i / steps; mouse(6, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t); delay(secs / steps); }
80
+ mouse(2, x2, y2); return out({ ok: true });
81
+ }
82
+ if (verb === 'scroll') {
83
+ activate(); var sx = n(1), sy = n(2), dy = n(3), dx = n(4), k = 6;
84
+ mouse(5, sx, sy); delay(0.1);
85
+ for (var j = 0; j < k; j++) { var e = $.CGEventCreateScrollWheelEvent2($(), 0, 2, Math.round(dy / k), Math.round(dx / k), 0); $.CGEventSetLocation(e, { x: sx, y: sy }); $.CGEventPost(0, e); delay(0.03); }
86
+ return out({ ok: true });
87
+ }
88
+ if (verb === 'key') { activate(); var parts = argv[1].split('+'); chord(parts.slice(0, -1), n(2)); return out({ ok: true }); }
89
+ if (verb === 'keycodes') {
90
+ activate(); var codes = JSON.parse(argv[1]);
91
+ codes.forEach(function (c) { chord(c[1] ? ['shift'] : [], c[0]); delay(0.03); });
92
+ return out({ ok: true });
93
+ }
94
+ if (verb === 'paste') {
95
+ var pb = $.NSPasteboard.generalPasteboard; pb.clearContents; pb.setStringForType($(argv[1]), $.NSPasteboardTypeString);
96
+ if (ObjC.unwrap(pb.stringForType($.NSPasteboardTypeString)) !== argv[1]) throw new Error('the clipboard did not take the text, so nothing was pasted');
97
+ activate(); delay(0.15); chord(['cmd'], 9); return out({ ok: true });
98
+ }
99
+ if (verb === 'ocr') {
100
+ ObjC.import('Vision');
101
+ var handler = $.VNImageRequestHandler.alloc.initWithURLOptions($.NSURL.fileURLWithPath(argv[1]), $());
102
+ var req = $.VNRecognizeTextRequest.alloc.init; req.recognitionLevel = 0;
103
+ if (!handler.performRequestsError($.NSArray.arrayWithObject(req), $())) throw new Error('Vision text recognition failed');
104
+ var res = req.results, items = [];
105
+ for (var r = 0; r < res.count; r++) {
106
+ var obs = res.objectAtIndex(r), c = obs.topCandidates(1); if (c.count === 0) continue;
107
+ var bb = obs.boundingBox, best = c.objectAtIndex(0);
108
+ items.push({ text: ObjC.unwrap(best.string), confidence: best.confidence, x: bb.origin.x, y: bb.origin.y, w: bb.size.width, h: bb.size.height });
109
+ }
110
+ return out({ items: items });
111
+ }
112
+ throw new Error('unknown verb ' + verb);
113
+ }
114
+ `;
115
+ // US-layout virtual keycodes (mirror.py _KEYCODES / _PUNCT_KEYCODES / _SHIFTED), for keystroke typing and named keys.
116
+ const BASE = {
117
+ a: 0, s: 1, d: 2, f: 3, h: 4, g: 5, z: 6, x: 7, c: 8, v: 9, b: 11, q: 12, w: 13, e: 14, r: 15, y: 16, t: 17, o: 31, u: 32,
118
+ i: 34, p: 35, l: 37, j: 38, k: 40, n: 45, m: 46, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22, "7": 26, "8": 28,
119
+ "9": 25, "0": 29, ".": 47, ",": 43, "/": 44, ";": 41, "'": 39, "[": 33, "]": 30, "\\": 42, "-": 27, "=": 24, "`": 50, " ": 49,
120
+ };
121
+ const SHIFTED = {
122
+ "!": "1", "@": "2", "#": "3", $: "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", ")": "0", _: "-", "+": "=", ":": ";",
123
+ '"': "'", "<": ",", ">": ".", "?": "/", "~": "`", "{": "[", "}": "]", "|": "\\",
124
+ };
125
+ export const NAMED_KEYCODES = {
126
+ return: 36, enter: 36, tab: 48, space: 49, delete: 51, escape: 53, left: 123, right: 124, down: 125, up: 126,
127
+ ...BASE,
128
+ };
129
+ /** Each character → [keycode, needs shift]; null when a character has no US-layout key (emoji, accents). */
130
+ export function keycodesFor(text) {
131
+ const out = [];
132
+ for (const ch of text) {
133
+ if (ch === "\n") {
134
+ out.push([36, false]);
135
+ continue;
136
+ }
137
+ const lower = ch.toLowerCase();
138
+ const upper = ch !== lower;
139
+ const base = SHIFTED[ch] ?? lower;
140
+ const code = BASE[base];
141
+ if (code === undefined)
142
+ return null;
143
+ out.push([code, upper || ch in SHIFTED]);
144
+ }
145
+ return out;
146
+ }