@0perator/operator 0.1.360-next.2 → 0.2.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 (104) hide show
  1. package/README.md +5 -4
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +159 -0
  6. package/dist/autonomy/delegate.js +42 -15
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +13 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +336 -45
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/resume.js +125 -0
  18. package/dist/background/synthesis.js +25 -0
  19. package/dist/browser/engine.js +163 -0
  20. package/dist/browser/session.js +130 -140
  21. package/dist/bus/inbox.js +150 -6
  22. package/dist/cli.js +343 -86
  23. package/dist/config/features.js +3 -3
  24. package/dist/config/persona.js +29 -3
  25. package/dist/config/settings.js +262 -21
  26. package/dist/config/staff-prompt.js +12 -0
  27. package/dist/engine/agent.js +52 -41
  28. package/dist/engine/aurora.js +40 -8
  29. package/dist/engine/batch-scheduler.js +4 -13
  30. package/dist/engine/compaction.js +2 -2
  31. package/dist/engine/continuation.js +30 -32
  32. package/dist/engine/decision-points.js +2 -3
  33. package/dist/engine/fanout.js +16 -0
  34. package/dist/engine/loop-guard.js +26 -83
  35. package/dist/engine/messages.js +2 -2
  36. package/dist/engine/moa.js +18 -2
  37. package/dist/engine/native-vision-node.js +72 -0
  38. package/dist/engine/native-vision.js +103 -0
  39. package/dist/engine/selfheal.js +1 -1
  40. package/dist/engine/toolcalls.js +6 -6
  41. package/dist/engine/verify-gate.js +37 -7
  42. package/dist/gateway-cli.js +14 -3
  43. package/dist/index.js +3 -0
  44. package/dist/mcp/phone-server.js +30 -0
  45. package/dist/memory/live-progress.js +4 -5
  46. package/dist/moa/codeact-lane.js +98 -0
  47. package/dist/moa/codeact-sandbox.js +409 -0
  48. package/dist/moa/codeact.js +140 -0
  49. package/dist/permissions/artifact-visibility.js +10 -0
  50. package/dist/permissions/index.js +33 -17
  51. package/dist/permissions/signature.js +5 -0
  52. package/dist/permissions/tier.js +4 -2
  53. package/dist/phone-cli.js +65 -0
  54. package/dist/products/craft.js +2 -2
  55. package/dist/remote/grants.js +119 -0
  56. package/dist/remote/host.js +63 -6
  57. package/dist/router/models.js +29 -29
  58. package/dist/selfimprove/index.js +9 -7
  59. package/dist/services/preflight.js +35 -91
  60. package/dist/session.js +173 -46
  61. package/dist/skills/install-guard.js +68 -0
  62. package/dist/skills/install.js +67 -0
  63. package/dist/toolchain/manifest.json +13 -13
  64. package/dist/tools/background-result.js +1 -1
  65. package/dist/tools/classes.js +103 -0
  66. package/dist/tools/contract.js +1 -1
  67. package/dist/tools/craft.js +13 -2
  68. package/dist/tools/deferred.js +1 -0
  69. package/dist/tools/device/android.js +227 -0
  70. package/dist/tools/device/classify.js +127 -0
  71. package/dist/tools/device/deps.js +69 -0
  72. package/dist/tools/device/desktop.js +82 -0
  73. package/dist/tools/device/harness.js +262 -0
  74. package/dist/tools/device/iphone.js +206 -0
  75. package/dist/tools/device/mirroring-jxa.js +146 -0
  76. package/dist/tools/device/setup.js +90 -0
  77. package/dist/tools/device/tools.js +70 -0
  78. package/dist/tools/device/types.js +19 -0
  79. package/dist/tools/executor.js +25 -15
  80. package/dist/tools/generation-gateway.js +94 -0
  81. package/dist/tools/registry.js +95 -155
  82. package/dist/ui/App.js +18 -6
  83. package/dist/ui/ApprovalPrompt.js +10 -4
  84. package/dist/ui/BgPanel.js +17 -12
  85. package/dist/ui/Header.js +1 -6
  86. package/dist/ui/StatusRule.js +18 -7
  87. package/dist/ui/ToolStep.js +3 -3
  88. package/dist/ui/Transcript.js +36 -14
  89. package/dist/ui/UpdatePrompt.js +40 -0
  90. package/dist/ui/batchLine.js +4 -4
  91. package/dist/ui/editdiff.js +2 -4
  92. package/dist/ui/format.js +4 -20
  93. package/dist/ui/liveTools.js +3 -3
  94. package/dist/ui/modelPicker.js +1 -1
  95. package/dist/ui/opsMode.js +20 -0
  96. package/dist/ui/slashCommands.js +1 -0
  97. package/dist/ui/types.js +0 -2
  98. package/dist/update-check.js +145 -0
  99. package/dist/update.js +59 -15
  100. package/dist/util/slash.js +2 -2
  101. package/package.json +4 -2
  102. package/src/tools/device/NOTICE +37 -0
  103. package/dist/browser/cdp.js +0 -271
  104. package/dist/tools/mutating.js +0 -15
