omowright 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -2
  3. package/TOOLS.md +366 -0
  4. package/bin/omowright-cloak.mjs +112 -0
  5. package/package.json +57 -4
  6. package/presets/agent-events/SKILL.md +75 -0
  7. package/presets/captcha/SKILL.md +129 -0
  8. package/presets/chrome/SKILL.md +84 -0
  9. package/presets/cloak-bridge/SKILL.md +43 -0
  10. package/presets/network/SKILL.md +126 -0
  11. package/presets/visual-browse/SKILL.md +103 -0
  12. package/skills/omowright/SKILL.md +193 -0
  13. package/skills/omowright/references/1password.md +118 -0
  14. package/skills/omowright/references/browserskill.md +186 -0
  15. package/skills/omowright/references/eval-kernel.md +100 -0
  16. package/skills/omowright/references/frames-layers-human.md +123 -0
  17. package/skills/omowright/references/quickstart.md +96 -0
  18. package/skills/omowright/references/stealth.md +174 -0
  19. package/src/agent-tabs.js +160 -0
  20. package/src/bridge-schemas.js +44 -0
  21. package/src/bridge-transport.js +57 -0
  22. package/src/browser-process.js +122 -0
  23. package/src/bsk/browser-signals.js +90 -0
  24. package/src/bsk/browsers.js +114 -0
  25. package/src/bsk/connect.js +45 -0
  26. package/src/bsk/daemon-info.js +100 -0
  27. package/src/bsk/external-extension.js +110 -0
  28. package/src/bsk/identify-browser.js +88 -0
  29. package/src/bsk/install-cli.js +81 -0
  30. package/src/bsk/ipc-client.js +236 -0
  31. package/src/bsk/onboard.js +133 -0
  32. package/src/bsk/screenshot.js +49 -0
  33. package/src/bsk/session.js +131 -0
  34. package/src/bsk/snapshot.js +56 -0
  35. package/src/bsk/targets.js +25 -0
  36. package/src/captcha-wait.js +74 -0
  37. package/src/captcha.js +142 -0
  38. package/src/cdp-errors.js +23 -0
  39. package/src/cdp-methods.js +61 -0
  40. package/src/chrome-profile.js +176 -0
  41. package/src/chrome.js +192 -0
  42. package/src/cloak-profile.js +266 -0
  43. package/src/connection.js +135 -0
  44. package/src/cookies.js +29 -0
  45. package/src/core.js +1710 -0
  46. package/src/cua.js +74 -0
  47. package/src/dialog-policy.js +80 -0
  48. package/src/emulate.js +127 -0
  49. package/src/events.js +111 -0
  50. package/src/frames-snapshot.js +138 -0
  51. package/src/har.js +103 -0
  52. package/src/human-handoff.js +122 -0
  53. package/src/index.js +86 -0
  54. package/src/injected.js +3 -0
  55. package/src/instance-lock.js +230 -0
  56. package/src/instances.js +493 -0
  57. package/src/internal-capability.js +1 -0
  58. package/src/launch-endpoint.js +185 -0
  59. package/src/layers.js +138 -0
  60. package/src/llm.js +201 -0
  61. package/src/lock-file.js +130 -0
  62. package/src/native-host-win32.js +201 -0
  63. package/src/network-events.js +201 -0
  64. package/src/network-snoop.js +229 -0
  65. package/src/open-shadow-query.js +22 -0
  66. package/src/owner-only.js +109 -0
  67. package/src/page-bundle.js +1397 -0
  68. package/src/page-routes.js +94 -0
  69. package/src/pipe.js +391 -0
  70. package/src/routes.js +256 -0
  71. package/src/running-browser.js +85 -0
  72. package/src/scroll-collect.js +73 -0
  73. package/src/serial-emitter.js +17 -0
  74. package/src/shared-connections.js +278 -0
  75. package/src/snapshot-diff.js +75 -0
  76. package/src/trace.js +183 -0
  77. package/src/url-match.js +148 -0
  78. package/src/viewport.js +12 -0
