@capybara-hq/plugin-browser 0.1.0-rc.14 → 0.1.0-rc.15

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "name": "browser",
4
- "version": "0.1.0-rc.14",
4
+ "version": "0.1.0-rc.15",
5
5
  "publisher": "Capybara",
6
6
  "description": {
7
7
  "en": "A real browser in the conversation owner's device for agents: navigate, read and act on pages through tools, with a live view in the conversation panel and takeover by the person",
@@ -17,7 +17,7 @@
17
17
  "entry": "./dist/index.mjs",
18
18
  "manifest": {
19
19
  "name": "browser",
20
- "version": "0.1.0-rc.14",
20
+ "version": "0.1.0-rc.15",
21
21
  "sdk": "^0.1.0-rc.83",
22
22
  "provides": [],
23
23
  "requires": [],
package/dist/index.mjs CHANGED
@@ -1514,7 +1514,7 @@ function registerBrowserTools(ctx, deps) {
1514
1514
  // src/index.ts
1515
1515
  var index_default = defineExtension({
1516
1516
  name: "browser",
1517
- version: "0.1.0-rc.14",
1517
+ version: "0.1.0-rc.15",
1518
1518
  sdk: "^0.1.0-rc.83",
1519
1519
  provides: [],
1520
1520
  ui: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-browser",
3
- "version": "0.1.0-rc.14",
3
+ "version": "0.1.0-rc.15",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "A real browser in the person's device for agents: navigate, read and act on pages through tools, with a live view in the conversation and takeover by the person",
@@ -175,6 +175,8 @@ import { basename, extname, join, sep } from "node:path";
175
175
 
176
176
  // daemon/protocol.ts
177
177
  var ROLL_CHECK_REQUEST = '{"capybara":"roll-check"}';
178
+ var BROWSER_CRASHED_MESSAGE = "The browser in the device stopped unexpectedly while this ran (it crashed). It starts again on the next browser call, with this conversation's tabs reopened; call browser_snapshot to see the page, and retry if the action did not happen.";
179
+ var BROWSER_RESTARTED_NOTE = "The browser in the device stopped unexpectedly (it crashed) and was started again: this conversation's tabs were reopened at their last addresses, and anything typed into them but not submitted is gone.";
178
180
  var CONVERSATION_DELETED_MESSAGE = "This conversation was deleted; its browser tabs are closed.";
179
181
  var VIEWPORT = { width: 1280, height: 800 };
180
182
  var VIEWPORT_PROFILES = {
@@ -1259,6 +1261,8 @@ var MAX_URL_CHARS = 2048;
1259
1261
  var MAX_DIALOG_CHARS = 4096;
1260
1262
  var DEFAULT_WAIT_MS = 1e4;
1261
1263
  var MAX_UNREPORTED = 20;
1264
+ var RESTORE_NAV_WAIT_MS = 1e4;
1265
+ var LOST_TAB_WINDOW_MS = 5e3;
1262
1266
  var TAKEN_OVER_MESSAGE = "The user is controlling the browser; call wait or handoff.";
1263
1267
  function clip(s, max) {
1264
1268
  return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}\u2026`;
@@ -1778,6 +1782,12 @@ var BrowserSession = class {
1778
1782
  watches;
1779
1783
  /** Short download waits: resolved with the saved path when a download of `conv` is saved. */
1780
1784
  downloadWaiters = /* @__PURE__ */ new Set();
1785
+ /** The restore navigation of each restored tab, until it settles (see restoredTabsOf). */
1786
+ restoring = /* @__PURE__ */ new Map();
1787
+ /** Pages the session closes itself (a tab close, a popup past a cap): never "lost". */
1788
+ closedOnPurpose = /* @__PURE__ */ new WeakSet();
1789
+ /** Owned tabs that closed without the session closing them, newest last (see lostTabs). */
1790
+ lost = [];
1781
1791
  /** The dialog each tab holds until answered (one per tab: JS dialogs are modal per page). */
1782
1792
  held = /* @__PURE__ */ new Map();
1783
1793
  dialogSeq = 0;
@@ -1960,6 +1970,31 @@ var BrowserSession = class {
1960
1970
  };
1961
1971
  });
1962
1972
  }
1973
+ recordLost(o, id, page) {
1974
+ const url = page.url();
1975
+ if (!/^https?:\/\//i.test(url)) return;
1976
+ this.lost.push({
1977
+ url,
1978
+ owner: o.owner,
1979
+ root: o.root,
1980
+ active: this.activeOf.get(o.owner) === id,
1981
+ at: this.clock.now()
1982
+ });
1983
+ if (this.lost.length > MAX_TABS) this.lost.shift();
1984
+ }
1985
+ /**
1986
+ * The owned http(s) tabs that closed without the session closing them in the last
1987
+ * {@link LOST_TAB_WINDOW_MS}, in the order they closed: after a crash, the tabs the browser had.
1988
+ */
1989
+ lostTabs() {
1990
+ const since = this.clock.now() - LOST_TAB_WINDOW_MS;
1991
+ return this.lost.filter((t) => t.at >= since).map((t) => ({ ...t }));
1992
+ }
1993
+ /** Closes a tab on purpose (the agent's or a viewer's close). */
1994
+ async closeTab(page) {
1995
+ this.closedOnPurpose.add(page);
1996
+ await page.close();
1997
+ }
1963
1998
  /** Makes a tab the conversation's active tab (it must own it). */
1964
1999
  setActive(conversationId, tabId) {
1965
2000
  if (this.owners.get(tabId)?.owner !== conversationId) return;
@@ -2175,9 +2210,37 @@ var BrowserSession = class {
2175
2210
  target = normalizeUrl(url);
2176
2211
  } catch {
2177
2212
  }
2178
- if (target !== void 0) void this.viewerNav(page, { url: target });
2213
+ if (target !== void 0) {
2214
+ const nav = this.viewerNav(page, { url: target }).finally(() => {
2215
+ if (this.restoring.get(id) === nav) this.restoring.delete(id);
2216
+ });
2217
+ this.restoring.set(id, nav);
2218
+ }
2179
2219
  return id;
2180
2220
  }
2221
+ /**
2222
+ * Waits, at most {@link RESTORE_NAV_WAIT_MS}, for the restore navigations of the conversation's
2223
+ * tabs: its first request after a restart (or a crash) must not race them (a navigation of its
2224
+ * own would be interrupted by the restore's). Other conversations' tabs are not waited for.
2225
+ */
2226
+ async restoredTabsOf(conv) {
2227
+ const navs = this.tabsOf(conv).map((id) => this.restoring.get(id)).filter((n) => n !== void 0);
2228
+ if (navs.length === 0) return;
2229
+ await this.boundedWait(Promise.all(navs), RESTORE_NAV_WAIT_MS);
2230
+ }
2231
+ async boundedWait(p, ms) {
2232
+ let timer;
2233
+ await Promise.race([
2234
+ p.then(
2235
+ () => void 0,
2236
+ () => void 0
2237
+ ),
2238
+ new Promise((r) => {
2239
+ timer = this.clock.schedule(r, ms);
2240
+ })
2241
+ ]);
2242
+ this.clock.cancel(timer);
2243
+ }
2181
2244
  /**
2182
2245
  * Closes an idle conversation's tabs (except those a park pins) and forgets what the session
2183
2246
  * keeps for it.
@@ -2312,6 +2375,9 @@ var BrowserSession = class {
2312
2375
  });
2313
2376
  page.on("popup", (p) => this.onPopup(page, p));
2314
2377
  page.on("close", () => {
2378
+ const lostOwner = this.owners.get(id);
2379
+ if (lostOwner !== void 0 && !this.closing.has(id) && !this.closedOnPurpose.has(page))
2380
+ this.recordLost(lostOwner, id, page);
2315
2381
  this.pendingNavs.delete(page);
2316
2382
  this.pages.delete(id);
2317
2383
  this.closing.delete(id);
@@ -2345,6 +2411,7 @@ var BrowserSession = class {
2345
2411
  const o = this.owners.get(this.tabIdOf(opener));
2346
2412
  if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
2347
2413
  const closeIt = (why) => {
2414
+ this.closedOnPurpose.add(popup);
2348
2415
  popup.close().catch(() => void 0);
2349
2416
  this.noteTo(
2350
2417
  o.owner,
@@ -2524,10 +2591,56 @@ var BrowserSession = class {
2524
2591
  this.signIn(origin, m.username, m.password);
2525
2592
  for (const [id, x] of [...this.held])
2526
2593
  if (x.view.kind === "auth" && x.view.origin === origin) this.clearHeld(id);
2527
- this.noteTo(h.owner.owner, `The user signed in to ${origin} (HTTP auth).`);
2528
- const page = this.pageById(h.view.tabId);
2529
- if (page !== void 0)
2530
- await this.viewerNav(page, h.atUrl === void 0 ? { action: "reload" } : { url: h.atUrl });
2594
+ const tabId = h.view.tabId;
2595
+ const page = this.pageById(tabId);
2596
+ if (page === void 0) {
2597
+ this.authNote(
2598
+ h.owner.owner,
2599
+ origin,
2600
+ "the user entered credentials, but the tab closed before the site answered."
2601
+ );
2602
+ return;
2603
+ }
2604
+ await this.viewerNav(page, h.atUrl === void 0 ? { action: "reload" } : { url: h.atUrl });
2605
+ this.authNote(h.owner.owner, origin, this.authOutcome(page, tabId, origin));
2606
+ }
2607
+ /**
2608
+ * What the site answered the credentials the person entered, after the tab loaded again with
2609
+ * them: rejected when the tab holds a new auth dialog for the origin, its document answered
2610
+ * 401 / 407 or the 401 to a signed request dropped them; accepted when the tab shows a document
2611
+ * of the origin with another status; unknown otherwise (the load failed or went elsewhere).
2612
+ */
2613
+ authOutcome(page, tabId, origin) {
2614
+ const again = this.held.get(tabId);
2615
+ if (again?.view.kind === "auth" && again.view.origin === origin)
2616
+ return `the site rejected the credentials the user entered and asks to sign in again (dialog ${again.view.id}); ask the user to sign in again with browser_handoff, or dismiss the dialog.`;
2617
+ const status = this.docStatus.get(tabId);
2618
+ if (status === 401 || status === 407 || !this.credentials.has(origin))
2619
+ return `the site rejected the credentials the user entered${status === void 0 ? "" : ` (status ${status})`}; ask the user to sign in again with browser_handoff.`;
2620
+ if (status !== void 0 && !page.isClosed() && originOf(page.url()) === origin)
2621
+ return `the site accepted the credentials the user entered (status ${status}).`;
2622
+ return "the user entered credentials, but the page did not load, so whether the site accepted them is unknown; call browser_snapshot to check.";
2623
+ }
2624
+ /**
2625
+ * The outcome note of a sign-in to `origin` for a conversation: it replaces the outcome of an
2626
+ * earlier attempt for the same origin that no reply carried yet (each attempt says only what
2627
+ * the site answered last). Never carries the credentials.
2628
+ */
2629
+ authNote(conversationId, origin, outcome) {
2630
+ const prefix = `HTTP sign-in to ${origin}: `;
2631
+ const stale = (n) => n.startsWith(prefix);
2632
+ const waiting = this.unreported.get(conversationId);
2633
+ if (waiting !== void 0) {
2634
+ const kept = waiting.filter((n) => !stale(n));
2635
+ if (kept.length === 0) this.unreported.delete(conversationId);
2636
+ else this.unreported.set(conversationId, kept);
2637
+ }
2638
+ for (const c of this.collectors) {
2639
+ if (c.conv !== conversationId) continue;
2640
+ const kept = c.notes.filter((n) => !stale(n));
2641
+ c.notes.splice(0, c.notes.length, ...kept);
2642
+ }
2643
+ this.noteTo(conversationId, `${prefix}${outcome}`);
2531
2644
  }
2532
2645
  // ---- HTTP Basic auth (dialogs spec §4)
2533
2646
  /**
@@ -3278,6 +3391,7 @@ var BrowserSession = class {
3278
3391
  let reply;
3279
3392
  try {
3280
3393
  await this.viewportGate;
3394
+ await this.restoredTabsOf(conv);
3281
3395
  const beside = req.op === "wait" || req.op === "watch_end" || req.op === "dialog" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
3282
3396
  this.refuseIfBlocked(req);
3283
3397
  const out = await (beside ? req.op === "wait" ? this.raceDialog(conv, req.op, () => this.exec(req)) : this.exec(req) : this.serial(conv, () => {
@@ -3843,7 +3957,7 @@ var BrowserSession = class {
3843
3957
  }
3844
3958
  case "close": {
3845
3959
  const page = this.ownTab(conv, req.tabId);
3846
- await page.close();
3960
+ await this.closeTab(page);
3847
3961
  return {};
3848
3962
  }
3849
3963
  case "adopt": {
@@ -5060,7 +5174,7 @@ var ViewerSession = class {
5060
5174
  else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
5061
5175
  else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
5062
5176
  this.concern(m.tabId);
5063
- await this.browser.tabById(m.tabId).close();
5177
+ await this.browser.closeTab(this.browser.tabById(m.tabId));
5064
5178
  }
5065
5179
  } catch {
5066
5180
  }
@@ -5754,6 +5868,9 @@ async function startDaemon(opts) {
5754
5868
  let current;
5755
5869
  let running;
5756
5870
  let restored = false;
5871
+ let crashNotes = /* @__PURE__ */ new Set();
5872
+ const crashed = /* @__PURE__ */ new WeakSet();
5873
+ const streams = /* @__PURE__ */ new Set();
5757
5874
  function within2(value, ms) {
5758
5875
  let timer;
5759
5876
  return Promise.race([
@@ -5763,6 +5880,23 @@ async function startDaemon(opts) {
5763
5880
  })
5764
5881
  ]).finally(() => clock.cancel(timer));
5765
5882
  }
5883
+ function reopenAfterCrash(lost) {
5884
+ if (lost.length === 0) return;
5885
+ const conversations = [];
5886
+ for (const t of lost) {
5887
+ if (conversations.some((c) => c.id === t.owner)) continue;
5888
+ const active = lost.findLastIndex((x) => x.owner === t.owner && x.active);
5889
+ conversations.push({ id: t.owner, root: t.root, ...active < 0 ? {} : { active } });
5890
+ }
5891
+ saved = {
5892
+ version: SESSION_FILE_VERSION,
5893
+ savedAt: clock.now(),
5894
+ tabs: lost.map((t) => ({ url: t.url, owner: t.owner, root: t.root })),
5895
+ conversations
5896
+ };
5897
+ restored = false;
5898
+ crashNotes = new Set(lost.map((t) => t.owner));
5899
+ }
5766
5900
  function browser() {
5767
5901
  if (current !== void 0) return current;
5768
5902
  if (closing) return Promise.reject(new Error("The browser daemon is stopping."));
@@ -5792,16 +5926,29 @@ async function startDaemon(opts) {
5792
5926
  return starting;
5793
5927
  async function sessionOn(ctx, setPid, failed) {
5794
5928
  let gone = false;
5929
+ let pid;
5930
+ let session;
5931
+ const unlisten = [];
5795
5932
  ctx.on("close", () => {
5796
5933
  gone = true;
5797
5934
  if (running?.launch === starting) running = void 0;
5798
- if (!closing && !failed()) opts.onBrowserGone?.();
5935
+ if (closing || failed()) return;
5936
+ if (current === starting) current = void 0;
5937
+ for (const off of unlisten.splice(0)) off();
5938
+ if (session !== void 0) {
5939
+ crashed.add(session);
5940
+ if (live === session) live = void 0;
5941
+ reopenAfterCrash(session.lostTabs());
5942
+ }
5943
+ if (pid !== void 0) killChromium(pid);
5944
+ for (const s2 of streams) s2.destroy();
5945
+ opts.onBrowserGone?.();
5799
5946
  });
5800
- const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
5947
+ pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
5801
5948
  setPid(pid);
5802
5949
  if (!gone) running = { launch: starting, pid, ctx };
5803
5950
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
5804
- const session = new BrowserSession(ctx, {
5951
+ session = new BrowserSession(ctx, {
5805
5952
  proxy: plan.proxy,
5806
5953
  clock,
5807
5954
  usage: state,
@@ -5815,24 +5962,31 @@ async function startDaemon(opts) {
5815
5962
  ...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
5816
5963
  });
5817
5964
  await session.ready;
5818
- state.onChange(() => {
5819
- if (state.control === "agent") void session.restoreDesktop();
5820
- });
5965
+ const s = session;
5966
+ unlisten.push(
5967
+ state.onChange(() => {
5968
+ if (state.control === "agent") void s.restoreDesktop();
5969
+ })
5970
+ );
5821
5971
  if (plan.shippedDir !== void 0)
5822
5972
  session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
5823
5973
  if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
5824
5974
  session.note(HEADLESS_SHELL_NOTE);
5825
5975
  if (!closing) await restoreCookies(ctx, opts.stateDir);
5976
+ let reopened = false;
5826
5977
  if (!restored && !closing) {
5827
5978
  restored = true;
5828
5979
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
5980
+ reopened = crashNotes.size > 0;
5981
+ for (const conv of crashNotes) session.noteTo(conv, BROWSER_RESTARTED_NOTE);
5982
+ crashNotes = /* @__PURE__ */ new Set();
5829
5983
  }
5830
- if (!closing) {
5831
- const save = () => sessionFile.save(session, state);
5832
- session.on(save);
5833
- state.onChange(save);
5984
+ if (!closing && !gone) {
5985
+ const save = () => sessionFile.save(s, state);
5986
+ unlisten.push(session.on(save), state.onChange(save));
5987
+ if (reopened) save();
5834
5988
  }
5835
- if (!failed()) live = session;
5989
+ if (!failed() && !gone) live = session;
5836
5990
  return session;
5837
5991
  }
5838
5992
  }
@@ -6000,7 +6154,9 @@ async function startDaemon(opts) {
6000
6154
  } catch (e) {
6001
6155
  return launchFailure(e);
6002
6156
  }
6003
- const reply = await session.run(req, { takenOver: () => state.control === "user" });
6157
+ let reply = await session.run(req, { takenOver: () => state.control === "user" });
6158
+ if (!reply.ok && crashed.has(session))
6159
+ reply = { ...fail(BROWSER_CRASHED_MESSAGE), blockedHosts: reply.blockedHosts };
6004
6160
  if (reply.ok) {
6005
6161
  const since = state.takeHandbackNote(req.conversationId);
6006
6162
  if (since !== void 0) reply.userControlledSince = since;
@@ -6019,6 +6175,7 @@ async function startDaemon(opts) {
6019
6175
  let viewerChain = Promise.resolve();
6020
6176
  const end = () => {
6021
6177
  sockets.delete(sock);
6178
+ streams.delete(sock);
6022
6179
  if (viewer !== void 0) {
6023
6180
  const v = viewer;
6024
6181
  viewer = void 0;
@@ -6050,6 +6207,7 @@ async function startDaemon(opts) {
6050
6207
  rootConversationId: ctx.rootConversationId
6051
6208
  };
6052
6209
  const viewerContext = context;
6210
+ streams.add(sock);
6053
6211
  opened = true;
6054
6212
  state.viewerOpened();
6055
6213
  browser().then(
@@ -6195,7 +6353,10 @@ async function main() {
6195
6353
  stateDir,
6196
6354
  env: process.env,
6197
6355
  onIdle: () => stop(0, "idle"),
6198
- onBrowserGone: () => stop(1, "Chromium exited"),
6356
+ // the daemon stays: the next request or viewer launches Chromium again
6357
+ onBrowserGone: () => process.stderr.write(
6358
+ "browser daemon: Chromium exited unexpectedly; relaunched on next use\n"
6359
+ ),
6199
6360
  // installed and sealed: the next start runs the browser read only
6200
6361
  onSealed: () => stop(0, "browser installed and sealed; restart to run it")
6201
6362
  });