@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.
Files changed (49) 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 +2 -0
  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 +130 -140
  9. package/dist/cli.js +174 -12
  10. package/dist/config/settings.js +1 -1
  11. package/dist/engine/agent.js +1 -1
  12. package/dist/engine/aurora.js +4 -4
  13. package/dist/engine/compaction.js +1 -1
  14. package/dist/engine/moa.js +2 -1
  15. package/dist/engine/selfheal.js +1 -1
  16. package/dist/engine/toolcalls.js +6 -6
  17. package/dist/index.js +3 -0
  18. package/dist/mcp/phone-server.js +30 -0
  19. package/dist/permissions/index.js +33 -17
  20. package/dist/permissions/signature.js +5 -0
  21. package/dist/phone-cli.js +65 -0
  22. package/dist/remote/host.js +31 -2
  23. package/dist/router/models.js +5 -15
  24. package/dist/selfimprove/index.js +1 -1
  25. package/dist/session.js +48 -7
  26. package/dist/tools/deferred.js +1 -0
  27. package/dist/tools/device/android.js +227 -0
  28. package/dist/tools/device/classify.js +127 -0
  29. package/dist/tools/device/deps.js +69 -0
  30. package/dist/tools/device/desktop.js +82 -0
  31. package/dist/tools/device/harness.js +262 -0
  32. package/dist/tools/device/iphone.js +206 -0
  33. package/dist/tools/device/mirroring-jxa.js +146 -0
  34. package/dist/tools/device/setup.js +90 -0
  35. package/dist/tools/device/tools.js +70 -0
  36. package/dist/tools/device/types.js +19 -0
  37. package/dist/tools/registry.js +12 -3
  38. package/dist/ui/App.js +4 -3
  39. package/dist/ui/ApprovalPrompt.js +10 -4
  40. package/dist/ui/BgPanel.js +2 -2
  41. package/dist/ui/UpdatePrompt.js +40 -0
  42. package/dist/ui/modelPicker.js +1 -1
  43. package/dist/ui/slashCommands.js +1 -0
  44. package/dist/update-check.js +134 -0
  45. package/dist/update.js +59 -15
  46. package/dist/util/slash.js +2 -2
  47. package/package.json +4 -2
  48. package/src/tools/device/NOTICE +37 -0
  49. package/dist/browser/cdp.js +0 -271
