omowright 0.1.0 → 0.2.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.
@@ -4,6 +4,36 @@ import { compact } from "./targets.js";
4
4
 
5
5
  const DEFAULT_WAIT_FOR_BROWSER_MS = 15_000;
6
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
+
7
37
  export async function listBrowsers(client, { waitForBrowserMs } = {}) {
8
38
  const status = await client.call("system.status", compact({ wait_for_browser_ms: waitForBrowserMs }), { idPrefix: "status" });
9
39
  return status.browsers ?? [];
@@ -33,7 +63,7 @@ export async function connectBrowserSkill({
33
63
  }
34
64
  const started = await ipc.call("session.start", compact({
35
65
  task_name: name,
36
- browser_instance_id: resolveBrowser(browser, browsers),
66
+ browser_instance_id: chooseBrowser(browser, browsers),
37
67
  width, height, focused,
38
68
  }), { idPrefix: "session-start" });
39
69
  return new BskSession(ipc, {
@@ -1,7 +1,7 @@
1
1
  import { homedir } from "node:os";
2
2
  import { findBskBinary } from "./daemon-info.js";
3
3
  import { BskIpcClient } from "./ipc-client.js";
4
- import { listBrowsers } from "./connect.js";
4
+ import { isTabGroupingExtension, listBrowsers, TAB_GROUPING_EXTENSION_STEP } from "./connect.js";
5
5
  import { catalogBrowsers, externalExtensionEntry, registerExternalExtension, STORE_PAGE_URLS } from "./external-extension.js";
6
6
  import { probeBrowserSignals } from "./browser-signals.js";
7
7
  import { identifyBrowser } from "./identify-browser.js";
@@ -65,7 +65,7 @@ function choiceStep(identification) {
65
65
  }
66
66
 
67
67
  function nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary }) {
68
- if (browsersConnected.length > 0) return null;
68
+ if (browsersConnected.length > 0) return browsersConnected.every(isTabGroupingExtension) ? TAB_GROUPING_EXTENSION_STEP : null;
69
69
  if (!cli.installed) return "Install the bsk CLI (bskOnboard() runs the official installer).";
70
70
  if (!daemon.running) return daemonStep(daemon);
71
71
  if (browsers.length === 0 && !primary) return NO_BROWSER_STEP;
@@ -83,7 +83,8 @@ export async function bskDoctor({
83
83
  const daemon = await daemonReport(ipc, waitForBrowserMs);
84
84
  const { browsers, identification, primary } = await identify({ platform, home, env, exists, browser, connected: daemon.browsers.map((b) => b.browser_name), signals, probeSignals, now });
85
85
  const browsersConnected = daemon.browsers;
86
- const report = { cli, daemon, browsers, primary: primary ?? null, identification, browsersConnected, ready: browsersConnected.length > 0 };
86
+ const outdatedExtensions = browsersConnected.filter(isTabGroupingExtension);
87
+ const report = { cli, daemon, browsers, primary: primary ?? null, identification, browsersConnected, outdatedExtensions, ready: browsersConnected.length > outdatedExtensions.length };
87
88
  report.nextStep = nextStepFor(report);
88
89
  return report;
89
90
  }
@@ -127,7 +128,13 @@ export async function bskOnboard({
127
128
  if (waitForBrowserMs === 0) break;
128
129
  }
129
130
  daemon = { ...daemon, browsers: browsersConnected };
130
- const ready = browsersConnected.length > 0;
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
+ }
131
138
  const nextStep = ready ? null : humanStep ?? nextStepFor({ cli, daemon, browsers, browsersConnected, identification, primary });
132
- return { cli, install, daemon, browsers, primary: primary ?? null, identification, needsChoice, registrations, humanStep: ready ? null : humanStep, nextStep, browsersConnected, ready };
139
+ return { cli, install, daemon, browsers, primary: primary ?? null, identification, needsChoice, registrations, humanStep: ready ? null : humanStep, nextStep, browsersConnected, outdatedExtensions, ready };
133
140
  }
@@ -37,13 +37,17 @@ export async function waitForCaptcha(page, {
37
37
  if (initial) return result(initial);
38
38
  signal?.addEventListener("abort", stop, { once: true });
39
39
  scheduleDeadline();
40
+ // The first evaluation only yields to cancellation: a scheduling stall
41
+ // between the call and this microtask must not time the wait out unevaluated.
42
+ let evaluated = false;
40
43
  for (;;) {
41
44
  let accepted;
42
45
  try {
43
46
  // Promise.race keeps a rejection handler on a non-cooperative predicate
44
47
  // even after this wait has timed out or been cancelled.
45
48
  accepted = await Promise.race([
46
- Promise.resolve().then(() => terminal() ? STOP : until(page, { signal: operation.signal })),
49
+ Promise.resolve().then(() => (evaluated ? terminal() : signal?.aborted)
50
+ ? STOP : until(page, { signal: operation.signal })),
47
51
  stopped,
48
52
  ]);
49
53
  } catch (error) {
@@ -51,6 +55,7 @@ export async function waitForCaptcha(page, {
51
55
  if (outcome) return result(outcome);
52
56
  throw error;
53
57
  }
58
+ evaluated = true;
54
59
  const outcome = terminal();
55
60
  if (outcome) return result(outcome);
56
61
  if (accepted === true) return result("matched");
@@ -20,6 +20,7 @@ export const OMOWRIGHT_PAGE_CDP_METHODS = Object.freeze([
20
20
  "DOM.setFileInputFiles",
21
21
  "Emulation.setDeviceMetricsOverride",
22
22
  "Emulation.setFocusEmulationEnabled",
23
+ "Emulation.setEmulatedMedia",
23
24
  "Input.dispatchKeyEvent",
24
25
  "Input.dispatchMouseEvent",
25
26
  "Input.insertText",
@@ -27,6 +28,7 @@ export const OMOWRIGHT_PAGE_CDP_METHODS = Object.freeze([
27
28
  "Network.disable",
28
29
  "Network.enable",
29
30
  "Network.getResponseBody",
31
+ "Network.setExtraHTTPHeaders",
30
32
  "Page.addScriptToEvaluateOnNewDocument",
31
33
  "Page.captureScreenshot",
32
34
  "Page.close",
@@ -47,8 +49,14 @@ export const OMOWRIGHT_PAGE_CDP_METHODS = Object.freeze([
47
49
  "Page.startScreencast",
48
50
  "Page.stopScreencast",
49
51
  "Runtime.callFunctionOn",
52
+ "Runtime.addBinding",
53
+ "Runtime.disable",
54
+ "Runtime.discardConsoleEntries",
55
+ "Runtime.enable",
50
56
  "Runtime.evaluate",
51
57
  "Runtime.releaseObject",
58
+ "Runtime.removeBinding",
59
+ "Runtime.runIfWaitingForDebugger",
52
60
  "Target.activateTarget",
53
61
  "Target.attachToTarget",
54
62
  "Target.closeTarget",
package/src/chrome.js CHANGED
@@ -5,6 +5,11 @@ import { UnsupportedOperationError } from "./core.js";
5
5
  import { createProfileApis, chromeTimeToMs } from "./chrome-profile.js";
6
6
 
7
7
  const EXTENSION_BRIDGE_REQUIRED = "requires the extension bridge in standalone OmOWright";
8
+ // CDP has no window-focus state, and document.hasFocus() is no substitute: OmOWright
9
+ // enables focus emulation on every page it attaches to (other automation clients do
10
+ // too), so those pages report focus, background agent windows included (#122).
11
+ const WINDOW_FOCUS_UNKNOWN = "is unavailable in standalone OmOWright: CDP exposes no window focus state; " +
12
+ "track chrome.windows.onFocusChanged through the extension bridge instead";
8
13
  const DOWNLOAD_TIMEOUT_MS = 30_000;
9
14
 
10
15
  function matchUrlPattern(url, pattern) {
@@ -73,10 +78,9 @@ export function createChromeApi(connection, options = {}) {
73
78
  list.push(tab);
74
79
  byWindow.set(tab.windowId, list);
75
80
  }
76
- return [...byWindow.entries()].map(([windowId, windowTabs], index) => {
81
+ return [...byWindow.entries()].map(([windowId, windowTabs]) => {
77
82
  const win = {
78
83
  id: windowId,
79
- focused: index === 0,
80
84
  type: "normal",
81
85
  state: "normal",
82
86
  alwaysOnTop: false,
@@ -99,10 +103,8 @@ export function createChromeApi(connection, options = {}) {
99
103
  if (all.length === 0) throw new Error("No browser window found");
100
104
  return all[0];
101
105
  },
102
- async getLastFocused(queryOptions = {}) {
103
- const all = await collectWindows(queryOptions);
104
- if (all.length === 0) throw new Error("No browser window found");
105
- return all[0];
106
+ async getLastFocused() {
107
+ throw new UnsupportedOperationError(`chrome.windows.getLastFocused ${WINDOW_FOCUS_UNKNOWN}`);
106
108
  },
107
109
  async getAll(queryOptions = {}) {
108
110
  return collectWindows(queryOptions);
package/src/connection.js CHANGED
@@ -7,6 +7,9 @@ import {
7
7
  SessionManager,
8
8
  } from "./core.js";
9
9
  import { acquireSharedConnection, canShareConnection } from "./shared-connections.js";
10
+ import { createAgentTabs, getAgentTabs } from "./agent-tabs.js";
11
+ import { repinViewport } from "./viewport.js";
12
+ import { BrowserContext } from "./browser-context.js";
10
13
 
11
14
  export class TabRepository {
12
15
  #client;
@@ -18,13 +21,37 @@ export class BrowserConnection {
18
21
  #client;
19
22
  #sessions;
20
23
  #pages = new Map();
24
+ #contexts = new Map();
21
25
  #storageRoot;
26
+ #popups = new Map();
27
+ #popupTargets = new Map();
28
+ #attachingPopups = new Map();
29
+ #ownedPopups = new Set();
30
+ #popupOff = [];
22
31
 
23
32
  constructor(client, options = {}) {
24
33
  this.#client = client;
25
34
  this.#sessions = new SessionManager(client);
26
35
  this.tabs = new TabRepository(client);
27
36
  this.#storageRoot = path.resolve(options.storageRoot ?? process.cwd());
37
+ this.#popupOff.push(client.on("Target.targetCreated", ({ targetInfo }) => {
38
+ if (targetInfo?.type !== "page" || !this.#acceptsPopup(targetInfo.openerId)) return;
39
+ // Target discovery and Page.windowOpen are independently dispatched. Keep
40
+ // the target's opener identity even when discovery wins that race.
41
+ const targets = this.#popupTargets.get(targetInfo.openerId) ?? [];
42
+ targets.push({ targetId: targetInfo.targetId });
43
+ this.#popupTargets.set(targetInfo.openerId, targets);
44
+ this.#matchPopups(targetInfo.openerId);
45
+ }));
46
+ this.#popupOff.push(client.on("Target.targetDestroyed", ({ targetId }) => {
47
+ this.#ownedPopups.delete(targetId);
48
+ const error = Error("Popup closed before attachment completed");
49
+ this.#attachingPopups.get(targetId)?.reject(error);
50
+ for (const targets of this.#popupTargets.values()) {
51
+ const target = targets.find(target => target.targetId === targetId);
52
+ if (target) target.error = error;
53
+ }
54
+ }));
28
55
  }
29
56
 
30
57
  async initialize() {
@@ -44,8 +71,39 @@ export class BrowserConnection {
44
71
  async listTargets() { return this.tabs.listTargets(); }
45
72
 
46
73
  async newTab(url = "about:blank") {
47
- const { createAgentTabs } = await import("./agent-tabs.js");
48
- return (await createAgentTabs(this).create(url)).page;
74
+ return (await (getAgentTabs(this) ?? createAgentTabs(this)).create(url)).page;
75
+ }
76
+
77
+ #acceptsPopup(openerId) {
78
+ return !!getAgentTabs(this)?.get(openerId) &&
79
+ this.#pages.get(openerId)?.page.events.listenerCount("popup") > 0;
80
+ }
81
+
82
+ #matchPopups(openerId) {
83
+ const targets = this.#popupTargets.get(openerId);
84
+ const queue = this.#popups.get(openerId);
85
+ while (targets?.length && queue?.length) {
86
+ const target = targets.shift();
87
+ const pending = queue.shift();
88
+ if (target.error) pending.reject(target.error);
89
+ else {
90
+ this.#attachingPopups.set(target.targetId, pending);
91
+ this.#ownedPopups.add(target.targetId);
92
+ pending.operation = this.#attachPopup(target.targetId, pending).catch(pending.reject).finally(() => {
93
+ this.#attachingPopups.delete(target.targetId);
94
+ });
95
+ }
96
+ }
97
+ if (!targets?.length) this.#popupTargets.delete(openerId);
98
+ if (!queue?.length) this.#popups.delete(openerId);
99
+ }
100
+
101
+ async #attachPopup(targetId, pending) {
102
+ const tabs = getAgentTabs(this) ?? createAgentTabs(this);
103
+ const { page } = await tabs.adopt(targetId);
104
+ page.popupMetadata = Object.freeze(pending.metadata);
105
+ await page.waitForLoadState("interactive");
106
+ pending.resolve(page);
49
107
  }
50
108
 
51
109
  async attachPage(targetId) {
@@ -57,6 +115,13 @@ export class BrowserConnection {
57
115
  const entry = { frames, page: null };
58
116
  const host = this.#createPageHost(targetId, entry);
59
117
  const page = new OmOPage(this.#client, frames, targetId, sessionId, host);
118
+ const { targetInfo } = await this.#client.send("Target.getTargetInfo", { targetId });
119
+ const contextId = targetInfo.browserContextId;
120
+ if (!this.#contexts.has(contextId)) this.#contexts.set(contextId, new BrowserContext(this, contextId));
121
+ const context = this.#contexts.get(contextId);
122
+ page.context = () => context;
123
+ for (const frame of frames.frames.values()) context.trackOrigin(frame.url);
124
+ page.on("framenavigated", frame => context.trackOrigin(frame.url));
60
125
  entry.page = page;
61
126
  this.#pages.set(targetId, entry);
62
127
  return page;
@@ -68,6 +133,11 @@ export class BrowserConnection {
68
133
  extensionBridgeRoute: {},
69
134
  page: null,
70
135
  resolvePageSession: (id, preferred) => this.#sessions.resolvePageSession(id, preferred),
136
+ setViewportSize: async size => {
137
+ const tabs = getAgentTabs(this);
138
+ if (tabs?.get(targetId)) await tabs.repin(targetId, size);
139
+ else await repinViewport(entry.page, size);
140
+ },
71
141
  resolvePath: value => path.resolve(this.#storageRoot, value),
72
142
  ensurePath: async value => {
73
143
  const resolved = path.resolve(this.#storageRoot, value);
@@ -76,6 +146,16 @@ export class BrowserConnection {
76
146
  },
77
147
  registerReadableDownload: value => value,
78
148
  isReadableDownload: () => false,
149
+ resolvePopup: async metadata => {
150
+ if (!this.#acceptsPopup(targetId)) return;
151
+ const queue = this.#popups.get(targetId) ?? [];
152
+ const promise = new Promise((resolve, reject) => queue.push({
153
+ resolve, reject, metadata: { url: metadata.url, windowName: metadata.windowName },
154
+ }));
155
+ this.#popups.set(targetId, queue);
156
+ this.#matchPopups(targetId);
157
+ return promise;
158
+ },
79
159
  openPopupTab: async () => { throw Error("Popup tab control requires the extension bridge"); },
80
160
  closeTab: async (_page, options = {}) => {
81
161
  if (options.runBeforeUnload) {
@@ -91,6 +171,19 @@ export class BrowserConnection {
91
171
  }
92
172
 
93
173
  async close() {
174
+ for (const off of this.#popupOff) off();
175
+ for (const queue of this.#popups.values()) {
176
+ for (const pending of queue) pending.reject(Error("Browser connection closed"));
177
+ }
178
+ this.#popups.clear();
179
+ this.#popupTargets.clear();
180
+ for (const pending of this.#attachingPopups.values()) pending.reject(Error("Browser connection closed"));
181
+ await Promise.all([...this.#attachingPopups.values()].map(pending => pending.operation));
182
+ const tabs = getAgentTabs(this);
183
+ if (tabs) {
184
+ await Promise.all([...this.#ownedPopups].filter(id => tabs.get(id)).map(id => tabs.close(id)));
185
+ await tabs.dispose({ closeOwned: false });
186
+ }
94
187
  for (const [targetId, entry] of [...this.#pages]) {
95
188
  await entry.page.dispose().catch(() => {});
96
189
  await entry.frames.dispose().catch(() => {});
@@ -99,6 +192,12 @@ export class BrowserConnection {
99
192
  await this.#sessions.dispose();
100
193
  await this.#client.close();
101
194
  }
195
+
196
+ // `await using browser = await connect(...)` closes the connection when the
197
+ // scope ends, also on a throw, so an agent script exits on its own (#244).
198
+ async [Symbol.asyncDispose]() {
199
+ await this.close();
200
+ }
102
201
  }
103
202
 
104
203
  // The browser's WebSocket URL carries its GUID: a ws:// URL is one already, an
@@ -0,0 +1,12 @@
1
+ export function subscribeConsoleEvents(page) {
2
+ return page.cdp.on("Runtime.consoleAPICalled", (event, metadata) => {
3
+ if (!metadata.sessionId || !page.frameManager.hasSession(metadata.sessionId)) return;
4
+ const text = (event.args ?? []).map(arg => {
5
+ if (arg.unserializableValue !== undefined) return arg.unserializableValue;
6
+ if (arg.value !== undefined) return typeof arg.value === "string" ? arg.value : String(arg.value);
7
+ return arg.description ?? arg.type;
8
+ }).join(" ");
9
+ page.events.emit("console", { type: () => event.type, text: () => text })
10
+ .catch(error => console.warn("[console] page event listener failed", error));
11
+ });
12
+ }
package/src/cookies.js CHANGED
@@ -1,3 +1,13 @@
1
+ export function cookieToCdp(cookie) {
2
+ const { name, value, url, domain, path, httpOnly, secure, sameSite } = cookie;
3
+ const out = { name, value, url, domain, path, httpOnly, secure, sameSite };
4
+ if (cookie.expires !== undefined && cookie.expires !== -1) out.expires = cookie.expires;
5
+ if (cookie.partitionKey !== undefined) {
6
+ out.partitionKey = { topLevelSite: cookie.partitionKey, hasCrossSiteAncestor: true };
7
+ }
8
+ return out;
9
+ }
10
+
1
11
  export function sanitizeCookies(cookies) {
2
12
  const byKey = new Map();
3
13
  for (const cookie of cookies) {
@@ -25,5 +35,5 @@ export function sanitizeCookies(cookies) {
25
35
  }
26
36
 
27
37
  export async function injectCookies(page, cookies) {
28
- await page._sendToTarget("Network.setCookies", { cookies: sanitizeCookies(cookies) });
38
+ await page._sendToTarget("Network.setCookies", { cookies: sanitizeCookies(cookies).map(cookieToCdp) });
29
39
  }