omowright 0.0.0-stage → 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 +61 -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,57 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import { mkdir, open, readFile, rename, lstat, chmod } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { TextDecoder } from "node:util";
6
+ import { createChromeApi as createStandaloneChromeApi } from "./chrome.js";
7
+ import { UnsupportedOperationError } from "./core.js";
8
+ import { WIN32_REGISTRY_KEYS, installWin32NativeHost, isWin32RegistryKey } from "./native-host-win32.js";
9
+ import { HOST_NAME, PROTOCOL, MAX_MESSAGE_BYTES, EVENT_NAMES, COMMAND_NAMES, payloadSchemas, ExtensionHelloSchema, HostHelloSchema, EventSchema, CommandSchema, ResponseSchema } from "./bridge-schemas.js";
10
+ export { HOST_NAME, PROTOCOL, MAX_MESSAGE_BYTES, EVENT_NAMES, COMMAND_NAMES, ExtensionHelloSchema, HostHelloSchema, EventSchema, CommandSchema, ResponseSchema } from "./bridge-schemas.js";
11
+
12
+ export class BridgeUnavailableError extends Error { constructor(message = "Cloak bridge is unavailable") { super(message); this.name = "BridgeUnavailableError"; } }
13
+ export class BridgeProtocolError extends Error { constructor(message) { super(message); this.name = "BridgeProtocolError"; } }
14
+ const decoder = new TextDecoder("utf-8", { fatal: true });
15
+ const checked = (schema, value, message) => { const result = schema.safeParse(value); if (!result.success) throw new BridgeProtocolError(message); return result.data; };
16
+ function schemaFor(value) { if (value.type === "hello") return value.role === "host" ? HostHelloSchema : ExtensionHelloSchema; if (value.type === "event") return EventSchema; if (value.type === "command") return CommandSchema; if (value.type === "response") return ResponseSchema; return null; }
17
+ export function encodeFrame(value, maxMessageBytes = MAX_MESSAGE_BYTES) { const schema = schemaFor(value); if (schema) checked(schema, value, "invalid outbound message"); let json; try { json = JSON.stringify(value); } catch { throw new BridgeProtocolError("invalid JSON"); } const body = Buffer.from(json, "utf8"); if (body.length === 0 || body.length > maxMessageBytes) throw new BridgeProtocolError("PAYLOAD_TOO_LARGE"); const frame = Buffer.allocUnsafe(4 + body.length); frame.writeUInt32LE(body.length, 0); body.copy(frame, 4); return frame; }
18
+ export function decodeFrames(buffer, maxMessageBytes = MAX_MESSAGE_BYTES) { const frames = []; let offset = 0; while (buffer.length - offset >= 4) { const length = buffer.readUInt32LE(offset); if (!length || length > maxMessageBytes) throw new BridgeProtocolError("PAYLOAD_TOO_LARGE"); if (buffer.length - offset < length + 4) break; const body = buffer.subarray(offset + 4, offset + 4 + length); let text; try { text = decoder.decode(body); } catch { throw new BridgeProtocolError("invalid UTF-8"); } try { frames.push(JSON.parse(text)); } catch { throw new BridgeProtocolError("invalid JSON"); } offset += length + 4; } return { frames, remainder: buffer.subarray(offset) }; }
19
+
20
+ export function createNativeMessagingHost({ stdin = process.stdin, stdout = process.stdout, stderr = process.stderr, extensionId, hostName = HOST_NAME, maxMessageBytes = MAX_MESSAGE_BYTES, commandTimeoutMs = 30_000, maxPendingWrites = 256, onEvent, onDisconnect } = {}) {
21
+ if (!/^[a-p]{32}$/.test(extensionId ?? "")) throw new BridgeProtocolError("a valid extensionId is required");
22
+ if (!/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName) || hostName !== HOST_NAME) throw new BridgeProtocolError("invalid hostName");
23
+ let buffer = Buffer.alloc(0), closed = false, hello = null, hostConnectionId = null, effectiveMax = maxMessageBytes, lastEventSeq = 0, sequence = 0, mutationBusy = false;
24
+ const pending = new Map(), listeners = new Map(), commandQueue = [], writeQueue = []; let writing = false;
25
+ const disconnect = reason => { if (closed) return; closed = true; const error = reason instanceof Error ? reason : new BridgeUnavailableError(reason ?? "native host disconnected"); for (const item of pending.values()) { item.cleanup?.(); item.reject(error); } pending.clear(); for (const item of commandQueue.splice(0)) { item.cleanup?.(); item.reject(error); } for (const item of writeQueue.splice(0)) item.reject(error); onDisconnect?.(error); };
26
+ const write = value => { if (closed) return Promise.reject(new BridgeUnavailableError()); let frame; try { const schema = schemaFor(value); if (!schema) throw new BridgeProtocolError("invalid outbound message type"); checked(schema, value, "invalid outbound message"); frame = encodeFrame(value, effectiveMax); } catch (error) { return Promise.reject(error); } if (writeQueue.length + (writing ? 1 : 0) >= maxPendingWrites) return Promise.reject(new BridgeProtocolError("BOUNDED_TRANSPORT")); return new Promise((resolve, reject) => { writeQueue.push({ frame, resolve, reject }); pumpWrites(); }); };
27
+ const pumpWrites = () => { if (writing || closed || !writeQueue.length) return; writing = true; const item = writeQueue.shift(); let finished = false; const done = error => { if (finished) return; finished = true; writing = false; if (error) { item.reject(error); disconnect(error); } else item.resolve(); pumpWrites(); }; try { const result = stdout.write(item.frame, error => done(error)); if (result === false && stdout.once) stdout.once("error", done); } catch (error) { done(error); } };
28
+ const pumpCommands = () => { if (closed || mutationBusy || !commandQueue.length) return; const item = commandQueue.shift(); item.started = true; mutationBusy = true; pending.set(item.requestId, item); write(item.command).catch(error => { if (pending.delete(item.requestId)) { item.settled = true; item.cleanup(); item.reject(error); } disconnect(error); }); };
29
+ const dispatchEvent = event => { if (!hello || event.connectionId !== hello.connectionId || event.seq <= lastEventSeq || !hello.events.includes(event.name)) throw new BridgeProtocolError("invalid event ordering or capability"); lastEventSeq = event.seq; try { Promise.resolve(onEvent?.(event)).catch(error => stderr.write?.(`bridge listener: ${error.message}\n`)); } catch (error) { stderr.write?.(`bridge listener: ${error.message}\n`); } for (const fn of listeners.get(event.name) ?? []) { try { Promise.resolve(fn(event.payload)).catch(error => stderr.write?.(`bridge listener: ${error.message}\n`)); } catch (error) { stderr.write?.(`bridge listener: ${error.message}\n`); } } };
30
+ const handle = raw => { if (!hello) { const parsed = checked(ExtensionHelloSchema, raw, "extension hello rejected"); if (parsed.extensionId !== extensionId) throw new BridgeProtocolError("extension hello rejected"); hello = parsed; hostConnectionId = randomUUID(); effectiveMax = Math.min(maxMessageBytes, parsed.maxMessageBytes); lastEventSeq = 0; return write({ protocol: PROTOCOL, type: "hello", role: "host", connectionId: hostConnectionId, hostName, hostVersion: "0.1.0", events: EVENT_NAMES.filter(x => parsed.events.includes(x)), commands: COMMAND_NAMES.filter(x => parsed.commands.includes(x)), maxMessageBytes: effectiveMax }); }
31
+ if (raw.type === "event") return dispatchEvent(checked(EventSchema, raw, "invalid event"));
32
+ if (raw.type === "response") { const parsed = checked(ResponseSchema, raw, "invalid response"); if (parsed.name === "protocolError") throw Object.assign(new BridgeProtocolError(parsed.error.message), { code: parsed.error.code, details: parsed.error.details }); const item = pending.get(parsed.requestId); if (!item || item.name !== parsed.name) throw new BridgeProtocolError("invalid or unknown response"); item.settled = true; pending.delete(parsed.requestId); item.cleanup(); mutationBusy = false; if (parsed.ok) item.resolve(parsed.result); else item.reject(Object.assign(new Error(parsed.error.message), { code: parsed.error.code, details: parsed.error.details })); pumpCommands(); return; }
33
+ throw new BridgeProtocolError("unexpected message");
34
+ };
35
+ const onData = chunk => { try { buffer = Buffer.concat([buffer, Buffer.from(chunk)]); const out = decodeFrames(buffer, effectiveMax); buffer = out.remainder; for (const raw of out.frames) Promise.resolve(handle(raw)).catch(error => { stderr.write?.(`bridge: ${error.message}\n`); disconnect(error); }); } catch (error) { stderr.write?.(`bridge: ${error.message}\n`); disconnect(error); } };
36
+ stdin.on("data", onData); stdin.once?.("end", () => disconnect()); stdin.once?.("error", disconnect);
37
+ return { get isConnected() { return !closed && !!hello; }, get capabilities() { return { commands: new Set(hello?.commands ?? []), events: new Set(hello?.events ?? []) }; }, send: write,
38
+ request(name, params, { signal, timeoutMs = commandTimeoutMs } = {}) { if (!hello || !hello.commands.includes(name)) return Promise.reject(new BridgeUnavailableError(`unsupported bridge command: ${name}`)); let command; try { command = checked(CommandSchema, { protocol: PROTOCOL, type: "command", requestId: randomUUID(), name, params }, "invalid command parameters"); } catch (error) { return Promise.reject(error); } return new Promise((resolve, reject) => { if (commandQueue.length + pending.size >= maxPendingWrites) { reject(new BridgeProtocolError("BOUNDED_TRANSPORT")); return; } const item = { requestId: command.requestId, name, command, resolve, reject, timer: null, abortHandler: null, cleanup: null, settled: false }; const cleanup = () => { clearTimeout(item.timer); if (item.abortHandler) { signal?.removeEventListener("abort", item.abortHandler); item.abortHandler = null; } }; item.cleanup = cleanup; const failIndeterminate = (code, reason = null) => { if (item.settled) return; item.settled = true; cleanup(); if (pending.delete(item.requestId) || commandQueue.includes(item)) { const i = commandQueue.indexOf(item); if (i >= 0) commandQueue.splice(i, 1); item.reject(reason ?? Object.assign(new Error(`bridge command timed out: ${name}`), { code })); } if (item.started) disconnect(Object.assign(new Error("mutation completion is indeterminate"), { code })); }; item.timer = setTimeout(() => failIndeterminate("TIMEOUT"), timeoutMs); if (signal?.aborted) { item.settled = true; cleanup(); reject(signal.reason ?? Object.assign(new Error(`bridge command aborted: ${name}`), { code: "ABORT_ERR" })); return; } item.abortHandler = () => failIndeterminate("ABORT_ERR", signal.reason); signal?.addEventListener("abort", item.abortHandler, { once: true }); commandQueue.push(item); pumpCommands(); }); },
39
+ on(name, listener) { if (!EVENT_NAMES.includes(name)) throw new BridgeProtocolError("invalid event name"); const set = listeners.get(name) ?? new Set(); set.add(listener); listeners.set(name, set); return () => { set.delete(listener); if (!set.size) listeners.delete(name); }; },
40
+ emitEvent(name, payload) { if (!hello?.events.includes(name)) return Promise.reject(new BridgeUnavailableError("unsupported bridge event")); const checkedPayload = payloadSchemas[name].safeParse(payload); if (!checkedPayload.success) return Promise.reject(new BridgeProtocolError("invalid event payload")); sequence += 1; return write({ protocol: PROTOCOL, type: "event", connectionId: hostConnectionId, seq: sequence, occurredAt: Date.now(), name, payload: checkedPayload.data }); },
41
+ close() { disconnect("closed"); stdin.removeListener?.("data", onData); } };
42
+ }
43
+
44
+ const NATIVE_HOST_DIRS = {
45
+ darwin: { chrome: ["Library", "Application Support", "Google", "Chrome"], chromium: ["Library", "Application Support", "Chromium"] },
46
+ linux: { chrome: [".config", "google-chrome"], chromium: [".config", "chromium"] },
47
+ };
48
+ export function defaultNativeMessagingHostDir(browser = "chrome", platform = process.platform) { if (platform === "win32") { if (!WIN32_REGISTRY_KEYS[browser]) throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir"); return path.win32.join(process.env.LOCALAPPDATA || path.win32.join(homedir(), "AppData", "Local"), "omowright", "NativeMessagingHosts", browser); } const byBrowser = NATIVE_HOST_DIRS[platform]; if (!byBrowser) throw new BridgeProtocolError(`no default nativeMessagingHostDir on ${platform}; pass nativeMessagingHostDir`); const segments = byBrowser[browser]; if (!segments) throw new BridgeProtocolError("custom browser requires nativeMessagingHostDir"); return path.join(homedir(), ...segments, "NativeMessagingHosts"); }
49
+ async function secureDirectory(dir) { const absolute = path.resolve(dir); const parts = absolute.split(path.sep).filter(Boolean); let current = path.parse(absolute).root; let final; for (const [index, part] of parts.entries()) { current = path.join(current, part); let info = await lstat(current).catch(() => null); if (!info) { await mkdir(current, { mode: 0o700 }); info = await lstat(current); } if (current !== "/var" && (info.isSymbolicLink() || !info.isDirectory())) throw new BridgeProtocolError("nativeMessagingHostDir security rejected"); if (current !== "/var" && info.uid !== process.getuid?.() && info.uid !== 0) throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected"); const stickyRootAncestor = index < parts.length - 1 && info.uid === 0 && (info.mode & 0o1000) !== 0; if (current !== "/var" && !stickyRootAncestor && (info.mode & 0o022) !== 0) throw new BridgeProtocolError("nativeMessagingHostDir security rejected"); final = info; } if (!final || (final.uid !== process.getuid?.() && final.uid !== 0)) throw new BridgeProtocolError("nativeMessagingHostDir ownership rejected"); if ((final.mode & 0o077) !== 0) await chmod(absolute, 0o700); }
50
+ async function secureExecutable(hostPath) { const info = await lstat(hostPath).catch(() => null); if (!info?.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.() || (info.mode & 0o111) === 0 || (info.mode & 0o022) !== 0) throw new BridgeProtocolError("hostPath must be a securely owned executable file"); }
51
+ export async function installNativeMessagingHost({ hostName = HOST_NAME, hostPath, extensionId, browser = "chrome", nativeMessagingHostDir, force = false, endpointPath, registryKey } = {}) { const win32 = process.platform === "win32"; if (endpointPath !== undefined) throw new BridgeProtocolError("endpointPath is not supported"); if (hostName !== HOST_NAME || !/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/.test(hostName)) throw new BridgeProtocolError("invalid hostName"); if (!path.isAbsolute(hostPath ?? "")) throw new BridgeProtocolError("hostPath must be absolute"); if (!win32) await secureExecutable(hostPath); if (!/^[a-p]{32}$/.test(extensionId ?? "")) throw new BridgeProtocolError("invalid extensionId"); if (!nativeMessagingHostDir && browser === "cloakbrowser") throw new BridgeProtocolError("CloakBrowser nativeMessagingHostDir must be explicit and verified"); if (registryKey !== undefined && !win32) throw new BridgeProtocolError("registryKey is only used on win32"); const dir = nativeMessagingHostDir ?? defaultNativeMessagingHostDir(browser);
52
+ const manifest = { name: hostName, description: "OmOWright internal CloakBrowser native messaging bridge.", path: hostPath, type: "stdio", allowed_origins: [`chrome-extension://${extensionId}/`] };
53
+ const writeManifest = async file => { if (!force && await lstat(file).catch(() => null)) throw new BridgeProtocolError("registration manifest already exists; use force"); const temp = `${file}.${process.pid}.${randomUUID()}.tmp`; const handle = await open(temp, "wx", 0o600); try { await handle.writeFile(JSON.stringify(manifest, null, 2) + "\n"); await handle.sync(); } finally { await handle.close(); } await rename(temp, file); return JSON.parse(await readFile(file, "utf8")); };
54
+ if (win32) { const key = registryKey ?? WIN32_REGISTRY_KEYS[browser]; if (!isWin32RegistryKey(key)) throw new BridgeProtocolError(registryKey === undefined ? "custom browser requires registryKey on win32" : "registryKey must be HKCU\\Software\\...\\NativeMessagingHosts"); try { return await installWin32NativeHost({ hostName, hostPath, dir, registryKey: key, force, writeManifest }); } catch (error) { throw error instanceof BridgeProtocolError ? error : new BridgeProtocolError(error.message); } }
55
+ await secureDirectory(dir); const file = path.join(dir, `${hostName}.json`); const parsed = await writeManifest(file); await chmod(file, 0o600); return { path: file, manifest: parsed }; }
56
+ export function createBridgeClient(options = {}) { return createNativeMessagingHost(options); }
57
+ export function createChromeApi(connection, options = {}) { const chrome = createStandaloneChromeApi(connection, options); const bridge = options.bridge; const request = (wire, params) => bridge?.isConnected && bridge.capabilities?.commands?.has(wire) ? bridge.request(wire, params) : Promise.reject(new UnsupportedOperationError(`chrome.${wire} requires the extension bridge in standalone OmOWright`)); chrome.bookmarks.create = details => request("bookmarks.create", { details }); chrome.bookmarks.move = (id, details = {}) => request("bookmarks.move", { details: { ...details, id: String(id) } }); chrome.bookmarks.remove = id => request("bookmarks.remove", { details: { id: String(id) } }); chrome.history.deleteUrl = details => request("history.deleteUrl", { details }); chrome.history.deleteRange = details => request("history.deleteRange", { details }); chrome.tabGroups = { update: (groupId, updateProperties) => request("tabGroups.update", { details: { groupId, updateProperties } }) }; chrome.debugger = { attach: (target, requiredVersion) => request("debugger.attach", { details: { tabId: target.tabId ?? target, requiredVersion } }), detach: target => request("debugger.detach", { details: { tabId: target.tabId ?? target } }) }; const eventMap = { notifications: ["onShown", "onClicked", "onClosed"], tabGroups: ["onCreated", "onUpdated", "onMoved"], tabs: ["onActivated"], windows: ["onFocusChanged"] }; for (const [namespace, events] of Object.entries(eventMap)) { chrome[namespace] ??= {}; for (const event of events) { const wire = `${namespace}.${event.slice(2, 3).toLowerCase() + event.slice(3)}`; const subscriptions = new Map(); chrome[namespace][event] = { addListener(listener) { if (!bridge?.on) return undefined; const unsubscribe = bridge.on(wire, payload => listener(...(namespace === "notifications" && event === "onClosed" ? [payload.notificationId, payload.byUser] : namespace === "notifications" ? [payload.notificationId] : namespace === "tabGroups" ? [payload.group] : namespace === "windows" ? [payload.windowId] : [payload]))); subscriptions.set(listener, unsubscribe); return unsubscribe; }, removeListener(listener) { const unsubscribe = subscriptions.get(listener); if (unsubscribe) { unsubscribe(); subscriptions.delete(listener); } } }; } } return chrome; }
@@ -0,0 +1,122 @@
1
+ // Lifecycle of a browser the pipe transport spawns. Chrome removes its per-launch
2
+ // state (the macOS code-sign clone of the app bundle, a temp profile) only when
3
+ // it quits cleanly, so nothing here sends SIGKILL before a quit request and a
4
+ // bounded grace window (omo#12067). On POSIX the request is SIGTERM; on Windows
5
+ // it is the CDP Browser.close the caller sends first (see terminateChild).
6
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { setTimeout as sleep } from "node:timers/promises";
9
+ import { isPidAlive } from "./instance-lock.js";
10
+ import { ownProcessStartTime, processStartTime } from "./lock-file.js";
11
+
12
+ export const TERM_GRACE_MS = 5_000;
13
+ const PID_FILE_NAME = "omowright-browser.pid";
14
+ const REAP_POLL_MS = 50;
15
+
16
+ // Own process group on POSIX: a group-wide SIGKILL of the caller (an eval cell
17
+ // settling, `timeout -s KILL`) no longer takes the browser with it; the browser
18
+ // instead reads EOF on its CDP pipe and quits on its own. Windows has no process
19
+ // groups to escape, and `detached` there would open a console window.
20
+ export const browserSpawnDetached = process.platform !== "win32";
21
+
22
+ export function profileDirFromArgs(browserArgs) {
23
+ for (let index = 0; index < browserArgs.length; index += 1) {
24
+ const argument = browserArgs[index];
25
+ if (argument === "--user-data-dir" && browserArgs[index + 1]) return path.resolve(browserArgs[index + 1]);
26
+ if (argument.startsWith("--user-data-dir=")) return path.resolve(argument.slice("--user-data-dir=".length));
27
+ }
28
+ return null;
29
+ }
30
+
31
+ // On Windows child.kill() is TerminateProcess whatever signal it names, so no
32
+ // signal can ask the browser to quit. There the request is the CDP
33
+ // Browser.close the caller already sent (`quitRequested`), and the grace window
34
+ // runs only when one was sent.
35
+ const signalsCanAskToQuit = process.platform !== "win32";
36
+
37
+ export async function terminateChild(child, { quitRequested = false } = {}) {
38
+ if (child.exitCode !== null || child.signalCode !== null) return;
39
+ const exited = new Promise((resolve) => child.once("exit", resolve));
40
+ if (signalsCanAskToQuit) {
41
+ try { child.kill("SIGTERM"); } catch {}
42
+ }
43
+ if (signalsCanAskToQuit || quitRequested) {
44
+ let timer;
45
+ const graceOver = new Promise((resolve) => { timer = setTimeout(resolve, TERM_GRACE_MS); });
46
+ await Promise.race([exited, graceOver]);
47
+ clearTimeout(timer);
48
+ }
49
+ if (child.exitCode === null && child.signalCode === null) {
50
+ try { child.kill("SIGKILL"); } catch {}
51
+ await exited;
52
+ }
53
+ }
54
+
55
+ function pidFilePath(profileDir) {
56
+ return path.join(profileDir, PID_FILE_NAME);
57
+ }
58
+
59
+ // Records the browser and the caller that owns it. The profile dir is created
60
+ // first: the pidfile is written right after spawn, before Chrome has made its
61
+ // --user-data-dir (Chrome itself is happy with a dir that already exists).
62
+ export async function writeBrowserPidFile(profileDir, pid) {
63
+ if (!profileDir || !pid) return;
64
+ const [start, ownerStart] = await Promise.all([processStartTime(pid), ownProcessStartTime()]);
65
+ mkdirSync(profileDir, { recursive: true });
66
+ const record = { pid, start, profileDir, owner: { pid: process.pid, start: ownerStart } };
67
+ writeFileSync(pidFilePath(profileDir), `${JSON.stringify(record)}\n`, { mode: 0o600 });
68
+ }
69
+
70
+ export function removeBrowserPidFile(profileDir, pid) {
71
+ if (!profileDir) return;
72
+ try {
73
+ const recorded = JSON.parse(readFileSync(pidFilePath(profileDir), "utf8"));
74
+ if (recorded.pid !== pid) return;
75
+ } catch {
76
+ return;
77
+ }
78
+ rmSync(pidFilePath(profileDir), { force: true });
79
+ }
80
+
81
+ // Same process as when recorded: alive, and (when a start time was recorded and
82
+ // can be read now) the same start time, so a recycled pid does not count.
83
+ // Returns null when the answer cannot be determined.
84
+ async function sameProcessAlive(pid, start) {
85
+ if (!Number.isInteger(pid) || pid <= 0) return null;
86
+ if (!isPidAlive(pid)) return false;
87
+ if (start === null || start === undefined) return null;
88
+ const now = await processStartTime(pid);
89
+ if (now === null) return null;
90
+ return now === start;
91
+ }
92
+
93
+ // A pidfile left in the profile names a browser whose caller died without
94
+ // close(). Give it the same SIGTERM-then-grace treatment before reusing the
95
+ // profile. Every doubt fails toward keeping the browser: it is reaped only when
96
+ // it is provably the recorded process AND its recorded caller is provably gone,
97
+ // so a live client's browser on the same profile is never touched.
98
+ export async function reapOrphanedBrowser(profileDir) {
99
+ if (!profileDir) return;
100
+ let recorded;
101
+ try {
102
+ recorded = JSON.parse(readFileSync(pidFilePath(profileDir), "utf8"));
103
+ } catch {
104
+ return;
105
+ }
106
+ const { pid, start, owner } = recorded;
107
+ const browserAlive = Number.isInteger(pid) && pid > 0 ? await sameProcessAlive(pid, start) : false;
108
+ if (browserAlive === false) {
109
+ rmSync(pidFilePath(profileDir), { force: true });
110
+ return;
111
+ }
112
+ if (browserAlive === null || pid === process.pid) return;
113
+ const ownerAlive = await sameProcessAlive(owner?.pid, owner?.start);
114
+ if (ownerAlive !== false) return;
115
+ try { process.kill(pid, "SIGTERM"); } catch {}
116
+ const deadline = Date.now() + TERM_GRACE_MS;
117
+ while (isPidAlive(pid) && Date.now() < deadline) await sleep(REAP_POLL_MS);
118
+ if (isPidAlive(pid)) {
119
+ try { process.kill(pid, "SIGKILL"); } catch {}
120
+ }
121
+ rmSync(pidFilePath(profileDir), { force: true });
122
+ }
@@ -0,0 +1,90 @@
1
+ import { execFile } from "node:child_process";
2
+ import { statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { windowsSystemTool } from "../owner-only.js";
6
+ import { pathFor } from "./browsers.js";
7
+
8
+ const PROBE_TIMEOUT_MS = 3_000;
9
+
10
+ function runDefault(command, args) {
11
+ return new Promise((resolve) => {
12
+ execFile(command, args, { timeout: PROBE_TIMEOUT_MS, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
13
+ resolve(error ? null : String(stdout));
14
+ });
15
+ });
16
+ }
17
+
18
+ export function parseMacDefaultBrowser(plistJson) {
19
+ let handlers;
20
+ try { handlers = JSON.parse(plistJson)?.LSHandlers; } catch { return null; }
21
+ if (!Array.isArray(handlers)) return null;
22
+ const pick = (scheme) => handlers.find((h) => h?.LSHandlerURLScheme === scheme && typeof h.LSHandlerRoleAll === "string");
23
+ const handler = pick("https") ?? pick("http");
24
+ return handler ? handler.LSHandlerRoleAll.toLowerCase() : "com.apple.safari";
25
+ }
26
+
27
+ export function parseWindowsProgId(regOutput) {
28
+ const match = /ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput ?? "");
29
+ return match ? match[1].toLowerCase() : null;
30
+ }
31
+
32
+ export function parseProcessNames(platform, output) {
33
+ const names = new Set();
34
+ for (const raw of String(output ?? "").split(/\r?\n/)) {
35
+ const line = raw.trim();
36
+ if (!line) continue;
37
+ if (platform === "win32") {
38
+ const image = /^"([^"]+)"/.exec(line)?.[1];
39
+ if (image) names.add(image.toLowerCase());
40
+ } else if (platform === "darwin") {
41
+ if (/\.app\/Contents\/MacOS\/[^/]+$/.test(line)) names.add(line);
42
+ } else {
43
+ names.add(path.posix.basename(line));
44
+ }
45
+ }
46
+ return [...names];
47
+ }
48
+
49
+ async function probeDefault({ platform, home, run }) {
50
+ if (platform === "darwin") {
51
+ const plist = path.posix.join(home, "Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");
52
+ const json = await run("plutil", ["-convert", "json", "-o", "-", plist]);
53
+ return json === null ? null : parseMacDefaultBrowser(json);
54
+ }
55
+ if (platform === "linux") {
56
+ const out = await run("xdg-settings", ["get", "default-web-browser"]);
57
+ return out?.trim() ? out.trim().toLowerCase() : null;
58
+ }
59
+ if (platform === "win32") {
60
+ const key = "HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";
61
+ return parseWindowsProgId(await run(windowsSystemTool("reg.exe"), ["query", key, "/v", "ProgId"]));
62
+ }
63
+ return null;
64
+ }
65
+
66
+ async function probeRunning({ platform, run }) {
67
+ const out = platform === "win32"
68
+ ? await run(windowsSystemTool("tasklist.exe"), ["/fo", "csv", "/nh"])
69
+ : await run("ps", platform === "darwin" ? ["-axo", "comm="] : ["-eo", "comm="]);
70
+ return out === null ? null : parseProcessNames(platform, out);
71
+ }
72
+
73
+ function lastUsedAt(browser, stat, { join }) {
74
+ let latest = null;
75
+ for (const rel of [["Local State"], ["Default", "History"], ["Default", "Preferences"]]) {
76
+ try {
77
+ const mtime = stat(join(browser.userDataDir, ...rel)).mtimeMs;
78
+ if (latest === null || mtime > latest) latest = mtime;
79
+ } catch {}
80
+ }
81
+ return latest;
82
+ }
83
+
84
+ // Reads the machine-wide facts that say which browser the user actually uses. Every probe degrades to
85
+ // null (unknown) instead of throwing, so a locked-down machine yields "ask the user", never a guess.
86
+ export async function probeBrowserSignals({ platform = process.platform, home = homedir(), browsers = [], run = runDefault, stat = statSync } = {}) {
87
+ const [defaultBrowser, running] = await Promise.all([probeDefault({ platform, home, run }), probeRunning({ platform, run })]);
88
+ const lastUsed = Object.fromEntries(browsers.map((b) => [b.id, lastUsedAt(b, stat, pathFor(platform))]));
89
+ return { defaultBrowser, running, lastUsed };
90
+ }
@@ -0,0 +1,114 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const BROWSERSKILL_EXTENSION_IDS = Object.freeze({
6
+ chrome: "hhcmgoofomhgciiibhipgmgkgnoenaoi",
7
+ edge: "emacgiaaaiojkkpkddmmdfhmokgmnikg",
8
+ });
9
+
10
+ export const STORE_UPDATE_URLS = Object.freeze({
11
+ chrome: "https://clients2.google.com/service/update2/crx",
12
+ edge: "https://edge.microsoft.com/extensionwebstorebase/v1/crx",
13
+ });
14
+
15
+ export const STORE_PAGE_URLS = Object.freeze({
16
+ chrome: `https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,
17
+ edge: `https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`,
18
+ });
19
+
20
+ export const NON_CHROMIUM_DEFAULTS = Object.freeze([
21
+ { id: "safari", label: "Safari", match: ["com.apple.safari", "safarihtml"] },
22
+ { id: "firefox", label: "Firefox", match: ["org.mozilla.firefox", "firefox.desktop", "firefoxurl", "firefoxhtml"] },
23
+ { id: "zen", label: "Zen", match: ["app.zen-browser.zen", "zen.desktop", "zenhtml"] },
24
+ { id: "orion", label: "Orion", match: ["com.kagi.kagimacos"] },
25
+ ]);
26
+
27
+ // externalExtensions: false marks a browser whose external-extension path is unknown or not honoured;
28
+ // onboarding hands the user that browser's store link instead of writing a file nobody reads.
29
+ const MAC = [
30
+ { id: "chrome", label: "Google Chrome", store: "chrome", userData: "Library/Application Support/Google/Chrome", app: "Google Chrome", bundleId: "com.google.Chrome" },
31
+ { id: "edge", label: "Microsoft Edge", store: "edge", userData: "Library/Application Support/Microsoft Edge", app: "Microsoft Edge", bundleId: "com.microsoft.edgemac" },
32
+ { id: "brave", label: "Brave", store: "chrome", userData: "Library/Application Support/BraveSoftware/Brave-Browser", app: "Brave Browser", bundleId: "com.brave.Browser" },
33
+ { id: "chromium", label: "Chromium", store: "chrome", userData: "Library/Application Support/Chromium", app: "Chromium", bundleId: "org.chromium.Chromium" },
34
+ { id: "arc", label: "Arc", store: "chrome", userData: "Library/Application Support/Arc/User Data", app: "Arc", bundleId: "company.thebrowser.Browser" },
35
+ { id: "dia", label: "Dia", store: "chrome", userData: "Library/Application Support/Dia/User Data", app: "Dia", bundleId: "company.thebrowser.dia" },
36
+ { id: "vivaldi", label: "Vivaldi", store: "chrome", userData: "Library/Application Support/Vivaldi", app: "Vivaldi", bundleId: "com.vivaldi.Vivaldi" },
37
+ { id: "opera", label: "Opera", store: "chrome", userData: "Library/Application Support/com.operasoftware.Opera", app: "Opera", bundleId: "com.operasoftware.Opera", externalExtensions: false },
38
+ { id: "comet", label: "Comet", store: "chrome", userData: "Library/Application Support/Comet", app: "Comet", bundleId: "ai.perplexity.comet" },
39
+ { id: "aside", label: "Aside", store: "chrome", userData: "Library/Application Support/Aside", app: "Aside", bundleId: "at.studio.AsideBrowser" },
40
+ { id: "whale", label: "Naver Whale", store: "chrome", userData: "Library/Application Support/Naver/Whale", app: "Naver Whale", bundleId: "com.naver.Whale" },
41
+ ];
42
+
43
+ const LINUX = [
44
+ { id: "chrome", label: "Google Chrome", store: "chrome", userData: ".config/google-chrome", binaries: ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/opt/google/chrome/chrome"], externalDir: "/opt/google/chrome/extensions", userExternalDir: false, desktopIds: ["google-chrome.desktop", "google-chrome-stable.desktop", "com.google.Chrome.desktop"], processNames: ["chrome", "google-chrome"] },
45
+ { id: "chromium", label: "Chromium", store: "chrome", userData: ".config/chromium", binaries: ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/snap/bin/chromium"], externalDir: "/usr/share/chromium/extensions", userExternalDir: true, desktopIds: ["chromium.desktop", "chromium-browser.desktop", "chromium_chromium.desktop", "org.chromium.Chromium.desktop"], processNames: ["chromium", "chromium-browse"] },
46
+ { id: "edge", label: "Microsoft Edge", store: "edge", userData: ".config/microsoft-edge", binaries: ["/usr/bin/microsoft-edge", "/opt/microsoft/msedge/msedge"], externalDir: "/usr/share/microsoft-edge/extensions", userExternalDir: false, desktopIds: ["microsoft-edge.desktop", "microsoft-edge-stable.desktop", "com.microsoft.Edge.desktop"], processNames: ["msedge"] },
47
+ { id: "brave", label: "Brave", store: "chrome", userData: ".config/BraveSoftware/Brave-Browser", binaries: ["/usr/bin/brave-browser", "/opt/brave.com/brave/brave"], externalDir: "/usr/share/brave/extensions", userExternalDir: false, desktopIds: ["brave-browser.desktop", "com.brave.Browser.desktop"], processNames: ["brave"] },
48
+ { id: "vivaldi", label: "Vivaldi", store: "chrome", userData: ".config/vivaldi", binaries: ["/usr/bin/vivaldi", "/opt/vivaldi/vivaldi"], externalDir: null, userExternalDir: false, externalExtensions: false, desktopIds: ["vivaldi-stable.desktop", "vivaldi.desktop"], processNames: ["vivaldi-bin"] },
49
+ { id: "opera", label: "Opera", store: "chrome", userData: ".config/opera", binaries: ["/usr/bin/opera"], externalDir: null, userExternalDir: false, externalExtensions: false, desktopIds: ["opera.desktop"], processNames: ["opera"] },
50
+ ];
51
+
52
+ const WINDOWS = [
53
+ { id: "chrome", label: "Google Chrome", store: "chrome", userData: "Google/Chrome/User Data", registryKey: "HKCU\\Software\\Google\\Chrome\\Extensions", binaryRel: "Google/Chrome/Application/chrome.exe", progIds: ["chromehtml"], processNames: ["chrome.exe"] },
54
+ { id: "edge", label: "Microsoft Edge", store: "edge", userData: "Microsoft/Edge/User Data", registryKey: "HKCU\\Software\\Microsoft\\Edge\\Extensions", binaryRel: "Microsoft/Edge/Application/msedge.exe", progIds: ["msedgehtm"], processNames: ["msedge.exe"] },
55
+ { id: "brave", label: "Brave", store: "chrome", userData: "BraveSoftware/Brave-Browser/User Data", registryKey: "HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions", binaryRel: "BraveSoftware/Brave-Browser/Application/brave.exe", progIds: ["bravehtml"], processNames: ["brave.exe"] },
56
+ { id: "chromium", label: "Chromium", store: "chrome", userData: "Chromium/User Data", registryKey: "HKCU\\Software\\Chromium\\Extensions", binaryRel: "Chromium/Application/chrome.exe", progIds: ["chromiumhtm"], processNames: [] },
57
+ { id: "vivaldi", label: "Vivaldi", store: "chrome", userData: "Vivaldi/User Data", registryKey: null, externalExtensions: false, binaryRel: "Vivaldi/Application/vivaldi.exe", progIds: ["vivaldihtm"], processNames: ["vivaldi.exe"] },
58
+ { id: "whale", label: "Naver Whale", store: "chrome", userData: "Naver/Naver Whale/User Data", registryKey: null, externalExtensions: false, binaryRel: "Naver/Naver Whale/Application/whale.exe", progIds: ["whalehtml"], processNames: ["whale.exe"] },
59
+ ];
60
+
61
+ export const BROWSER_IDS = Object.freeze([...new Set([...MAC, ...LINUX, ...WINDOWS].map((b) => b.id))]);
62
+
63
+ // Paths are built for the TARGET platform, not the host: a darwin/linux row is the same on every host.
64
+ export const pathFor = (platform) => (platform === "win32" ? path.win32 : path.posix);
65
+
66
+ function macRow(b, home, exists) {
67
+ const { join } = path.posix;
68
+ const apps = [join("/Applications", `${b.app}.app`), join(home, "Applications", `${b.app}.app`)];
69
+ const appPath = apps.find((p) => exists(p)) ?? null;
70
+ const userDataDir = join(home, b.userData);
71
+ return {
72
+ id: b.id, label: b.label, store: b.store, userDataDir,
73
+ binary: join(appPath ?? apps[0], "Contents", "MacOS", b.app), bundleId: b.bundleId,
74
+ processNames: apps.map((a) => join(a, "Contents", "MacOS", b.app)), defaultIds: [b.bundleId.toLowerCase()], externalExtensions: b.externalExtensions !== false,
75
+ installed: appPath !== null || exists(userDataDir), hasProfile: exists(userDataDir),
76
+ };
77
+ }
78
+
79
+ function linuxRow(b, home, exists) {
80
+ const userDataDir = path.posix.join(home, b.userData);
81
+ const binary = b.binaries.find((p) => exists(p)) ?? null;
82
+ return {
83
+ id: b.id, label: b.label, store: b.store, userDataDir, binary,
84
+ externalDir: b.externalDir, userExternalDir: b.userExternalDir,
85
+ processNames: b.processNames, defaultIds: b.desktopIds.map((d) => d.toLowerCase()), externalExtensions: b.externalExtensions !== false,
86
+ installed: binary !== null || exists(userDataDir), hasProfile: exists(userDataDir),
87
+ };
88
+ }
89
+
90
+ function windowsRow(b, env, home, exists) {
91
+ const { join } = path.win32;
92
+ const localAppData = env.LOCALAPPDATA ?? join(home, "AppData", "Local");
93
+ const programFiles = [localAppData, env.PROGRAMFILES, env["PROGRAMFILES(X86)"], "C:\\Program Files", "C:\\Program Files (x86)"].filter(Boolean);
94
+ const userDataDir = join(localAppData, b.userData);
95
+ const binary = programFiles.map((root) => join(root, b.binaryRel)).find((p) => exists(p)) ?? null;
96
+ return {
97
+ id: b.id, label: b.label, store: b.store, userDataDir, registryKey: b.registryKey, binary,
98
+ processNames: b.processNames, defaultIds: b.progIds, externalExtensions: b.externalExtensions !== false,
99
+ installed: binary !== null || exists(userDataDir), hasProfile: exists(userDataDir),
100
+ };
101
+ }
102
+
103
+ // Every catalog browser for the platform with installed/hasProfile flags; `detectBrowsers` keeps the
104
+ // installed ones. Being installed says nothing about use — `identifyBrowser` ranks by usage signals.
105
+ export function catalogBrowsers({ platform = process.platform, home = homedir(), env = process.env, exists = existsSync } = {}) {
106
+ if (platform === "darwin") return MAC.map((b) => macRow(b, home, exists));
107
+ if (platform === "linux") return LINUX.map((b) => linuxRow(b, home, exists));
108
+ if (platform === "win32") return WINDOWS.map((b) => windowsRow(b, env, home, exists));
109
+ return [];
110
+ }
111
+
112
+ export function detectBrowsers(options = {}) {
113
+ return catalogBrowsers(options).filter((b) => b.installed);
114
+ }
@@ -0,0 +1,45 @@
1
+ import { BskIpcClient, BskRpcError } from "./ipc-client.js";
2
+ import { BskSession } from "./session.js";
3
+ import { compact } from "./targets.js";
4
+
5
+ const DEFAULT_WAIT_FOR_BROWSER_MS = 15_000;
6
+
7
+ export async function listBrowsers(client, { waitForBrowserMs } = {}) {
8
+ const status = await client.call("system.status", compact({ wait_for_browser_ms: waitForBrowserMs }), { idPrefix: "status" });
9
+ return status.browsers ?? [];
10
+ }
11
+
12
+ // session.start matches only an instance id or a unique label; a browser name such as "chrome"
13
+ // (what bskDoctor reports) maps to the one connected browser with that name.
14
+ function resolveBrowser(browser, browsers) {
15
+ if (browser === undefined || browser === null) return browser;
16
+ if (browsers.some((b) => b.instance_id === browser || (b.label && b.label === browser))) return browser;
17
+ const named = browsers.filter((b) => b.browser_name === browser);
18
+ if (named.length > 1) {
19
+ throw new BskRpcError("invalid_params", `browser "${browser}" matches ${named.length} connected browsers (${named.map((b) => b.instance_id).join(", ")}); pass the instance id instead`);
20
+ }
21
+ return named.length === 1 ? named[0].instance_id : browser;
22
+ }
23
+
24
+ export async function connectBrowserSkill({
25
+ client, home, env, sockPath, autoStart, timeoutMs, bskBin,
26
+ name, browser, width, height, focused = false,
27
+ waitForBrowserMs = DEFAULT_WAIT_FOR_BROWSER_MS,
28
+ } = {}) {
29
+ const ipc = client ?? new BskIpcClient({ home, env, sockPath, autoStart, timeoutMs, bskBin });
30
+ const browsers = await listBrowsers(ipc, { waitForBrowserMs });
31
+ if (browsers.length === 0) {
32
+ throw new BskRpcError("no_browser_connected", "the BrowserSkill daemon is up but no browser extension is connected; open the browser that has the BrowserSkill extension enabled (bskDoctor() explains the remaining step) instead of falling back to a headless browser");
33
+ }
34
+ const started = await ipc.call("session.start", compact({
35
+ task_name: name,
36
+ browser_instance_id: resolveBrowser(browser, browsers),
37
+ width, height, focused,
38
+ }), { idPrefix: "session-start" });
39
+ return new BskSession(ipc, {
40
+ sessionId: started.session_id,
41
+ browserInstanceId: started.browser_instance_id ?? null,
42
+ agentWindowId: started.agent_window_id ?? null,
43
+ interaction: started.interaction ?? null,
44
+ });
45
+ }
@@ -0,0 +1,100 @@
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
+ }