@capybara-hq/plugin-browser 0.1.0-rc.0 → 0.1.0-rc.2

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.0",
4
+ "version": "0.1.0-rc.2",
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.0",
20
+ "version": "0.1.0-rc.2",
21
21
  "sdk": "^0.1.0-rc.69",
22
22
  "provides": [],
23
23
  "requires": [],
package/dist/index.mjs CHANGED
@@ -859,7 +859,7 @@ function registerBrowserTools(ctx, deps) {
859
859
  // src/index.ts
860
860
  var index_default = defineExtension({
861
861
  name: "browser",
862
- version: "0.1.0-rc.0",
862
+ version: "0.1.0-rc.2",
863
863
  sdk: "^0.1.0-rc.69",
864
864
  provides: [],
865
865
  ui: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-browser",
3
- "version": "0.1.0-rc.0",
3
+ "version": "0.1.0-rc.2",
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",
@@ -434,6 +434,11 @@ var BrowserSession = class {
434
434
  /** Downloads in progress, cancelled together when their bytes pass the cap. */
435
435
  activeDownloads = /* @__PURE__ */ new Set();
436
436
  downloadPoll;
437
+ /**
438
+ * Files of downloads cancelled at the cap: Playwright removes them later, and until then they
439
+ * do not count toward the cap of the downloads that follow.
440
+ */
441
+ cancelledTmp = /* @__PURE__ */ new Set();
437
442
  pages = /* @__PURE__ */ new Map();
438
443
  ids = /* @__PURE__ */ new WeakMap();
439
444
  titles = /* @__PURE__ */ new Map();
@@ -682,19 +687,24 @@ var BrowserSession = class {
682
687
  this.downloadPoll = void 0;
683
688
  if (this.activeDownloads.size === 0) return;
684
689
  let bytes = 0;
690
+ let names = [];
685
691
  const dir = this.downloadsTmp;
686
692
  if (dir !== void 0) {
687
693
  try {
688
- for (const f of readdirSync(dir)) {
689
- try {
690
- bytes += statSync(join(dir, f)).size;
691
- } catch {
692
- }
693
- }
694
+ names = readdirSync(dir);
694
695
  } catch {
695
696
  }
697
+ for (const f of this.cancelledTmp) if (!names.includes(f)) this.cancelledTmp.delete(f);
698
+ for (const f of names) {
699
+ if (this.cancelledTmp.has(f)) continue;
700
+ try {
701
+ bytes += statSync(join(dir, f)).size;
702
+ } catch {
703
+ }
704
+ }
696
705
  }
697
706
  if (bytes > this.downloadMaxBytes) {
707
+ for (const f of names) this.cancelledTmp.add(f);
698
708
  for (const d of this.activeDownloads) {
699
709
  this.note(
700
710
  `The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
@@ -1280,21 +1290,27 @@ async function loadPlaywright(browsersPath) {
1280
1290
  loaded = { browsersPath, pw: pw.default ?? pw };
1281
1291
  return loaded.pw;
1282
1292
  }
1283
- async function ensureChromium(browsersPath) {
1293
+ async function headlessShell(browsersPath) {
1284
1294
  await loadPlaywright(browsersPath);
1285
1295
  const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
1286
1296
  const registry = (mod.registry ?? mod.default?.registry)?.registry;
1287
1297
  if (registry === void 0) throw new Error("playwright-core has no browser registry");
1288
1298
  const exe = registry.findExecutable("chromium-headless-shell");
1289
1299
  if (exe === void 0) throw new Error("playwright-core does not know chromium-headless-shell");
1290
- const path = exe.executablePath();
1291
- if (path !== void 0 && existsSync(path)) return path;
1292
- await registry.install([exe], { gc: false });
1293
- const installed = exe.executablePath();
1294
- if (installed === void 0 || !existsSync(installed)) {
1300
+ const executablePath = exe.executablePath();
1301
+ if (executablePath === void 0 || exe.directory === void 0)
1302
+ throw new Error("playwright-core has no chromium-headless-shell for this platform");
1303
+ return { registry, exe, executablePath, directory: exe.directory };
1304
+ }
1305
+ async function ensureChromium(browsersPath) {
1306
+ const { registry, exe, executablePath, directory } = await headlessShell(browsersPath);
1307
+ const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
1308
+ if (marked && existsSync(executablePath)) return executablePath;
1309
+ await registry.install([exe], { gc: false, force: marked });
1310
+ if (!existsSync(executablePath)) {
1295
1311
  throw new Error("the Chromium download finished without an executable");
1296
1312
  }
1297
- return installed;
1313
+ return executablePath;
1298
1314
  }
1299
1315
  async function launchChromium(plan) {
1300
1316
  const executablePath = await ensureChromium(plan.browsersPath);
@@ -1310,6 +1326,32 @@ async function launchChromium(plan) {
1310
1326
  ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
1311
1327
  });
1312
1328
  }
1329
+ async function browserProcessId(ctx) {
1330
+ const browser = ctx.browser();
1331
+ if (browser === null) return void 0;
1332
+ try {
1333
+ const cdp = await browser.newBrowserCDPSession();
1334
+ try {
1335
+ const info = await cdp.send("SystemInfo.getProcessInfo");
1336
+ return info.processInfo.find((p) => p.type === "browser")?.id;
1337
+ } finally {
1338
+ await cdp.detach().catch(() => void 0);
1339
+ }
1340
+ } catch {
1341
+ return void 0;
1342
+ }
1343
+ }
1344
+ function killChromium(pid) {
1345
+ if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return;
1346
+ try {
1347
+ process.kill(-pid, "SIGKILL");
1348
+ } catch {
1349
+ try {
1350
+ process.kill(pid, "SIGKILL");
1351
+ } catch {
1352
+ }
1353
+ }
1354
+ }
1313
1355
 
1314
1356
  // daemon/session-file.ts
1315
1357
  import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
@@ -1734,6 +1776,7 @@ var ViewerSession = class {
1734
1776
 
1735
1777
  // daemon/main.ts
1736
1778
  var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
1779
+ var BROWSER_CLOSE_GRACE_MS = 3e3;
1737
1780
  var enc = new TextEncoder();
1738
1781
  var dec = new TextDecoder();
1739
1782
  var REQUEST_OPS = /* @__PURE__ */ new Set([
@@ -1813,14 +1856,55 @@ async function startDaemon(opts) {
1813
1856
  if (saved?.handoff !== void 0)
1814
1857
  state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
1815
1858
  const launch = opts.launch ?? launchChromium;
1859
+ const closeGraceMs = opts.browserCloseGraceMs ?? BROWSER_CLOSE_GRACE_MS;
1816
1860
  let current;
1861
+ let running;
1817
1862
  let restored = false;
1863
+ function within(value, ms) {
1864
+ let timer;
1865
+ return Promise.race([
1866
+ value,
1867
+ new Promise((r) => {
1868
+ timer = clock.schedule(() => r(void 0), ms);
1869
+ })
1870
+ ]).finally(() => clock.cancel(timer));
1871
+ }
1818
1872
  function browser() {
1819
1873
  if (current !== void 0) return current;
1874
+ if (closing) return Promise.reject(new Error("The browser daemon is stopping."));
1820
1875
  const starting = launch(plan).then(async (ctx) => {
1876
+ let pid;
1877
+ let failed = false;
1878
+ try {
1879
+ return await sessionOn(
1880
+ ctx,
1881
+ (id) => {
1882
+ pid = id;
1883
+ },
1884
+ () => failed
1885
+ );
1886
+ } catch (e) {
1887
+ failed = true;
1888
+ await closeOrKill(ctx.close(), () => pid);
1889
+ throw e;
1890
+ }
1891
+ });
1892
+ current = starting;
1893
+ starting.catch(() => {
1894
+ if (current === starting) current = void 0;
1895
+ if (running?.launch === starting) running = void 0;
1896
+ });
1897
+ return starting;
1898
+ async function sessionOn(ctx, setPid, failed) {
1899
+ let gone = false;
1821
1900
  ctx.on("close", () => {
1822
- if (!closing) opts.onBrowserGone?.();
1901
+ gone = true;
1902
+ if (running?.launch === starting) running = void 0;
1903
+ if (!closing && !failed()) opts.onBrowserGone?.();
1823
1904
  });
1905
+ const pid = await within(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
1906
+ setPid(pid);
1907
+ if (!gone) running = { launch: starting, pid };
1824
1908
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
1825
1909
  const session = new BrowserSession(ctx, {
1826
1910
  proxy: plan.proxy,
@@ -1830,20 +1914,28 @@ async function startDaemon(opts) {
1830
1914
  downloadMaxBytes: downloadMaxBytes(opts.env),
1831
1915
  ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
1832
1916
  });
1833
- if (!restored) {
1917
+ if (!restored && !closing) {
1834
1918
  restored = true;
1835
1919
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
1836
1920
  }
1837
- const save = () => sessionFile.save(session, () => state.handoff);
1838
- session.on(save);
1839
- state.onChange(save);
1921
+ if (!closing) {
1922
+ const save = () => sessionFile.save(session, () => state.handoff);
1923
+ session.on(save);
1924
+ state.onChange(save);
1925
+ }
1840
1926
  return session;
1841
- });
1842
- current = starting;
1843
- starting.catch(() => {
1844
- if (current === starting) current = void 0;
1845
- });
1846
- return starting;
1927
+ }
1928
+ }
1929
+ async function closeOrKill(closingBrowser, pid) {
1930
+ const done = closingBrowser.then(
1931
+ () => true,
1932
+ () => true
1933
+ );
1934
+ if (await within(done, closeGraceMs) === true) return;
1935
+ const id = pid();
1936
+ if (id === void 0) return;
1937
+ killChromium(id);
1938
+ await within(done, closeGraceMs);
1847
1939
  }
1848
1940
  async function launchFailure(e) {
1849
1941
  const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
@@ -1864,6 +1956,17 @@ async function startDaemon(opts) {
1864
1956
  `The browser could not start in the device: ${cause}. The next browser call tries again.`
1865
1957
  );
1866
1958
  }
1959
+ async function stopBrowser() {
1960
+ const starting = current;
1961
+ if (starting === void 0) return;
1962
+ await closeOrKill(
1963
+ starting.then(
1964
+ (session) => session.close(),
1965
+ () => void 0
1966
+ ),
1967
+ () => running?.launch === starting ? running.pid : void 0
1968
+ );
1969
+ }
1867
1970
  const ready = browser().then(() => void 0);
1868
1971
  ready.catch(() => void 0);
1869
1972
  async function handoffOp(req) {
@@ -2009,8 +2112,7 @@ async function startDaemon(opts) {
2009
2112
  server.close(() => r());
2010
2113
  for (const s of sockets) s.destroy();
2011
2114
  });
2012
- const session = await current?.catch(() => void 0);
2013
- await session?.close();
2115
+ await stopBrowser();
2014
2116
  if (existsSync2(opts.socketPath)) {
2015
2117
  try {
2016
2118
  unlinkSync(opts.socketPath);