@@ -1,271 +0,0 @@
1
- // Browser automation core (HV3-02) — a zero-new-dependency Chrome DevTools Protocol client.
2
- // WHY: web_fetch is a dumb GET; agents need a REAL page — JS-rendered content, forms, clicks, and
3
- // session state across calls. The discipline inherited from the reference browser layer: TEXT-FIRST —
4
- // read pages as DOM text / JS eval; screenshots only when a human must see pixels.
5
- // Purity: EVERY node builtin is reached via lazy getBuiltinModule/import (same contract as
6
- // src/tools/shell-session.ts) — registry.ts imports this module's wrapper, and run() bodies only
7
- // ever execute on the node CLI (never the neutral browser bundle).
8
- // Transport: global WebSocket (node >=22); falls back to the shipped `ws` dependency on node 20.
9
- const IDLE_TTL_MS = 9 * 60_000; // an idle browser decommissions after 9 min (mirrors the persistent shell)
10
- const CALL_TIMEOUT_MS = 20_000; // per CDP call
11
- const NAV_TIMEOUT_MS = 30_000; // page-load budget
12
- const LAUNCH_TIMEOUT_MS = 15_000; // DevTools URL handshake
13
- async function nodeImport(id) {
14
- const g = globalThis;
15
- try {
16
- const m = g.process?.getBuiltinModule?.(id);
17
- if (m)
18
- return m;
19
- }
20
- catch { /* fall through to dynamic import */ }
21
- return import(id);
22
- }
23
- async function webSocketCtor() {
24
- if (typeof globalThis.WebSocket === "function") {
25
- return globalThis.WebSocket;
26
- }
27
- // string-typed specifier: node 20 fallback to the shipped ws dep without pulling its types into tsc
28
- const modName = "ws";
29
- const mod = (await import(/* webpackIgnore: true */ modName));
30
- return mod.default ?? mod;
31
- }
32
- // ── URL policy — the browser can read anything the USER's session can; that is exactly why the
33
- // policy exists: no file:// (secret paths adjacent), no chrome:// internals.
34
- export function checkNavigationUrl(raw) {
35
- let u;
36
- try {
37
- u = new URL(raw);
38
- }
39
- catch {
40
- return `browser: not a valid URL: ${raw.slice(0, 120)}`;
41
- }
42
- const scheme = u.protocol;
43
- if (scheme === "http:" || scheme === "https:" || scheme === "about:" || scheme === "data:")
44
- return null;
45
- return `browser: scheme '${scheme}' blocked (allow: http, https, about, data — file:// and chrome:// are off the policy)`;
46
- }
47
- /** One CDP connection: id-matched requests, event fan-out, flat multi-session routing. */
48
- export class CdpConnection {
49
- url;
50
- nextId = 1;
51
- pending = new Map();
52
- handlers = new Map();
53
- ws = null;
54
- closed = false;
55
- constructor(url) {
56
- this.url = url;
57
- }
58
- async connect() {
59
- const Ctor = await webSocketCtor();
60
- this.ws = new Ctor(this.url);
61
- const w = this.ws;
62
- await new Promise((res, rej) => {
63
- const to = setTimeout(() => rej(new Error(`browser: ws connect timeout (${CALL_TIMEOUT_MS / 1000}s)`)), CALL_TIMEOUT_MS);
64
- const ok = () => { clearTimeout(to); res(); };
65
- const bad = (m) => { clearTimeout(to); rej(new Error(m)); };
66
- if (typeof w.addEventListener === "function") {
67
- w.addEventListener("open", ok);
68
- w.addEventListener("error", (e) => bad(`browser: ws error: ${String(e?.message ?? e)}`));
69
- }
70
- else if (typeof w.on === "function") {
71
- w.on("open", ok);
72
- w.on("error", (e) => bad(`browser: ws error: ${String(e)}`));
73
- }
74
- else
75
- bad("browser: no usable WebSocket API");
76
- });
77
- const onData = (data) => {
78
- let msg;
79
- try {
80
- msg = JSON.parse(typeof data === "string" ? data : String(data));
81
- }
82
- catch {
83
- return;
84
- }
85
- if (typeof msg.id === "number") {
86
- const p = this.pending.get(msg.id);
87
- if (p) {
88
- this.pending.delete(msg.id);
89
- clearTimeout(p.timer);
90
- if (msg.error)
91
- p.reject(new Error(`cdp ${msg.method ?? "?"}: ${msg.error.message}`));
92
- else
93
- p.resolve(msg.result);
94
- }
95
- return;
96
- }
97
- if (msg.method) {
98
- const set = this.handlers.get(msg.method);
99
- if (set)
100
- for (const f of set) {
101
- try {
102
- f(msg.params);
103
- }
104
- catch { /* a listener never breaks the stream */ }
105
- }
106
- }
107
- };
108
- if (typeof this.ws.addEventListener === "function")
109
- this.ws.addEventListener("message", (e) => onData(e.data));
110
- else if (typeof this.ws.on === "function")
111
- this.ws.on("message", onData);
112
- }
113
- send(method, params, sessionId) {
114
- if (this.closed || !this.ws)
115
- return Promise.reject(new Error("browser: connection closed"));
116
- const id = this.nextId++;
117
- const payload = sessionId ? { id, method, params, sessionId } : { id, method, params };
118
- return new Promise((res, rej) => {
119
- const timer = setTimeout(() => { this.pending.delete(id); rej(new Error(`cdp timeout: ${method}`)); }, CALL_TIMEOUT_MS);
120
- this.pending.set(id, { resolve: res, reject: rej, timer });
121
- try {
122
- this.ws.send(JSON.stringify(payload));
123
- }
124
- catch (e) {
125
- this.pending.delete(id);
126
- clearTimeout(timer);
127
- rej(e);
128
- }
129
- });
130
- }
131
- on(method, fn) {
132
- let set = this.handlers.get(method);
133
- if (!set) {
134
- set = new Set();
135
- this.handlers.set(method, set);
136
- }
137
- set.add(fn);
138
- return () => set.delete(fn);
139
- }
140
- once(method) {
141
- return new Promise((res) => { const off = this.on(method, (p) => { off(); res(p); }); });
142
- }
143
- close() {
144
- this.closed = true;
145
- try {
146
- this.ws?.close();
147
- }
148
- catch { /* already gone */ }
149
- for (const p of this.pending.values()) {
150
- clearTimeout(p.timer);
151
- p.reject(new Error("browser: connection closed"));
152
- }
153
- this.pending.clear();
154
- }
155
- }
156
- // ── Chrome discovery + launch ───────────────────────────────────────────────
157
- export function chromeCandidates() {
158
- const env = globalThis.process?.env;
159
- if (env?.KODE_CHROME)
160
- return [env.KODE_CHROME];
161
- return [
162
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
163
- "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
164
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
165
- "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser",
166
- ];
167
- }
168
- export function chromeArgv(wsPort, profileDir) {
169
- return [
170
- "--headless=new", `--remote-debugging-port=${wsPort}`, `--user-data-dir=${profileDir}`,
171
- "--no-first-run", "--no-default-browser-check", "--disable-background-networking",
172
- "--disable-component-update", "--disable-sync", "about:blank",
173
- ];
174
- }
175
- /** Launch a headless Chrome, resolve its DevTools WebSocket URL from the "DevTools listening on" line. */
176
- export async function launchChrome() {
177
- const cp = await nodeImport("node:child_process");
178
- const fs = await nodeImport("node:fs");
179
- const { spawn } = cp;
180
- const exe = chromeCandidates().find((c) => fs.existsSync(c));
181
- if (!exe)
182
- throw new Error(`browser: no Chrome found among: ${chromeCandidates().join(", ")} — install Chrome or set the browser executable override in the environment`);
183
- let profileDir;
184
- try {
185
- const { operatorPath } = await nodeImport("../config/home.js");
186
- profileDir = operatorPath("browser"); // $KODE_HOME/browser — profile persists across relaunches
187
- fs.mkdirSync(profileDir, { recursive: true });
188
- }
189
- catch {
190
- const os = await nodeImport("node:os");
191
- profileDir = fs.mkdtempSync(`${os.tmpdir()}/kode-browser-`);
192
- }
193
- // Hardening: pre-seed profile prefs so Chrome never saves submitted credentials into the
194
- // profile's Login Data (the vault owns secrets; a browser profile that silently hoards them
195
- // would break the zero-secret invariant the HV3-02b proof asserts).
196
- try {
197
- const prefDir = `${profileDir}/Default`;
198
- fs.mkdirSync(prefDir, { recursive: true });
199
- const prefFile = `${prefDir}/Preferences`;
200
- if (!fs.existsSync(prefFile)) {
201
- fs.writeFileSync(prefFile, JSON.stringify({
202
- credentials_enable_service: false,
203
- profile: { password_manager_enabled: false },
204
- }));
205
- }
206
- }
207
- catch { /* best-effort; e2e scan is the backstop */ }
208
- const proc = spawn(exe, chromeArgv(0, profileDir), { stdio: ["ignore", "ignore", "pipe"], detached: false });
209
- try { // killed at exit, reaped if we crash (Chrome outlives a SIGKILLed parent). Lazy like every import here; never blocks the launch.
210
- const { ownChild } = await nodeImport("../util/owned-children.js");
211
- ownChild(proc, "chrome", { cmd: exe });
212
- }
213
- catch { /* tracking is best-effort */ }
214
- const wsUrl = await new Promise((res, rej) => {
215
- let buf = "";
216
- const to = setTimeout(() => rej(new Error(`browser: Chrome printed no DevTools URL within ${LAUNCH_TIMEOUT_MS / 1000}s${buf ? `; stderr tail: ${buf.slice(-300)}` : ""}`)), LAUNCH_TIMEOUT_MS);
217
- proc.stderr?.on("data", (d) => {
218
- buf += d.toString("utf8");
219
- const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
220
- if (m) {
221
- clearTimeout(to);
222
- res(m[1]);
223
- }
224
- });
225
- proc.on("exit", (code) => {
226
- const late = buf.match(/DevTools listening on (ws:\/\/\S+)/);
227
- if (late) {
228
- clearTimeout(to);
229
- res(late[1]);
230
- return;
231
- }
232
- clearTimeout(to);
233
- rej(new Error(`browser: Chrome exited (code ${code}) before DevTools: ${buf.slice(0, 300)}`));
234
- });
235
- proc.on("error", (e) => { clearTimeout(to); rej(new Error(`browser: spawn failed: ${e.message}`)); });
236
- });
237
- return { proc, wsUrl };
238
- }
239
- // ── Runtime value shaping ───────────────────────────────────────────────────
240
- /** Shape a Runtime.evaluate response into plain text, or throw a readable error. Exported for tests. */
241
- export function evalResultToText(raw) {
242
- if (raw?.exceptionDetails) {
243
- const e = raw.exceptionDetails;
244
- throw new Error(`browser js error: ${e.exception?.description ?? e.text ?? "unknown"}`);
245
- }
246
- const v = raw?.result?.value;
247
- if (typeof v === "string")
248
- return v;
249
- if (v === undefined || v === null)
250
- return String(v);
251
- try {
252
- return JSON.stringify(v);
253
- }
254
- catch {
255
- return String(v);
256
- }
257
- }
258
- /** JS that fills an input like a user (React/Vue-safe: native value setter, then input+change events). */
259
- export function fillScript(selector, value) {
260
- return `(() => {
261
- const el = document.querySelector(${JSON.stringify(selector)});
262
- if (!el) throw new Error("element not found: " + ${JSON.stringify(selector)});
263
- const proto = el.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
264
- const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
265
- if (setter) setter.call(el, ${JSON.stringify(value)}); else el.value = ${JSON.stringify(value)};
266
- el.dispatchEvent(new Event("input", { bubbles: true }));
267
- el.dispatchEvent(new Event("change", { bubbles: true }));
268
- return String(el.value);
269
- })()`;
270
- }
271
- export const BROWSER_CONSTANTS = { IDLE_TTL_MS, CALL_TIMEOUT_MS, NAV_TIMEOUT_MS, LAUNCH_TIMEOUT_MS };