omowright 0.2.0 → 0.3.1

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 +43 -29
  2. package/TOOLS.md +9 -8
  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} +12 -55
  57. package/dist/index.js +39478 -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 +1597 -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 +83 -49
  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 +7 -4
  106. package/skills/omowright/references/stealth.md +11 -8
  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,236 +0,0 @@
1
- // CLI-shaped client for the BrowserSkill daemon IPC: one Unix-socket
2
- // connection per call, one JSON Lines request frame out, one response frame
3
- // back (`crates/bsk-cli/src/ipc_client.rs`, `crates/bsk-protocol/src/frame.rs`).
4
- // `cancel` opens a second connection exactly as the CLI's SIGINT path does.
5
- import { connect } from "node:net";
6
- import { existsSync, readdirSync } from "node:fs";
7
- import path from "node:path";
8
- import { randomBytes } from "node:crypto";
9
- import { readDaemonInfo, resolveBskHome, startDaemonWithCli } from "./daemon-info.js";
10
-
11
- export { readDaemonInfo, resolveBskHome } from "./daemon-info.js";
12
-
13
- const DEFAULT_TIMEOUT_MS = 35_000; // daemon tool budget 30s + grace, as cli/mod.rs
14
- const DISCOVERY_RETRY_MS = 250;
15
- const DISCOVERY_BUDGET_MS = 15_000;
16
- // A tool call that names its own budget (timeout_ms, or confirmation_timeout_ms for a tab borrow)
17
- // gets that budget plus this grace on the IPC wait.
18
- const TOOL_TIMEOUT_GRACE_MS = 5_000;
19
- // Tools that wait for a person: the daemon owns their deadline, so with no budget from the caller the
20
- // client only keeps a long backstop, and it never cancels them (that would tear down the user's overlay).
21
- const HUMAN_WAIT_METHODS = new Set(["tool.request_help", "tool.tab_borrow"]);
22
- const HUMAN_WAIT_BACKSTOP_MS = 3_600_000;
23
-
24
- function ownBudgetMs(params) {
25
- const budgets = [params?.timeout_ms, params?.confirmation_timeout_ms].filter((value) => typeof value === "number");
26
- return budgets.length > 0 ? Math.max(...budgets) + TOOL_TIMEOUT_GRACE_MS : undefined;
27
- }
28
- const PROBE_TIMEOUT_MS = 2_000;
29
-
30
- // Where the daemon listens when it was started with the default layout
31
- // (`crates/bsk-cli/src/daemon/paths.rs`): `$BSK_HOME/run/daemon.sock`, or on Windows the named pipe
32
- // `render_pipe_name` derives from USERNAME and the home.
33
- export function defaultSocketPath(home, env = process.env) {
34
- if (process.platform !== "win32") return path.join(home, "run", "daemon.sock");
35
- return `\\\\.\\pipe\\bsk-daemon-${rustStrHash(env.USERNAME ?? "default", home)}`;
36
- }
37
-
38
- // Rust's DefaultHasher (SipHash-1-3, zero keys) over each value's UTF-8 bytes plus the 0xff
39
- // terminator `str::hash` writes, which is how bsk hashes the pipe name.
40
- function rustStrHash(...values) {
41
- const bytes = Buffer.concat(values.flatMap((value) => [Buffer.from(value, "utf8"), Buffer.from([0xff])]));
42
- const mask = (1n << 64n) - 1n;
43
- const rotl = (x, b) => ((x << b) | (x >> (64n - b))) & mask;
44
- let [v0, v1, v2, v3] = [0x736f6d6570736575n, 0x646f72616e646f6dn, 0x6c7967656e657261n, 0x7465646279746573n];
45
- const round = () => {
46
- v0 = (v0 + v1) & mask; v1 = rotl(v1, 13n) ^ v0; v0 = rotl(v0, 32n);
47
- v2 = (v2 + v3) & mask; v3 = rotl(v3, 16n) ^ v2;
48
- v0 = (v0 + v3) & mask; v3 = rotl(v3, 21n) ^ v0;
49
- v2 = (v2 + v1) & mask; v1 = rotl(v1, 17n) ^ v2; v2 = rotl(v2, 32n);
50
- };
51
- const compress = (word) => { v3 ^= word; round(); v0 ^= word; };
52
- const whole = bytes.length - (bytes.length % 8);
53
- for (let i = 0; i < whole; i += 8) compress(bytes.readBigUInt64LE(i));
54
- let last = BigInt(bytes.length & 0xff) << 56n;
55
- for (let i = whole; i < bytes.length; i += 1) last |= BigInt(bytes[i]) << BigInt(8 * (i - whole));
56
- compress(last);
57
- v2 ^= 0xffn;
58
- round(); round(); round();
59
- return ((v0 ^ v1 ^ v2 ^ v3) & mask).toString(16).padStart(16, "0");
60
- }
61
-
62
- // Node's existsSync cannot see a named pipe, so on Windows the pipe namespace is listed instead;
63
- // a listing that fails counts as no pipe, so discovery falls back to starting the daemon.
64
- function socketExists(sockPath) {
65
- if (process.platform !== "win32") return existsSync(sockPath);
66
- try { return readdirSync("\\\\.\\pipe\\").includes(path.win32.basename(sockPath)); } catch { return false; }
67
- }
68
-
69
- // True when something answers system.ping on `sockPath`: a live daemon whose daemon.json was lost.
70
- function probeSocket(sockPath) {
71
- if (!socketExists(sockPath)) return Promise.resolve(false);
72
- return new Promise((resolve) => {
73
- const socket = connect(sockPath);
74
- const done = (alive) => { clearTimeout(timer); socket.destroy(); resolve(alive); };
75
- const timer = setTimeout(() => done(false), PROBE_TIMEOUT_MS);
76
- socket.on("error", () => done(false));
77
- socket.on("connect", () => socket.write(JSON.stringify({ id: "probe-orphan", method: "system.ping" }) + "\n"));
78
- socket.on("data", () => done(true));
79
- });
80
- }
81
-
82
- export class BskRpcError extends Error {
83
- constructor(code, message, data) {
84
- super(message);
85
- this.name = "BskRpcError";
86
- this.code = code;
87
- this.data = data;
88
- }
89
- }
90
-
91
- function shortId() { return randomBytes(6).toString("hex"); }
92
- function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
93
-
94
- // daemon.json outlives a daemon that was killed, as when a host closes the job it ran in. Only its socket
95
- // says so: a connect that fails with one of these reached no listener. Its pid cannot, since a client in
96
- // another PID namespace sees a live daemon's pid as gone and a reused pid makes a dead one look alive.
97
- const NO_LISTENER = new Set(["ENOENT", "ECONNREFUSED"]);
98
-
99
- function sameRecord(info, stale) {
100
- return Boolean(stale) && JSON.stringify(info) === JSON.stringify(stale.info);
101
- }
102
-
103
- export class BskIpcClient {
104
- #home; #env; #sockPath; #autoStart; #startDaemon; #timeoutMs; #starting = null;
105
-
106
- constructor({ home, env = process.env, sockPath, autoStart, startDaemon, timeoutMs = DEFAULT_TIMEOUT_MS, bskBin } = {}) {
107
- this.#home = home ?? resolveBskHome(env);
108
- this.#sockPath = sockPath ?? null;
109
- this.#autoStart = autoStart ?? env.BSK_AUTO_START !== "0";
110
- this.#startDaemon = startDaemon ?? (() => startDaemonWithCli({ home: this.#home, env, bskBin }));
111
- this.#timeoutMs = timeoutMs;
112
- this.#env = env;
113
- }
114
-
115
- get home() { return this.#home; }
116
-
117
- // `stale` is a daemon.json record ({info, code}) whose socket refused a connect; it is skipped until rewritten.
118
- async resolveSocket({ isAborted = () => false, stale } = {}) {
119
- if (this.#sockPath) return this.#sockPath;
120
- const found = readDaemonInfo(this.#home);
121
- if (found && !sameRecord(found, stale)) return found.sock_path;
122
- // daemon.json can vanish while the daemon keeps running; starting another one then fails on the held port.
123
- const orphan = defaultSocketPath(this.#home, this.#env);
124
- // Probe only when the socket file exists, so a fresh home starts its daemon in the same tick as before.
125
- if (socketExists(orphan)) {
126
- if (await probeSocket(orphan)) return orphan;
127
- if (isAborted()) throw new BskRpcError("cancelled", "cancelled before the daemon was located");
128
- }
129
- if (!this.#autoStart) {
130
- if (stale) {
131
- throw new BskRpcError("no_daemon", `${this.#home}/daemon.json names a BrowserSkill daemon at ${stale.info.sock_path} that is no longer listening (${stale.code}) and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`);
132
- }
133
- throw new BskRpcError("no_daemon", `no BrowserSkill daemon published at ${this.#home}/daemon.json and automatic start is disabled (BSK_AUTO_START=0); run \`bsk daemon start\` in the environment that owns it`);
134
- }
135
- if (!this.#starting) this.#starting = this.#startDaemon().finally(() => { this.#starting = null; });
136
- await this.#starting;
137
- const deadline = Date.now() + DISCOVERY_BUDGET_MS;
138
- while (Date.now() < deadline && !isAborted()) {
139
- const info = readDaemonInfo(this.#home);
140
- if (info && !sameRecord(info, stale)) return info.sock_path;
141
- await sleep(DISCOVERY_RETRY_MS);
142
- }
143
- if (isAborted()) throw new BskRpcError("cancelled", "cancelled while waiting for the daemon to publish daemon.json");
144
- throw new BskRpcError("no_daemon", `daemon start was requested but ${this.#home}/daemon.json never appeared`);
145
- }
146
-
147
- call(method, params, options = {}) {
148
- return this.callWithHandle(method, params, options).promise;
149
- }
150
-
151
- // {rpcId, promise, abort()} — rpcId is known before the frame is sent so a
152
- // caller can cancel a long tool call from another connection.
153
- callWithHandle(method, params, { idPrefix = method.replace(/[^a-z0-9]+/gi, "-"), timeoutMs } = {}) {
154
- const ownBudget = ownBudgetMs(params);
155
- const humanWait = HUMAN_WAIT_METHODS.has(method);
156
- // An explicit timeoutMs is a floor, never a cut below the tool's own budget.
157
- const waitMs = humanWait && ownBudget === undefined && timeoutMs === undefined
158
- ? HUMAN_WAIT_BACKSTOP_MS
159
- : Math.max(timeoutMs ?? this.#timeoutMs, ownBudget ?? 0);
160
- const rpcId = `${idPrefix}-${shortId()}`;
161
- const frame = { id: rpcId, method };
162
- if (params !== undefined) frame.params = params;
163
- let aborted = false;
164
- let abortSocket = () => {};
165
- const exchange = (sockPath, onNoListener) => new Promise((resolve, reject) => {
166
- const socket = connect(sockPath);
167
- let buffer = "";
168
- let settled = false;
169
- const finish = (fn, value) => {
170
- if (settled) return;
171
- settled = true;
172
- clearTimeout(timer);
173
- socket.destroy();
174
- fn(value);
175
- };
176
- const timer = setTimeout(() => {
177
- const cancels = method !== "cancel" && !humanWait;
178
- finish(reject, new BskRpcError("timeout", `${method} did not answer within ${waitMs}ms${cancels ? "; a cancel was requested at the daemon" : ""}`));
179
- // The daemon would otherwise keep running it and hold the session for the next call.
180
- if (cancels) this.cancel(rpcId).catch(() => {});
181
- }, waitMs);
182
- abortSocket = () => finish(reject, new BskRpcError("cancelled", `${method} cancelled by caller`));
183
- socket.on("error", (error) => {
184
- if (NO_LISTENER.has(error.code)) onNoListener(error.code);
185
- finish(reject, new BskRpcError("no_daemon", `IPC socket ${sockPath}: ${error.code ?? error.message}`));
186
- });
187
- socket.setEncoding("utf8");
188
- socket.on("connect", () => socket.write(JSON.stringify(frame) + "\n"));
189
- socket.on("data", (chunk) => {
190
- buffer += chunk;
191
- const idx = buffer.indexOf("\n");
192
- if (idx === -1) return;
193
- try { finish(resolve, decodeResponse(buffer.slice(0, idx), rpcId, method)); } catch (error) { finish(reject, error); }
194
- });
195
- socket.on("close", () => finish(reject, new BskRpcError("protocol_error", `${method}: daemon closed the connection without a reply`)));
196
- });
197
- const promise = (async () => {
198
- let stale;
199
- for (;;) {
200
- const sockPath = await this.resolveSocket({ isAborted: () => aborted, stale });
201
- if (aborted) throw new BskRpcError("cancelled", `${method} cancelled by caller`);
202
- let refused;
203
- try {
204
- return await exchange(sockPath, (code) => { refused = code; });
205
- } catch (error) {
206
- // The frame never left, so one retry past the stale record sends nothing twice.
207
- const info = refused && !stale && !this.#sockPath ? readDaemonInfo(this.#home) : null;
208
- if (info?.sock_path !== sockPath) throw error;
209
- stale = { info, code: refused };
210
- }
211
- }
212
- })();
213
- return { rpcId, promise, abort: () => { aborted = true; abortSocket(); } };
214
- }
215
-
216
- async cancel(rpcId) {
217
- return this.call("cancel", { rpc_id: rpcId }, { idPrefix: "cancel", timeoutMs: 2_000 });
218
- }
219
- }
220
-
221
- function decodeResponse(line, rpcId, method) {
222
- let reply;
223
- try { reply = JSON.parse(line); } catch {
224
- throw new BskRpcError("protocol_error", `${method}: daemon reply is not JSON: ${line.slice(0, 120)}`);
225
- }
226
- // The daemon answers a frame it could not decode under id "0".
227
- const undecodableFrame = reply.id === "0" && reply.error;
228
- if (reply.id !== rpcId && !undecodableFrame) {
229
- throw new BskRpcError("protocol_error", `${method}: reply id ${reply.id} does not match request ${rpcId}`);
230
- }
231
- if (reply.error) {
232
- const { code = "protocol_error", message = "daemon error", data } = reply.error;
233
- throw new BskRpcError(code, message, data);
234
- }
235
- return reply.result;
236
- }
@@ -1,140 +0,0 @@
1
- import { homedir } from "node:os";
2
- import { findBskBinary } from "./daemon-info.js";
3
- import { BskIpcClient } from "./ipc-client.js";
4
- import { isTabGroupingExtension, listBrowsers, TAB_GROUPING_EXTENSION_STEP } from "./connect.js";
5
- import { catalogBrowsers, externalExtensionEntry, registerExternalExtension, STORE_PAGE_URLS } from "./external-extension.js";
6
- import { probeBrowserSignals } from "./browser-signals.js";
7
- import { identifyBrowser } from "./identify-browser.js";
8
- import { existsSync, readFileSync } from "node:fs";
9
- import { cliVersionDefault, installBskCli } from "./install-cli.js";
10
-
11
- const DEFAULT_WAIT_TOTAL_MS = 180_000;
12
-
13
- function resolveBskBin(bskBin, env) {
14
- if (bskBin === null) return null;
15
- return bskBin ?? findBskBinary(env);
16
- }
17
-
18
- async function cliReport({ bskBin, env, cliVersion }) {
19
- const bin = resolveBskBin(bskBin, env);
20
- if (!bin) return { installed: false, bskBin: null, version: null };
21
- const raw = await cliVersion(bin);
22
- return raw ? { installed: true, bskBin: bin, version: raw.replace(/^bsk\s+/, "") } : { installed: false, bskBin: bin, version: null };
23
- }
24
-
25
- async function daemonReport(client, waitForBrowserMs) {
26
- try {
27
- const status = await client.call("system.status", waitForBrowserMs > 0 ? { wait_for_browser_ms: waitForBrowserMs } : {}, { idPrefix: "status" });
28
- return { running: true, version: status.daemon_version, protocolVersion: status.protocol_version, browsers: status.browsers ?? [], sessions: status.sessions ?? [] };
29
- } catch (error) {
30
- return { running: false, error: error.message, code: error.code, startBlocked: NO_BREAKAWAY.test(error.message), browsers: [], sessions: [] };
31
- }
32
- }
33
-
34
- // bsk's refusal when the host's Windows Job Object forbids breakaway: a detached start fails the same way every retry.
35
- const NO_BREAKAWAY = /Job Object|breakaway/i;
36
- const FOREGROUND_STEP = "run `bsk daemon start --foreground` in a persistent background session of the agent host (one that outlives the command, not a one-shot shell call), then check it with `bsk status` from a separate call";
37
-
38
- function daemonStep(daemon) {
39
- if (daemon.startBlocked) return `Start the BrowserSkill daemon: this host does not let a command detach it (Windows Job Object breakaway is prohibited), so retrying \`bsk status\` or \`bsk daemon start\` fails the same way; ${FOREGROUND_STEP}.`;
40
- return `Start the BrowserSkill daemon: bskOnboard() (or \`bsk status\` once) starts it. If the host reaps background processes or the start fails, ${FOREGROUND_STEP}; do not retry a detached \`bsk daemon start\`.`;
41
- }
42
-
43
- const NO_BROWSER_STEP = `No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;
44
-
45
- function withRegistration(platform, browser) {
46
- const entry = externalExtensionEntry({ platform, browser });
47
- const extensionRegistered = entry.kind === "file" && existsSync(entry.path) && readFileSync(entry.path, "utf8") === entry.content;
48
- return { ...browser, registration: entry, extensionRegistered };
49
- }
50
-
51
- async function identify({ platform, home, env, exists, browser, connected, signals, probeSignals, now }) {
52
- const catalog = catalogBrowsers({ platform, home, env, exists }).map((b) => withRegistration(platform, b));
53
- const observed = signals ?? await probeSignals({ platform, home, browsers: catalog.filter((b) => b.hasProfile) });
54
- const explicit = browser ?? env.OMOWRIGHT_BROWSER ?? null;
55
- const { primary, ...identification } = identifyBrowser({ catalog, signals: observed, explicit: explicit || null, connected, now });
56
- const browsers = catalog.filter((b) => b.installed);
57
- const registeredElsewhere = browsers.filter((b) => b.extensionRegistered && b.id !== identification.primaryId).map((b) => b.id);
58
- return { browsers, identification: { ...identification, registeredElsewhere }, primary };
59
- }
60
-
61
- function choiceStep(identification) {
62
- const listed = identification.candidates.map((c) => `${c.label} [${c.id}]${c.signals.length ? ` — ${c.signals.join(", ")}` : ""}`).join("; ");
63
- const hint = identification.suggested ? ` Likely ${identification.suggested}, but confirm first.` : "";
64
- return `Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`;
65
- }
66
-
67
- function nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary }) {
68
- if (browsersConnected.length > 0) return browsersConnected.every(isTabGroupingExtension) ? TAB_GROUPING_EXTENSION_STEP : null;
69
- if (!cli.installed) return "Install the bsk CLI (bskOnboard() runs the official installer).";
70
- if (!daemon.running) return daemonStep(daemon);
71
- if (browsers.length === 0 && !primary) return NO_BROWSER_STEP;
72
- if (identification.needsChoice) return choiceStep(identification);
73
- if (!primary.extensionRegistered && primary.registration.kind !== "store") return `Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;
74
- return primary.registration.humanStep;
75
- }
76
-
77
- export async function bskDoctor({
78
- platform = process.platform, home = homedir(), env = process.env, client, bskBin, cliVersion = cliVersionDefault, waitForBrowserMs = 0,
79
- exists = existsSync, browser, signals, probeSignals = probeBrowserSignals, now = Date.now(),
80
- } = {}) {
81
- const cli = await cliReport({ bskBin, env, cliVersion });
82
- const ipc = client ?? new BskIpcClient({ env, bskBin: cli.bskBin ?? undefined, autoStart: false });
83
- const daemon = await daemonReport(ipc, waitForBrowserMs);
84
- const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
85
- const browsersConnected = daemon.browsers;
86
- const outdatedExtensions = browsersConnected.filter(isTabGroupingExtension);
87
- const report = { cli, daemon, browsers, primary: primary ?? null, identification, browsersConnected, outdatedExtensions, ready: browsersConnected.length > outdatedExtensions.length };
88
- report.nextStep = nextStepFor(report);
89
- return report;
90
- }
91
-
92
- export async function bskOnboard({
93
- platform = process.platform, home = homedir(), env = process.env, client, bskBin, installDir,
94
- installCli = installBskCli, cliVersion = cliVersionDefault, onHumanStep = () => {},
95
- waitForBrowserMs = 15_000, waitTotalMs = DEFAULT_WAIT_TOTAL_MS,
96
- exists = existsSync, browser, signals, probeSignals = probeBrowserSignals, now = Date.now(),
97
- } = {}) {
98
- let cli = await cliReport({ bskBin, env, cliVersion });
99
- let install = null;
100
- if (!cli.installed) {
101
- install = await installCli({ platform, home, installDir });
102
- cli = install.installed ? await cliReport({ bskBin: install.bskBin, env, cliVersion }) : cli;
103
- }
104
- const ipc = client ?? new BskIpcClient({ env, bskBin: cli.bskBin ?? undefined, autoStart: true });
105
- let daemon = await daemonReport(ipc, 0);
106
- const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
107
- const registrations = [];
108
- let humanStep = null;
109
- let needsChoice = false;
110
- if (daemon.browsers.length === 0) {
111
- if (browsers.length === 0 && !primary) {
112
- humanStep = NO_BROWSER_STEP;
113
- } else if (identification.needsChoice) {
114
- needsChoice = true;
115
- humanStep = choiceStep(identification);
116
- } else if (daemon.running) {
117
- // A down daemon hides whether the extension is already enabled, so no step goes to the user until it is up.
118
- const registration = await registerExternalExtension({ platform, browser: primary });
119
- registrations.push({ browser: primary.id, ...registration });
120
- humanStep = registration.humanStep;
121
- onHumanStep({ browser: primary.id, step: registration.humanStep, registered: registration.registered, needsRestart: registration.needsRestart });
122
- }
123
- }
124
- const deadline = Date.now() + waitTotalMs;
125
- let browsersConnected = daemon.browsers;
126
- while (!needsChoice && browsersConnected.length === 0 && daemon.running && Date.now() < deadline) {
127
- browsersConnected = await listBrowsers(ipc, { waitForBrowserMs });
128
- if (waitForBrowserMs === 0) break;
129
- }
130
- daemon = { ...daemon, browsers: browsersConnected };
131
- // An installed 0.4.0 extension needs the user to update it, not another registration: see bskDoctor.
132
- const outdatedExtensions = browsersConnected.filter(isTabGroupingExtension);
133
- const ready = browsersConnected.length > outdatedExtensions.length;
134
- if (!ready && outdatedExtensions.length > 0) {
135
- humanStep = TAB_GROUPING_EXTENSION_STEP;
136
- onHumanStep({ browser: outdatedExtensions[0].browser_name, step: humanStep, registered: true, needsRestart: false });
137
- }
138
- const nextStep = ready ? null : humanStep ?? nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary });
139
- return { cli, install, daemon, browsers, primary: primary ?? null, identification, needsChoice, registrations, humanStep: ready ? null : humanStep, nextStep, browsersConnected, outdatedExtensions, ready };
140
- }
@@ -1,49 +0,0 @@
1
- export async function captureScreenshot(session, { ref, tabId, fullPage = false, scope, timeoutMs, context, dependsOn } = {}) {
2
- if (!fullPage) {
3
- const result = await session.tool("screenshot", { ref, tab_id: tabId });
4
- return {
5
- buffer: Buffer.from(result.image_base64, "base64"),
6
- width: result.width,
7
- height: result.height,
8
- format: result.format,
9
- captureId: result.capture_id ?? null,
10
- captureUnavailable: result.capture_unavailable ?? null,
11
- tabId: result.tab_id,
12
- dialogs: result.dialogs ?? [],
13
- };
14
- }
15
- const started = await session.tool("screenshot_full_page", { scope, tab_id: tabId, timeout_ms: timeoutMs, context_id: context, depends_on: dependsOn });
16
- const buffer = await readCapture(session, started.capture_id, started.byte_size);
17
- return {
18
- buffer,
19
- width: started.width,
20
- height: started.height,
21
- format: started.format,
22
- captureId: started.capture_id,
23
- scope: started.scope ?? scope ?? null,
24
- tabId: started.tab_id,
25
- dialogs: started.dialogs ?? [],
26
- };
27
- }
28
-
29
- async function readCapture(session, captureId, byteSize) {
30
- const chunks = [];
31
- let offset = 0;
32
- try {
33
- for (;;) {
34
- const chunk = await session.tool("screenshot_read", { capture_id: captureId, offset });
35
- const bytes = Buffer.from(chunk.data_base64 ?? "", "base64");
36
- chunks.push(bytes);
37
- if (chunk.eof || bytes.length === 0) break;
38
- if (chunk.next_offset <= offset) throw new Error(`screenshot_read did not advance past offset ${offset}`);
39
- offset = chunk.next_offset;
40
- }
41
- } finally {
42
- await session.tool("screenshot_release", { capture_id: captureId }).catch(() => {});
43
- }
44
- const buffer = Buffer.concat(chunks);
45
- if (typeof byteSize === "number" && buffer.length !== byteSize) {
46
- throw new Error(`screenshot capture ${captureId}: expected ${byteSize} bytes, assembled ${buffer.length}`);
47
- }
48
- return buffer;
49
- }
@@ -1,131 +0,0 @@
1
- import { compact, optionalTarget, resolveTarget } from "./targets.js";
2
- import { captureScreenshot } from "./screenshot.js";
3
-
4
- const SESSION_STOP_TIMEOUT_MS = 3_600_000;
5
-
6
- // BrowserSkill 0.4 refuses a page action (cooperation_sync_required) unless it
7
- // carries the single-use context_id of the latest tool.cooperate sync, and the
8
- // daemon never fills it in for the caller. Any other key left over after a method's own options
9
- // is a misspelling (for example `contextId`) that would otherwise send no context, so it throws.
10
- function sharedTab({ context, dependsOn, ...unknown }) {
11
- const extra = Object.keys(unknown);
12
- if (extra.length > 0) {
13
- throw new TypeError(`unknown option ${extra.map((key) => JSON.stringify(key)).join(", ")}: a shared-tab action takes { context, dependsOn } besides its own options`);
14
- }
15
- return { context_id: context, depends_on: dependsOn };
16
- }
17
-
18
- export class BskSession {
19
- #client; #stopped = false;
20
-
21
- constructor(client, { sessionId, browserInstanceId = null, agentWindowId = null, interaction = null } = {}) {
22
- if (typeof sessionId !== "string" || sessionId.length === 0) throw new TypeError("BskSession requires a sessionId");
23
- this.#client = client;
24
- this.sessionId = sessionId;
25
- this.browserInstanceId = browserInstanceId;
26
- this.agentWindowId = agentWindowId;
27
- this.interaction = interaction;
28
- }
29
-
30
- get client() { return this.#client; }
31
- get stopped() { return this.#stopped; }
32
-
33
- tool(name, params = {}) {
34
- if (this.#stopped) return Promise.reject(new Error(`BrowserSkill session ${this.sessionId} is stopped`));
35
- return this.#client.call(`tool.${name}`, compact({ session_id: this.sessionId, ...params }), { idPrefix: name.replace(/_/g, "-") });
36
- }
37
-
38
- cooperate(action, { tabId, timeoutMs, maxTokens } = {}) {
39
- return this.tool("cooperate", { action, tab_id: tabId, timeout_ms: timeoutMs, max_tokens: maxTokens });
40
- }
41
-
42
- navigate(url, { tabId, waitUntil, timeoutMs, ...shared } = {}) {
43
- return this.tool("navigate", { url, tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, ...sharedTab(shared) });
44
- }
45
- back({ tabId, waitUntil, timeoutMs, ...shared } = {}) {
46
- return this.tool("navigate_back", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, ...sharedTab(shared) });
47
- }
48
- forward({ tabId, waitUntil, timeoutMs, ...shared } = {}) {
49
- return this.tool("navigate_forward", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, ...sharedTab(shared) });
50
- }
51
- reload({ tabId, waitUntil, timeoutMs, hard, ...shared } = {}) {
52
- return this.tool("reload", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs, hard, ...sharedTab(shared) });
53
- }
54
-
55
- observe({ cursor, tabId, maxDepth, maxTokens, debugSurfaces, probeHover, ...shared } = {}) {
56
- return this.tool("observe", { cursor, tab_id: tabId, max_depth: maxDepth, max_tokens: maxTokens, debug_surfaces: debugSurfaces, probe_hover: probeHover, ...sharedTab(shared) });
57
- }
58
- snapshot({ tabId, maxDepth, maxTokens } = {}) {
59
- return this.tool("snapshot", { tab_id: tabId, max_depth: maxDepth, max_tokens: maxTokens });
60
- }
61
- getHtml({ ref, tabId, maxBytes } = {}) {
62
- return this.tool("get_html", { ref, tab_id: tabId, max_bytes: maxBytes });
63
- }
64
- screenshot(options) { return captureScreenshot(this, options); }
65
-
66
- click(target, { button, clickCount, modifiers, tabId, timeoutMs, ...shared } = {}) {
67
- return this.tool("click", { ...resolveTarget(target), button, click_count: clickCount, modifiers, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
68
- }
69
- hover(target, { modifiers, settleMs, tabId, timeoutMs, ...shared } = {}) {
70
- return this.tool("hover", { ...resolveTarget(target), modifiers, settle_ms: settleMs, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
71
- }
72
- focus(target, { tabId, timeoutMs, ...shared } = {}) {
73
- return this.tool("focus", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
74
- }
75
- blur(target, { tabId, timeoutMs, ...shared } = {}) {
76
- return this.tool("blur", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
77
- }
78
- fill(target, value, { clearBefore, tabId, timeoutMs, ...shared } = {}) {
79
- return this.tool("fill", { ...resolveTarget(target), value, clear_before: clearBefore, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
80
- }
81
- press(key, { target, modifiers, holdMs, tabId, timeoutMs, ...shared } = {}) {
82
- return this.tool("press", { key, ...optionalTarget(target), modifiers, hold_ms: holdMs, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
83
- }
84
- select(target, values, { tabId, timeoutMs, ...shared } = {}) {
85
- return this.tool("select", { ...resolveTarget(target), values: Array.isArray(values) ? values : [values], tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
86
- }
87
- scrollTo(target, { tabId, timeoutMs, ...shared } = {}) {
88
- return this.tool("scroll_to", { ...resolveTarget(target), tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
89
- }
90
- wheel({ deltaX = 0, deltaY = 0, target, modifiers, tabId, timeoutMs, ...shared } = {}) {
91
- return this.tool("wheel", { ...optionalTarget(target), delta_x: deltaX, delta_y: deltaY, modifiers, tab_id: tabId, timeout_ms: timeoutMs, ...sharedTab(shared) });
92
- }
93
-
94
- evaluate(expression, { tabId, awaitPromise, returnByValue, timeoutMs, ...shared } = {}) {
95
- return this.tool("evaluate", { expression, tab_id: tabId, await_promise: awaitPromise, return_by_value: returnByValue, timeout_ms: timeoutMs, ...sharedTab(shared) });
96
- }
97
-
98
- tabList({ scope } = {}) { return this.tool("tab_list", { scope }); }
99
- tabCreate({ url, active, index } = {}) { return this.tool("tab_create", { url, active, index }); }
100
- tabClose(tabId, shared = {}) { return this.tool("tab_close", { tab_id: tabId, ...sharedTab(shared) }); }
101
- tabSelect(tabId) { return this.tool("tab_select", { tab_id: tabId }); }
102
- tabBorrow(tabId, { confirmationTimeoutMs } = {}) {
103
- return this.tool("tab_borrow", { tab_id: tabId, confirmation_timeout_ms: confirmationTimeoutMs });
104
- }
105
- tabReturn(tabId) { return this.tool("tab_return", { tab_id: tabId }); }
106
-
107
- waitForNavigation({ tabId, waitUntil, timeoutMs } = {}) {
108
- return this.tool("wait_for_navigation", { tab_id: tabId, wait_until: waitUntil, timeout_ms: timeoutMs });
109
- }
110
- requestHelp({ prompt, title, targets, completionCriteria, tabId, timeoutMs } = {}) {
111
- return this.tool("request_help", {
112
- prompt, title, tab_id: tabId, timeout_ms: timeoutMs,
113
- targets: targets?.map((t) => resolveTarget(t)),
114
- completion_criteria: completionCriteria,
115
- });
116
- }
117
- console({ tabId, since, limit, maxTextChars, includeStack } = {}) {
118
- return this.tool("console", { tab_id: tabId, since, limit, max_text_chars: maxTextChars, include_stack: includeStack });
119
- }
120
- network({ tabId, since, limit, maxTextChars } = {}) {
121
- return this.tool("network", { tab_id: tabId, since, limit, max_text_chars: maxTextChars });
122
- }
123
- resize(width, height, shared = {}) { return this.tool("window_resize", { width, height, ...sharedTab(shared) }); }
124
- emulate({ tabId, off, overrides, ...shared } = {}) { return this.tool("emulate", { tab_id: tabId, off, overrides, ...sharedTab(shared) }); }
125
-
126
- async stop() {
127
- if (this.#stopped) return null;
128
- this.#stopped = true;
129
- return this.#client.call("session.stop", { session_id: this.sessionId }, { idPrefix: "session-stop", timeoutMs: SESSION_STOP_TIMEOUT_MS });
130
- }
131
- }
@@ -1,56 +0,0 @@
1
- // OmOWright-style {tree, refs} snapshot from a BrowserSkill session without
2
- // leaving a trace in the page: the page bundle assigns `globalThis.__omowright`
3
- // exactly once, so shadowing `globalThis` with a local object keeps the real
4
- // window untouched, and the css paths let a ref be clicked through the
5
- // daemon's `selector` target (no DOM attribute is written).
6
- import { pageBundle } from "../injected.js";
7
-
8
- const CSS_PATH_FN = String(function cssPath(el) {
9
- if (!(el instanceof Element)) return null;
10
- if (el.getRootNode() !== document) return null;
11
- const parts = [];
12
- let node = el;
13
- while (node && node.nodeType === 1 && node !== document.documentElement) {
14
- let part = node.localName;
15
- if (node.id && /^[A-Za-z_][\w-]*$/.test(node.id) && document.querySelectorAll("#" + node.id).length === 1) {
16
- parts.unshift("#" + node.id);
17
- return parts.join(" > ");
18
- }
19
- const parent = node.parentElement;
20
- if (parent) {
21
- const same = Array.from(parent.children).filter((c) => c.localName === node.localName);
22
- if (same.length > 1) part += `:nth-of-type(${same.indexOf(node) + 1})`;
23
- }
24
- parts.unshift(part);
25
- node = parent;
26
- }
27
- parts.unshift("html");
28
- return parts.join(" > ");
29
- });
30
-
31
- export function buildSnapshotExpression(options = {}) {
32
- return `(function () {
33
- const globalThis = {};
34
- ${pageBundle}
35
- const api = globalThis.__omowright;
36
- const result = api.takeSnapshot(${JSON.stringify(options)});
37
- const cssPath = ${CSS_PATH_FN};
38
- const css = {};
39
- for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));
40
- return { tree: result.tree, refs: result.refs || {}, css, error: result.error };
41
- })()`;
42
- }
43
-
44
- export async function bskSnapshot(session, { tabId, timeoutMs, context, dependsOn, ...snapshotOptions } = {}) {
45
- const reply = await session.evaluate(buildSnapshotExpression(snapshotOptions), {
46
- tabId, timeoutMs, context, dependsOn, awaitPromise: false, returnByValue: true,
47
- });
48
- if (!reply || reply.ok === false) {
49
- const text = reply?.error?.text ?? "unknown error";
50
- throw new Error(`bskSnapshot failed inside the page: ${text}`);
51
- }
52
- const value = reply.value;
53
- if (!value || typeof value.tree !== "string") throw new Error("bskSnapshot: page returned no tree");
54
- if (value.error) throw new Error(`bskSnapshot: ${value.error}`);
55
- return { tree: value.tree, refs: value.refs, css: value.css };
56
- }
@@ -1,25 +0,0 @@
1
- const REF_SHAPE = /^@?e\d+$/;
2
-
3
- export function resolveTarget(target) {
4
- if (typeof target === "string") {
5
- return REF_SHAPE.test(target) ? { ref: target } : { selector: target };
6
- }
7
- if (target && typeof target === "object") {
8
- if (typeof target.ref === "string") return { ref: target.ref };
9
- if (typeof target.selector === "string") return { selector: target.selector };
10
- if (typeof target.captureId === "string") {
11
- return { capture_id: target.captureId, image_x: target.x, image_y: target.y };
12
- }
13
- }
14
- throw new TypeError("target must be a ref ('e3' / '@e3'), a CSS selector, or {captureId, x, y}");
15
- }
16
-
17
- export function optionalTarget(target) {
18
- return target === undefined ? {} : resolveTarget(target);
19
- }
20
-
21
- export function compact(params) {
22
- const out = {};
23
- for (const [key, value] of Object.entries(params)) if (value !== undefined) out[key] = value;
24
- return out;
25
- }