@0perator/operator 0.1.235 → 0.1.261
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 +2 -1
- package/dashboard/server.mjs +1 -1
- package/dist/acp/agent.js +290 -62
- package/dist/acp/auth.js +44 -0
- package/dist/acp/prompt.js +41 -0
- package/dist/acp/run.js +40 -15
- package/dist/acp/tool-map.js +48 -0
- package/dist/auth/byo.js +15 -8
- package/dist/auth/client.js +12 -6
- package/dist/auth/commands.js +39 -4
- package/dist/auth/identity.js +136 -0
- package/dist/auth/store.js +7 -5
- package/dist/autonomy/board.js +3 -2
- package/dist/autonomy/cron.js +332 -0
- package/dist/autonomy/delegate.js +168 -0
- package/dist/autonomy/media-robot.js +2 -3
- package/dist/autonomy/routines.js +5 -4
- package/dist/autonomy/session-factory.js +6 -1
- package/dist/browser/cdp.js +266 -0
- package/dist/browser/session.js +286 -0
- package/dist/cli.js +75 -11
- package/dist/config/brand.js +3 -3
- package/dist/config/home.js +70 -0
- package/dist/config/managed.js +230 -0
- package/dist/config/persona.js +59 -9
- package/dist/config/scaffold.js +142 -0
- package/dist/config/settings.js +38 -4
- package/dist/config/skills-index.js +175 -0
- package/dist/consolidation/scheduler.js +3 -3
- package/dist/consolidation/sleep.js +3 -3
- package/dist/engine/agent.js +80 -13
- package/dist/engine/aurora.js +6 -0
- package/dist/engine/batch-scheduler.js +128 -0
- package/dist/engine/json-repair.js +105 -0
- package/dist/engine/messages.js +50 -3
- package/dist/engine/rolling-summary.js +7 -5
- package/dist/enterprise/cli.js +137 -0
- package/dist/flywheel/processor.js +30 -2
- package/dist/flywheel/secret-gate.js +123 -0
- package/dist/mcp/index.js +18 -24
- package/dist/memory/index.js +0 -0
- package/dist/memory/session-index.js +324 -0
- package/dist/memory/session-rewind.js +92 -0
- package/dist/memory/state-maintenance.js +441 -0
- package/dist/observability/index.js +3 -3
- package/dist/permissions/index.js +24 -12
- package/dist/router/models.js +27 -8
- package/dist/selfimprove/index.js +9 -7
- package/dist/session.js +16 -6
- package/dist/skills/catalogue.js +167 -0
- package/dist/telemetry/audit-verify.js +94 -0
- package/dist/telemetry/events.js +86 -6
- package/dist/telemetry/lifecycle.js +18 -0
- package/dist/tools/deferred.js +117 -0
- package/dist/tools/executor.js +19 -20
- package/dist/tools/memory.js +117 -0
- package/dist/tools/registry.js +152 -21
- package/dist/tools/sandbox.js +63 -17
- package/dist/tools/searxng.js +2 -2
- package/dist/tools/tool-output-spill.js +2 -2
- package/dist/ui/Transcript.js +14 -2
- package/dist/ui/useInputHistory.js +3 -3
- package/dist/vault/cli.js +48 -0
- package/dist/vault/store.js +157 -0
- package/dist/vault/tool.js +50 -0
- package/package.json +3 -5
- package/CHANGELOG.md +0 -2487
- package/dist/ui/BusTray.js +0 -70
|
@@ -0,0 +1,266 @@
|
|
|
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 Hermes' 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
|
+
const wsUrl = await new Promise((res, rej) => {
|
|
210
|
+
let buf = "";
|
|
211
|
+
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);
|
|
212
|
+
proc.stderr?.on("data", (d) => {
|
|
213
|
+
buf += d.toString("utf8");
|
|
214
|
+
const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
|
|
215
|
+
if (m) {
|
|
216
|
+
clearTimeout(to);
|
|
217
|
+
res(m[1]);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
proc.on("exit", (code) => {
|
|
221
|
+
const late = buf.match(/DevTools listening on (ws:\/\/\S+)/);
|
|
222
|
+
if (late) {
|
|
223
|
+
clearTimeout(to);
|
|
224
|
+
res(late[1]);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
clearTimeout(to);
|
|
228
|
+
rej(new Error(`browser: Chrome exited (code ${code}) before DevTools: ${buf.slice(0, 300)}`));
|
|
229
|
+
});
|
|
230
|
+
proc.on("error", (e) => { clearTimeout(to); rej(new Error(`browser: spawn failed: ${e.message}`)); });
|
|
231
|
+
});
|
|
232
|
+
return { proc, wsUrl };
|
|
233
|
+
}
|
|
234
|
+
// ── Runtime value shaping ───────────────────────────────────────────────────
|
|
235
|
+
/** Shape a Runtime.evaluate response into plain text, or throw a readable error. Exported for tests. */
|
|
236
|
+
export function evalResultToText(raw) {
|
|
237
|
+
if (raw?.exceptionDetails) {
|
|
238
|
+
const e = raw.exceptionDetails;
|
|
239
|
+
throw new Error(`browser js error: ${e.exception?.description ?? e.text ?? "unknown"}`);
|
|
240
|
+
}
|
|
241
|
+
const v = raw?.result?.value;
|
|
242
|
+
if (typeof v === "string")
|
|
243
|
+
return v;
|
|
244
|
+
if (v === undefined || v === null)
|
|
245
|
+
return String(v);
|
|
246
|
+
try {
|
|
247
|
+
return JSON.stringify(v);
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return String(v);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** JS that fills an input like a user (React/Vue-safe: native value setter, then input+change events). */
|
|
254
|
+
export function fillScript(selector, value) {
|
|
255
|
+
return `(() => {
|
|
256
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
257
|
+
if (!el) throw new Error("element not found: " + ${JSON.stringify(selector)});
|
|
258
|
+
const proto = el.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
|
259
|
+
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
|
|
260
|
+
if (setter) setter.call(el, ${JSON.stringify(value)}); else el.value = ${JSON.stringify(value)};
|
|
261
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
262
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
263
|
+
return String(el.value);
|
|
264
|
+
})()`;
|
|
265
|
+
}
|
|
266
|
+
export const BROWSER_CONSTANTS = { IDLE_TTL_MS, CALL_TIMEOUT_MS, NAV_TIMEOUT_MS, LAUNCH_TIMEOUT_MS };
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
// Persistent browser session + the two registry surfaces for HV3-02.
|
|
2
|
+
// ONE headless Chrome per Operator session (mirrors src/tools/shell-session.ts): pages, cookies and
|
|
3
|
+
// scroll state persist across tool calls; an idle browser decommissions on TTL; a dead Chrome
|
|
4
|
+
// respawns transparently. Tools are split READ vs ACT so the registry-derived permission policy
|
|
5
|
+
// (0.1.226) can let gated/plan mode READ pages freely while every page MUTATION stays gated.
|
|
6
|
+
import { CdpConnection, launchChrome, checkNavigationUrl, evalResultToText, fillScript, BROWSER_CONSTANTS, } from "./cdp.js";
|
|
7
|
+
async function nodeImport(id) {
|
|
8
|
+
const g = globalThis;
|
|
9
|
+
try {
|
|
10
|
+
const m = g.process?.getBuiltinModule?.(id);
|
|
11
|
+
if (m)
|
|
12
|
+
return m;
|
|
13
|
+
}
|
|
14
|
+
catch { /* dynamic */ }
|
|
15
|
+
return import(id);
|
|
16
|
+
}
|
|
17
|
+
class BrowserSession {
|
|
18
|
+
conn = null;
|
|
19
|
+
proc = null;
|
|
20
|
+
tabs = [];
|
|
21
|
+
active = -1;
|
|
22
|
+
lastUsed = 0;
|
|
23
|
+
async ensure() {
|
|
24
|
+
const now = Date.now();
|
|
25
|
+
const alive = this.conn && this.proc && this.proc.exitCode == null &&
|
|
26
|
+
now - this.lastUsed < BROWSER_CONSTANTS.IDLE_TTL_MS;
|
|
27
|
+
if (alive) {
|
|
28
|
+
this.lastUsed = now;
|
|
29
|
+
return this.conn;
|
|
30
|
+
}
|
|
31
|
+
await this.dispose(); // TTL expiry or dead child: rebuild clean (cookies live in the $KODE_HOME/browser profile, so a relaunch is cheap for state)
|
|
32
|
+
const { proc, wsUrl } = await launchChrome();
|
|
33
|
+
const conn = new CdpConnection(wsUrl);
|
|
34
|
+
await conn.connect();
|
|
35
|
+
this.proc = proc;
|
|
36
|
+
this.conn = conn;
|
|
37
|
+
this.tabs = [];
|
|
38
|
+
this.active = -1;
|
|
39
|
+
this.lastUsed = Date.now();
|
|
40
|
+
return conn;
|
|
41
|
+
}
|
|
42
|
+
/** Attach a fresh tab (target) and make it active. */
|
|
43
|
+
async newTab(conn, url) {
|
|
44
|
+
const created = await conn.send("Target.createTarget", { url: "about:blank" });
|
|
45
|
+
const attached = await conn.send("Target.attachToTarget", { targetId: created.targetId, flatten: true });
|
|
46
|
+
const tab = { targetId: created.targetId, sessionId: attached.sessionId, url: "about:blank" };
|
|
47
|
+
this.tabs.push(tab);
|
|
48
|
+
this.active = this.tabs.length - 1;
|
|
49
|
+
await conn.send("Page.enable", {}, tab.sessionId);
|
|
50
|
+
await conn.send("Runtime.enable", {}, tab.sessionId);
|
|
51
|
+
if (url !== "about:blank")
|
|
52
|
+
await this.navigate(conn, tab, url);
|
|
53
|
+
return tab;
|
|
54
|
+
}
|
|
55
|
+
tab() {
|
|
56
|
+
if (this.active < 0 || !this.tabs[this.active])
|
|
57
|
+
throw new Error("browser: no active tab — call open first");
|
|
58
|
+
return this.tabs[this.active];
|
|
59
|
+
}
|
|
60
|
+
async navigate(conn, tab, url) {
|
|
61
|
+
const blocked = checkNavigationUrl(url);
|
|
62
|
+
if (blocked)
|
|
63
|
+
throw new Error(blocked);
|
|
64
|
+
const loadFired = conn.once("Page.loadEventFired"); // subscribe BEFORE navigate so we never miss it
|
|
65
|
+
await conn.send("Page.navigate", { url }, tab.sessionId);
|
|
66
|
+
const settled = await Promise.race([
|
|
67
|
+
loadFired.then(() => "load"),
|
|
68
|
+
new Promise((res) => setTimeout(() => res("timeout"), BROWSER_CONSTANTS.NAV_TIMEOUT_MS)),
|
|
69
|
+
]);
|
|
70
|
+
// load fired (or timed out) — give SPAs a beat to paint, then confirm readyState
|
|
71
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
72
|
+
try {
|
|
73
|
+
const rs = await conn.send("Runtime.evaluate", { expression: "document.readyState", returnByValue: true }, tab.sessionId);
|
|
74
|
+
tab.url = (await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, tab.sessionId))?.result?.value ?? url;
|
|
75
|
+
void settled;
|
|
76
|
+
void rs;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
tab.url = url;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async evaluate(expr, awaitPromise = false) {
|
|
83
|
+
const conn = await this.ensure();
|
|
84
|
+
const t = this.tab();
|
|
85
|
+
const raw = await conn.send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise }, t.sessionId);
|
|
86
|
+
return evalResultToText(raw);
|
|
87
|
+
}
|
|
88
|
+
async run(action, a) {
|
|
89
|
+
const conn = await this.ensure();
|
|
90
|
+
switch (action) {
|
|
91
|
+
case "open": {
|
|
92
|
+
const url = String(a.url ?? "about:blank");
|
|
93
|
+
await this.newTab(conn, url);
|
|
94
|
+
return this.infoInner(conn);
|
|
95
|
+
}
|
|
96
|
+
case "navigate": {
|
|
97
|
+
await this.navigate(conn, this.tab(), String(a.url));
|
|
98
|
+
return this.infoInner(conn);
|
|
99
|
+
}
|
|
100
|
+
case "reload": {
|
|
101
|
+
await conn.send("Page.reload", { ignoreCache: !!a.cache_bust }, this.tab().sessionId);
|
|
102
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
103
|
+
return this.infoInner(conn);
|
|
104
|
+
}
|
|
105
|
+
case "back":
|
|
106
|
+
case "forward": {
|
|
107
|
+
// history via JS (no CDP history domain): simplest reliable path
|
|
108
|
+
await this.evaluate(action === "back" ? "history.back(); 'back'" : "history.forward(); 'forward'");
|
|
109
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
110
|
+
return this.infoInner(conn);
|
|
111
|
+
}
|
|
112
|
+
case "info": return this.infoInner(conn);
|
|
113
|
+
case "text": {
|
|
114
|
+
const max = Math.max(500, Math.min(Number(a.max_chars ?? 20000), 100_000));
|
|
115
|
+
const title = await this.evaluate("document.title");
|
|
116
|
+
const url = await this.evaluate("location.href");
|
|
117
|
+
const body = await this.evaluate("(() => { const b = document.body; const t = b ? b.innerText : ''; return t.replace(/\\n{3,}/g, '\\n\\n').slice(0, " + max + "); })()");
|
|
118
|
+
return `# ${title}\n${url}\n\n${body}`;
|
|
119
|
+
}
|
|
120
|
+
case "eval": {
|
|
121
|
+
const out = await this.evaluate(String(a.js ?? "1"), true);
|
|
122
|
+
return String(out);
|
|
123
|
+
}
|
|
124
|
+
case "click": {
|
|
125
|
+
const sel = String(a.selector);
|
|
126
|
+
const out = await this.evaluate(`(() => {
|
|
127
|
+
const el = document.querySelector(${JSON.stringify(sel)});
|
|
128
|
+
if (!el) throw new Error("element not found: " + ${JSON.stringify(sel)});
|
|
129
|
+
el.scrollIntoView({ block: "center" });
|
|
130
|
+
if (typeof el.click === "function") el.click(); else el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
|
131
|
+
return "clicked " + (el.tagName + (el.id ? "#" + el.id : "")).toLowerCase();
|
|
132
|
+
})()`);
|
|
133
|
+
await new Promise((r) => setTimeout(r, Number(a.settle_ms ?? 250)));
|
|
134
|
+
return String(out);
|
|
135
|
+
}
|
|
136
|
+
case "fill": {
|
|
137
|
+
const out = await this.evaluate(fillScript(String(a.selector), String(a.text ?? "")));
|
|
138
|
+
return `filled ${a.selector}: ${out}`;
|
|
139
|
+
}
|
|
140
|
+
case "submit": {
|
|
141
|
+
return String(await this.evaluate(`(() => {
|
|
142
|
+
const el = document.querySelector(${JSON.stringify(String(a.selector))});
|
|
143
|
+
const f = el && (el.form || (el.tagName === "FORM" ? el : null));
|
|
144
|
+
if (!f) throw new Error("no form for selector: " + ${JSON.stringify(String(a.selector))});
|
|
145
|
+
if (typeof f.requestSubmit === "function") f.requestSubmit(); else f.submit();
|
|
146
|
+
return "submitted " + (f.action || "(inline)");
|
|
147
|
+
})()`));
|
|
148
|
+
}
|
|
149
|
+
case "tab_list": {
|
|
150
|
+
const list = await conn.send("Target.getTargets", {});
|
|
151
|
+
const pages = list.targetInfos.filter((x) => x.type === "page");
|
|
152
|
+
return pages.map((p, i) => `${i === this.active ? "*" : " "} ${i} ${p.title || "(untitled)"} — ${p.url.slice(0, 120)}`).join("\n") || "(no pages)";
|
|
153
|
+
}
|
|
154
|
+
case "tab_select": {
|
|
155
|
+
const i = Number(a.index);
|
|
156
|
+
if (!this.tabs[i])
|
|
157
|
+
throw new Error(`browser: no tab ${i} (have ${this.tabs.length})`);
|
|
158
|
+
this.active = i;
|
|
159
|
+
return this.infoInner(conn);
|
|
160
|
+
}
|
|
161
|
+
case "tab_close": {
|
|
162
|
+
const i = Number.isFinite(Number(a.index)) ? Number(a.index) : this.active;
|
|
163
|
+
const t = this.tabs[i];
|
|
164
|
+
if (!t)
|
|
165
|
+
throw new Error(`browser: no tab ${i}`);
|
|
166
|
+
await conn.send("Target.closeTarget", { targetId: t.targetId }).catch(() => undefined);
|
|
167
|
+
this.tabs.splice(i, 1);
|
|
168
|
+
this.active = Math.min(this.active, this.tabs.length - 1);
|
|
169
|
+
return `closed tab ${i}; ${this.tabs.length} left`;
|
|
170
|
+
}
|
|
171
|
+
case "screenshot": {
|
|
172
|
+
const shot = await conn.send("Page.captureScreenshot", { format: "png" }, this.tab().sessionId);
|
|
173
|
+
const bytes = Math.round(shot.data.length * 3 / 4); // base64 → raw size
|
|
174
|
+
const { mkdirSync, writeFileSync } = await nodeImport("node:fs");
|
|
175
|
+
const { operatorPath } = await nodeImport("../config/home.js");
|
|
176
|
+
let path;
|
|
177
|
+
try {
|
|
178
|
+
const dir = operatorPath("cache", "browser");
|
|
179
|
+
mkdirSync(dir, { recursive: true });
|
|
180
|
+
path = `${dir}/shot-${Date.now()}.png`;
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
const os = await nodeImport("node:os");
|
|
184
|
+
path = `${os.tmpdir()}/kode-shot-${Date.now()}.png`;
|
|
185
|
+
}
|
|
186
|
+
writeFileSync(path, shot.data, "base64");
|
|
187
|
+
return `screenshot ${path} (${Math.round(bytes / 1024)} KB) — pass to image_analyze if you must see pixels; prefer text/eval`;
|
|
188
|
+
}
|
|
189
|
+
case "close": {
|
|
190
|
+
await this.dispose();
|
|
191
|
+
return "browser closed";
|
|
192
|
+
}
|
|
193
|
+
default: throw new Error(`browser: unknown action '${action}'`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
async infoInner(conn) {
|
|
197
|
+
try {
|
|
198
|
+
const title = await conn.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, this.tab().sessionId);
|
|
199
|
+
const url = await conn.send("Runtime.evaluate", { expression: "location.href + ' | ' + document.readyState", returnByValue: true }, this.tab().sessionId);
|
|
200
|
+
return `${title?.result?.value || "(untitled)"} — ${url?.result?.value ?? "?"}`;
|
|
201
|
+
}
|
|
202
|
+
catch (e) {
|
|
203
|
+
return `info failed: ${e.message}`;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async dispose() {
|
|
207
|
+
try {
|
|
208
|
+
this.conn?.close();
|
|
209
|
+
}
|
|
210
|
+
catch { /* gone */ }
|
|
211
|
+
this.conn = null;
|
|
212
|
+
try {
|
|
213
|
+
this.proc?.kill?.("SIGTERM");
|
|
214
|
+
}
|
|
215
|
+
catch { /* gone */ }
|
|
216
|
+
this.proc = null;
|
|
217
|
+
this.tabs = [];
|
|
218
|
+
this.active = -1;
|
|
219
|
+
}
|
|
220
|
+
/** href of the active tab (origin-bound vault checks). Throws cleanly when no page. */
|
|
221
|
+
async href() {
|
|
222
|
+
const conn = await this.ensure();
|
|
223
|
+
const t = this.tab();
|
|
224
|
+
const r = await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, t.sessionId);
|
|
225
|
+
const v = r?.result?.value;
|
|
226
|
+
if (!v)
|
|
227
|
+
throw new Error("no active page href");
|
|
228
|
+
return v;
|
|
229
|
+
}
|
|
230
|
+
/** Fill user+password fields atomically from the VAULT PATH — the secret value is a parameter to
|
|
231
|
+
* this function only; callers above (tool glue) must never echo it back. */
|
|
232
|
+
async fillPair(userSel, userVal, passSel, passVal) {
|
|
233
|
+
await this.evaluate(fillScript(userSel, userVal));
|
|
234
|
+
await this.evaluate(fillScript(passSel, passVal));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
let singleton = null;
|
|
238
|
+
function session() {
|
|
239
|
+
if (!singleton)
|
|
240
|
+
singleton = new BrowserSession();
|
|
241
|
+
return singleton;
|
|
242
|
+
}
|
|
243
|
+
/** Async graceful teardown (TTL/idle paths). */
|
|
244
|
+
export async function disposeBrowser() {
|
|
245
|
+
if (singleton) {
|
|
246
|
+
await singleton.dispose();
|
|
247
|
+
singleton = null;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/** SYNC teardown for process-exit hooks — the same contract as disposeShellSession(): the SIGTERM
|
|
251
|
+
* is delivered synchronously inside dispose(), so the Chrome child is signaled before
|
|
252
|
+
* process.exit() can leave it orphaned. */
|
|
253
|
+
export function disposeBrowserNow() {
|
|
254
|
+
if (!singleton)
|
|
255
|
+
return;
|
|
256
|
+
void singleton.dispose().catch(() => undefined);
|
|
257
|
+
singleton = null;
|
|
258
|
+
}
|
|
259
|
+
export const BROWSER_READ_ACTIONS = ["info", "text", "tab_list"];
|
|
260
|
+
export const BROWSER_ACT_ACTIONS = ["open", "navigate", "reload", "back", "forward", "eval", "click", "fill", "submit", "tab_select", "tab_close", "screenshot", "close"];
|
|
261
|
+
/** The vault glue needs these two session primitives. */
|
|
262
|
+
export const browserSessionHooks = {
|
|
263
|
+
activeHref: () => session().href(),
|
|
264
|
+
fillPair: (u, uv, p, pv) => session().fillPair(u, uv, p, pv),
|
|
265
|
+
};
|
|
266
|
+
/** run() for the `browser` tool (ACT side, plus reads for convenience in ungated modes). */
|
|
267
|
+
export async function runBrowser(args) {
|
|
268
|
+
try {
|
|
269
|
+
return await session().run(String(args.action ?? "info"), args);
|
|
270
|
+
}
|
|
271
|
+
catch (e) {
|
|
272
|
+
const msg = e?.message ?? String(e);
|
|
273
|
+
if (/devtools|spawn|ws |Chrome|chrome/.test(msg))
|
|
274
|
+
return `browser: ${msg}`;
|
|
275
|
+
return `browser error: ${msg}`;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** run() for the `browser_read` tool — read-only actions ONLY (the registry-derived permission
|
|
279
|
+
* policy lets safe tools flow in gated/plan/dream; eval/click/fill stay behind the gated one). */
|
|
280
|
+
export async function runBrowserRead(args) {
|
|
281
|
+
const action = String(args.action ?? "info");
|
|
282
|
+
if (!BROWSER_READ_ACTIONS.includes(action)) {
|
|
283
|
+
return `browser_read: '${action}' mutates or executes — use the gated 'browser' tool`;
|
|
284
|
+
}
|
|
285
|
+
return runBrowser({ ...args, action });
|
|
286
|
+
}
|