omowright 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/README.md +24 -22
  2. package/TOOLS.md +6 -6
  3. package/dist/agent-tabs.d.ts +56 -0
  4. package/dist/aria-hidden.d.ts +1 -0
  5. package/dist/aside/cli-binary.d.ts +7 -0
  6. package/dist/aside/cli-contract.d.ts +9 -0
  7. package/dist/aside/errors.d.ts +8 -0
  8. package/dist/aside/line-transport.d.ts +11 -0
  9. package/dist/aside/mcp-transport.d.ts +11 -0
  10. package/dist/aside/onboard.d.ts +76 -0
  11. package/dist/aside/session-types.d.ts +68 -0
  12. package/dist/aside/session.d.ts +20 -0
  13. package/{bin/omowright-cloak.mjs → dist/bin/omowright-cloak.js} +28 -31
  14. package/dist/bridge-schemas.d.ts +326 -0
  15. package/dist/bridge-transport.d.ts +144 -0
  16. package/dist/browser-context.d.ts +4024 -0
  17. package/dist/browser-process.d.ts +10 -0
  18. package/dist/bsk/browser-signals.d.ts +23 -0
  19. package/dist/bsk/browsers.d.ts +46 -0
  20. package/dist/bsk/connect.d.ts +23 -0
  21. package/dist/bsk/daemon-info.d.ts +16 -0
  22. package/dist/bsk/external-extension.d.ts +74 -0
  23. package/dist/bsk/identify-browser.d.ts +48 -0
  24. package/dist/bsk/install-cli.d.ts +37 -0
  25. package/dist/bsk/ipc-client.d.ts +45 -0
  26. package/dist/bsk/onboard.d.ts +96 -0
  27. package/dist/bsk/reply-fields.d.ts +3 -0
  28. package/dist/bsk/screenshot.d.ts +24 -0
  29. package/dist/bsk/session.d.ts +142 -0
  30. package/dist/bsk/snapshot.d.ts +16 -0
  31. package/dist/bsk/targets.d.ts +20 -0
  32. package/dist/captcha-wait.d.ts +17 -0
  33. package/dist/captcha.d.ts +46 -0
  34. package/dist/cdp-errors.d.ts +38 -0
  35. package/dist/cdp-methods.d.ts +10 -0
  36. package/dist/cdp-protocol.d.ts +459 -0
  37. package/dist/chrome-profile.d.ts +77 -0
  38. package/dist/chrome.d.ts +130 -0
  39. package/dist/cloak-profile.d.ts +43 -0
  40. package/dist/connection.d.ts +4024 -0
  41. package/dist/console-events.d.ts +22 -0
  42. package/dist/cookies.d.ts +42 -0
  43. package/dist/core.d.ts +10810 -0
  44. package/dist/cua.d.ts +56 -0
  45. package/dist/dialog-policy.d.ts +43 -0
  46. package/dist/ego/bindings.d.ts +68 -0
  47. package/dist/ego/cdp-client.d.ts +28 -0
  48. package/dist/ego/client.d.ts +8 -0
  49. package/dist/ego/errors.d.ts +7 -0
  50. package/dist/emulate.d.ts +62 -0
  51. package/dist/engines.d.ts +59 -0
  52. package/dist/events.d.ts +93 -0
  53. package/dist/frames-snapshot.d.ts +58 -0
  54. package/dist/har.d.ts +88 -0
  55. package/dist/human-handoff.d.ts +30 -0
  56. package/{src/index.js → dist/index.d.ts} +11 -55
  57. package/dist/index.js +39262 -0
  58. package/dist/injected.d.ts +1 -0
  59. package/dist/instance-lock.d.ts +5 -0
  60. package/dist/instances.d.ts +45 -0
  61. package/dist/internal-capability.d.ts +1 -0
  62. package/dist/launch-endpoint.d.ts +34 -0
  63. package/dist/layers.d.ts +31 -0
  64. package/dist/llm.d.ts +1349 -0
  65. package/dist/lock-backend-win32-xbcm60vz.js +57 -0
  66. package/dist/lock-backend-win32.d.ts +3 -0
  67. package/dist/lock-backend.d.ts +6 -0
  68. package/dist/native-host-win32.d.ts +38 -0
  69. package/dist/network-events.d.ts +66 -0
  70. package/dist/network-snoop.d.ts +56 -0
  71. package/dist/nul-frames.d.ts +4 -0
  72. package/dist/open-shadow-query.d.ts +1 -0
  73. package/dist/owner-only.d.ts +15 -0
  74. package/dist/page-bundle.js +1587 -0
  75. package/dist/page-events.d.ts +25 -0
  76. package/dist/page-routes.d.ts +30 -0
  77. package/dist/page-setup.d.ts +55 -0
  78. package/dist/pipe.d.ts +71 -0
  79. package/dist/process-start-time.d.ts +2 -0
  80. package/dist/read-property.d.ts +2 -0
  81. package/dist/routes.d.ts +60 -0
  82. package/dist/running-browser.d.ts +39 -0
  83. package/dist/scroll-collect.d.ts +36 -0
  84. package/dist/serial-emitter.d.ts +5 -0
  85. package/dist/shared-connections.d.ts +11 -0
  86. package/dist/snapshot-diff.d.ts +57 -0
  87. package/dist/text-matching.d.ts +21 -0
  88. package/dist/trace.d.ts +59 -0
  89. package/dist/url-match.d.ts +7 -0
  90. package/dist/viewport.d.ts +26 -0
  91. package/dist/ws.d.ts +62 -0
  92. package/package.json +47 -26
  93. package/presets/agent-events/SKILL.md +1 -1
  94. package/presets/captcha/SKILL.md +1 -3
  95. package/presets/chrome/SKILL.md +2 -2
  96. package/presets/cloak-bridge/SKILL.md +11 -11
  97. package/presets/network/SKILL.md +15 -13
  98. package/presets/visual-browse/SKILL.md +14 -10
  99. package/skills/omowright/SKILL.md +77 -47
  100. package/skills/omowright/references/aside.md +50 -0
  101. package/skills/omowright/references/browserskill.md +29 -32
  102. package/skills/omowright/references/ego.md +24 -0
  103. package/skills/omowright/references/eval-kernel.md +44 -23
  104. package/skills/omowright/references/frames-layers-human.md +16 -7
  105. package/skills/omowright/references/quickstart.md +3 -3
  106. package/skills/omowright/references/stealth.md +7 -7
  107. package/src/agent-tabs.js +0 -179
  108. package/src/aria-hidden.js +0 -47
  109. package/src/bridge-schemas.js +0 -44
  110. package/src/bridge-transport.js +0 -83
  111. package/src/browser-context.js +0 -105
  112. package/src/browser-process.js +0 -127
  113. package/src/bsk/browser-signals.js +0 -90
  114. package/src/bsk/browsers.js +0 -114
  115. package/src/bsk/connect.js +0 -75
  116. package/src/bsk/daemon-info.js +0 -100
  117. package/src/bsk/external-extension.js +0 -110
  118. package/src/bsk/identify-browser.js +0 -88
  119. package/src/bsk/install-cli.js +0 -81
  120. package/src/bsk/ipc-client.js +0 -236
  121. package/src/bsk/onboard.js +0 -140
  122. package/src/bsk/screenshot.js +0 -49
  123. package/src/bsk/session.js +0 -131
  124. package/src/bsk/snapshot.js +0 -56
  125. package/src/bsk/targets.js +0 -25
  126. package/src/captcha-wait.js +0 -79
  127. package/src/captcha.js +0 -142
  128. package/src/cdp-errors.js +0 -23
  129. package/src/cdp-methods.js +0 -69
  130. package/src/chrome-profile.js +0 -176
  131. package/src/chrome.js +0 -194
  132. package/src/cloak-profile.js +0 -266
  133. package/src/connection.js +0 -234
  134. package/src/console-events.js +0 -12
  135. package/src/cookies.js +0 -39
  136. package/src/core.js +0 -1702
  137. package/src/cua.js +0 -74
  138. package/src/dialog-policy.js +0 -80
  139. package/src/emulate.js +0 -127
  140. package/src/events.js +0 -111
  141. package/src/frames-snapshot.js +0 -138
  142. package/src/har.js +0 -103
  143. package/src/human-handoff.js +0 -124
  144. package/src/injected.js +0 -3
  145. package/src/instance-lock.js +0 -74
  146. package/src/instances.js +0 -490
  147. package/src/internal-capability.js +0 -1
  148. package/src/launch-endpoint.js +0 -185
  149. package/src/layers.js +0 -138
  150. package/src/llm.js +0 -201
  151. package/src/lock-backend-win32.js +0 -54
  152. package/src/lock-backend.js +0 -81
  153. package/src/native-host-win32.js +0 -201
  154. package/src/network-events.js +0 -223
  155. package/src/network-snoop.js +0 -229
  156. package/src/nul-frames.js +0 -28
  157. package/src/open-shadow-query.js +0 -101
  158. package/src/owner-only.js +0 -196
  159. package/src/page-bundle.js +0 -1478
  160. package/src/page-events.js +0 -45
  161. package/src/page-routes.js +0 -94
  162. package/src/page-setup.js +0 -239
  163. package/src/pipe.js +0 -418
  164. package/src/process-start-time.js +0 -64
  165. package/src/routes.js +0 -256
  166. package/src/running-browser.js +0 -85
  167. package/src/scroll-collect.js +0 -73
  168. package/src/serial-emitter.js +0 -17
  169. package/src/shared-connections.js +0 -285
  170. package/src/snapshot-diff.js +0 -75
  171. package/src/text-matching.js +0 -101
  172. package/src/trace.js +0 -183
  173. package/src/url-match.js +0 -148
  174. package/src/viewport.js +0 -12
