@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.
- 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 +8 -2
- 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 +172 -134
- package/dist/cli.js +261 -70
- package/dist/config/settings.js +28 -7
- package/dist/config/skills-index.js +4 -0
- package/dist/engine/agent.js +1 -1
- package/dist/engine/aurora.js +22 -13
- package/dist/engine/compaction.js +1 -1
- package/dist/engine/moa.js +2 -1
- package/dist/engine/selfheal.js +1 -1
- package/dist/engine/speed-compaction.js +37 -0
- package/dist/engine/toolcalls.js +6 -6
- package/dist/gateway-cli.js +14 -5
- 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 +49 -25
- package/dist/selfimprove/index.js +1 -1
- package/dist/services/preflight.js +31 -8
- package/dist/session.js +96 -14
- 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 +242 -48
- package/dist/tools/vision-media.js +162 -0
- 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 +26 -8
- package/dist/ui/slashCommands.js +1 -0
- package/dist/update-check.js +134 -0
- package/dist/update.js +82 -13
- 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
package/dist/update.js
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
// `operator update` — self-update (bareword, like a CLI self-updater). Two install shapes:
|
|
2
2
|
// • packaged → the published package. update = the channel's build from the public download URL (the one
|
|
3
3
|
// install.sh uses), sha256-verified: `latest` (main's releases, the default and `--latest`) or `next`
|
|
4
|
-
// (`--next`:
|
|
4
|
+
// (`--next`: M.N.P-next.K prereleases from develop). When that URL can't be reached, the npm
|
|
5
5
|
// registry's dist-tag of the same name, as before.
|
|
6
6
|
// • source/dev → a git checkout linked via `npm link`; update = pull + rebuild.
|
|
7
7
|
// We detect the shape from where THIS module resolves: a checkout still has a .git above it;
|
|
8
8
|
// a global install lives under a node_modules tree with no repo around it.
|
|
9
|
-
import { spawnSync, execSync } from "node:child_process";
|
|
9
|
+
import { execFile, spawnSync, execSync } from "node:child_process";
|
|
10
10
|
import { createHash } from "node:crypto";
|
|
11
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { existsSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
12
12
|
import { homedir, tmpdir } from "node:os";
|
|
13
13
|
import { dirname, join, resolve } from "node:path";
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
15
|
const PKG = "@0perator/operator"; // published (private) scope/name — keep in sync with package.json
|
|
16
16
|
const DIST_BASE = "https://0perator.co/dl"; // latest.txt, next.txt, SHA256SUMS, operator-<version>.tgz (docs/INSTALL-CURL.md)
|
|
17
|
+
export const distBase = () => process.env.OPERATOR_DIST_BASE || DIST_BASE;
|
|
17
18
|
// An install made by install.sh: <root>/releases/<version>/node_modules/@0perator/operator, linked into a bin folder.
|
|
18
19
|
const RELEASE_PKG = /^(.*)\/releases\/[^/]+\/node_modules\/@0perator\/operator\/package\.json$/;
|
|
19
20
|
/** `--next` or `--latest`; `explicit` says a flag picked it. Both flags is a usage error. With no flag an install stays
|
|
@@ -27,8 +28,26 @@ export function updateChannel(args, current) {
|
|
|
27
28
|
return { channel: next ? "next" : "latest", explicit: true };
|
|
28
29
|
return { channel: current ? channelOf(current) : "latest", explicit: false };
|
|
29
30
|
}
|
|
30
|
-
// A next build is a
|
|
31
|
-
const channelOf = (version) => (/-next\.\d+$/.test(version) ? "next" : "latest");
|
|
31
|
+
// A next build is a M.N.P-next.K prerelease; a release is a plain M.N.P.
|
|
32
|
+
export const channelOf = (version) => (/-next\.\d+$/.test(version) ? "next" : "latest");
|
|
33
|
+
/** A published version, release or next: what a channel file or dist-tag must hold. */
|
|
34
|
+
export const VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-next\.(\d+))?$/;
|
|
35
|
+
/** Whether `target` is older than `current`. M.N.P-next.K precedes M.N.P. An unparsable version is never older. */
|
|
36
|
+
export function isOlder(target, current) {
|
|
37
|
+
const parse = (v) => {
|
|
38
|
+
const m = VERSION.exec(v);
|
|
39
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] === undefined ? Infinity : Number(m[4])] : undefined;
|
|
40
|
+
};
|
|
41
|
+
const t = parse(target), c = parse(current);
|
|
42
|
+
if (!t || !c)
|
|
43
|
+
return false;
|
|
44
|
+
const i = t.findIndex((n, k) => n !== c[k]);
|
|
45
|
+
return i >= 0 && t[i] < c[i];
|
|
46
|
+
}
|
|
47
|
+
// A plain `operator update` never goes back: a build older than the running one installs only when a flag names its
|
|
48
|
+
// channel.
|
|
49
|
+
const refusedAsOlder = (channel, target, current) => `operator update: the ${channel} channel is v${target}, older than this v${current} — nothing installed. ` +
|
|
50
|
+
`To go back on purpose: operator update --${channel}\n`;
|
|
32
51
|
// Walk up from the running file looking for a .git dir (source checkout) before we hit a
|
|
33
52
|
// node_modules boundary (global install). Returns the repo root, or null for a packaged install.
|
|
34
53
|
function findRepoRoot() {
|
|
@@ -45,6 +64,18 @@ function findRepoRoot() {
|
|
|
45
64
|
}
|
|
46
65
|
return null;
|
|
47
66
|
}
|
|
67
|
+
/** A source checkout updates by git, so it never offers or runs a packaged update. */
|
|
68
|
+
export const isSourceCheckout = () => findRepoRoot() !== null;
|
|
69
|
+
/** An install made by install.sh (a release folder). Its update never falls back to the registry. */
|
|
70
|
+
export const isReleaseInstall = (pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) => RELEASE_PKG.test(pkgJson);
|
|
71
|
+
/** The platform as install.sh names it ("macOS (Apple Silicon)"). */
|
|
72
|
+
export function platformLabel(platform = process.platform, arch = process.arch) {
|
|
73
|
+
if (platform === "darwin")
|
|
74
|
+
return `macOS (${arch === "arm64" ? "Apple Silicon" : arch === "x64" ? "Intel" : arch})`;
|
|
75
|
+
if (platform === "linux")
|
|
76
|
+
return `Linux (${arch === "x64" ? "x86_64" : arch})`;
|
|
77
|
+
return `${platform} (${arch})`;
|
|
78
|
+
}
|
|
48
79
|
function run(cmd, args, cwd) {
|
|
49
80
|
const r = spawnSync(cmd, args, { stdio: "inherit", cwd });
|
|
50
81
|
return r.status ?? 1;
|
|
@@ -52,21 +83,32 @@ function run(cmd, args, cwd) {
|
|
|
52
83
|
/** The registry's dist-tags for PKG (`{ latest: "0.1.352", next: "0.1.353-next.0" }`), or why they can't be read. */
|
|
53
84
|
function distTags() {
|
|
54
85
|
const r = spawnSync("npm", ["view", PKG, "dist-tags", "--json"], { encoding: "utf8" });
|
|
86
|
+
return readTags(r.status, r.stdout, r.stderr, r.signal);
|
|
87
|
+
}
|
|
88
|
+
/** distTags without blocking, for the startup check (update-check.ts), which must never hold the TUI. */
|
|
89
|
+
export function distTagsAsync(timeoutMs) {
|
|
90
|
+
return new Promise((done) => {
|
|
91
|
+
execFile("npm", ["view", PKG, "dist-tags", "--json"], { encoding: "utf8", timeout: timeoutMs }, (err, stdout, stderr) => {
|
|
92
|
+
done(readTags(err ? (typeof err.code === "number" ? err.code : 1) : 0, stdout, stderr, err?.signal ?? null));
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
function readTags(status, stdout, stderr, signal) {
|
|
55
97
|
let out;
|
|
56
98
|
try {
|
|
57
|
-
const parsed = JSON.parse(
|
|
99
|
+
const parsed = JSON.parse(stdout);
|
|
58
100
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
59
101
|
out = parsed;
|
|
60
102
|
}
|
|
61
103
|
catch { /* not JSON */ }
|
|
62
|
-
if (
|
|
104
|
+
if (status === 0 && out && !("error" in out))
|
|
63
105
|
return { tags: out };
|
|
64
106
|
// With --json npm puts its own error on stdout ({ error: { code, summary } }); stderr ends with the log file's path.
|
|
65
107
|
const e = out?.error;
|
|
66
108
|
if (e?.code || e?.summary)
|
|
67
109
|
return { error: [e.code, e.summary].filter(Boolean).join(" ") };
|
|
68
|
-
const lines = `${
|
|
69
|
-
return { error: lines.slice(0, 2).join(" · ") || `npm exited ${
|
|
110
|
+
const lines = `${stderr ?? ""}`.split("\n").map((l) => l.trim()).filter((l) => l && !/complete log of this run/i.test(l));
|
|
111
|
+
return { error: lines.slice(0, 2).join(" · ") || `npm exited ${status ?? signal}` };
|
|
70
112
|
}
|
|
71
113
|
function versionAt(pkgJson) {
|
|
72
114
|
try {
|
|
@@ -80,7 +122,7 @@ function versionAt(pkgJson) {
|
|
|
80
122
|
* the other channel: a tag the registry doesn't have, or a registry it can't read, installs nothing and exits 1.
|
|
81
123
|
* Before and after are read from THIS install's package.json (npm replaces it in place), not from `npm root -g`: npm
|
|
82
124
|
* redacts UUID-shaped path segments in its output as `***`. */
|
|
83
|
-
export function installChannel(channel, pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) {
|
|
125
|
+
export function installChannel(channel, pkgJson = fileURLToPath(new URL("../package.json", import.meta.url)), refuseOlder = false) {
|
|
84
126
|
const current = versionAt(pkgJson) ?? "?";
|
|
85
127
|
const read = distTags();
|
|
86
128
|
if ("error" in read) {
|
|
@@ -94,6 +136,10 @@ export function installChannel(channel, pkgJson = fileURLToPath(new URL("../pack
|
|
|
94
136
|
process.stderr.write(`operator update: ${PKG} has no ${channel} channel on the registry yet (it has ${has}) — nothing installed.\n`);
|
|
95
137
|
return 1;
|
|
96
138
|
}
|
|
139
|
+
if (refuseOlder && isOlder(target, current)) {
|
|
140
|
+
process.stderr.write(refusedAsOlder(channel, target, current));
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
97
143
|
process.stderr.write(`operator update: v${current} (${channelOf(current)}) → ${PKG}@${channel} (v${target})\n`);
|
|
98
144
|
const code = run("npm", ["install", "-g", `${PKG}@${channel}`]);
|
|
99
145
|
if (code !== 0) {
|
|
@@ -120,18 +166,22 @@ async function download(url, ms) {
|
|
|
120
166
|
* old ones (kept for rollback) and its bin link moved; any other install is replaced in place by `npm install -g`.
|
|
121
167
|
* Returns null, having installed nothing, when the URL can't be reached and the registry can stand in (not for an
|
|
122
168
|
* install.sh install, which exits 1 instead). */
|
|
123
|
-
export async function installFromDist(channel, pkgJson = fileURLToPath(new URL("../package.json", import.meta.url)), base =
|
|
169
|
+
export async function installFromDist(channel, pkgJson = fileURLToPath(new URL("../package.json", import.meta.url)), base = distBase(), refuseOlder = false) {
|
|
124
170
|
const current = versionAt(pkgJson) ?? "?";
|
|
125
171
|
const release = RELEASE_PKG.exec(pkgJson);
|
|
126
172
|
let target, tarball, sums;
|
|
127
173
|
try {
|
|
128
174
|
target = (await download(`${base}/${channel}.txt`, 15_000)).toString("utf8").trim();
|
|
129
|
-
if (
|
|
175
|
+
if (!VERSION.test(target))
|
|
130
176
|
throw new Error(`${base}/${channel}.txt is not a version`);
|
|
131
177
|
if (target === current) {
|
|
132
178
|
process.stderr.write(`operator update: already on v${current} (${channel}).\n`);
|
|
133
179
|
return 0;
|
|
134
180
|
}
|
|
181
|
+
if (refuseOlder && isOlder(target, current)) {
|
|
182
|
+
process.stderr.write(refusedAsOlder(channel, target, current));
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
135
185
|
[tarball, sums] = await Promise.all([
|
|
136
186
|
download(`${base}/operator-${target}.tgz`, 300_000),
|
|
137
187
|
download(`${base}/SHA256SUMS`, 15_000).then((b) => b.toString("utf8")),
|
|
@@ -176,6 +226,25 @@ export async function installFromDist(channel, pkgJson = fileURLToPath(new URL("
|
|
|
176
226
|
process.stderr.write(`operator update: done — now v${now} (${channel}).\n`);
|
|
177
227
|
return 0;
|
|
178
228
|
}
|
|
229
|
+
/** The packaged update `operator update` runs: the public download URL, else (not for an install.sh install) the
|
|
230
|
+
* registry. */
|
|
231
|
+
export async function installPackaged(channel, refuseOlder, pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) {
|
|
232
|
+
return (await installFromDist(channel, pkgJson, undefined, refuseOlder)) ?? installChannel(channel, pkgJson, refuseOlder);
|
|
233
|
+
}
|
|
234
|
+
/** The version the next `operator` starts, read back after an update: an install.sh install follows its bin link into
|
|
235
|
+
* the release folder it now points at; any other install is this package, which npm replaced in place. */
|
|
236
|
+
export function installedVersion(pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) {
|
|
237
|
+
if (!RELEASE_PKG.test(pkgJson))
|
|
238
|
+
return versionAt(pkgJson);
|
|
239
|
+
try {
|
|
240
|
+
const link = join(process.env.OPERATOR_BIN_DIR || join(homedir(), ".local", "bin"), "operator");
|
|
241
|
+
const bin = resolve(dirname(link), readlinkSync(link)); // <release>/node_modules/.bin/operator, as installFromDist links it
|
|
242
|
+
return versionAt(join(dirname(dirname(bin)), "@0perator", "operator", "package.json"));
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
return undefined;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
179
248
|
export async function runUpdate(args = [], pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) {
|
|
180
249
|
const pick = updateChannel(args, versionAt(pkgJson));
|
|
181
250
|
if ("error" in pick) {
|
|
@@ -235,5 +304,5 @@ export async function runUpdate(args = [], pkgJson = fileURLToPath(new URL("../p
|
|
|
235
304
|
}
|
|
236
305
|
return code;
|
|
237
306
|
}
|
|
238
|
-
return (
|
|
307
|
+
return installPackaged(pick.channel, !pick.explicit);
|
|
239
308
|
}
|
package/dist/util/slash.js
CHANGED
|
@@ -6,7 +6,7 @@ const KNOWN = new Set([
|
|
|
6
6
|
"think", "ultrathink", "compact", "remember", "memory", "mcp", "whoami", "agents", "jobs", "monitor",
|
|
7
7
|
"bg", "new", "clear", "exit", "quit", "stats", "login", "logout", "remote", "remotecontrol", "rc",
|
|
8
8
|
"artifacts", "sessions", "skills", "skill", "allow", "caffeinate", "caffeine", "deep-research", "deepresearch",
|
|
9
|
-
"research", "pair",
|
|
9
|
+
"research", "pair", "delegate",
|
|
10
10
|
]);
|
|
11
11
|
export const KNOWN_COMMANDS = KNOWN;
|
|
12
12
|
export function isSlashCommand(text) {
|
|
@@ -24,7 +24,7 @@ export const MIDTURN = {
|
|
|
24
24
|
help: "now", agents: "now", jobs: "now", stats: "now", endpoints: "now", audit: "now", memory: "now", skills: "now",
|
|
25
25
|
skill: "now", whoami: "now", monitor: "now", remember: "now", caffeinate: "now", caffeine: "now", bg: "now", dashboard: "now",
|
|
26
26
|
remote: "now", remotecontrol: "now", rc: "now", pair: "now",
|
|
27
|
-
think: "next", ultrathink: "next", context: "next", ctx: "next", mode: "next", plan: "next", allow: "next",
|
|
27
|
+
think: "next", ultrathink: "next", context: "next", ctx: "next", mode: "next", plan: "next", allow: "next", delegate: "next",
|
|
28
28
|
model: "after", new: "after", compact: "after", clear: "after", route: "after", mcp: "after", login: "after", logout: "after",
|
|
29
29
|
sessions: "after", artifacts: "after", services: "after",
|
|
30
30
|
"deep-research": "after", deepresearch: "after", research: "after", exit: "after", quit: "after",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0perator/operator",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"bin": {
|
|
6
6
|
"operator": "dist/cli.js",
|
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
"dashboard/index.html",
|
|
15
15
|
"dashboard/server.mjs",
|
|
16
16
|
"mcp/*.mjs",
|
|
17
|
-
"mcp/ocr-macos.swift"
|
|
17
|
+
"mcp/ocr-macos.swift",
|
|
18
|
+
"src/tools/device/NOTICE"
|
|
18
19
|
],
|
|
19
20
|
"engines": {
|
|
20
21
|
"node": ">=20"
|
|
@@ -37,6 +38,7 @@
|
|
|
37
38
|
"ink": "^5.0.1",
|
|
38
39
|
"marked": "^12.0.2",
|
|
39
40
|
"pdfkit": "^0.15.2",
|
|
41
|
+
"playwright-core": "1.65.0",
|
|
40
42
|
"qrcode": "^1.5.4",
|
|
41
43
|
"react": "^18.3.1",
|
|
42
44
|
"ws": "^8.18.0"
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
Operator device harness (src/tools/device/)
|
|
2
|
+
|
|
3
|
+
The iPhone (iPhone Mirroring) and Android (adb) backends in this directory are a
|
|
4
|
+
TypeScript port of phone-harness, https://github.com/phone-harness/phone-harness
|
|
5
|
+
(commit f5096606b10e, read on 2026-11-25). Ported: the adb command set and its device
|
|
6
|
+
states (android.py), the uiautomator tree parse, the lock gate, the iPhone
|
|
7
|
+
Mirroring window discovery by bundle id, window capture with region fallback,
|
|
8
|
+
CGEvent taps / drags / scroll-wheel swipes, keys held as real modifier keys,
|
|
9
|
+
paste-based typing, Spotlight app launch and the Cmd+1/2/3 shortcuts
|
|
10
|
+
(mirror.py, ios.py), and Vision OCR with the bottom-left box flip (ocr.py).
|
|
11
|
+
Rewritten for Operator: argv-only process calls with bounded timeouts, one
|
|
12
|
+
backend interface shared with the macOS desktop (Chauffeur), Operator's
|
|
13
|
+
permission gate, signature lines and audit trail.
|
|
14
|
+
|
|
15
|
+
phone-harness is used under the MIT License:
|
|
16
|
+
|
|
17
|
+
MIT License
|
|
18
|
+
|
|
19
|
+
Copyright (c) 2026 shawn pana
|
|
20
|
+
|
|
21
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
22
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
23
|
+
in the Software without restriction, including without limitation the rights
|
|
24
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
25
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
26
|
+
furnished to do so, subject to the following conditions:
|
|
27
|
+
|
|
28
|
+
The above copyright notice and this permission notice shall be included in all
|
|
29
|
+
copies or substantial portions of the Software.
|
|
30
|
+
|
|
31
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
32
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
33
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
34
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
35
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
36
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
37
|
+
SOFTWARE.
|
package/dist/browser/cdp.js
DELETED
|
@@ -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 };
|