omowright 0.2.0 → 0.3.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 +24 -22
- package/TOOLS.md +6 -6
- package/dist/agent-tabs.d.ts +56 -0
- package/dist/aria-hidden.d.ts +1 -0
- package/dist/aside/cli-binary.d.ts +7 -0
- package/dist/aside/cli-contract.d.ts +9 -0
- package/dist/aside/errors.d.ts +8 -0
- package/dist/aside/line-transport.d.ts +11 -0
- package/dist/aside/mcp-transport.d.ts +11 -0
- package/dist/aside/onboard.d.ts +76 -0
- package/dist/aside/session-types.d.ts +68 -0
- package/dist/aside/session.d.ts +20 -0
- package/{bin/omowright-cloak.mjs → dist/bin/omowright-cloak.js} +28 -31
- package/dist/bridge-schemas.d.ts +326 -0
- package/dist/bridge-transport.d.ts +144 -0
- package/dist/browser-context.d.ts +4024 -0
- package/dist/browser-process.d.ts +10 -0
- package/dist/bsk/browser-signals.d.ts +23 -0
- package/dist/bsk/browsers.d.ts +46 -0
- package/dist/bsk/connect.d.ts +23 -0
- package/dist/bsk/daemon-info.d.ts +16 -0
- package/dist/bsk/external-extension.d.ts +74 -0
- package/dist/bsk/identify-browser.d.ts +48 -0
- package/dist/bsk/install-cli.d.ts +37 -0
- package/dist/bsk/ipc-client.d.ts +45 -0
- package/dist/bsk/onboard.d.ts +96 -0
- package/dist/bsk/reply-fields.d.ts +3 -0
- package/dist/bsk/screenshot.d.ts +24 -0
- package/dist/bsk/session.d.ts +142 -0
- package/dist/bsk/snapshot.d.ts +16 -0
- package/dist/bsk/targets.d.ts +20 -0
- package/dist/captcha-wait.d.ts +17 -0
- package/dist/captcha.d.ts +46 -0
- package/dist/cdp-errors.d.ts +38 -0
- package/dist/cdp-methods.d.ts +10 -0
- package/dist/cdp-protocol.d.ts +459 -0
- package/dist/chrome-profile.d.ts +77 -0
- package/dist/chrome.d.ts +130 -0
- package/dist/cloak-profile.d.ts +43 -0
- package/dist/connection.d.ts +4024 -0
- package/dist/console-events.d.ts +22 -0
- package/dist/cookies.d.ts +42 -0
- package/dist/core.d.ts +10810 -0
- package/dist/cua.d.ts +56 -0
- package/dist/dialog-policy.d.ts +43 -0
- package/dist/ego/bindings.d.ts +68 -0
- package/dist/ego/cdp-client.d.ts +28 -0
- package/dist/ego/client.d.ts +8 -0
- package/dist/ego/errors.d.ts +7 -0
- package/dist/emulate.d.ts +62 -0
- package/dist/engines.d.ts +59 -0
- package/dist/events.d.ts +93 -0
- package/dist/frames-snapshot.d.ts +58 -0
- package/dist/har.d.ts +88 -0
- package/dist/human-handoff.d.ts +30 -0
- package/{src/index.js → dist/index.d.ts} +11 -55
- package/dist/index.js +39262 -0
- package/dist/injected.d.ts +1 -0
- package/dist/instance-lock.d.ts +5 -0
- package/dist/instances.d.ts +45 -0
- package/dist/internal-capability.d.ts +1 -0
- package/dist/launch-endpoint.d.ts +34 -0
- package/dist/layers.d.ts +31 -0
- package/dist/llm.d.ts +1349 -0
- package/dist/lock-backend-win32-xbcm60vz.js +57 -0
- package/dist/lock-backend-win32.d.ts +3 -0
- package/dist/lock-backend.d.ts +6 -0
- package/dist/native-host-win32.d.ts +38 -0
- package/dist/network-events.d.ts +66 -0
- package/dist/network-snoop.d.ts +56 -0
- package/dist/nul-frames.d.ts +4 -0
- package/dist/open-shadow-query.d.ts +1 -0
- package/dist/owner-only.d.ts +15 -0
- package/dist/page-bundle.js +1587 -0
- package/dist/page-events.d.ts +25 -0
- package/dist/page-routes.d.ts +30 -0
- package/dist/page-setup.d.ts +55 -0
- package/dist/pipe.d.ts +71 -0
- package/dist/process-start-time.d.ts +2 -0
- package/dist/read-property.d.ts +2 -0
- package/dist/routes.d.ts +60 -0
- package/dist/running-browser.d.ts +39 -0
- package/dist/scroll-collect.d.ts +36 -0
- package/dist/serial-emitter.d.ts +5 -0
- package/dist/shared-connections.d.ts +11 -0
- package/dist/snapshot-diff.d.ts +57 -0
- package/dist/text-matching.d.ts +21 -0
- package/dist/trace.d.ts +59 -0
- package/dist/url-match.d.ts +7 -0
- package/dist/viewport.d.ts +26 -0
- package/dist/ws.d.ts +62 -0
- package/package.json +47 -26
- package/presets/agent-events/SKILL.md +1 -1
- package/presets/captcha/SKILL.md +1 -3
- package/presets/chrome/SKILL.md +2 -2
- package/presets/cloak-bridge/SKILL.md +11 -11
- package/presets/network/SKILL.md +15 -13
- package/presets/visual-browse/SKILL.md +14 -10
- package/skills/omowright/SKILL.md +77 -47
- package/skills/omowright/references/aside.md +50 -0
- package/skills/omowright/references/browserskill.md +29 -32
- package/skills/omowright/references/ego.md +24 -0
- package/skills/omowright/references/eval-kernel.md +44 -23
- package/skills/omowright/references/frames-layers-human.md +16 -7
- package/skills/omowright/references/quickstart.md +3 -3
- package/skills/omowright/references/stealth.md +7 -7
- package/src/agent-tabs.js +0 -179
- package/src/aria-hidden.js +0 -47
- package/src/bridge-schemas.js +0 -44
- package/src/bridge-transport.js +0 -83
- package/src/browser-context.js +0 -105
- package/src/browser-process.js +0 -127
- package/src/bsk/browser-signals.js +0 -90
- package/src/bsk/browsers.js +0 -114
- package/src/bsk/connect.js +0 -75
- package/src/bsk/daemon-info.js +0 -100
- package/src/bsk/external-extension.js +0 -110
- package/src/bsk/identify-browser.js +0 -88
- package/src/bsk/install-cli.js +0 -81
- package/src/bsk/ipc-client.js +0 -236
- package/src/bsk/onboard.js +0 -140
- package/src/bsk/screenshot.js +0 -49
- package/src/bsk/session.js +0 -131
- package/src/bsk/snapshot.js +0 -56
- package/src/bsk/targets.js +0 -25
- package/src/captcha-wait.js +0 -79
- package/src/captcha.js +0 -142
- package/src/cdp-errors.js +0 -23
- package/src/cdp-methods.js +0 -69
- package/src/chrome-profile.js +0 -176
- package/src/chrome.js +0 -194
- package/src/cloak-profile.js +0 -266
- package/src/connection.js +0 -234
- package/src/console-events.js +0 -12
- package/src/cookies.js +0 -39
- package/src/core.js +0 -1702
- package/src/cua.js +0 -74
- package/src/dialog-policy.js +0 -80
- package/src/emulate.js +0 -127
- package/src/events.js +0 -111
- package/src/frames-snapshot.js +0 -138
- package/src/har.js +0 -103
- package/src/human-handoff.js +0 -124
- package/src/injected.js +0 -3
- package/src/instance-lock.js +0 -74
- package/src/instances.js +0 -490
- package/src/internal-capability.js +0 -1
- package/src/launch-endpoint.js +0 -185
- package/src/layers.js +0 -138
- package/src/llm.js +0 -201
- package/src/lock-backend-win32.js +0 -54
- package/src/lock-backend.js +0 -81
- package/src/native-host-win32.js +0 -201
- package/src/network-events.js +0 -223
- package/src/network-snoop.js +0 -229
- package/src/nul-frames.js +0 -28
- package/src/open-shadow-query.js +0 -101
- package/src/owner-only.js +0 -196
- package/src/page-bundle.js +0 -1478
- package/src/page-events.js +0 -45
- package/src/page-routes.js +0 -94
- package/src/page-setup.js +0 -239
- package/src/pipe.js +0 -418
- package/src/process-start-time.js +0 -64
- package/src/routes.js +0 -256
- package/src/running-browser.js +0 -85
- package/src/scroll-collect.js +0 -73
- package/src/serial-emitter.js +0 -17
- package/src/shared-connections.js +0 -285
- package/src/snapshot-diff.js +0 -75
- package/src/text-matching.js +0 -101
- package/src/trace.js +0 -183
- package/src/url-match.js +0 -148
- package/src/viewport.js +0 -12
package/src/bsk/daemon-info.js
DELETED
|
@@ -1,100 +0,0 @@
|
|
|
1
|
-
// Discovery of a running BrowserSkill daemon: `$BSK_HOME/daemon.json` is the
|
|
2
|
-
// file the daemon writes at start-up (`crates/bsk-cli/src/daemon/info.rs`)
|
|
3
|
-
// and the CLI reads to find the IPC socket. Nothing here talks to the socket.
|
|
4
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
-
import { homedir } from "node:os";
|
|
6
|
-
import path from "node:path";
|
|
7
|
-
import { spawn } from "node:child_process";
|
|
8
|
-
import { createHash } from "node:crypto";
|
|
9
|
-
import { windowsSystemTool } from "../owner-only.js";
|
|
10
|
-
|
|
11
|
-
export function resolveBskHome(env = process.env) {
|
|
12
|
-
const override = env.BSK_HOME;
|
|
13
|
-
if (typeof override === "string" && override.length > 0) return override;
|
|
14
|
-
const home = env.HOME && env.HOME.length > 0 ? env.HOME : homedir();
|
|
15
|
-
return path.join(home, ".bsk");
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export function daemonInfoPath(home) {
|
|
19
|
-
return path.join(home, "daemon.json");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function readDaemonInfo(home) {
|
|
23
|
-
let raw;
|
|
24
|
-
try { raw = readFileSync(daemonInfoPath(home), "utf8"); } catch { return null; }
|
|
25
|
-
let info;
|
|
26
|
-
try { info = JSON.parse(raw); } catch { return null; }
|
|
27
|
-
if (!info || typeof info.sock_path !== "string" || info.sock_path.length === 0) return null;
|
|
28
|
-
return info;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function findBskBinary(env = process.env) {
|
|
32
|
-
const home = env.HOME && env.HOME.length > 0 ? env.HOME : homedir();
|
|
33
|
-
const candidates = [
|
|
34
|
-
env.BSK_BIN,
|
|
35
|
-
path.join(home, ".local", "bin", process.platform === "win32" ? "bsk.exe" : "bsk"),
|
|
36
|
-
].filter(Boolean);
|
|
37
|
-
for (const candidate of candidates) if (existsSync(candidate)) return candidate;
|
|
38
|
-
return "bsk";
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// bsk refuses to detach its daemon when the caller's Job Object forbids breakaway, as agent
|
|
42
|
-
// sandboxes on Windows do, and asks for `bsk daemon start --foreground` in a persistent host task.
|
|
43
|
-
const NO_BREAKAWAY = /Job Object/;
|
|
44
|
-
|
|
45
|
-
export function windowsDaemonTaskName(home) {
|
|
46
|
-
return `bsk-daemon-${createHash("sha256").update(path.resolve(home).toLowerCase()).digest("hex").slice(0, 12)}`;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// Task Scheduler starts the action outside the caller's job. conhost --headless gives the console
|
|
50
|
-
// program a console without a window; a task that starts bsk directly opens one in the default
|
|
51
|
-
// terminal, and Windows Terminal ignores the hidden-window flag a task or PowerShell passes.
|
|
52
|
-
// The home and binary travel as PowerShell single-quoted literals inside -EncodedCommand: conhost
|
|
53
|
-
// re-parses a cmd.exe line and drops it at the first &, (, ^ or |, and cmd.exe expands % in quotes.
|
|
54
|
-
function windowsDaemonLaunch(home, bskBin) {
|
|
55
|
-
const literal = (value) => `'${value.replace(/['\u2018\u2019\u201A\u201B]/g, (quote) => quote + quote)}'`;
|
|
56
|
-
const script = `$env:BSK_HOME = ${literal(home)}; & ${literal(bskBin)} daemon start --foreground; exit $LASTEXITCODE`;
|
|
57
|
-
return `--headless "${windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe")}" -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function startDaemonInWindowsTask({ home, bskBin, timeoutMs }) {
|
|
61
|
-
const script = [
|
|
62
|
-
"$action = New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32\\conhost.exe') -Argument $env:BSK_TASK_ARGUMENT",
|
|
63
|
-
"$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew",
|
|
64
|
-
"Register-ScheduledTask -TaskName $env:BSK_TASK_NAME -Action $action -Settings $settings -Force | Out-Null",
|
|
65
|
-
"Start-ScheduledTask -TaskName $env:BSK_TASK_NAME",
|
|
66
|
-
].join("; ");
|
|
67
|
-
return runToExit(windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"), ["-NoProfile", "-NonInteractive", "-Command", script], {
|
|
68
|
-
env: { ...process.env, BSK_TASK_NAME: windowsDaemonTaskName(home), BSK_TASK_ARGUMENT: windowsDaemonLaunch(home, bskBin) },
|
|
69
|
-
timeoutMs,
|
|
70
|
-
label: "registering the bsk daemon task",
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function runToExit(command, args, { env, timeoutMs, label }) {
|
|
75
|
-
return new Promise((resolve, reject) => {
|
|
76
|
-
const child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
77
|
-
let output = "";
|
|
78
|
-
const keep = (chunk) => { output = (output + chunk).slice(-4096); };
|
|
79
|
-
child.stdout.on("data", keep);
|
|
80
|
-
child.stderr.on("data", keep);
|
|
81
|
-
const timer = setTimeout(() => {
|
|
82
|
-
child.kill("SIGKILL");
|
|
83
|
-
reject(new Error(`${label} did not return within ${timeoutMs}ms`));
|
|
84
|
-
}, timeoutMs);
|
|
85
|
-
child.on("error", (error) => { clearTimeout(timer); reject(new Error(`could not run ${command}: ${error.message}`)); });
|
|
86
|
-
child.on("exit", (code) => { clearTimeout(timer); resolve({ code, output: output.trim() }); });
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export async function startDaemonWithCli({ home, env = process.env, bskBin = findBskBinary(env), timeoutMs = 20_000 } = {}) {
|
|
91
|
-
const status = await runToExit(bskBin, ["status", "--json"], { env: { ...env, BSK_HOME: home }, timeoutMs, label: "bsk status" });
|
|
92
|
-
if (status.code === 0) return;
|
|
93
|
-
if (process.platform === "win32" && NO_BREAKAWAY.test(status.output)) {
|
|
94
|
-
const task = await startDaemonInWindowsTask({ home, bskBin, timeoutMs });
|
|
95
|
-
if (task.code === 0) return;
|
|
96
|
-
// Keep bsk's refusal in the message: it is why a retry cannot help, and bskDoctor reads it.
|
|
97
|
-
throw new Error(`${status.output}; registering the bsk daemon task exited with ${task.code}${task.output ? `: ${task.output}` : ""}`);
|
|
98
|
-
}
|
|
99
|
-
throw new Error(`bsk status exited with ${status.code}${status.output ? `: ${status.output}` : ""}`);
|
|
100
|
-
}
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
// Registers the Web Store extension through Chrome's "external extensions"
|
|
2
|
-
// mechanism (the only non-enterprise path that survives Chrome 25's ban on
|
|
3
|
-
// silent installs): a per-user JSON file on macOS/Chromium-Linux, an HKCU
|
|
4
|
-
// registry value on Windows, a root-owned directory for Google Chrome on
|
|
5
|
-
// Linux. Windows and macOS still show one "Enable extension?" prompt.
|
|
6
|
-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
-
import { spawn } from "node:child_process";
|
|
8
|
-
import path from "node:path";
|
|
9
|
-
import { windowsSystemTool } from "../owner-only.js";
|
|
10
|
-
import { BROWSERSKILL_EXTENSION_IDS, STORE_PAGE_URLS, STORE_UPDATE_URLS, pathFor } from "./browsers.js";
|
|
11
|
-
|
|
12
|
-
export { BROWSERSKILL_EXTENSION_IDS, STORE_PAGE_URLS, STORE_UPDATE_URLS, catalogBrowsers, detectBrowsers } from "./browsers.js";
|
|
13
|
-
|
|
14
|
-
const ENABLE_STEP = (browser) => `Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;
|
|
15
|
-
const BADGE_STEP = (browser) => `In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;
|
|
16
|
-
|
|
17
|
-
const storeStep = (browser, label) => `Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;
|
|
18
|
-
|
|
19
|
-
export function externalExtensionEntry({ platform = process.platform, browser }) {
|
|
20
|
-
const id = BROWSERSKILL_EXTENSION_IDS[browser.store];
|
|
21
|
-
const updateUrl = STORE_UPDATE_URLS[browser.store];
|
|
22
|
-
const label = browser.label ?? browser.id.charAt(0).toUpperCase() + browser.id.slice(1);
|
|
23
|
-
if (browser.externalExtensions === false) {
|
|
24
|
-
return { kind: "store", needsRestart: false, storeUrl: STORE_PAGE_URLS[browser.store], humanStep: storeStep(browser, label) };
|
|
25
|
-
}
|
|
26
|
-
if (platform === "win32") {
|
|
27
|
-
const key = `${browser.registryKey}\\${id}`;
|
|
28
|
-
return {
|
|
29
|
-
kind: "registry", key, needsRestart: false, storeUrl: STORE_PAGE_URLS[browser.store],
|
|
30
|
-
regAddArgs: ["add", key, "/v", "update_url", "/t", "REG_SZ", "/d", updateUrl, "/f"],
|
|
31
|
-
regDeleteArgs: ["delete", key, "/f"],
|
|
32
|
-
humanStep: BADGE_STEP(label),
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
const content = JSON.stringify({ external_update_url: updateUrl }, null, 2) + "\n";
|
|
36
|
-
if (platform === "linux" && !browser.userExternalDir) {
|
|
37
|
-
return {
|
|
38
|
-
kind: "file", path: pathFor(platform).join(browser.externalDir, `${id}.json`), content, needsRestart: true,
|
|
39
|
-
storeUrl: STORE_PAGE_URLS[browser.store],
|
|
40
|
-
humanStep: `Quit ${label} completely and open it again; the extension installs without a prompt.`,
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
return {
|
|
44
|
-
kind: "file", path: pathFor(platform).join(browser.userDataDir, "External Extensions", `${id}.json`), content, needsRestart: true,
|
|
45
|
-
storeUrl: STORE_PAGE_URLS[browser.store],
|
|
46
|
-
humanStep: platform === "linux" ? `Quit ${label} completely and open it again; the extension installs without a prompt.` : ENABLE_STEP(label),
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function isBlocklisted(browser, id, { readFile = readFileSync } = {}) {
|
|
51
|
-
if (!browser.userDataDir) return false;
|
|
52
|
-
for (const profile of ["Default", "Profile 1", "Profile 2", "Profile 3"]) {
|
|
53
|
-
const file = path.join(browser.userDataDir, profile, "Preferences");
|
|
54
|
-
let prefs;
|
|
55
|
-
try { prefs = JSON.parse(readFile(file, "utf8")); } catch { continue; }
|
|
56
|
-
if (Array.isArray(prefs?.extensions?.external_uninstalls) && prefs.extensions.external_uninstalls.includes(id)) return true;
|
|
57
|
-
}
|
|
58
|
-
return false;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function runRegDefault(args) {
|
|
62
|
-
return new Promise((resolve) => {
|
|
63
|
-
const child = spawn(windowsSystemTool("reg.exe"), args, { stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
|
|
64
|
-
let stderr = "";
|
|
65
|
-
child.stderr.on("data", (c) => { stderr += c; });
|
|
66
|
-
child.on("error", (error) => resolve({ code: -1, stderr: error.message }));
|
|
67
|
-
child.on("exit", (code) => resolve({ code, stderr }));
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export async function registerExternalExtension({ platform = process.platform, browser, writeFile = writeFileSync, readFile = readFileSync, runReg = runRegDefault } = {}) {
|
|
72
|
-
const entry = externalExtensionEntry({ platform, browser });
|
|
73
|
-
const id = BROWSERSKILL_EXTENSION_IDS[browser.store];
|
|
74
|
-
const label = browser.label ?? browser.id;
|
|
75
|
-
const storeStep = `Open ${entry.storeUrl} in ${label} and click the "Add" button.`;
|
|
76
|
-
if (entry.kind === "store") return { ...entry, registered: false, alreadyPresent: false, reason: "store_only" };
|
|
77
|
-
if (isBlocklisted(browser, id, { readFile })) {
|
|
78
|
-
return { ...entry, registered: false, alreadyPresent: false, reason: "blocklisted", humanStep: `The extension was removed from ${label} before, so external registration is ignored. ${storeStep}` };
|
|
79
|
-
}
|
|
80
|
-
if (entry.kind === "registry") {
|
|
81
|
-
const result = await runReg(entry.regAddArgs);
|
|
82
|
-
if (result.code !== 0) return { ...entry, registered: false, alreadyPresent: false, reason: "reg_failed", detail: result.stderr, humanStep: storeStep };
|
|
83
|
-
return { ...entry, registered: true, alreadyPresent: false };
|
|
84
|
-
}
|
|
85
|
-
let alreadyPresent = false;
|
|
86
|
-
try { alreadyPresent = readFile(entry.path, "utf8") === entry.content; } catch {}
|
|
87
|
-
if (alreadyPresent) return { ...entry, registered: true, alreadyPresent: true };
|
|
88
|
-
try {
|
|
89
|
-
mkdirSync(path.dirname(entry.path), { recursive: true });
|
|
90
|
-
writeFile(entry.path, entry.content);
|
|
91
|
-
} catch (error) {
|
|
92
|
-
if (error.code === "EACCES" || error.code === "EPERM" || error.code === "EROFS") {
|
|
93
|
-
return { ...entry, registered: false, alreadyPresent: false, reason: "not_writable", humanStep: `${entry.path} is not writable without administrator rights. ${storeStep}` };
|
|
94
|
-
}
|
|
95
|
-
throw error;
|
|
96
|
-
}
|
|
97
|
-
return { ...entry, registered: true, alreadyPresent: false };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export async function unregisterExternalExtension({ platform = process.platform, browser, runReg = runRegDefault } = {}) {
|
|
101
|
-
const entry = externalExtensionEntry({ platform, browser });
|
|
102
|
-
if (entry.kind === "store") return { ...entry, removed: false };
|
|
103
|
-
if (entry.kind === "registry") {
|
|
104
|
-
const result = await runReg(entry.regDeleteArgs);
|
|
105
|
-
return { ...entry, removed: result.code === 0, detail: result.stderr };
|
|
106
|
-
}
|
|
107
|
-
const present = existsSync(entry.path);
|
|
108
|
-
if (present) rmSync(entry.path, { force: true });
|
|
109
|
-
return { ...entry, removed: present };
|
|
110
|
-
}
|
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { NON_CHROMIUM_DEFAULTS } from "./browsers.js";
|
|
2
|
-
|
|
3
|
-
export const RECENT_USE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
4
|
-
|
|
5
|
-
// BrowserSkill's extension derives browser_name from the user agent (detectBrowserMeta in
|
|
6
|
-
// Tencent/BrowserSkill apps/extension/src/transport/handshake.ts). Only a user-agent token names one
|
|
7
|
-
// browser; forks such as Brave and Arc normally keep Chrome's user agent and report "chrome", so
|
|
8
|
-
// "chrome"/"chromium" count only when exactly one browser able to send them is running.
|
|
9
|
-
// "brave" and "arc" stay in OWN_TOKEN_NAMES anyway: they only matter if the extension ever sends those
|
|
10
|
-
// names itself, and then the name can only mean that browser. Without them such a name would match no
|
|
11
|
-
// browser at all, so keep them.
|
|
12
|
-
const OWN_TOKEN_NAMES = new Set(["edge", "opera", "brave", "arc"]);
|
|
13
|
-
const FAMILY_NAMES = new Set(["chrome", "chromium"]);
|
|
14
|
-
const ALWAYS_SEND_OWN_TOKEN = new Set(["edge", "opera"]);
|
|
15
|
-
|
|
16
|
-
function sentBy(name, candidates) {
|
|
17
|
-
if (OWN_TOKEN_NAMES.has(name)) return candidates.filter((c) => c.id === name);
|
|
18
|
-
if (!FAMILY_NAMES.has(name)) return [];
|
|
19
|
-
const running = candidates.filter((c) => !ALWAYS_SEND_OWN_TOKEN.has(c.id) && c.running === true);
|
|
20
|
-
return running.length === 1 ? running : [];
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function matchesDefault(browser, defaultId) {
|
|
24
|
-
if (!defaultId) return false;
|
|
25
|
-
return browser.defaultIds.some((id) => defaultId === id || defaultId.startsWith(id));
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function describeDefault(defaultId, catalog) {
|
|
29
|
-
if (defaultId === null || defaultId === undefined) return { raw: null, id: null, label: null, supported: null };
|
|
30
|
-
const hit = catalog.find((b) => matchesDefault(b, defaultId));
|
|
31
|
-
if (hit) return { raw: defaultId, id: hit.id, label: hit.label, supported: true };
|
|
32
|
-
const other = NON_CHROMIUM_DEFAULTS.find((b) => b.match.some((m) => defaultId === m || defaultId.startsWith(m)));
|
|
33
|
-
return other ? { raw: defaultId, id: other.id, label: other.label, supported: false } : { raw: defaultId, id: null, label: defaultId, supported: false };
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function candidateRow(browser, { defaultBrowser, running, lastUsed }, now) {
|
|
37
|
-
const isDefault = defaultBrowser.id === browser.id;
|
|
38
|
-
const isRunning = Array.isArray(running) ? browser.processNames.some((n) => running.includes(n) || running.includes(n.toLowerCase())) : null;
|
|
39
|
-
const last = lastUsed?.[browser.id] ?? null;
|
|
40
|
-
const recentlyUsed = last !== null && now - last <= RECENT_USE_MS;
|
|
41
|
-
const signals = [isDefault && "default browser", isRunning && "running now", recentlyUsed && "used in the last 7 days"].filter(Boolean);
|
|
42
|
-
return { id: browser.id, label: browser.label, installed: browser.installed, isDefault, running: isRunning, lastUsedAt: last === null ? null : new Date(last).toISOString(), recentlyUsed, signals, browser };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
function choose(candidates, primary, confidence, reason, defaultBrowser) {
|
|
46
|
-
return { primary: primary.browser, primaryId: primary.id, confidence, needsChoice: false, reason, defaultBrowser, candidates: candidates.map(({ browser, ...row }) => row) };
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function ask(candidates, reason, defaultBrowser, suggested = null) {
|
|
50
|
-
return { primary: null, primaryId: null, confidence: null, needsChoice: true, reason, suggested, defaultBrowser, candidates: candidates.map(({ browser, ...row }) => row) };
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Picks the one Chromium browser the user actually uses, or refuses to pick. Order of authority: an
|
|
54
|
-
// explicit choice, the one browser whose BrowserSkill extension is connected to the daemon, the OS
|
|
55
|
-
// default browser when it is also in use (or nothing else is), a single browser that is the only one
|
|
56
|
-
// in use. Anything else — a default the user is not using while another browser runs, a Safari/Firefox
|
|
57
|
-
// default, several browsers in use — is a question for the user.
|
|
58
|
-
export function identifyBrowser({ catalog, signals = {}, explicit = null, connected = [], now = Date.now() }) {
|
|
59
|
-
const defaultBrowser = describeDefault(signals.defaultBrowser ?? null, catalog);
|
|
60
|
-
const installed = catalog.filter((b) => b.installed || b.id === explicit);
|
|
61
|
-
const candidates = installed.map((b) => candidateRow(b, { defaultBrowser, running: signals.running ?? null, lastUsed: signals.lastUsed }, now));
|
|
62
|
-
|
|
63
|
-
if (explicit) {
|
|
64
|
-
const hit = candidates.find((c) => c.id === explicit);
|
|
65
|
-
if (hit) return choose(candidates, hit, "explicit", `${hit.label} was chosen explicitly`, defaultBrowser);
|
|
66
|
-
return ask(candidates, `"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`, defaultBrowser);
|
|
67
|
-
}
|
|
68
|
-
if (candidates.length === 0) return ask(candidates, "no Chromium-family browser is installed", defaultBrowser);
|
|
69
|
-
|
|
70
|
-
const attached = [...new Set(connected.flatMap((name) => sentBy(name, candidates)))];
|
|
71
|
-
if (attached.length === 1) return choose(candidates, attached[0], "connected", `${attached[0].label} has the BrowserSkill extension connected`, defaultBrowser);
|
|
72
|
-
|
|
73
|
-
const inUse = candidates.filter((c) => c.running || c.recentlyUsed);
|
|
74
|
-
const def = candidates.find((c) => c.isDefault);
|
|
75
|
-
if (def && (def.running || def.recentlyUsed)) return choose(candidates, def, "default-and-in-use", `${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`, defaultBrowser);
|
|
76
|
-
if (def && inUse.length === 0) return choose(candidates, def, "default", `${def.label} is the default browser`, defaultBrowser);
|
|
77
|
-
if (def) return ask(candidates, `${def.label} is the default browser, but ${inUse.map((c) => c.label).join(" and ")} ${inUse.length === 1 ? "is" : "are"} the one in use`, defaultBrowser);
|
|
78
|
-
|
|
79
|
-
if (defaultBrowser.supported === false) {
|
|
80
|
-
const suggested = inUse.length === 1 ? inUse[0].id : null;
|
|
81
|
-
return ask(candidates, `the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`, defaultBrowser, suggested);
|
|
82
|
-
}
|
|
83
|
-
const runningNow = inUse.filter((c) => c.running);
|
|
84
|
-
if (inUse.length === 1) return choose(candidates, inUse[0], "only-in-use", `${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`, defaultBrowser);
|
|
85
|
-
if (runningNow.length === 1) return choose(candidates, runningNow[0], "only-running", `${runningNow[0].label} is the only browser running now`, defaultBrowser);
|
|
86
|
-
if (inUse.length === 0 && candidates.length === 1) return choose(candidates, candidates[0], "only-installed", `${candidates[0].label} is the only Chromium-family browser installed`, defaultBrowser);
|
|
87
|
-
return ask(candidates, inUse.length > 1 ? `several browsers are in use (${inUse.map((c) => c.label).join(", ")})` : "no browser shows recent use", defaultBrowser);
|
|
88
|
-
}
|
package/src/bsk/install-cli.js
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { spawn } from "node:child_process";
|
|
5
|
-
import { windowsSystemTool } from "../owner-only.js";
|
|
6
|
-
|
|
7
|
-
const INSTALL_SH = "https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";
|
|
8
|
-
const INSTALL_PS1 = "https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";
|
|
9
|
-
const RC_FILES = [".zshrc", ".bashrc", ".profile"];
|
|
10
|
-
|
|
11
|
-
// A PowerShell 7 parent hands its own module dirs to the Windows PowerShell 5.1
|
|
12
|
-
// child through PSModulePath. They shadow 5.1's Microsoft.PowerShell.Utility, so
|
|
13
|
-
// Get-FileHash is missing and the installer dies at checksum verification. Keep
|
|
14
|
-
// every entry except PowerShell 7's (...\PowerShell\..., never ...\WindowsPowerShell\...).
|
|
15
|
-
function windowsPowerShellEnv(env) {
|
|
16
|
-
const key = Object.keys(process.env).find((name) => name.toUpperCase() === "PSMODULEPATH");
|
|
17
|
-
if (!key) return env;
|
|
18
|
-
const kept = process.env[key].split(";").filter((entry) => entry && !/[\\/]PowerShell[\\/]/i.test(entry));
|
|
19
|
-
return { ...env, [key]: kept.length > 0 ? kept.join(";") : undefined };
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function cliInstallCommand({ platform = process.platform, installDir, version } = {}) {
|
|
23
|
-
const env = { BSK_INSTALL_DIR: installDir };
|
|
24
|
-
if (version) env.BSK_VERSION = version;
|
|
25
|
-
if (platform === "win32") {
|
|
26
|
-
return { command: windowsSystemTool("WindowsPowerShell\\v1.0\\powershell.exe"), args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `irm ${INSTALL_PS1} | iex`], env: windowsPowerShellEnv(env) };
|
|
27
|
-
}
|
|
28
|
-
return { command: "sh", args: ["-c", `curl -fsSL ${INSTALL_SH} | sh`], env };
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function runDefault(command, args, env) {
|
|
32
|
-
return new Promise((resolve) => {
|
|
33
|
-
const child = spawn(command, args, { env: { ...process.env, ...env }, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
34
|
-
let stdout = "", stderr = "";
|
|
35
|
-
child.stdout.on("data", (c) => { stdout = (stdout + c).slice(-8192); });
|
|
36
|
-
child.stderr.on("data", (c) => { stderr = (stderr + c).slice(-8192); });
|
|
37
|
-
child.on("error", (error) => resolve({ code: -1, stdout, stderr: error.message }));
|
|
38
|
-
child.on("exit", (code) => resolve({ code, stdout, stderr }));
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function snapshotRcFiles(home) {
|
|
43
|
-
const snapshot = new Map();
|
|
44
|
-
for (const name of RC_FILES) {
|
|
45
|
-
const file = path.join(home, name);
|
|
46
|
-
snapshot.set(file, existsSync(file) ? readFileSync(file) : null);
|
|
47
|
-
}
|
|
48
|
-
return snapshot;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function restoreRcFiles(snapshot) {
|
|
52
|
-
const restored = [];
|
|
53
|
-
for (const [file, before] of snapshot) {
|
|
54
|
-
const after = existsSync(file) ? readFileSync(file) : null;
|
|
55
|
-
if (before === null && after === null) continue;
|
|
56
|
-
if (before !== null && after !== null && before.equals(after)) continue;
|
|
57
|
-
if (before === null) rmSync(file, { force: true }); else writeFileSync(file, before);
|
|
58
|
-
restored.push(file);
|
|
59
|
-
}
|
|
60
|
-
return restored;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export async function installBskCli({ platform = process.platform, home = homedir(), installDir = path.join(home, ".local", "bin"), version, run = runDefault } = {}) {
|
|
64
|
-
const spec = cliInstallCommand({ platform, installDir, version });
|
|
65
|
-
const rcBefore = platform === "win32" ? new Map() : snapshotRcFiles(home);
|
|
66
|
-
const result = await run(spec.command, spec.args, spec.env);
|
|
67
|
-
const restoredRcFiles = restoreRcFiles(rcBefore);
|
|
68
|
-
const bskBin = path.join(installDir, platform === "win32" ? "bsk.exe" : "bsk");
|
|
69
|
-
const installed = result.code === 0 && existsSync(bskBin);
|
|
70
|
-
return { installed, bskBin: installed ? bskBin : null, code: result.code, stdout: result.stdout, stderr: result.stderr, restoredRcFiles };
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export function cliVersionDefault(bskBin) {
|
|
74
|
-
return new Promise((resolve) => {
|
|
75
|
-
const child = spawn(bskBin, ["--version"], { stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
76
|
-
let out = "";
|
|
77
|
-
child.stdout.on("data", (c) => { out += c; });
|
|
78
|
-
child.on("error", () => resolve(null));
|
|
79
|
-
child.on("exit", (code) => resolve(code === 0 ? out.trim() : null));
|
|
80
|
-
});
|
|
81
|
-
}
|
package/src/bsk/ipc-client.js
DELETED
|
@@ -1,236 +0,0 @@
|
|
|
1
|
-
// CLI-shaped client for the BrowserSkill daemon IPC: one Unix-socket
|
|
2
|
-
// connection per call, one JSON Lines request frame out, one response frame
|
|
3
|
-
// back (`crates/bsk-cli/src/ipc_client.rs`, `crates/bsk-protocol/src/frame.rs`).
|
|
4
|
-
// `cancel` opens a second connection exactly as the CLI's SIGINT path does.
|
|
5
|
-
import { connect } from "node:net";
|
|
6
|
-
import { existsSync, readdirSync } from "node:fs";
|
|
7
|
-
import path from "node:path";
|
|
8
|
-
import { randomBytes } from "node:crypto";
|
|
9
|
-
import { readDaemonInfo, resolveBskHome, startDaemonWithCli } from "./daemon-info.js";
|
|
10
|
-
|
|
11
|
-
export { readDaemonInfo, resolveBskHome } from "./daemon-info.js";
|
|
12
|
-
|
|
13
|
-
const DEFAULT_TIMEOUT_MS = 35_000; // daemon tool budget 30s + grace, as cli/mod.rs
|
|
14
|
-
const DISCOVERY_RETRY_MS = 250;
|
|
15
|
-
const DISCOVERY_BUDGET_MS = 15_000;
|
|
16
|
-
// A tool call that names its own budget (timeout_ms, or confirmation_timeout_ms for a tab borrow)
|
|
17
|
-
// gets that budget plus this grace on the IPC wait.
|
|
18
|
-
const TOOL_TIMEOUT_GRACE_MS = 5_000;
|
|
19
|
-
// Tools that wait for a person: the daemon owns their deadline, so with no budget from the caller the
|
|
20
|
-
// client only keeps a long backstop, and it never cancels them (that would tear down the user's overlay).
|
|
21
|
-
const HUMAN_WAIT_METHODS = new Set(["tool.request_help", "tool.tab_borrow"]);
|
|
22
|
-
const HUMAN_WAIT_BACKSTOP_MS = 3_600_000;
|
|
23
|
-
|
|
24
|
-
function ownBudgetMs(params) {
|
|
25
|
-
const budgets = [params?.timeout_ms, params?.confirmation_timeout_ms].filter((value) => typeof value === "number");
|
|
26
|
-
return budgets.length > 0 ? Math.max(...budgets) + TOOL_TIMEOUT_GRACE_MS : undefined;
|
|
27
|
-
}
|
|
28
|
-
const PROBE_TIMEOUT_MS = 2_000;
|
|
29
|
-
|
|
30
|
-
// Where the daemon listens when it was started with the default layout
|
|
31
|
-
// (`crates/bsk-cli/src/daemon/paths.rs`): `$BSK_HOME/run/daemon.sock`, or on Windows the named pipe
|
|
32
|
-
// `render_pipe_name` derives from USERNAME and the home.
|
|
33
|
-
export function defaultSocketPath(home, env = process.env) {
|
|
34
|
-
if (process.platform !== "win32") return path.join(home, "run", "daemon.sock");
|
|
35
|
-
return `\\\\.\\pipe\\bsk-daemon-${rustStrHash(env.USERNAME ?? "default", home)}`;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Rust's DefaultHasher (SipHash-1-3, zero keys) over each value's UTF-8 bytes plus the 0xff
|
|
39
|
-
// terminator `str::hash` writes, which is how bsk hashes the pipe name.
|
|
40
|
-
function rustStrHash(...values) {
|
|
41
|
-
const bytes = Buffer.concat(values.flatMap((value) => [Buffer.from(value, "utf8"), Buffer.from([0xff])]));
|
|
42
|
-
const mask = (1n << 64n) - 1n;
|
|
43
|
-
const rotl = (x, b) => ((x << b) | (x >> (64n - b))) & mask;
|
|
44
|
-
let [v0, v1, v2, v3] = [0x736f6d6570736575n, 0x646f72616e646f6dn, 0x6c7967656e657261n, 0x7465646279746573n];
|
|
45
|
-
const round = () => {
|
|
46
|
-
v0 = (v0 + v1) & mask; v1 = rotl(v1, 13n) ^ v0; v0 = rotl(v0, 32n);
|
|
47
|
-
v2 = (v2 + v3) & mask; v3 = rotl(v3, 16n) ^ v2;
|
|
48
|
-
v0 = (v0 + v3) & mask; v3 = rotl(v3, 21n) ^ v0;
|
|
49
|
-
v2 = (v2 + v1) & mask; v1 = rotl(v1, 17n) ^ v2; v2 = rotl(v2, 32n);
|
|
50
|
-
};
|
|
51
|
-
const compress = (word) => { v3 ^= word; round(); v0 ^= word; };
|
|
52
|
-
const whole = bytes.length - (bytes.length % 8);
|
|
53
|
-
for (let i = 0; i < whole; i += 8) compress(bytes.readBigUInt64LE(i));
|
|
54
|
-
let last = BigInt(bytes.length & 0xff) << 56n;
|
|
55
|
-
for (let i = whole; i < bytes.length; i += 1) last |= BigInt(bytes[i]) << BigInt(8 * (i - whole));
|
|
56
|
-
compress(last);
|
|
57
|
-
v2 ^= 0xffn;
|
|
58
|
-
round(); round(); round();
|
|
59
|
-
return ((v0 ^ v1 ^ v2 ^ v3) & mask).toString(16).padStart(16, "0");
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// Node's existsSync cannot see a named pipe, so on Windows the pipe namespace is listed instead;
|
|
63
|
-
// a listing that fails counts as no pipe, so discovery falls back to starting the daemon.
|
|
64
|
-
function socketExists(sockPath) {
|
|
65
|
-
if (process.platform !== "win32") return existsSync(sockPath);
|
|
66
|
-
try { return readdirSync("\\\\.\\pipe\\").includes(path.win32.basename(sockPath)); } catch { return false; }
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// True when something answers system.ping on `sockPath`: a live daemon whose daemon.json was lost.
|
|
70
|
-
function probeSocket(sockPath) {
|
|
71
|
-
if (!socketExists(sockPath)) return Promise.resolve(false);
|
|
72
|
-
return new Promise((resolve) => {
|
|
73
|
-
const socket = connect(sockPath);
|
|
74
|
-
const done = (alive) => { clearTimeout(timer); socket.destroy(); resolve(alive); };
|
|
75
|
-
const timer = setTimeout(() => done(false), PROBE_TIMEOUT_MS);
|
|
76
|
-
socket.on("error", () => done(false));
|
|
77
|
-
socket.on("connect", () => socket.write(JSON.stringify({ id: "probe-orphan", method: "system.ping" }) + "\n"));
|
|
78
|
-
socket.on("data", () => done(true));
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export class BskRpcError extends Error {
|
|
83
|
-
constructor(code, message, data) {
|
|
84
|
-
super(message);
|
|
85
|
-
this.name = "BskRpcError";
|
|
86
|
-
this.code = code;
|
|
87
|
-
this.data = data;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function shortId() { return randomBytes(6).toString("hex"); }
|
|
92
|
-
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
|
|
93
|
-
|
|
94
|
-
// daemon.json outlives a daemon that was killed, as when a host closes the job it ran in. Only its socket
|
|
95
|
-
// says so: a connect that fails with one of these reached no listener. Its pid cannot, since a client in
|
|
96
|
-
// another PID namespace sees a live daemon's pid as gone and a reused pid makes a dead one look alive.
|
|
97
|
-
const NO_LISTENER = new Set(["ENOENT", "ECONNREFUSED"]);
|
|
98
|
-
|
|
99
|
-
function sameRecord(info, stale) {
|
|
100
|
-
return Boolean(stale) && JSON.stringify(info) === JSON.stringify(stale.info);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
export class BskIpcClient {
|
|
104
|
-
#home; #env; #sockPath; #autoStart; #startDaemon; #timeoutMs; #starting = null;
|
|
105
|
-
|
|
106
|
-
constructor({ home, env = process.env, sockPath, autoStart, startDaemon, timeoutMs = DEFAULT_TIMEOUT_MS, bskBin } = {}) {
|
|
107
|
-
this.#home = home ?? resolveBskHome(env);
|
|
108
|
-
this.#sockPath = sockPath ?? null;
|
|
109
|
-
this.#autoStart = autoStart ?? env.BSK_AUTO_START !== "0";
|
|
110
|
-
this.#startDaemon = startDaemon ?? (() => startDaemonWithCli({ home: this.#home, env, bskBin }));
|
|
111
|
-
this.#timeoutMs = timeoutMs;
|
|
112
|
-
this.#env = env;
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
get home() { return this.#home; }
|
|
116
|
-
|
|
117
|
-
// `stale` is a daemon.json record ({info, code}) whose socket refused a connect; it is skipped until rewritten.
|
|
118
|
-
async resolveSocket({ isAborted = () => false, stale } = {}) {
|
|
119
|
-
if (this.#sockPath) return this.#sockPath;
|
|
120
|
-
const found = readDaemonInfo(this.#home);
|
|
121
|
-
if (found && !sameRecord(found, stale)) return found.sock_path;
|
|
122
|
-
// daemon.json can vanish while the daemon keeps running; starting another one then fails on the held port.
|
|
123
|
-
const orphan = defaultSocketPath(this.#home, this.#env);
|
|
124
|
-
// Probe only when the socket file exists, so a fresh home starts its daemon in the same tick as before.
|
|
125
|
-
if (socketExists(orphan)) {
|
|
126
|
-
if (await probeSocket(orphan)) return orphan;
|
|
127
|
-
if (isAborted()) throw new BskRpcError("cancelled", "cancelled before the daemon was located");
|
|
128
|
-
}
|
|
129
|
-
if (!this.#autoStart) {
|
|
130
|
-
if (stale) {
|
|
131
|
-
throw new BskRpcError("no_daemon", `${this.#home}/daemon.json names a BrowserSkill daemon at ${stale.info.sock_path} that is no longer listening (${stale.code}) and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`);
|
|
132
|
-
}
|
|
133
|
-
throw new BskRpcError("no_daemon", `no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`);
|
|
134
|
-
}
|
|
135
|
-
if (!this.#starting) this.#starting = this.#startDaemon().finally(() => { this.#starting = null; });
|
|
136
|
-
await this.#starting;
|
|
137
|
-
const deadline = Date.now() + DISCOVERY_BUDGET_MS;
|
|
138
|
-
while (Date.now() < deadline && !isAborted()) {
|
|
139
|
-
const info = readDaemonInfo(this.#home);
|
|
140
|
-
if (info && !sameRecord(info, stale)) return info.sock_path;
|
|
141
|
-
await sleep(DISCOVERY_RETRY_MS);
|
|
142
|
-
}
|
|
143
|
-
if (isAborted()) throw new BskRpcError("cancelled", "cancelled while waiting for the daemon to publish daemon.json");
|
|
144
|
-
throw new BskRpcError("no_daemon", `daemon start was requested but ${this.#home}/daemon.json never appeared`);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
call(method, params, options = {}) {
|
|
148
|
-
return this.callWithHandle(method, params, options).promise;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// {rpcId, promise, abort()} — rpcId is known before the frame is sent so a
|
|
152
|
-
// caller can cancel a long tool call from another connection.
|
|
153
|
-
callWithHandle(method, params, { idPrefix = method.replace(/[^a-z0-9]+/gi, "-"), timeoutMs } = {}) {
|
|
154
|
-
const ownBudget = ownBudgetMs(params);
|
|
155
|
-
const humanWait = HUMAN_WAIT_METHODS.has(method);
|
|
156
|
-
// An explicit timeoutMs is a floor, never a cut below the tool's own budget.
|
|
157
|
-
const waitMs = humanWait && ownBudget === undefined && timeoutMs === undefined
|
|
158
|
-
? HUMAN_WAIT_BACKSTOP_MS
|
|
159
|
-
: Math.max(timeoutMs ?? this.#timeoutMs, ownBudget ?? 0);
|
|
160
|
-
const rpcId = `${idPrefix}-${shortId()}`;
|
|
161
|
-
const frame = { id: rpcId, method };
|
|
162
|
-
if (params !== undefined) frame.params = params;
|
|
163
|
-
let aborted = false;
|
|
164
|
-
let abortSocket = () => {};
|
|
165
|
-
const exchange = (sockPath, onNoListener) => new Promise((resolve, reject) => {
|
|
166
|
-
const socket = connect(sockPath);
|
|
167
|
-
let buffer = "";
|
|
168
|
-
let settled = false;
|
|
169
|
-
const finish = (fn, value) => {
|
|
170
|
-
if (settled) return;
|
|
171
|
-
settled = true;
|
|
172
|
-
clearTimeout(timer);
|
|
173
|
-
socket.destroy();
|
|
174
|
-
fn(value);
|
|
175
|
-
};
|
|
176
|
-
const timer = setTimeout(() => {
|
|
177
|
-
const cancels = method !== "cancel" && !humanWait;
|
|
178
|
-
finish(reject, new BskRpcError("timeout", `${method} did not answer within ${waitMs}ms${cancels ? "; a cancel was requested at the daemon" : ""}`));
|
|
179
|
-
// The daemon would otherwise keep running it and hold the session for the next call.
|
|
180
|
-
if (cancels) this.cancel(rpcId).catch(() => {});
|
|
181
|
-
}, waitMs);
|
|
182
|
-
abortSocket = () => finish(reject, new BskRpcError("cancelled", `${method} cancelled by caller`));
|
|
183
|
-
socket.on("error", (error) => {
|
|
184
|
-
if (NO_LISTENER.has(error.code)) onNoListener(error.code);
|
|
185
|
-
finish(reject, new BskRpcError("no_daemon", `IPC socket ${sockPath}: ${error.code ?? error.message}`));
|
|
186
|
-
});
|
|
187
|
-
socket.setEncoding("utf8");
|
|
188
|
-
socket.on("connect", () => socket.write(JSON.stringify(frame) + "\n"));
|
|
189
|
-
socket.on("data", (chunk) => {
|
|
190
|
-
buffer += chunk;
|
|
191
|
-
const idx = buffer.indexOf("\n");
|
|
192
|
-
if (idx === -1) return;
|
|
193
|
-
try { finish(resolve, decodeResponse(buffer.slice(0, idx), rpcId, method)); } catch (error) { finish(reject, error); }
|
|
194
|
-
});
|
|
195
|
-
socket.on("close", () => finish(reject, new BskRpcError("protocol_error", `${method}: daemon closed the connection without a reply`)));
|
|
196
|
-
});
|
|
197
|
-
const promise = (async () => {
|
|
198
|
-
let stale;
|
|
199
|
-
for (;;) {
|
|
200
|
-
const sockPath = await this.resolveSocket({ isAborted: () => aborted, stale });
|
|
201
|
-
if (aborted) throw new BskRpcError("cancelled", `${method} cancelled by caller`);
|
|
202
|
-
let refused;
|
|
203
|
-
try {
|
|
204
|
-
return await exchange(sockPath, (code) => { refused = code; });
|
|
205
|
-
} catch (error) {
|
|
206
|
-
// The frame never left, so one retry past the stale record sends nothing twice.
|
|
207
|
-
const info = refused && !stale && !this.#sockPath ? readDaemonInfo(this.#home) : null;
|
|
208
|
-
if (info?.sock_path !== sockPath) throw error;
|
|
209
|
-
stale = { info, code: refused };
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
})();
|
|
213
|
-
return { rpcId, promise, abort: () => { aborted = true; abortSocket(); } };
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
async cancel(rpcId) {
|
|
217
|
-
return this.call("cancel", { rpc_id: rpcId }, { idPrefix: "cancel", timeoutMs: 2_000 });
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
function decodeResponse(line, rpcId, method) {
|
|
222
|
-
let reply;
|
|
223
|
-
try { reply = JSON.parse(line); } catch {
|
|
224
|
-
throw new BskRpcError("protocol_error", `${method}: daemon reply is not JSON: ${line.slice(0, 120)}`);
|
|
225
|
-
}
|
|
226
|
-
// The daemon answers a frame it could not decode under id "0".
|
|
227
|
-
const undecodableFrame = reply.id === "0" && reply.error;
|
|
228
|
-
if (reply.id !== rpcId && !undecodableFrame) {
|
|
229
|
-
throw new BskRpcError("protocol_error", `${method}: reply id ${reply.id} does not match request ${rpcId}`);
|
|
230
|
-
}
|
|
231
|
-
if (reply.error) {
|
|
232
|
-
const { code = "protocol_error", message = "daemon error", data } = reply.error;
|
|
233
|
-
throw new BskRpcError(code, message, data);
|
|
234
|
-
}
|
|
235
|
-
return reply.result;
|
|
236
|
-
}
|