@0perator/operator 0.1.360-next.2 → 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.
- package/README.md +1 -1
- package/dist/autonomy/delegate-mode.js +159 -0
- package/dist/autonomy/delegate.js +1 -1
- package/dist/autonomy/session-factory.js +2 -0
- package/dist/background/index.js +26 -2
- package/dist/background/resume.js +125 -0
- package/dist/browser/engine.js +163 -0
- package/dist/browser/session.js +130 -140
- package/dist/cli.js +174 -12
- package/dist/config/settings.js +1 -1
- package/dist/engine/agent.js +1 -1
- package/dist/engine/aurora.js +4 -4
- package/dist/engine/compaction.js +1 -1
- package/dist/engine/moa.js +2 -1
- package/dist/engine/selfheal.js +1 -1
- package/dist/engine/toolcalls.js +6 -6
- package/dist/index.js +3 -0
- package/dist/mcp/phone-server.js +30 -0
- package/dist/permissions/index.js +33 -17
- package/dist/permissions/signature.js +5 -0
- package/dist/phone-cli.js +65 -0
- package/dist/remote/host.js +31 -2
- package/dist/router/models.js +5 -15
- package/dist/selfimprove/index.js +1 -1
- package/dist/session.js +48 -7
- package/dist/tools/deferred.js +1 -0
- package/dist/tools/device/android.js +227 -0
- package/dist/tools/device/classify.js +127 -0
- package/dist/tools/device/deps.js +69 -0
- package/dist/tools/device/desktop.js +82 -0
- package/dist/tools/device/harness.js +262 -0
- package/dist/tools/device/iphone.js +206 -0
- package/dist/tools/device/mirroring-jxa.js +146 -0
- package/dist/tools/device/setup.js +90 -0
- package/dist/tools/device/tools.js +70 -0
- package/dist/tools/device/types.js +19 -0
- package/dist/tools/registry.js +12 -3
- package/dist/ui/App.js +4 -3
- package/dist/ui/ApprovalPrompt.js +10 -4
- package/dist/ui/BgPanel.js +2 -2
- package/dist/ui/UpdatePrompt.js +40 -0
- package/dist/ui/modelPicker.js +1 -1
- package/dist/ui/slashCommands.js +1 -0
- package/dist/update-check.js +134 -0
- package/dist/update.js +59 -15
- package/dist/util/slash.js +2 -2
- package/package.json +4 -2
- package/src/tools/device/NOTICE +37 -0
- package/dist/browser/cdp.js +0 -271
|
@@ -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
|
+
}
|
|
@@ -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
|
+
});
|