@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,227 @@
1
+ // Android over adb — macOS, Linux and Windows alike. Ported from phone-harness's android.py (MIT, see ./NOTICE):
2
+ // `adb devices -l` states, screencap for pixels, `uiautomator dump` for the text tree, `input` for taps, swipes, keys
3
+ // and text, `am start` / `cmd package resolve-activity` for apps, and the lock gate (a locked phone is the owner's;
4
+ // a PIN is never typed). Tightened: every adb call is an argv array with a deadline. `adb shell` hands its words to
5
+ // the phone's own sh, so every word that reaches it is either a validated number, a key from a fixed table, a
6
+ // package id matching PACKAGE, or text single-quoted by devQuote — nothing the model sends is spliced in raw.
7
+ import { deviceDeps, pngSize } from "./deps.js";
8
+ import { NeedsOwner, Unsupported } from "./types.js";
9
+ export const ADB_INSTALL = {
10
+ darwin: "brew install android-platform-tools",
11
+ linux: "sudo apt install adb (Fedora: sudo dnf install android-tools)",
12
+ win32: "winget install Google.PlatformTools",
13
+ };
14
+ const T_QUICK = 10_000;
15
+ const T_SHOT = 20_000;
16
+ const T_TREE = 30_000;
17
+ const KEYCODES = {
18
+ home: "HOME", back: "BACK", recents: "APP_SWITCH", enter: "ENTER", delete: "DEL", tab: "TAB", space: "SPACE",
19
+ escape: "ESCAPE", up: "DPAD_UP", down: "DPAD_DOWN", left: "DPAD_LEFT", right: "DPAD_RIGHT", volume_up: "VOLUME_UP",
20
+ volume_down: "VOLUME_DOWN", power: "POWER", search: "SEARCH", menu: "MENU",
21
+ };
22
+ // Names people say → package ids that do not contain them (phone-harness _APP_IDS). First installed one wins.
23
+ const APP_IDS = {
24
+ tiktok: ["com.zhiliaoapp.musically", "com.ss.android.ugc.trill"], x: ["com.twitter.android"], twitter: ["com.twitter.android"],
25
+ threads: ["com.instagram.barcelona"], facebook: ["com.facebook.katana", "com.facebook.lite"], messenger: ["com.facebook.orca"],
26
+ signal: ["org.thoughtcrime.securesms"], gmail: ["com.google.android.gm"], playstore: ["com.android.vending"],
27
+ googleplay: ["com.android.vending"], uber: ["com.ubercab"], ubereats: ["com.ubercab.eats"], cashapp: ["com.squareup.cash"],
28
+ amazon: ["com.amazon.mShop.android.shopping"], googlemaps: ["com.google.android.apps.maps"], maps: ["com.google.android.apps.maps"],
29
+ messages: ["com.google.android.apps.messaging"], phone: ["com.google.android.dialer", "com.android.dialer"],
30
+ clock: ["com.google.android.deskclock", "com.android.deskclock"], files: ["com.google.android.documentsui", "com.android.documentsui"],
31
+ settings: ["com.android.settings"], chrome: ["com.android.chrome"], camera: ["com.google.android.GoogleCamera", "com.android.camera"],
32
+ };
33
+ export const PACKAGE = /^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/;
34
+ const SERIAL = /^[\w.:\-[\]%]+$/;
35
+ /** One word for the phone's sh: single-quoted, with embedded quotes closed and escaped. */
36
+ export function devQuote(s) {
37
+ return `'${s.replace(/'/g, `'\\''`)}'`;
38
+ }
39
+ /** `adb devices -l` → rows. The first line is the header; a row is `<serial> <state> [key:value …]`. */
40
+ export function parseDevices(out) {
41
+ return out.split(/\r?\n/).slice(1).map((l) => l.trim()).filter(Boolean).map((l) => {
42
+ const [serial = "", state = "", ...rest] = l.split(/\s+/);
43
+ const model = rest.find((p) => p.startsWith("model:"))?.slice(6).replace(/_/g, " ");
44
+ return { serial, state, model, transport: serial.includes(":") || serial.startsWith("adb-") ? "wifi" : "usb" };
45
+ }).filter((d) => d.serial && d.state);
46
+ }
47
+ const XML_ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
48
+ const unxml = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos);/gi, (_, e) => e[0] === "#" ? String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : XML_ENT[e.toLowerCase()] ?? _);
49
+ /** `uiautomator dump` XML → the visible text with box centres (device pixels = screenshot pixels on Android). */
50
+ export function parseTree(xml) {
51
+ const out = [];
52
+ for (const m of xml.matchAll(/<node\b([^>]*?)\/?>/g)) {
53
+ const attrs = {};
54
+ for (const a of m[1].matchAll(/([\w-]+)="([^"]*)"/g))
55
+ attrs[a[1]] = unxml(a[2]);
56
+ const text = (attrs.text || attrs["content-desc"] || "").trim();
57
+ const b = /\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(attrs.bounds ?? "");
58
+ if (!text || !b)
59
+ continue;
60
+ const [x1, y1, x2, y2] = b.slice(1).map(Number);
61
+ out.push({ text, x: Math.round((x1 + x2) / 2), y: Math.round((y1 + y2) / 2), w: x2 - x1, h: y2 - y1 });
62
+ }
63
+ return out;
64
+ }
65
+ export class AndroidBackend {
66
+ serial;
67
+ adb;
68
+ kind = "android";
69
+ gateAt = 0;
70
+ constructor(serial, adb = "adb") {
71
+ this.serial = serial;
72
+ this.adb = adb;
73
+ if (serial !== undefined && !SERIAL.test(serial))
74
+ throw new Unsupported(`"${serial}" is not an adb serial`);
75
+ }
76
+ async raw(args, timeoutMs = T_QUICK) {
77
+ return deviceDeps().run(this.adb, this.serial ? ["-s", this.serial, ...args] : args, { timeoutMs });
78
+ }
79
+ async must(args, timeoutMs = T_QUICK) {
80
+ const r = await this.raw(args, timeoutMs);
81
+ if (r.missing)
82
+ throw new NeedsOwner("adb is not installed", ADB_INSTALL[deviceDeps().platform] ?? "install Android platform-tools");
83
+ if (r.timedOut)
84
+ throw new Error(`adb ${args[0]} did not answer in ${Math.round(timeoutMs / 1000)} s`);
85
+ if (r.code !== 0)
86
+ throw new Error(`adb ${args[0]} failed: ${(r.stderr || r.stdout).trim().slice(0, 300)}`);
87
+ return r;
88
+ }
89
+ sh(...words) { return this.must(["shell", ...words]); }
90
+ async devices() {
91
+ const r = await deviceDeps().run(this.adb, ["devices", "-l"], { timeoutMs: T_QUICK });
92
+ if (r.missing)
93
+ return { devices: [], missing: true };
94
+ return { devices: r.code === 0 ? parseDevices(r.stdout) : [], missing: false };
95
+ }
96
+ async status() {
97
+ const base = { kind: "android", backend: "adb" };
98
+ const { devices, missing } = await this.devices();
99
+ if (missing)
100
+ return { ...base, state: "missing-tool", detail: "adb is not installed", fix: ADB_INSTALL[deviceDeps().platform] ?? "install Android platform-tools" };
101
+ const mine = this.serial ? devices.filter((d) => d.serial === this.serial) : devices;
102
+ const ready = mine.filter((d) => d.state === "device");
103
+ if (ready.length > 1 && !this.serial) {
104
+ return { ...base, state: "ready", detail: `${ready.length} phones attached: ${ready.map((d) => `${d.serial} (${d.model ?? "?"})`).join(", ")} — pass device: "<serial>"`, name: ready[0].model, serial: ready[0].serial };
105
+ }
106
+ if (ready.length) {
107
+ const d = ready[0];
108
+ const locked = await this.lockState(d.serial).catch(() => null);
109
+ if (locked)
110
+ return { ...base, state: "locked", detail: `${d.model ?? d.serial} is locked`, fix: "unlock the phone (Operator never types a PIN)", name: d.model, serial: d.serial };
111
+ return { ...base, state: "ready", detail: `${d.model ?? "Android phone"} over ${d.transport}`, name: d.model, serial: d.serial };
112
+ }
113
+ if (mine.some((d) => d.state === "unauthorized")) {
114
+ return { ...base, state: "unauthorized", detail: "a phone is attached but has not allowed this computer", fix: 'on the phone tap "Allow USB debugging" (tick "Always allow from this computer")' };
115
+ }
116
+ if (mine.length)
117
+ return { ...base, state: "offline", detail: `phone ${mine[0].serial} is ${mine[0].state}`, fix: "unplug and replug the cable, or run: adb kill-server" };
118
+ return { ...base, state: "no-device", detail: "no Android phone attached", fix: "Settings > About phone > tap Build number 7 times, then Developer options > USB debugging on, and plug the phone in" };
119
+ }
120
+ /** true when the keyguard is up. Two dumpsys reads, filtered here (no pipes on the phone). */
121
+ async lockState(serial) {
122
+ const r = await deviceDeps().run(this.adb, ["-s", serial, "shell", "dumpsys", "window"], { timeoutMs: T_QUICK });
123
+ return /isKeyguardShowing=true|mDreamingLockscreen=true/.test(r.stdout);
124
+ }
125
+ /** Wake the screen if it is off (harmless), refuse when it is locked. Cached 2 s so a burst of taps checks once. */
126
+ async gate() {
127
+ const d = deviceDeps();
128
+ if (d.now() - this.gateAt < 2000)
129
+ return;
130
+ const power = await this.sh("dumpsys", "power");
131
+ if (!/mWakefulness=Awake/.test(power.stdout)) {
132
+ await this.sh("input", "keyevent", "KEYCODE_WAKEUP");
133
+ await d.sleep(500);
134
+ }
135
+ const win = await this.sh("dumpsys", "window");
136
+ if (/isKeyguardShowing=true/.test(win.stdout))
137
+ throw new NeedsOwner("the Android phone is locked", "unlock it (PIN or fingerprint); Operator never types a PIN");
138
+ this.gateAt = d.now();
139
+ }
140
+ async ensure() {
141
+ const s = await this.status();
142
+ if (s.state !== "ready")
143
+ throw new NeedsOwner(s.detail, s.fix);
144
+ }
145
+ async screenshot() {
146
+ await this.ensure();
147
+ const r = await this.must(["exec-out", "screencap", "-p"], T_SHOT);
148
+ const size = pngSize(r.bytes);
149
+ if (!size)
150
+ throw new Error("screencap returned no PNG (the screen may be protected: DRM video and some banking apps capture black)");
151
+ const path = await deviceDeps().tempFile("android", "png");
152
+ await deviceDeps().writeFile(path, r.bytes);
153
+ return { path, ...size };
154
+ }
155
+ async read() {
156
+ await this.gate();
157
+ const r = await this.raw(["exec-out", "uiautomator", "dump", "/dev/tty"], T_TREE);
158
+ const xml = r.stdout.slice(Math.max(0, r.stdout.indexOf("<?xml")));
159
+ if (r.code !== 0 || !xml.startsWith("<?xml")) {
160
+ const why = (r.stdout || r.stderr).trim();
161
+ return { source: "none", items: [], note: /idle/.test(why) ? "the accessibility tree is not available on this screen (it never goes idle: video, animation)" : `uiautomator: ${why.slice(0, 200) || "no tree"}` };
162
+ }
163
+ return { source: "accessibility", items: parseTree(xml) };
164
+ }
165
+ async tap(x, y) {
166
+ await this.gate();
167
+ await this.sh("input", "tap", String(Math.round(x)), String(Math.round(y)));
168
+ }
169
+ async swipe(from, to, _shot, durationMs) {
170
+ await this.gate();
171
+ const n = (v) => String(Math.round(v));
172
+ await this.sh("input", "swipe", n(from.x), n(from.y), n(to.x), n(to.y), n(Math.min(Math.max(durationMs, 50), 5000)));
173
+ }
174
+ /** `input text` takes one token: spaces become %s, a newline is ENTER, and the rest is quoted for the phone's sh. */
175
+ async type(text) {
176
+ await this.gate();
177
+ const lines = text.split("\n");
178
+ for (let i = 0; i < lines.length; i++) {
179
+ if (i)
180
+ await this.sh("input", "keyevent", "KEYCODE_ENTER");
181
+ const line = lines[i];
182
+ if (/[^\x20-\x7e]/.test(line))
183
+ throw new Unsupported("adb `input text` types ASCII only; this text has characters it cannot send (emoji, accents)");
184
+ for (let at = 0; at < line.length; at += 200) {
185
+ const chunk = line.slice(at, at + 200).replace(/ /g, "%s"); // a literal "%s" in the text also arrives as a space (an `input text` limit)
186
+ if (chunk)
187
+ await this.sh("input", "text", devQuote(chunk));
188
+ }
189
+ }
190
+ }
191
+ async key(key) {
192
+ const code = KEYCODES[key];
193
+ if (!code)
194
+ throw new Unsupported(`Android has no key named ${key}`);
195
+ if (key !== "power")
196
+ await this.gate();
197
+ await this.sh("input", "keyevent", `KEYCODE_${code}`);
198
+ }
199
+ async packages(all = true) {
200
+ const r = await this.sh("pm", "list", "packages", ...(all ? [] : ["-3"]));
201
+ return r.stdout.split(/\r?\n/).filter((l) => l.startsWith("package:")).map((l) => l.slice(8).trim()).sort();
202
+ }
203
+ /** A package id, or the name a person would say: an installed id, a well-known app, then a fragment of an id. */
204
+ async openApp(name) {
205
+ await this.gate();
206
+ const pkgs = await this.packages();
207
+ const want = name.toLowerCase().replace(/[^a-z0-9]+/g, "");
208
+ let pkg = pkgs.includes(name) ? name : (APP_IDS[want] ?? []).find((p) => pkgs.includes(p));
209
+ if (!pkg && want)
210
+ pkg = pkgs.filter((p) => p.toLowerCase().replace(/\./g, "").includes(want)).sort((a, b) => a.length - b.length)[0];
211
+ if (!pkg || !PACKAGE.test(pkg)) {
212
+ const third = await this.packages(false).catch(() => []);
213
+ throw new Error(`no installed app matches "${name}". Installed apps: ${third.slice(0, 40).join(", ") || "none"}. Pass one of these package ids.`);
214
+ }
215
+ const res = await this.sh("cmd", "package", "resolve-activity", "--brief", "-c", "android.intent.category.LAUNCHER", pkg);
216
+ const comp = res.stdout.split(/\r?\n/).reverse().map((l) => l.trim()).find((l) => l.includes("/"));
217
+ if (!comp || !/^[\w.]+\/[\w.$]+$/.test(comp))
218
+ throw new Error(`${pkg} has no launchable activity`);
219
+ await this.sh("am", "start", "-W", "-n", comp);
220
+ return pkg;
221
+ }
222
+ async currentApp() {
223
+ const r = await this.sh("dumpsys", "activity", "activities");
224
+ const m = /topResumedActivity=ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(r.stdout) ?? /mResumedActivity: ActivityRecord\{[^}]*?\bu\d+ ([\w.]+)\//.exec(r.stdout);
225
+ return m?.[1];
226
+ }
227
+ }
@@ -0,0 +1,127 @@
1
+ // The phone's human-signature lines: phone.spend (money), phone.send (messages, posts, calls), phone.account (sign-in,
2
+ // password, deleting or changing an account). A call in one of these classes ALWAYS asks the owner — in every mode,
3
+ // Autonomous included (an approved plan does not cover it), and "allow always" never covers it — with a screenshot of
4
+ // the screen it will act on. Pure and node-free: permissions/signature.ts imports it from every bundle.
5
+ //
6
+ // A class is read from what the call says (the element text it taps, the text it types, the key it presses, a declared
7
+ // `intent`) and from what Operator last saw on that device (the app in front, the text under a coordinate tap). Like the
8
+ // other signature lines it is conservative: a false positive costs one approval, a miss costs the owner's money.
9
+ //
10
+ // Belt and braces: the gate grants an approved call once (grantPhone); the tool itself refuses a classed call that holds
11
+ // no grant (takeGrant). A policy that skips the gate (a bypass seat, the MCP server, a headless run) therefore still
12
+ // cannot spend, send or change an account on the owner's phone.
13
+ export const PHONE_LINES = ["phone.spend", "phone.send", "phone.account"];
14
+ export const PHONE_LINE_WHAT = {
15
+ "phone.spend": "money: pay, buy, order, book, subscribe, transfer",
16
+ "phone.send": "messages and calls: send, post, reply, call, share",
17
+ "phone.account": "account changes: sign in or out, passwords, delete or change an account",
18
+ };
19
+ export const PHONE_ACTION_TOOLS = ["phone_tap", "phone_type", "phone_swipe", "phone_key", "phone_open_app"];
20
+ const SPEND = /\b(pay|payment|buy|purchase|order|checkout|check out|place order|book( now| ride)?|subscribe|subscription|upgrade|donate|tip|transfer|send money|request money|top ?up|add to cart|confirm (purchase|payment|order)|apple pay|google pay|wallet|bid)\b|[$€£¥₹]\s?\d/i;
21
+ const SEND = /\b(send|post|publish|reply|reply all|tweet|share|call|dial|facetime|video call|forward|invite|comment|submit|message)\b/i;
22
+ const ACCOUNT = /\b(sign (in|out)|log ?(in|out)|password|passcode|delete (my )?account|close account|deactivate|remove account|reset|erase|factory|two[- ]factor|2fa|verification code|recovery|change (email|phone|number)|authorize|allow access|trust this)\b/i;
23
+ // Apps where a bare coordinate tap is presumed to cross a line (nothing better is known about what is under it).
24
+ const SEND_APPS = /\b(messages|whatsapp|signal|telegram|messenger|mail|gmail|outlook|slack|discord|phone|dialer|facetime|instagram|x|twitter|threads|facebook|linkedin|tiktok|snapchat)\b|com\.(whatsapp|google\.android\.apps\.messaging|google\.android\.gm|google\.android\.dialer|android\.dialer|facebook\.orca|twitter\.android|instagram\.android|slack|discord|snapchat\.android)|org\.thoughtcrime\.securesms|org\.telegram/i;
25
+ const SPEND_APPS = /\b(wallet|app ?store|play ?store|amazon|uber|lyft|doordash|ubereats|venmo|paypal|cash ?app|zelle|revolut|wise|bank|banking|robinhood|coinbase|stripe|shop)\b|com\.(android\.vending|amazon|ubercab|squareup\.cash|venmo|paypal|coinbase|robinhood)/i;
26
+ const ACCOUNT_APPS = /\b(settings|passwords|keychain|authenticator|apple ?id|google account)\b|com\.android\.settings|com\.google\.android\.apps\.authenticator/i;
27
+ const observed = new Map();
28
+ /** The harness records what it last saw on a device: the app in front and the text with its boxes. */
29
+ export function observe(device, o) {
30
+ const prev = observed.get(device) ?? { items: [] };
31
+ observed.set(device, { app: o.app ?? prev.app, items: o.items ?? prev.items });
32
+ }
33
+ export function resetObserved() { observed.clear(); grants.clear(); }
34
+ export const deviceOf = (args) => (typeof args.device === "string" && args.device ? args.device : "default");
35
+ function textUnder(device, x, y) {
36
+ const o = observed.get(device) ?? observed.get("default");
37
+ const hits = (o?.items ?? []).filter((t) => Math.abs(x - t.x) <= Math.max(t.w / 2, 12) && Math.abs(y - t.y) <= Math.max(t.h / 2, 12));
38
+ return hits.sort((a, b) => a.w * a.h - b.w * b.h)[0]?.text;
39
+ }
40
+ function byWords(s) {
41
+ if (SPEND.test(s))
42
+ return "phone.spend";
43
+ if (ACCOUNT.test(s))
44
+ return "phone.account";
45
+ if (SEND.test(s))
46
+ return "phone.send";
47
+ return null;
48
+ }
49
+ function byApp(app) {
50
+ if (!app)
51
+ return null;
52
+ if (SPEND_APPS.test(app))
53
+ return "phone.spend";
54
+ if (ACCOUNT_APPS.test(app))
55
+ return "phone.account";
56
+ if (SEND_APPS.test(app))
57
+ return "phone.send";
58
+ return null;
59
+ }
60
+ /** Which phone line a call crosses, or null. Reads only the call and what was last observed. */
61
+ export function phoneLine(name, args) {
62
+ if (!PHONE_ACTION_TOOLS.includes(name))
63
+ return null;
64
+ const intent = typeof args.intent === "string" ? args.intent.toLowerCase() : "";
65
+ const declared = PHONE_LINES.find((l) => intent === l || intent === l.slice(6));
66
+ if (declared)
67
+ return declared;
68
+ const device = deviceOf(args);
69
+ const app = observed.get(device)?.app ?? observed.get("default")?.app;
70
+ switch (name) {
71
+ case "phone_tap": {
72
+ if (typeof args.text === "string" && args.text.trim())
73
+ return byWords(args.text) ?? null;
74
+ const x = Number(args.x), y = Number(args.y);
75
+ const under = Number.isFinite(x) && Number.isFinite(y) ? textUnder(device, x, y) : undefined;
76
+ if (under)
77
+ return byWords(under);
78
+ return byApp(app); // a blind tap: what it hits is unknown, so the app decides
79
+ }
80
+ case "phone_type": {
81
+ const text = typeof args.text === "string" ? args.text : "";
82
+ if (/\b\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{1,4}\b/.test(text))
83
+ return "phone.spend"; // a card number
84
+ if (args.submit === true)
85
+ return byWords(text) ?? byApp(app);
86
+ return byApp(app) === "phone.account" ? "phone.account" : null; // typing into Settings / a password field
87
+ }
88
+ case "phone_key":
89
+ return args.key === "enter" ? byApp(app) : null; // Return sends in a messaging app and confirms elsewhere
90
+ case "phone_swipe":
91
+ return typeof args.text === "string" ? byWords(args.text) : null; // slide-to-pay / slide-to-confirm, when named
92
+ case "phone_open_app":
93
+ return null; // opening an app changes nothing; what is done inside it is classed call by call
94
+ }
95
+ return null;
96
+ }
97
+ // ── One-shot grants: the gate approves, the tool consumes ────────────────────────────────────────────────────────
98
+ const grants = new Map();
99
+ const keyOf = (name, args) => {
100
+ const { intent: _i, ...rest } = args;
101
+ return `${name}\0${JSON.stringify(Object.keys(rest).sort().map((k) => [k, rest[k]]))}`;
102
+ };
103
+ const GRANT_TTL_MS = 120_000;
104
+ /** The owner approved exactly this call (name + args) for one run. */
105
+ export function grantPhone(name, args, now = Date.now()) {
106
+ grants.set(keyOf(name, args), now + GRANT_TTL_MS);
107
+ }
108
+ /** Consume the grant for this call; false when there is none (or it expired). */
109
+ export function takeGrant(name, args, now = Date.now()) {
110
+ const k = keyOf(name, args);
111
+ const until = grants.get(k);
112
+ grants.delete(k);
113
+ return until !== undefined && until >= now;
114
+ }
115
+ let previewFn = null;
116
+ export function setPhonePreview(fn) { previewFn = fn; }
117
+ /** A fresh screenshot of the screen the call will act on, and what it will touch. Never throws. */
118
+ export async function phonePreview(name, args) {
119
+ if (!previewFn)
120
+ return {};
121
+ try {
122
+ return await previewFn(name, args);
123
+ }
124
+ catch (e) {
125
+ return { error: e instanceof Error ? e.message : String(e) };
126
+ }
127
+ }
@@ -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
+ }