@@ -0,0 +1,69 @@
1
+ // What a device backend may touch on this machine: one process runner (argv only, never a shell string, always a
2
+ // deadline), the Chauffeur driver when it is installed, the vision route, temp files and the clock. Tests replace
3
+ // every one of them (setDeviceDeps) — nothing here is reached by a test.
4
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
5
+ async function runReal(bin, args, opts) {
6
+ const { execFile } = await nodeImport("node:child_process");
7
+ return new Promise((resolve) => {
8
+ // bins: adb osascript screencapture sw_vers
9
+ const child = execFile(bin, args, { timeout: opts.timeoutMs, maxBuffer: 64 * 1024 * 1024, encoding: "buffer", killSignal: "SIGKILL" }, (err, stdout, stderr) => {
10
+ const out = stdout ?? new Uint8Array();
11
+ const text = (b) => Buffer.from(b ?? []).toString("utf8");
12
+ if (err?.code === "ENOENT")
13
+ return resolve({ code: 127, stdout: "", bytes: new Uint8Array(), stderr: `${bin}: not found`, missing: true });
14
+ const timedOut = !!err && (err.killed === true || err.signal === "SIGKILL");
15
+ resolve({ code: err ? (typeof err.code === "number" ? err.code : 1) : 0, stdout: text(out), bytes: out, stderr: text(stderr), timedOut });
16
+ });
17
+ if (opts.input !== undefined)
18
+ child.stdin?.end(opts.input);
19
+ });
20
+ }
21
+ async function realChauffeur() {
22
+ const { buildChauffeurHub } = await import("../chauffeur.js");
23
+ const hub = await buildChauffeurHub();
24
+ if (!hub)
25
+ return null;
26
+ return async (tool, args) => {
27
+ const r = await hub.call(`chauffeur:${tool}`, args);
28
+ return typeof r === "string" ? r : JSON.stringify(r);
29
+ };
30
+ }
31
+ async function realVision(path, question) {
32
+ const { registry } = await import("../registry.js");
33
+ const t = registry.get("image_analyze");
34
+ return t ? t.run({ image: path, question }) : "vision is down: image_analyze is not registered";
35
+ }
36
+ export const realDeps = {
37
+ run: runReal,
38
+ chauffeur: realChauffeur,
39
+ vision: realVision,
40
+ platform: typeof process !== "undefined" ? process.platform : "unknown",
41
+ async tempFile(prefix, ext) {
42
+ const { mkdir } = await nodeImport("node:fs/promises");
43
+ const { operatorPath } = await import("../../config/home.js");
44
+ const dir = operatorPath("cache", "device");
45
+ await mkdir(dir, { recursive: true, mode: 0o700 });
46
+ return `${dir}/${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}.${ext}`;
47
+ },
48
+ async readFile(p) { const { readFile } = await nodeImport("node:fs/promises"); return readFile(p); },
49
+ async writeFile(p, d) { const { writeFile } = await nodeImport("node:fs/promises"); await writeFile(p, d, { mode: 0o600 }); },
50
+ async appendFile(p, line) {
51
+ const { appendFile, mkdir } = await nodeImport("node:fs/promises");
52
+ const { dirname } = await nodeImport("node:path");
53
+ await mkdir(dirname(p), { recursive: true });
54
+ await appendFile(p, line, { mode: 0o600 });
55
+ },
56
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
57
+ now: () => Date.now(),
58
+ };
59
+ let deps = realDeps;
60
+ export function deviceDeps() { return deps; }
61
+ /** Tests swap in fakes; pass nothing to restore the real machine. */
62
+ export function setDeviceDeps(d) { deps = d ? { ...realDeps, ...d } : realDeps; }
63
+ /** PNG width and height from the IHDR chunk, without an image library. */
64
+ export function pngSize(b) {
65
+ if (b.length < 24 || b[0] !== 0x89 || b[1] !== 0x50 || b[2] !== 0x4e || b[3] !== 0x47)
66
+ return null;
67
+ const be = (i) => ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0;
68
+ return { width: be(16), height: be(20) };
69
+ }
@@ -0,0 +1,82 @@
1
+ // The computer itself as a device. macOS goes through Chauffeur — the same driver and the same call shapes the desktop_*
2
+ // tools use (chauffeur-native.ts): click {x, y} / {element}, type_text {text}, launch_app {name}, press_key {key},
3
+ // drag {from_x, from_y, to_x, to_y}, get_desktop_state. The screenshot is the system's screencapture, so its pixel size
4
+ // is known and coordinates can be checked against it. Windows and Linux desktops are seams, not backends yet: they
5
+ // report "not supported yet" and run nothing.
6
+ import { deviceDeps, pngSize } from "./deps.js";
7
+ import { NeedsOwner, Unsupported } from "./types.js";
8
+ const OS_NAME = { darwin: "macOS", win32: "Windows", linux: "Linux" };
9
+ export const osName = (p) => OS_NAME[p] ?? p;
10
+ const CHAUFFEUR_KEYS = {
11
+ enter: "return", delete: "delete", tab: "tab", space: "space", escape: "escape", up: "up", down: "down", left: "left", right: "right",
12
+ };
13
+ export class DesktopBackend {
14
+ kind = "desktop";
15
+ call;
16
+ notYet() {
17
+ return new Unsupported(`desktop control on ${osName(deviceDeps().platform)} is not supported yet in this harness (macOS only today; an Android phone over adb works here)`);
18
+ }
19
+ async chauffeur() {
20
+ if (deviceDeps().platform !== "darwin")
21
+ throw this.notYet();
22
+ if (this.call === undefined)
23
+ this.call = await deviceDeps().chauffeur().catch(() => null);
24
+ if (!this.call)
25
+ throw new NeedsOwner("Chauffeur is not installed on this Mac", "install Chauffeur.app; the computer_* tools (osascript) still work without it");
26
+ return this.call;
27
+ }
28
+ async drive(tool, args) {
29
+ const r = await (await this.chauffeur())(tool, args);
30
+ if (/^error\b/i.test(r.trim()))
31
+ throw new Error(`Chauffeur ${tool}: ${r.trim().slice(0, 300)}`);
32
+ return r;
33
+ }
34
+ async status() {
35
+ const p = deviceDeps().platform;
36
+ const base = { kind: "desktop", backend: "chauffeur" };
37
+ if (p !== "darwin")
38
+ return { ...base, backend: "none", state: "unsupported", detail: `${osName(p)} desktop control is not built yet (a seam in src/tools/device/desktop.ts)` };
39
+ if (this.call === undefined)
40
+ this.call = await deviceDeps().chauffeur().catch(() => null);
41
+ if (!this.call)
42
+ return { ...base, state: "missing-tool", detail: "Chauffeur is not installed", fix: "install Chauffeur.app for background desktop control (computer_* tools work without it)" };
43
+ return { ...base, state: "ready", detail: "this Mac, through Chauffeur", name: "this Mac" };
44
+ }
45
+ async screenshot() {
46
+ if (deviceDeps().platform !== "darwin")
47
+ throw this.notYet();
48
+ const d = deviceDeps();
49
+ const path = await d.tempFile("desktop", "png");
50
+ const r = await d.run("screencapture", ["-x", path], { timeoutMs: 15_000 });
51
+ const size = r.code === 0 ? pngSize(await d.readFile(path).catch(() => new Uint8Array())) : null;
52
+ if (!size)
53
+ throw new NeedsOwner(`screen capture failed: ${(r.stderr || "empty capture").trim()}`, "System Settings > Privacy & Security > Screen & System Audio Recording: switch on the app that runs Operator");
54
+ return { path, ...size };
55
+ }
56
+ /** Chauffeur's accessibility read of the desktop, as text. It names elements, not boxes: tap them with `text`. */
57
+ async read() {
58
+ const r = await this.drive("get_desktop_state", { include_screenshot: false });
59
+ return { source: "accessibility", items: [], note: r.slice(0, 6000) };
60
+ }
61
+ /** Screenshot pixels → screen points (a Retina capture is 2× the points Chauffeur's desktop target takes). */
62
+ async points(x, y, shot) {
63
+ const r = await deviceDeps().run("osascript", ["-l", "JavaScript", "-e", "ObjC.import('AppKit'); var f = $.NSScreen.mainScreen.frame; JSON.stringify({ w: f.size.width, h: f.size.height })"], { timeoutMs: 10_000 });
64
+ const f = JSON.parse(r.stdout.trim() || "{}");
65
+ const sx = f.w ? f.w / shot.width : 1, sy = f.h ? f.h / shot.height : 1;
66
+ return { x: Math.round(x * sx), y: Math.round(y * sy) };
67
+ }
68
+ async tap(x, y, shot) { await this.drive("click", await this.points(x, y, shot)); }
69
+ async tapElement(text) { await this.drive("click", { element: text }); }
70
+ async type(text) { await this.drive("type_text", { text }); }
71
+ async swipe(from, to, shot) {
72
+ const a = await this.points(from.x, from.y, shot), b = await this.points(to.x, to.y, shot);
73
+ await this.drive("drag", { from_x: a.x, from_y: a.y, to_x: b.x, to_y: b.y });
74
+ }
75
+ async key(key) {
76
+ const k = CHAUFFEUR_KEYS[key];
77
+ if (!k)
78
+ throw new Unsupported(`the desktop has no ${key} key in this harness (use computer_key for other combos)`);
79
+ await this.drive("press_key", { key: k });
80
+ }
81
+ async openApp(name) { await this.drive("launch_app", { name }); return name; }
82
+ }
@@ -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
+ }