@@ -0,0 +1,110 @@
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
+ }
@@ -0,0 +1,88 @@
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
+ }
@@ -0,0 +1,81 @@
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
+ }
@@ -0,0 +1,236 @@
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
+ }
@@ -0,0 +1,133 @@
1
+ import { homedir } from "node:os";
2
+ import { findBskBinary } from "./daemon-info.js";
3
+ import { BskIpcClient } from "./ipc-client.js";
4
+ import { listBrowsers } from "./connect.js";
5
+ import { catalogBrowsers, externalExtensionEntry, registerExternalExtension, STORE_PAGE_URLS } from "./external-extension.js";
6
+ import { probeBrowserSignals } from "./browser-signals.js";
7
+ import { identifyBrowser } from "./identify-browser.js";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { cliVersionDefault, installBskCli } from "./install-cli.js";
10
+
11
+ const DEFAULT_WAIT_TOTAL_MS = 180_000;
12
+
13
+ function resolveBskBin(bskBin, env) {
14
+ if (bskBin === null) return null;
15
+ return bskBin ?? findBskBinary(env);
16
+ }
17
+
18
+ async function cliReport({ bskBin, env, cliVersion }) {
19
+ const bin = resolveBskBin(bskBin, env);
20
+ if (!bin) return { installed: false, bskBin: null, version: null };
21
+ const raw = await cliVersion(bin);
22
+ return raw ? { installed: true, bskBin: bin, version: raw.replace(/^bsk\s+/, "") } : { installed: false, bskBin: bin, version: null };
23
+ }
24
+
25
+ async function daemonReport(client, waitForBrowserMs) {
26
+ try {
27
+ const status = await client.call("system.status", waitForBrowserMs > 0 ? { wait_for_browser_ms: waitForBrowserMs } : {}, { idPrefix: "status" });
28
+ return { running: true, version: status.daemon_version, protocolVersion: status.protocol_version, browsers: status.browsers ?? [], sessions: status.sessions ?? [] };
29
+ } catch (error) {
30
+ return { running: false, error: error.message, code: error.code, startBlocked: NO_BREAKAWAY.test(error.message), browsers: [], sessions: [] };
31
+ }
32
+ }
33
+
34
+ // bsk's refusal when the host's Windows Job Object forbids breakaway: a detached start fails the same way every retry.
35
+ const NO_BREAKAWAY = /Job Object|breakaway/i;
36
+ const FOREGROUND_STEP = "run `bsk daemon start --foreground` in a persistent background session of the agent host (one that outlives the command, not a one-shot shell call), then check it with `bsk status` from a separate call";
37
+
38
+ function daemonStep(daemon) {
39
+ if (daemon.startBlocked) return `Start the BrowserSkill daemon: this host does not let a command detach it (Windows Job Object breakaway is prohibited), so retrying \`bsk status\` or \`bsk daemon start\` fails the same way; ${FOREGROUND_STEP}.`;
40
+ return `Start the BrowserSkill daemon: bskOnboard() (or \`bsk status\` once) starts it. If the host reaps background processes or the start fails, ${FOREGROUND_STEP}; do not retry a detached \`bsk daemon start\`.`;
41
+ }
42
+
43
+ const NO_BROWSER_STEP = `No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;
44
+
45
+ function withRegistration(platform, browser) {
46
+ const entry = externalExtensionEntry({ platform, browser });
47
+ const extensionRegistered = entry.kind === "file" && existsSync(entry.path) && readFileSync(entry.path, "utf8") === entry.content;
48
+ return { ...browser, registration: entry, extensionRegistered };
49
+ }
50
+
51
+ async function identify({ platform, home, env, exists, browser, connected, signals, probeSignals, now }) {
52
+ const catalog = catalogBrowsers({ platform, home, env, exists }).map((b) => withRegistration(platform, b));
53
+ const observed = signals ?? await probeSignals({ platform, home, browsers: catalog.filter((b) => b.hasProfile) });
54
+ const explicit = browser ?? env.OMOWRIGHT_BROWSER ?? null;
55
+ const { primary, ...identification } = identifyBrowser({ catalog, signals: observed, explicit: explicit || null, connected, now });
56
+ const browsers = catalog.filter((b) => b.installed);
57
+ const registeredElsewhere = browsers.filter((b) => b.extensionRegistered && b.id !== identification.primaryId).map((b) => b.id);
58
+ return { browsers, identification: { ...identification, registeredElsewhere }, primary };
59
+ }
60
+
61
+ function choiceStep(identification) {
62
+ const listed = identification.candidates.map((c) => `${c.label} [${c.id}]${c.signals.length ? ` — ${c.signals.join(", ")}` : ""}`).join("; ");
63
+ const hint = identification.suggested ? ` Likely ${identification.suggested}, but confirm first.` : "";
64
+ return `Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`;
65
+ }
66
+
67
+ function nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary }) {
68
+ if (browsersConnected.length > 0) return null;
69
+ if (!cli.installed) return "Install the bsk CLI (bskOnboard() runs the official installer).";
70
+ if (!daemon.running) return daemonStep(daemon);
71
+ if (browsers.length === 0 && !primary) return NO_BROWSER_STEP;
72
+ if (identification.needsChoice) return choiceStep(identification);
73
+ if (!primary.extensionRegistered && primary.registration.kind !== "store") return `Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;
74
+ return primary.registration.humanStep;
75
+ }
76
+
77
+ export async function bskDoctor({
78
+ platform = process.platform, home = homedir(), env = process.env, client, bskBin, cliVersion = cliVersionDefault, waitForBrowserMs = 0,
79
+ exists = existsSync, browser, signals, probeSignals = probeBrowserSignals, now = Date.now(),
80
+ } = {}) {
81
+ const cli = await cliReport({ bskBin, env, cliVersion });
82
+ const ipc = client ?? new BskIpcClient({ env, bskBin: cli.bskBin ?? undefined, autoStart: false });
83
+ const daemon = await daemonReport(ipc, waitForBrowserMs);
84
+ const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
85
+ const browsersConnected = daemon.browsers;
86
+ const report = { cli, daemon, browsers, primary: primary ?? null, identification, browsersConnected, ready: browsersConnected.length > 0 };
87
+ report.nextStep = nextStepFor(report);
88
+ return report;
89
+ }
90
+
91
+ export async function bskOnboard({
92
+ platform = process.platform, home = homedir(), env = process.env, client, bskBin, installDir,
93
+ installCli = installBskCli, cliVersion = cliVersionDefault, onHumanStep = () => {},
94
+ waitForBrowserMs = 15_000, waitTotalMs = DEFAULT_WAIT_TOTAL_MS,
95
+ exists = existsSync, browser, signals, probeSignals = probeBrowserSignals, now = Date.now(),
96
+ } = {}) {
97
+ let cli = await cliReport({ bskBin, env, cliVersion });
98
+ let install = null;
99
+ if (!cli.installed) {
100
+ install = await installCli({ platform, home, installDir });
101
+ cli = install.installed ? await cliReport({ bskBin: install.bskBin, env, cliVersion }) : cli;
102
+ }
103
+ const ipc = client ?? new BskIpcClient({ env, bskBin: cli.bskBin ?? undefined, autoStart: true });
104
+ let daemon = await daemonReport(ipc, 0);
105
+ const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
106
+ const registrations = [];
107
+ let humanStep = null;
108
+ let needsChoice = false;
109
+ if (daemon.browsers.length === 0) {
110
+ if (browsers.length === 0 && !primary) {
111
+ humanStep = NO_BROWSER_STEP;
112
+ } else if (identification.needsChoice) {
113
+ needsChoice = true;
114
+ humanStep = choiceStep(identification);
115
+ } else if (daemon.running) {
116
+ // A down daemon hides whether the extension is already enabled, so no step goes to the user until it is up.
117
+ const registration = await registerExternalExtension({ platform, browser: primary });
118
+ registrations.push({ browser: primary.id, ...registration });
119
+ humanStep = registration.humanStep;
120
+ onHumanStep({ browser: primary.id, step: registration.humanStep, registered: registration.registered, needsRestart: registration.needsRestart });
121
+ }
122
+ }
123
+ const deadline = Date.now() + waitTotalMs;
124
+ let browsersConnected = daemon.browsers;
125
+ while (!needsChoice && browsersConnected.length === 0 && daemon.running && Date.now() < deadline) {
126
+ browsersConnected = await listBrowsers(ipc, { waitForBrowserMs });
127
+ if (waitForBrowserMs === 0) break;
128
+ }
129
+ daemon = { ...daemon, browsers: browsersConnected };
130
+ const ready = browsersConnected.length > 0;
131
+ const nextStep = ready ? null : humanStep ?? nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary });
132
+ return { cli, install, daemon, browsers, primary: primary ?? null, identification, needsChoice, registrations, humanStep: ready ? null : humanStep, nextStep, browsersConnected, ready };
133
+ }