@1outres/dsh-bot-connector-browser 0.3.0 → 0.4.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.
package/lib/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // src/index.ts
2
- import { readFile } from "node:fs/promises";
2
+ import { randomBytes } from "node:crypto";
3
+ import { readdir, readFile } from "node:fs/promises";
3
4
 
4
5
  // src/generated/playwright-mcp.json
5
6
  var playwright_mcp_default = {
@@ -1070,7 +1071,7 @@ function parseToolList(value) {
1070
1071
  if (value.nextCursor !== void 0) {
1071
1072
  throw new McpProtocolError("tools/list answered in pages, which the connector does not read");
1072
1073
  }
1073
- return value.tools.map((tool, index) => parseTool(tool, `tool ${index + 1}`));
1074
+ return value.tools.map((tool2, index) => parseTool(tool2, `tool ${index + 1}`));
1074
1075
  }
1075
1076
  function parseCallResult(value) {
1076
1077
  if (!isRecord(value) || !Array.isArray(value.content)) {
@@ -1120,20 +1121,20 @@ function parseGeneratedServer(value) {
1120
1121
  version: record.version,
1121
1122
  server: { name: server.name, version: server.version },
1122
1123
  arguments: record.arguments,
1123
- tools: record.tools.map((tool, index) => parseTool(tool, `generated tool ${index + 1}`))
1124
+ tools: record.tools.map((tool2, index) => parseTool(tool2, `generated tool ${index + 1}`))
1124
1125
  };
1125
1126
  }
1126
1127
  var GENERATED_SERVER = parseGeneratedServer(playwright_mcp_default);
1127
1128
  function offeredTools(tools) {
1128
- return tools.filter((tool) => !NOT_OFFERED.includes(tool.name)).map((tool) => {
1129
- if (!tool.name.startsWith(UPSTREAM_PREFIX)) {
1130
- throw new Error(`Playwright MCP's tool ${tool.name} is not named ${UPSTREAM_PREFIX}\u2026`);
1129
+ return tools.filter((tool2) => !NOT_OFFERED.includes(tool2.name)).map((tool2) => {
1130
+ if (!tool2.name.startsWith(UPSTREAM_PREFIX)) {
1131
+ throw new Error(`Playwright MCP's tool ${tool2.name} is not named ${UPSTREAM_PREFIX}\u2026`);
1131
1132
  }
1132
1133
  return {
1133
- upstream: tool,
1134
- name: tool.name.slice(UPSTREAM_PREFIX.length),
1135
- permission: DISALLOWED.includes(tool.name) ? "disallow" : "allow",
1136
- readOnly: tool.annotations?.readOnlyHint === true
1134
+ upstream: tool2,
1135
+ name: tool2.name.slice(UPSTREAM_PREFIX.length),
1136
+ permission: DISALLOWED.includes(tool2.name) ? "disallow" : "allow",
1137
+ readOnly: tool2.annotations?.readOnlyHint === true
1137
1138
  };
1138
1139
  });
1139
1140
  }
@@ -1145,15 +1146,15 @@ var canonical = (value) => {
1145
1146
  );
1146
1147
  };
1147
1148
  function toolDifferences(expected, listed) {
1148
- const byName = new Map(listed.map((tool) => [tool.name, tool]));
1149
+ const byName = new Map(listed.map((tool2) => [tool2.name, tool2]));
1149
1150
  const differences = [];
1150
- for (const tool of expected) {
1151
- const other = byName.get(tool.name);
1152
- if (other === void 0) differences.push(`${tool.name} is missing`);
1153
- else if (JSON.stringify(canonical(other)) !== JSON.stringify(canonical(tool))) {
1154
- differences.push(`${tool.name} changed`);
1151
+ for (const tool2 of expected) {
1152
+ const other = byName.get(tool2.name);
1153
+ if (other === void 0) differences.push(`${tool2.name} is missing`);
1154
+ else if (JSON.stringify(canonical(other)) !== JSON.stringify(canonical(tool2))) {
1155
+ differences.push(`${tool2.name} changed`);
1155
1156
  }
1156
- byName.delete(tool.name);
1157
+ byName.delete(tool2.name);
1157
1158
  }
1158
1159
  for (const name2 of byName.keys()) differences.push(`${name2} is new`);
1159
1160
  return differences;
@@ -1183,10 +1184,15 @@ var BrowserConnections = class {
1183
1184
  var MCP_DIR = "/opt/dsh-browser/mcp";
1184
1185
  var MCP_SHRINKWRAP = `${MCP_DIR}/npm-shrinkwrap.json`;
1185
1186
  var MCP_CLI = `${MCP_DIR}/node_modules/@playwright/mcp/cli.js`;
1186
- var CDP_ENDPOINT = "http://127.0.0.1:9222";
1187
+ var HELPER_DIR = "/opt/dsh-browser/helper";
1188
+ var FILL_HELPER = `${HELPER_DIR}/dsh-browser-fill.mjs`;
1189
+ var PASSKEY_HELPER = `${HELPER_DIR}/dsh-browser-passkey.mjs`;
1190
+ var CDP_HOST_PORT = "127.0.0.1:9222";
1191
+ var CDP_ENDPOINT = `http://${CDP_HOST_PORT}`;
1187
1192
  var OUTPUT_MAX_BYTES = 256 << 20;
1188
1193
  var outputDir = (user) => `${user.home}/.cache/dsh-browser/output`;
1189
1194
  var stagingDir = (user) => `${user.home}/.cache/dsh-browser/staging`;
1195
+ var helperStagingDir = (user) => `${user.home}/.cache/dsh-browser/helper-staging`;
1190
1196
 
1191
1197
  // src/host/mcp/client.ts
1192
1198
  var McpCallError = class extends Error {
@@ -1411,6 +1417,7 @@ async function readVmUser(environment, signal) {
1411
1417
  }
1412
1418
 
1413
1419
  // src/host/preparation.ts
1420
+ var HELPER_FILE = /^[a-z][a-z0-9-]*\.mjs$/;
1414
1421
  var INSTALL_TIMEOUT_MS = 15 * 6e4;
1415
1422
  function chromeVersion(answer) {
1416
1423
  let parsed;
@@ -1433,9 +1440,9 @@ function createBrowserPreparation(deps) {
1433
1440
  await run(environment, ["rm", "-rf", "--", stage], { signal });
1434
1441
  await run(environment, ["mkdir", "-p", "-m", "0700", "--", stage], { signal });
1435
1442
  const files = [
1436
- ["package.json", deps.installation.packageJson],
1437
- ["npm-shrinkwrap.json", deps.installation.shrinkwrap],
1438
- ["install-mcp.sh", deps.installation.script]
1443
+ ["package.json", deps.installation.mcp.packageJson],
1444
+ ["npm-shrinkwrap.json", deps.installation.mcp.shrinkwrap],
1445
+ ["install-mcp.sh", deps.installation.mcp.script]
1439
1446
  ];
1440
1447
  for (const [name2, data] of files) {
1441
1448
  await environment.writeFile(`${stage}/${name2}`, data, { mode: 420, signal });
@@ -1452,7 +1459,37 @@ function createBrowserPreparation(deps) {
1452
1459
  accept: [0, 1],
1453
1460
  maxOutputBytes: 4 << 20
1454
1461
  });
1455
- return current.exitCode === 0 && current.stdout === decoder.decode(deps.installation.shrinkwrap);
1462
+ return current.exitCode === 0 && current.stdout === decoder.decode(deps.installation.mcp.shrinkwrap);
1463
+ };
1464
+ const helperInstalled = async (context) => {
1465
+ for (const file of deps.installation.helper.files) {
1466
+ const current = await run(context.environment, ["cat", "--", `${HELPER_DIR}/${file.name}`], {
1467
+ signal: context.signal,
1468
+ accept: [0, 1],
1469
+ maxOutputBytes: 1 << 20
1470
+ });
1471
+ if (current.exitCode !== 0 || current.stdout !== decoder.decode(file.data)) return false;
1472
+ }
1473
+ return true;
1474
+ };
1475
+ const installHelper = async (context, user) => {
1476
+ const stage = helperStagingDir(user);
1477
+ const { signal, environment } = context;
1478
+ await run(environment, ["rm", "-rf", "--", stage], { signal });
1479
+ await run(environment, ["mkdir", "-p", "-m", "0700", "--", stage], { signal });
1480
+ for (const file of deps.installation.helper.files) {
1481
+ if (!HELPER_FILE.test(file.name))
1482
+ throw new Error(`vm/helper/${file.name} is not a helper module`);
1483
+ await environment.writeFile(`${stage}/${file.name}`, file.data, { mode: 420, signal });
1484
+ }
1485
+ await environment.writeFile(`${stage}/install-helper.sh`, deps.installation.helper.script, {
1486
+ mode: 420,
1487
+ signal
1488
+ });
1489
+ await run(environment, ["sudo", "-n", "sh", `${stage}/install-helper.sh`, stage, HELPER_DIR], {
1490
+ signal
1491
+ });
1492
+ await run(environment, ["rm", "-rf", "--", stage], { signal });
1456
1493
  };
1457
1494
  const checkTools = async (context, user) => {
1458
1495
  const server = await startServer(
@@ -1485,6 +1522,11 @@ function createBrowserPreparation(deps) {
1485
1522
  progress(`installing Playwright MCP ${deps.generated.version}`);
1486
1523
  await install(context, user);
1487
1524
  }
1525
+ progress("checking the login helpers");
1526
+ if (!await helperInstalled(context)) {
1527
+ progress("installing the login helpers");
1528
+ await installHelper(context, user);
1529
+ }
1488
1530
  progress("checking the desktop's Chrome");
1489
1531
  const answer = await run(
1490
1532
  context.environment,
@@ -1498,6 +1540,246 @@ function createBrowserPreparation(deps) {
1498
1540
  };
1499
1541
  }
1500
1542
 
1543
+ // src/host/vault/failures.ts
1544
+ var TEXTS = {
1545
+ devtools: "the browser's DevTools could not be reached; check that the browser is ready and try again",
1546
+ "not-found": "the marked element is gone (the page changed); take a new browser_snapshot and use its ref",
1547
+ ambiguous: "the element could not be told apart from another; take a new browser_snapshot",
1548
+ "not-editable": "the element is not a text field (an enabled input, textarea or editable element); pick the field's ref",
1549
+ "not-password-field": "a password goes only into a password field (type=password, or autocomplete current-password / new-password)",
1550
+ "not-text": "the value is not text that can be typed",
1551
+ "opaque-origin": "the field is in a frame without a web origin (sandboxed, or not http/https); nothing was filled",
1552
+ "origin-changed": "the page went to another site before the value was entered; nothing was filled",
1553
+ "focus-lost": "the field lost the focus; take a new browser_snapshot to see what the field holds before trying again",
1554
+ rejected: "the browser did not take the passkey",
1555
+ protocol: "the browser's login helper failed",
1556
+ failed: "the browser's login helper failed"
1557
+ };
1558
+ var HelperFailureError = class extends Error {
1559
+ constructor(code) {
1560
+ super(TEXTS[code]);
1561
+ this.code = code;
1562
+ this.name = "HelperFailureError";
1563
+ }
1564
+ code;
1565
+ };
1566
+
1567
+ // src/host/vault/protocol.ts
1568
+ var FAILURES = [
1569
+ "devtools",
1570
+ "not-found",
1571
+ "ambiguous",
1572
+ "not-editable",
1573
+ "not-password-field",
1574
+ "not-text",
1575
+ "opaque-origin",
1576
+ "origin-changed",
1577
+ "focus-lost",
1578
+ "rejected",
1579
+ "protocol",
1580
+ "failed"
1581
+ ];
1582
+ var ENDS = ["used", "expired", "navigated", "closed", "released"];
1583
+ var ORIGIN = /^https?:\/\/[^/\s]{1,260}$/;
1584
+ var ELEMENT = /^(?:input:[a-z]{1,16}|textarea|contenteditable)$/;
1585
+ var HelperProtocolError = class extends Error {
1586
+ constructor(what) {
1587
+ super(`the browser's login helper answered ${what}`);
1588
+ this.name = "HelperProtocolError";
1589
+ }
1590
+ };
1591
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1592
+ var oneKey = (value) => {
1593
+ const keys = Object.keys(value);
1594
+ if (keys.length !== 1) throw new HelperProtocolError("a line that is not one answer");
1595
+ return keys[0];
1596
+ };
1597
+ function parseReply(value) {
1598
+ if (!isRecord3(value)) throw new HelperProtocolError("a line that is not an object");
1599
+ const key = oneKey(value);
1600
+ const body = value[key];
1601
+ switch (key) {
1602
+ case "located": {
1603
+ if (!isRecord3(body) || typeof body.origin !== "string" || !ORIGIN.test(body.origin)) {
1604
+ throw new HelperProtocolError("a location without a web origin");
1605
+ }
1606
+ if (body.element !== void 0 && (typeof body.element !== "string" || !ELEMENT.test(body.element))) {
1607
+ throw new HelperProtocolError("an unknown kind of element");
1608
+ }
1609
+ return {
1610
+ kind: "located",
1611
+ origin: body.origin,
1612
+ ...body.element === void 0 ? {} : { element: body.element }
1613
+ };
1614
+ }
1615
+ case "filled":
1616
+ if (!isRecord3(body) || typeof body.submitted !== "boolean") {
1617
+ throw new HelperProtocolError("a malformed fill");
1618
+ }
1619
+ return { kind: "filled", submitted: body.submitted };
1620
+ case "ready":
1621
+ return { kind: "ready" };
1622
+ case "ended":
1623
+ if (!ENDS.includes(body))
1624
+ throw new HelperProtocolError("an unknown end");
1625
+ return { kind: "ended", reason: body };
1626
+ case "cancelled":
1627
+ return { kind: "cancelled" };
1628
+ case "error":
1629
+ return {
1630
+ kind: "error",
1631
+ code: FAILURES.includes(body) ? body : "failed"
1632
+ };
1633
+ default:
1634
+ throw new HelperProtocolError("an unknown line");
1635
+ }
1636
+ }
1637
+
1638
+ // src/host/vault/helper.ts
1639
+ var MAX_LINE_BYTES = 4096;
1640
+ var NEWLINE2 = 10;
1641
+ var HelperEndedError = class extends Error {
1642
+ constructor() {
1643
+ super("the browser's login helper ended without an answer");
1644
+ this.name = "HelperEndedError";
1645
+ }
1646
+ };
1647
+ async function* lines(stdout) {
1648
+ let buffer = new Uint8Array(0);
1649
+ for await (const chunk of stdout) {
1650
+ const joined = new Uint8Array(buffer.byteLength + chunk.byteLength);
1651
+ joined.set(buffer);
1652
+ joined.set(chunk, buffer.byteLength);
1653
+ buffer = joined;
1654
+ let index = buffer.indexOf(NEWLINE2);
1655
+ while (index >= 0) {
1656
+ yield buffer.slice(0, index);
1657
+ buffer = buffer.slice(index + 1);
1658
+ index = buffer.indexOf(NEWLINE2);
1659
+ }
1660
+ if (buffer.byteLength > MAX_LINE_BYTES) {
1661
+ throw new HelperProtocolError(`a line longer than ${MAX_LINE_BYTES} bytes`);
1662
+ }
1663
+ }
1664
+ }
1665
+ function helperRun(process, kit) {
1666
+ const encoder = new TextEncoder();
1667
+ const decoder = new TextDecoder();
1668
+ const reader = lines(process.stdout);
1669
+ return {
1670
+ done: process.done,
1671
+ async next() {
1672
+ const line = await reader.next();
1673
+ if (line.done === true) throw new HelperEndedError();
1674
+ let value;
1675
+ try {
1676
+ value = JSON.parse(decoder.decode(line.value));
1677
+ } catch {
1678
+ throw new HelperProtocolError("a line that is not JSON");
1679
+ }
1680
+ return parseReply(value);
1681
+ },
1682
+ send: (message) => process.stdin.write(encoder.encode(`${JSON.stringify(message)}
1683
+ `)),
1684
+ async sendSecret(header, secret) {
1685
+ const line = encoder.encode(`${JSON.stringify(header(secret.length))}
1686
+ `);
1687
+ await secret.use(async (bytes) => {
1688
+ const frame = kit.concat([line, bytes]);
1689
+ try {
1690
+ await process.stdin.write(frame);
1691
+ } finally {
1692
+ kit.wipe(frame);
1693
+ }
1694
+ });
1695
+ },
1696
+ end: () => process.stdin.end(),
1697
+ terminate: () => process.terminate()
1698
+ };
1699
+ }
1700
+ async function startHelper(environment, script, signal, kit) {
1701
+ return helperRun(await environment.spawn({ argv: ["node", script], signal }), kit);
1702
+ }
1703
+
1704
+ // src/host/vault/passkeys.ts
1705
+ var PASSKEY_SECONDS = 60;
1706
+ var STEP_TIMEOUT_MS = 3e4;
1707
+ var base64 = (bytes) => Buffer.from(bytes).toString("base64");
1708
+ function passkeySlot(deps) {
1709
+ let current;
1710
+ const release = () => {
1711
+ current?.terminate();
1712
+ current = void 0;
1713
+ };
1714
+ const answer = async (run2) => {
1715
+ const timeout = deps.deadline(STEP_TIMEOUT_MS);
1716
+ const timedOut = new Promise((_, reject) => {
1717
+ timeout.addEventListener("abort", () => reject(new HelperFailureError("failed")), {
1718
+ once: true
1719
+ });
1720
+ });
1721
+ const reply = await Promise.race([run2.next(), timedOut]);
1722
+ if (reply.kind === "error") throw new HelperFailureError(reply.code);
1723
+ return reply;
1724
+ };
1725
+ const drain = async (run2) => {
1726
+ try {
1727
+ for (; ; ) await run2.next();
1728
+ } catch {
1729
+ } finally {
1730
+ if (current === run2) current = void 0;
1731
+ }
1732
+ };
1733
+ const order = (origin, passkey, length) => ({
1734
+ passkey: {
1735
+ origin,
1736
+ rpId: passkey.rpId,
1737
+ credentialId: base64(passkey.credentialId),
1738
+ ...passkey.userHandle === void 0 ? {} : { userHandle: base64(passkey.userHandle) },
1739
+ signCount: passkey.signCount,
1740
+ seconds: PASSKEY_SECONDS,
1741
+ length
1742
+ }
1743
+ });
1744
+ return {
1745
+ release,
1746
+ async locate(mark2) {
1747
+ release();
1748
+ const run2 = await startHelper(deps.environment, PASSKEY_HELPER, deps.signal, deps.kit);
1749
+ current = run2;
1750
+ try {
1751
+ const request = { devtools: CDP_HOST_PORT, mark: mark2 };
1752
+ await run2.send(request);
1753
+ const located = await answer(run2);
1754
+ if (located.kind !== "located") throw new HelperProtocolError("out of order");
1755
+ return {
1756
+ origin: located.origin,
1757
+ async offer(passkey) {
1758
+ const key = passkey.privateKey;
1759
+ try {
1760
+ await run2.sendSecret((length) => order(located.origin, passkey, length), key);
1761
+ const ready = await answer(run2);
1762
+ if (ready.kind !== "ready") throw new HelperProtocolError("out of order");
1763
+ void drain(run2);
1764
+ } catch (error) {
1765
+ if (current === run2) release();
1766
+ throw error;
1767
+ } finally {
1768
+ key.wipe();
1769
+ }
1770
+ },
1771
+ cancel() {
1772
+ if (current === run2) release();
1773
+ }
1774
+ };
1775
+ } catch (error) {
1776
+ if (current === run2) release();
1777
+ throw error;
1778
+ }
1779
+ }
1780
+ };
1781
+ }
1782
+
1501
1783
  // src/host/session.ts
1502
1784
  function browserAttachment(deps) {
1503
1785
  return {
@@ -1511,10 +1793,17 @@ function browserAttachment(deps) {
1511
1793
  deps
1512
1794
  );
1513
1795
  deps.connections.connected(context.bot.id);
1796
+ const passkeys = passkeySlot({
1797
+ environment: context.environment,
1798
+ signal: context.signal,
1799
+ kit: deps.kit,
1800
+ deadline: deps.deadline
1801
+ });
1514
1802
  return {
1515
- value: server,
1803
+ value: { mcp: server, passkeys },
1516
1804
  ended: server.ended,
1517
1805
  async dispose() {
1806
+ passkeys.release();
1518
1807
  server.close();
1519
1808
  }
1520
1809
  };
@@ -1633,9 +1922,9 @@ function valueType(value, path) {
1633
1922
  }
1634
1923
  return value.type;
1635
1924
  }
1636
- function toolSchema(inputSchema, tool) {
1637
- const converted = convert(inputSchema, tool);
1638
- if (converted.type !== "object") throw new Error(`${tool}'s arguments are not an object`);
1925
+ function toolSchema(inputSchema, tool2) {
1926
+ const converted = convert(inputSchema, tool2);
1927
+ if (converted.type !== "object") throw new Error(`${tool2}'s arguments are not an object`);
1639
1928
  return converted;
1640
1929
  }
1641
1930
 
@@ -1662,9 +1951,16 @@ function explain(error) {
1662
1951
  if (error instanceof McpCallError) return new Error(`Playwright MCP: ${error.message}`);
1663
1952
  return error instanceof Error ? error : new Error(String(error));
1664
1953
  }
1954
+ function withReconnection(result, connections, botId) {
1955
+ if (!connections.takeReconnected(botId)) return result;
1956
+ return {
1957
+ ...result,
1958
+ text: [RECONNECTED, ...result.text === void 0 ? [] : [result.text]].join("\n\n")
1959
+ };
1960
+ }
1665
1961
  function browserTools(offered, connections) {
1666
1962
  return offered.map((entry) => {
1667
- const tool = {
1963
+ const tool2 = {
1668
1964
  name: entry.name,
1669
1965
  description: entry.upstream.description,
1670
1966
  inputSchema: toolSchema(entry.upstream.inputSchema, entry.upstream.name),
@@ -1677,7 +1973,7 @@ function browserTools(offered, connections) {
1677
1973
  let result;
1678
1974
  try {
1679
1975
  result = await resultOf(
1680
- await run2.attachment.callTool(entry.upstream.name, args, {
1976
+ await run2.attachment.mcp.callTool(entry.upstream.name, args, {
1681
1977
  signal: run2.signal,
1682
1978
  timeoutMs: CALL_TIMEOUT_MS
1683
1979
  }),
@@ -1686,17 +1982,173 @@ function browserTools(offered, connections) {
1686
1982
  } catch (error) {
1687
1983
  throw explain(error);
1688
1984
  }
1689
- if (!connections.takeReconnected(run2.bot.id)) return result;
1690
- return {
1691
- ...result,
1692
- text: [RECONNECTED, ...result.text === void 0 ? [] : [result.text]].join("\n\n")
1693
- };
1985
+ return withReconnection(result, connections, run2.bot.id);
1694
1986
  }
1695
1987
  };
1696
- return tool;
1988
+ return tool2;
1697
1989
  });
1698
1990
  }
1699
1991
 
1992
+ // src/host/vault/marks.ts
1993
+ var FILL_ATTRIBUTE = "data-dsh-fill";
1994
+ var PASSKEY_ATTRIBUTE = "data-dsh-passkey";
1995
+ var MARK = /^[0-9a-f]{32}$/;
1996
+ function checkMark(mark2) {
1997
+ if (!MARK.test(mark2)) throw new Error("a mark is 32 lower-case hex digits");
1998
+ return mark2;
1999
+ }
2000
+ var markElement = (mark2) => `(element) => { element.setAttribute("${FILL_ATTRIBUTE}", "${checkMark(mark2)}"); return "marked" }`;
2001
+ var markTab = (mark2) => `() => { document.documentElement.setAttribute("${PASSKEY_ATTRIBUTE}", "${checkMark(mark2)}"); return "marked" }`;
2002
+
2003
+ // src/host/vault/tools.ts
2004
+ var FILL_FIELDS = ["username", "password", "otp"];
2005
+ var FILL_TIMEOUT_MS = 6e4;
2006
+ var EXCLUSIVE_PAGE2 = "page";
2007
+ var tool = (definition) => definition;
2008
+ function vaultOf(run2) {
2009
+ if (run2.vault === void 0) throw new Error("this run has no access to the bot's logins");
2010
+ return run2.vault;
2011
+ }
2012
+ var preview = (title, fields) => ({
2013
+ title,
2014
+ fields
2015
+ });
2016
+ async function mark(run2, args) {
2017
+ let result;
2018
+ try {
2019
+ result = await run2.attachment.mcp.callTool(
2020
+ "browser_evaluate",
2021
+ args.target === void 0 ? { function: args.function } : { element: "the field to fill", target: args.target, function: args.function },
2022
+ { signal: run2.signal, timeoutMs: 3e4 }
2023
+ );
2024
+ } catch (error) {
2025
+ throw explain(error);
2026
+ }
2027
+ if (result.isError) {
2028
+ const text = result.content.flatMap((block) => block.type === "text" ? [block.text] : []);
2029
+ throw new Error(
2030
+ `Playwright MCP: ${text.join("\n").slice(0, 2e3) || "the target was not found"}`
2031
+ );
2032
+ }
2033
+ }
2034
+ async function expect(helper, kind) {
2035
+ const reply = await helper.next();
2036
+ if (reply.kind === "error") throw new HelperFailureError(reply.code);
2037
+ if (reply.kind !== kind) throw new HelperProtocolError("out of order");
2038
+ return reply;
2039
+ }
2040
+ function requireKind(credential, kind) {
2041
+ if (credential.kinds.includes(kind)) return;
2042
+ throw new Error(
2043
+ kind === "passkey" ? `"${credential.label}" has no passkey this bot may use (its password manager may not hand out passkeys); sign in with browser_fill_credential instead` : `"${credential.label}" has no ${kind} this bot may use`
2044
+ );
2045
+ }
2046
+ async function fill(deps, run2, args) {
2047
+ const vault = vaultOf(run2);
2048
+ const credential = await vault.describe(args.credential);
2049
+ requireKind(credential, args.field);
2050
+ const markValue = deps.mark();
2051
+ await mark(run2, { target: args.ref, function: markElement(markValue) });
2052
+ const signal = AbortSignal.any([run2.signal, deps.deadline(FILL_TIMEOUT_MS)]);
2053
+ const helper = await startHelper(run2.environment, FILL_HELPER, signal, deps.kit);
2054
+ let secret;
2055
+ try {
2056
+ const request = { devtools: CDP_HOST_PORT, mark: markValue, field: args.field };
2057
+ await helper.send(request);
2058
+ const { origin } = await expect(helper, "located");
2059
+ try {
2060
+ secret = await vault.reveal(args.credential, args.field, { kind: "browser", origin });
2061
+ } catch (error) {
2062
+ await helper.end();
2063
+ await expect(helper, "cancelled");
2064
+ const reason = error instanceof Error ? error.message : "refused";
2065
+ throw new Error(
2066
+ `the ${args.field} of "${credential.label}" may not be filled in ${origin}: ${reason}`
2067
+ );
2068
+ }
2069
+ const submit = args.submit === true;
2070
+ await helper.sendSecret((length) => ({ fill: { origin, submit, length } }), secret);
2071
+ const filled = await expect(helper, "filled");
2072
+ return `Filled the ${args.field} of "${credential.label}" in ${origin}${filled.submitted ? " and pressed Enter" : ""}. The value is not shown to you; take a browser_snapshot to see the page.`;
2073
+ } finally {
2074
+ secret?.wipe();
2075
+ helper.terminate();
2076
+ }
2077
+ }
2078
+ function vaultTools(deps) {
2079
+ return [
2080
+ tool({
2081
+ name: "fill_credential",
2082
+ description: "Type one field (username, password or otp, a current one-time code) of one of your logins into a field of the page, by its ref from browser_snapshot, without you seeing the value. The field's frame must be one of the login's sites; a password goes only into a password field. Set submit to press Enter afterwards. List your logins with credentials_list first.",
2083
+ parameters: {
2084
+ credential: { type: "string", required: true, description: "The login's handle (cred-\u2026)." },
2085
+ field: {
2086
+ type: "string",
2087
+ enum: FILL_FIELDS,
2088
+ required: true,
2089
+ description: "Which field of the login."
2090
+ },
2091
+ ref: {
2092
+ type: "string",
2093
+ required: true,
2094
+ description: "The ref of the page's field from browser_snapshot."
2095
+ },
2096
+ submit: { type: "boolean", description: "Press Enter in the field afterwards." }
2097
+ },
2098
+ permission: "allow",
2099
+ exclusive: EXCLUSIVE_PAGE2,
2100
+ vault: true,
2101
+ preview: (args) => preview("Fill a login of the bot in its browser?", [
2102
+ { label: "login", value: args.credential },
2103
+ { label: "field", value: args.field },
2104
+ { label: "element", value: args.ref },
2105
+ ...args.submit === true ? [{ label: "then", value: "press Enter" }] : []
2106
+ ]),
2107
+ async execute(args, run2) {
2108
+ const text = await fill(deps, run2, args);
2109
+ return withReconnection({ text }, deps.connections, run2.bot.id);
2110
+ }
2111
+ }),
2112
+ tool({
2113
+ name: "use_passkey",
2114
+ description: `Offer the passkey of one of your logins to the current tab for ${PASSKEY_SECONDS} seconds, without you seeing it: right after this, press the site's sign-in with a passkey. It is used once at most and only while the tab stays on the same site. List your logins with credentials_list first.`,
2115
+ parameters: {
2116
+ credential: { type: "string", required: true, description: "The login's handle (cred-\u2026)." }
2117
+ },
2118
+ permission: "allow",
2119
+ exclusive: EXCLUSIVE_PAGE2,
2120
+ vault: true,
2121
+ preview: (args) => preview("Offer a passkey of the bot in its browser?", [
2122
+ { label: "login", value: args.credential }
2123
+ ]),
2124
+ async execute(args, run2) {
2125
+ const text = await offerPasskey(deps, run2, args);
2126
+ return withReconnection({ text }, deps.connections, run2.bot.id);
2127
+ }
2128
+ })
2129
+ ];
2130
+ }
2131
+ async function offerPasskey(deps, run2, args) {
2132
+ const vault = vaultOf(run2);
2133
+ const credential = await vault.describe(args.credential);
2134
+ requireKind(credential, "passkey");
2135
+ const markValue = deps.mark();
2136
+ await mark(run2, { function: markTab(markValue) });
2137
+ const tab = await run2.attachment.passkeys.locate(markValue);
2138
+ let passkey;
2139
+ try {
2140
+ passkey = await vault.passkey(args.credential, { kind: "browser", origin: tab.origin });
2141
+ } catch (error) {
2142
+ tab.cancel();
2143
+ const reason = error instanceof Error ? error.message : "refused";
2144
+ throw new Error(
2145
+ `the passkey of "${credential.label}" may not be used in ${tab.origin}: ${reason}`
2146
+ );
2147
+ }
2148
+ await tab.offer(passkey);
2149
+ return `The passkey of "${credential.label}" is offered to ${tab.origin} for ${PASSKEY_SECONDS} seconds. Now press the site's sign-in with a passkey (browser_click), then take a browser_snapshot. It goes away once used, when the tab leaves the site, or at your next browser_use_passkey.`;
2150
+ }
2151
+
1700
2152
  // src/host/connector.ts
1701
2153
  var BROWSER_MIN_MEMORY_MIB = 3072;
1702
2154
  function createBrowserConnector(deps) {
@@ -1720,7 +2172,10 @@ function createBrowserConnector(deps) {
1720
2172
  }
1721
2173
  },
1722
2174
  attachment: browserAttachment({ ...deps, connections }),
1723
- tools: browserTools(offeredTools(deps.generated.tools), connections)
2175
+ tools: [
2176
+ ...browserTools(offeredTools(deps.generated.tools), connections),
2177
+ ...vaultTools({ ...deps, connections })
2178
+ ]
1724
2179
  };
1725
2180
  }
1726
2181
 
@@ -1734,19 +2189,30 @@ function botOf(ctx) {
1734
2189
  return bot;
1735
2190
  }
1736
2191
  var VM = new URL("../vm/", import.meta.url);
1737
- async function readMcpInstallation(directory = VM) {
2192
+ async function readBrowserInstallation(directory = VM) {
1738
2193
  const read = async (path) => new Uint8Array(await readFile(new URL(path, directory)));
2194
+ const helpers = (await readdir(new URL("helper/", directory))).filter((name2) => name2.endsWith(".mjs")).sort();
1739
2195
  return {
1740
- packageJson: await read("mcp/package.json"),
1741
- shrinkwrap: await read("mcp/npm-shrinkwrap.json"),
1742
- script: await read("install-mcp.sh")
2196
+ mcp: {
2197
+ packageJson: await read("mcp/package.json"),
2198
+ shrinkwrap: await read("mcp/npm-shrinkwrap.json"),
2199
+ script: await read("install-mcp.sh")
2200
+ },
2201
+ helper: {
2202
+ files: await Promise.all(
2203
+ helpers.map(async (name2) => ({ name: name2, data: await read(`helper/${name2}`) }))
2204
+ ),
2205
+ script: await read("install-helper.sh")
2206
+ }
1743
2207
  };
1744
2208
  }
1745
2209
  async function apply(ctx) {
1746
2210
  const bot = botOf(ctx);
1747
2211
  const connector = createBrowserConnector({
1748
2212
  generated: GENERATED_SERVER,
1749
- installation: await readMcpInstallation(),
2213
+ installation: await readBrowserInstallation(),
2214
+ kit: bot.vaultKit(),
2215
+ mark: () => randomBytes(16).toString("hex"),
1750
2216
  deadline: (ms) => AbortSignal.timeout(ms)
1751
2217
  });
1752
2218
  ctx.effect(() => bot.registerConnector(connector), "browser: connector");
@@ -1758,5 +2224,5 @@ export {
1758
2224
  createBrowserConnector,
1759
2225
  inject,
1760
2226
  name,
1761
- readMcpInstallation
2227
+ readBrowserInstallation
1762
2228
  };