@@ -1,83 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import path from "node:path";
3
- import { mkdir, open, readFile, readlink, realpath, 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) {
50
- const absolute = path.resolve(dir); const parts = absolute.split(path.sep).filter(Boolean);
51
- let current = path.parse(absolute).root; let final;
52
- while (parts.length) {
53
- current = path.join(current, parts.shift());
54
- let info = await lstat(current).catch(() => null);
55
- if (!info) { await mkdir(current, { mode: 0o700 }); info = await lstat(current); }
56
- if (info.isSymbolicLink()) {
57
- if (process.platform !== "darwin" || !["/tmp", "/var", "/etc"].includes(current) || info.uid !== 0) throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: symlink is not a root-owned macOS system alias`);
58
- let target, resolved;
59
- try { target = await readlink(current); resolved = await realpath(current); }
60
- catch (error) { throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias could not be resolved (${error.code ?? error.message})`); }
61
- if (!resolved.startsWith("/private/")) throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: system alias target is outside /private`);
62
- // Walk the target from its root too: resolving the entire path would hide unsafe components.
63
- parts.unshift(...target.split(path.sep).filter(Boolean));
64
- current = path.isAbsolute(target) ? path.parse(target).root : path.dirname(current);
65
- continue;
66
- }
67
- if (!info.isDirectory()) throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: not a directory`);
68
- if (info.uid !== process.getuid?.() && info.uid !== 0) throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);
69
- const stickyRootAncestor = parts.length > 0 && info.uid === 0 && (info.mode & 0o1000) !== 0;
70
- if (!stickyRootAncestor && (info.mode & 0o022) !== 0) throw new BridgeProtocolError(`nativeMessagingHostDir security rejected at ${current}: writable by others`);
71
- final = info;
72
- }
73
- if (!final || (final.uid !== process.getuid?.() && final.uid !== 0)) throw new BridgeProtocolError(`nativeMessagingHostDir ownership rejected at ${current}: not owned by the current user or root`);
74
- if ((final.mode & 0o077) !== 0) await chmod(absolute, 0o700);
75
- }
76
- 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"); }
77
- 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);
78
- const manifest = { name: hostName, description: "OmOWright internal CloakBrowser native messaging bridge.", path: hostPath, type: "stdio", allowed_origins: [`chrome-extension://${extensionId}/`] };
79
- 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")); };
80
- 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); } }
81
- await secureDirectory(dir); const file = path.join(dir, `${hostName}.json`); const parsed = await writeManifest(file); await chmod(file, 0o600); return { path: file, manifest: parsed }; }
82
- export function createBridgeClient(options = {}) { return createNativeMessagingHost(options); }
83
- 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; }
@@ -1,105 +0,0 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { cookieToCdp } from "./cookies.js";
4
- import { createAgentTabs, getAgentTabs } from "./agent-tabs.js";
5
-
6
- export class BrowserContext {
7
- #connection;
8
- #scope;
9
- #origins = new Set();
10
-
11
- constructor(connection, browserContextId) {
12
- this.#connection = connection;
13
- this.#scope = browserContextId ? { browserContextId } : {};
14
- }
15
-
16
- trackOrigin(url) {
17
- if (!/^https?:\/\//.test(url ?? "")) return;
18
- this.#origins.add(new URL(url).origin);
19
- }
20
-
21
- async cookies(urls = []) {
22
- const { cookies } = await this.#connection.cdp.send("Storage.getCookies", this.#scope);
23
- const parsed = (typeof urls === "string" ? [urls] : urls).map(url => new URL(url));
24
- return cookies.filter(cookie => !parsed.length || parsed.some(url => {
25
- const domain = cookie.domain.startsWith(".") ? cookie.domain.slice(1) : cookie.domain;
26
- if (url.hostname !== domain && !(cookie.domain.startsWith(".") && url.hostname.endsWith(`.${domain}`))) return false;
27
- if (cookie.secure && url.protocol !== "https:" && url.hostname !== "localhost") return false;
28
- const pathname = cookie.path.endsWith("/") ? cookie.path : `${cookie.path}/`;
29
- return url.pathname === cookie.path || `${url.pathname}/`.startsWith(pathname);
30
- })).map(cookie => {
31
- const { name, value, domain, path, expires, httpOnly, secure } = cookie;
32
- const out = { name, value, domain, path, expires, httpOnly, secure, sameSite: cookie.sameSite ?? "Lax" };
33
- if (cookie.partitionKey) out.partitionKey = cookie.partitionKey.topLevelSite;
34
- return out;
35
- });
36
- }
37
-
38
- async addCookies(cookies) {
39
- const normalized = cookies.map(cookie => {
40
- if (typeof cookie.name !== "string" || typeof cookie.value !== "string") {
41
- throw new TypeError("Cookie name and value must be strings");
42
- }
43
- if (cookie.url !== undefined) {
44
- if (cookie.domain !== undefined || cookie.path !== undefined) throw new Error("Cookie must have either url or domain and path");
45
- const url = new URL(cookie.url);
46
- if (!/^https?:$/.test(url.protocol)) throw new Error("Cookie url must be HTTP or HTTPS");
47
- return cookieToCdp({
48
- ...cookie, domain: url.hostname,
49
- path: url.pathname.slice(0, url.pathname.lastIndexOf("/") + 1),
50
- secure: cookie.secure ?? url.protocol === "https:",
51
- });
52
- }
53
- if (!cookie.domain || !cookie.path) throw new Error("Cookie must have either url or domain and path");
54
- return cookieToCdp(cookie);
55
- });
56
- await this.#connection.cdp.send("Storage.setCookies", { ...this.#scope, cookies: normalized });
57
- }
58
-
59
- async clearCookies(options = {}) {
60
- const filters = Object.entries(options).filter(([key]) => ["name", "domain", "path"].includes(key));
61
- if (!filters.length) {
62
- await this.#connection.cdp.send("Storage.clearCookies", this.#scope);
63
- return;
64
- }
65
- // Storage.clearCookies is context scoped. Reinstall survivors rather than
66
- // issuing a browser-global Network.deleteCookies for another context.
67
- const survivors = (await this.cookies()).filter(cookie => !filters.every(([key, filter]) =>
68
- filter instanceof RegExp
69
- ? new RegExp(filter.source, filter.flags.replace(/[gy]/g, "")).test(cookie[key])
70
- : cookie[key] === filter));
71
- await this.#connection.cdp.send("Storage.clearCookies", this.#scope);
72
- await this.addCookies(survivors);
73
- }
74
-
75
- async newPage() {
76
- return (await (getAgentTabs(this.#connection) ?? createAgentTabs(this.#connection))
77
- .create("about:blank", this.#scope)).page;
78
- }
79
-
80
- async storageState(options = {}) {
81
- const state = { cookies: await this.cookies(), origins: [] };
82
- if (this.#origins.size) {
83
- // Read through a blank intercepted page: an origin may no longer have an
84
- // open frame, and visiting its real document could mutate saved storage.
85
- const page = await this.newPage();
86
- try {
87
- await page.route("**/*", route => route.fulfill({ contentType: "text/html", body: "<html></html>" }));
88
- for (const origin of this.#origins) {
89
- await page.goto(origin, { waitUntil: "domcontentloaded" });
90
- const { entries } = await page._sendToTarget("DOMStorage.getDOMStorageItems", {
91
- storageId: { securityOrigin: origin, isLocalStorage: true },
92
- });
93
- if (entries.length) state.origins.push({ origin, localStorage: entries.map(([name, value]) => ({ name, value })) });
94
- }
95
- } finally {
96
- await page.close();
97
- }
98
- }
99
- if (options.path !== undefined) {
100
- await mkdir(path.dirname(path.resolve(options.path)), { recursive: true });
101
- await writeFile(options.path, JSON.stringify(state, null, 2));
102
- }
103
- return state;
104
- }
105
- }
@@ -1,127 +0,0 @@
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 "./process-start-time.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
- // No pid means the spawn itself failed (e.g. ENOENT): there is no process to
39
- // end. Neither runtime emits "exit" for such a child; node at least sets a
40
- // negative exitCode, but bun leaves it null, so the wait below would hang
41
- // forever (#154).
42
- if (child.pid === undefined) return;
43
- if (child.exitCode !== null || child.signalCode !== null) return;
44
- const exited = new Promise((resolve) => child.once("exit", resolve));
45
- if (signalsCanAskToQuit) {
46
- try { child.kill("SIGTERM"); } catch {}
47
- }
48
- if (signalsCanAskToQuit || quitRequested) {
49
- let timer;
50
- const graceOver = new Promise((resolve) => { timer = setTimeout(resolve, TERM_GRACE_MS); });
51
- await Promise.race([exited, graceOver]);
52
- clearTimeout(timer);
53
- }
54
- if (child.exitCode === null && child.signalCode === null) {
55
- try { child.kill("SIGKILL"); } catch {}
56
- await exited;
57
- }
58
- }
59
-
60
- function pidFilePath(profileDir) {
61
- return path.join(profileDir, PID_FILE_NAME);
62
- }
63
-
64
- // Records the browser and the caller that owns it. The profile dir is created
65
- // first: the pidfile is written right after spawn, before Chrome has made its
66
- // --user-data-dir (Chrome itself is happy with a dir that already exists).
67
- export async function writeBrowserPidFile(profileDir, pid) {
68
- if (!profileDir || !pid) return;
69
- const [start, ownerStart] = await Promise.all([processStartTime(pid), ownProcessStartTime()]);
70
- mkdirSync(profileDir, { recursive: true });
71
- const record = { pid, start, profileDir, owner: { pid: process.pid, start: ownerStart } };
72
- writeFileSync(pidFilePath(profileDir), `${JSON.stringify(record)}\n`, { mode: 0o600 });
73
- }
74
-
75
- export function removeBrowserPidFile(profileDir, pid) {
76
- if (!profileDir) return;
77
- try {
78
- const recorded = JSON.parse(readFileSync(pidFilePath(profileDir), "utf8"));
79
- if (recorded.pid !== pid) return;
80
- } catch {
81
- return;
82
- }
83
- rmSync(pidFilePath(profileDir), { force: true });
84
- }
85
-
86
- // Same process as when recorded: alive, and (when a start time was recorded and
87
- // can be read now) the same start time, so a recycled pid does not count.
88
- // Returns null when the answer cannot be determined.
89
- async function sameProcessAlive(pid, start) {
90
- if (!Number.isInteger(pid) || pid <= 0) return null;
91
- if (!isPidAlive(pid)) return false;
92
- if (start === null || start === undefined) return null;
93
- const now = await processStartTime(pid);
94
- if (now === null) return null;
95
- return now === start;
96
- }
97
-
98
- // A pidfile left in the profile names a browser whose caller died without
99
- // close(). Give it the same SIGTERM-then-grace treatment before reusing the
100
- // profile. Every doubt fails toward keeping the browser: it is reaped only when
101
- // it is provably the recorded process AND its recorded caller is provably gone,
102
- // so a live client's browser on the same profile is never touched.
103
- export async function reapOrphanedBrowser(profileDir) {
104
- if (!profileDir) return;
105
- let recorded;
106
- try {
107
- recorded = JSON.parse(readFileSync(pidFilePath(profileDir), "utf8"));
108
- } catch {
109
- return;
110
- }
111
- const { pid, start, owner } = recorded;
112
- const browserAlive = Number.isInteger(pid) && pid > 0 ? await sameProcessAlive(pid, start) : false;
113
- if (browserAlive === false) {
114
- rmSync(pidFilePath(profileDir), { force: true });
115
- return;
116
- }
117
- if (browserAlive === null || pid === process.pid) return;
118
- const ownerAlive = await sameProcessAlive(owner?.pid, owner?.start);
119
- if (ownerAlive !== false) return;
120
- try { process.kill(pid, "SIGTERM"); } catch {}
121
- const deadline = Date.now() + TERM_GRACE_MS;
122
- while (isPidAlive(pid) && Date.now() < deadline) await sleep(REAP_POLL_MS);
123
- if (isPidAlive(pid)) {
124
- try { process.kill(pid, "SIGKILL"); } catch {}
125
- }
126
- rmSync(pidFilePath(profileDir), { force: true });
127
- }
@@ -1,90 +0,0 @@
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
- }
@@ -1,114 +0,0 @@
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
- }
@@ -1,75 +0,0 @@
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
- // BrowserSkill extension 0.4.0 put every task tab into a native "BrowserSkill" tab group. Chrome saves and syncs
8
- // native groups, so each task leaves a group in the user's own browser (and in every browser signed into the same
9
- // account) after it ends. Upstream removed the grouping in 0.4.1 and does not delete groups already saved.
10
- const TAB_GROUPING_EXTENSION_VERSIONS = new Set(["0.4.0"]);
11
-
12
- export function isTabGroupingExtension(browser) {
13
- return TAB_GROUPING_EXTENSION_VERSIONS.has(browser?.extension_version);
14
- }
15
-
16
- export const TAB_GROUPING_EXTENSION_STEP = "Update the BrowserSkill extension to 0.4.1 or later (chrome://extensions -> Developer mode -> Update, or wait for the store update). Version 0.4.0 puts each task's tabs into a \"BrowserSkill\" tab group that the browser saves and syncs, so the group stays after the task ends; delete any saved \"BrowserSkill\" tab groups by hand.";
17
-
18
- function outdatedError(browser) {
19
- return new BskRpcError("extension_outdated", `the BrowserSkill extension in ${browser.browser_name ?? "the browser"} [${browser.instance_id}] is 0.4.0, which leaves a "BrowserSkill" tab group behind in the user's browser after each task. ${TAB_GROUPING_EXTENSION_STEP}`);
20
- }
21
-
22
- // A named browser on 0.4.0 is refused; with no browser named, an up-to-date one is chosen over a 0.4.0 one.
23
- function chooseBrowser(browser, browsers) {
24
- const resolved = resolveBrowser(browser, browsers);
25
- if (resolved !== undefined && resolved !== null) {
26
- const entry = browsers.find((b) => b.instance_id === resolved || (b.label && b.label === resolved));
27
- if (entry && isTabGroupingExtension(entry)) throw outdatedError(entry);
28
- return resolved;
29
- }
30
- const outdated = browsers.filter(isTabGroupingExtension);
31
- if (outdated.length === 0) return resolved;
32
- const usable = browsers.find((b) => !isTabGroupingExtension(b));
33
- if (!usable) throw outdatedError(outdated[0]);
34
- return usable.instance_id;
35
- }
36
-
37
- export async function listBrowsers(client, { waitForBrowserMs } = {}) {
38
- const status = await client.call("system.status", compact({ wait_for_browser_ms: waitForBrowserMs }), { idPrefix: "status" });
39
- return status.browsers ?? [];
40
- }
41
-
42
- // session.start matches only an instance id or a unique label; a browser name such as "chrome"
43
- // (what bskDoctor reports) maps to the one connected browser with that name.
44
- function resolveBrowser(browser, browsers) {
45
- if (browser === undefined || browser === null) return browser;
46
- if (browsers.some((b) => b.instance_id === browser || (b.label && b.label === browser))) return browser;
47
- const named = browsers.filter((b) => b.browser_name === browser);
48
- if (named.length > 1) {
49
- throw new BskRpcError("invalid_params", `browser "${browser}" matches ${named.length} connected browsers (${named.map((b) => b.instance_id).join(", ")}); pass the instance id instead`);
50
- }
51
- return named.length === 1 ? named[0].instance_id : browser;
52
- }
53
-
54
- export async function connectBrowserSkill({
55
- client, home, env, sockPath, autoStart, timeoutMs, bskBin,
56
- name, browser, width, height, focused = false,
57
- waitForBrowserMs = DEFAULT_WAIT_FOR_BROWSER_MS,
58
- } = {}) {
59
- const ipc = client ?? new BskIpcClient({ home, env, sockPath, autoStart, timeoutMs, bskBin });
60
- const browsers = await listBrowsers(ipc, { waitForBrowserMs });
61
- if (browsers.length === 0) {
62
- 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");
63
- }
64
- const started = await ipc.call("session.start", compact({
65
- task_name: name,
66
- browser_instance_id: chooseBrowser(browser, browsers),
67
- width, height, focused,
68
- }), { idPrefix: "session-start" });
69
- return new BskSession(ipc, {
70
- sessionId: started.session_id,
71
- browserInstanceId: started.browser_instance_id ?? null,
72
- agentWindowId: started.agent_window_id ?? null,
73
- interaction: started.interaction ?? null,
74
- });
75
- }