dsh-builtin-browser 0.5.6 → 0.5.7

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 (63) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.en.md +67 -99
  3. package/README.md +67 -100
  4. package/client.js +381 -322
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/tool-reference.md +20 -1
  8. package/lib/browser/runtime.d.ts +3 -1
  9. package/lib/browser/runtime.js +9 -0
  10. package/lib/browser/types.d.ts +42 -0
  11. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  12. package/lib/browser-electron/authenticated-route.js +39 -0
  13. package/lib/browser-electron/bridge-endpoint.js +7 -0
  14. package/lib/browser-electron/bridge-install.d.ts +48 -0
  15. package/lib/browser-electron/bridge-install.js +98 -0
  16. package/lib/browser-electron/bridge-status.js +21 -2
  17. package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
  18. package/lib/browser-electron/desktop-bridge-host.js +36 -15
  19. package/lib/browser-electron/electron-provision.d.ts +1 -1
  20. package/lib/browser-electron/electron-provision.js +31 -11
  21. package/lib/browser-electron/entry.js +84 -8
  22. package/lib/browser-electron/host-main.js +48 -27
  23. package/lib/browser-electron/provider.d.ts +9 -2
  24. package/lib/browser-electron/provider.js +76 -6
  25. package/lib/browser-electron/remote-host.js +4 -4
  26. package/lib/browser-electron/runtime-route.d.ts +3 -5
  27. package/lib/browser-electron/runtime-status.js +4 -2
  28. package/lib/browser-electron/settings-route.d.ts +5 -18
  29. package/lib/browser-electron/settings-route.js +4 -14
  30. package/lib/browser-electron/settings-store.d.ts +17 -0
  31. package/lib/browser-electron/settings-store.js +24 -0
  32. package/lib/browser-electron/system-browser.d.ts +5 -2
  33. package/lib/browser-electron/system-browser.js +12 -4
  34. package/lib/tool-browser/index.js +1041 -4
  35. package/lib/tool-browser/page-probe.d.ts +86 -0
  36. package/lib/tool-browser/page-probe.js +460 -0
  37. package/package.json +4 -2
  38. package/scripts/verify-runtime-status.mjs +14 -0
  39. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  40. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  41. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  42. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  43. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  44. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  45. package/src/browser/runtime.ts +11 -0
  46. package/src/browser/types.ts +19 -0
  47. package/src/browser-electron/authenticated-route.ts +56 -0
  48. package/src/browser-electron/bridge-endpoint.ts +7 -0
  49. package/src/browser-electron/bridge-install.ts +122 -0
  50. package/src/browser-electron/bridge-status.ts +22 -2
  51. package/src/browser-electron/desktop-bridge-host.ts +33 -15
  52. package/src/browser-electron/electron-provision.ts +30 -12
  53. package/src/browser-electron/entry.ts +76 -8
  54. package/src/browser-electron/host-main.ts +41 -22
  55. package/src/browser-electron/provider.ts +90 -6
  56. package/src/browser-electron/remote-host.ts +4 -4
  57. package/src/browser-electron/runtime-route.ts +3 -5
  58. package/src/browser-electron/runtime-status.ts +4 -2
  59. package/src/browser-electron/settings-route.ts +9 -32
  60. package/src/browser-electron/settings-store.ts +39 -0
  61. package/src/browser-electron/system-browser.ts +9 -3
  62. package/src/tool-browser/index.ts +991 -7
  63. package/src/tool-browser/page-probe.ts +474 -0
@@ -13,7 +13,10 @@
13
13
  * over tabs, history, or navigation state.
14
14
  * @module dsh-browser/tool-browser
15
15
  */
16
+ import { statSync } from 'node:fs';
16
17
  import { defineTool } from '@deepseek-ai/dsh-tools';
18
+ import { pageOperationScript } from './page-probe.js';
19
+ import { SettingsStore } from '../browser-electron/settings-store.js';
17
20
  import { ELEMENT_ITEM_SCHEMA, NODE_ITEM_SCHEMA, projectElement, projectNode, } from './element-fields.js';
18
21
  /**
19
22
  * Register a cleanup that runs once when the process exits.
@@ -65,6 +68,13 @@ export const READ_ONLY_TOOLS = new Set([
65
68
  'dsh_browser_snapshot', 'dsh_browser_a11y', 'dsh_browser_content', 'dsh_browser_scrape',
66
69
  'dsh_browser_screenshot', 'dsh_browser_get_value', 'dsh_browser_wait', 'dsh_browser_challenge',
67
70
  'dsh_browser_list_tabs', 'dsh_browser_session', 'dsh_browser_history', 'dsh_browser_visited',
71
+ // Observation added in 0.5.7: console lines, network responses, an assertion, a self-check and the
72
+ // help index. All five only read (the probe's buffers belong to the page, not to the task), so an
73
+ // allow-list must not blind a task that restricted itself.
74
+ 'dsh_browser_console', 'dsh_browser_network', 'dsh_browser_wait_for_response',
75
+ 'dsh_browser_assert', 'dsh_browser_doctor', 'dsh_browser_help',
76
+ // Reading the page's own digest and searching its text: observation like the rest.
77
+ 'dsh_browser_find', 'dsh_browser_state',
68
78
  // dsh_browser_auth reads cookies out of the browser: an observation, and one the
69
79
  // credentials switch gates on its own (see credentials.allowRead in the settings).
70
80
  // dsh_browser_auth is deliberately NOT here. It reads cookies on "flush" but WRITES them on
@@ -302,7 +312,7 @@ export function apply(ctx, config = {}) {
302
312
  // Tool guidance band is 100-199; 150 keeps clear of the common 110/120
303
313
  // tool sections so ordering does not depend on plugin load sequence.
304
314
  order: 150,
305
- text: 'Use the dsh_browser_* tools to operate the built-in browser. Each task gets its own browser session AND its own window (with a real toolbar: address bar, back/forward/reload, tab strip) — the human can see it, use it like any browser, and take over at any time; your tabs and history are isolated from other tasks, so do not assume another task\'s navigation state is visible to you. Understand a page with dsh_browser_a11y (semantic roles/names/states — the best structure map) or dsh_browser_snapshot (numbered interactive elements), then drive it: dsh_browser_click/dsh_browser_type accept a target {by: css|text|xpath, value} for semantic locating, or coordinates from dsh_browser_screenshot for visual targeting. For form filling prefer dsh_browser_fill (batch) or dsh_browser_set_value/dsh_browser_check/dsh_browser_select/dsh_browser_clear (single control, target-based); verify with dsh_browser_get_value. Use dsh_browser_scrape for structured extraction from list pages instead of hand-written dsh_browser_execute. After navigating on slow sites, dsh_browser_wait for the page. Keep the human informed of what you are doing on the page. If a snapshot or dsh_browser_challenge reports a human-verification challenge (CAPTCHA), stop retrying and ask the human to complete it in the browser window, then re-check.',
315
+ text: 'Use the dsh_browser_* tools to operate the built-in browser. Each task gets its own browser session AND its own window (with a real toolbar: address bar, back/forward/reload, tab strip) — the human can see it, use it like any browser, and take over at any time; your tabs and history are isolated from other tasks, so do not assume another task\'s navigation state is visible to you. Understand a page with dsh_browser_a11y (semantic roles/names/states — the best structure map) or dsh_browser_snapshot (numbered interactive elements), then drive it: dsh_browser_click/dsh_browser_type accept a target {by: css|text|xpath, value} for semantic locating, or coordinates from dsh_browser_screenshot for visual targeting. For form filling prefer dsh_browser_fill (batch) or dsh_browser_set_value/dsh_browser_check/dsh_browser_select/dsh_browser_clear (single control, target-based); verify with dsh_browser_get_value. Use dsh_browser_scrape for structured extraction from list pages instead of hand-written dsh_browser_execute. After navigating on slow sites, dsh_browser_wait for the page. For a run of steps use dsh_browser_do (one call, stops at the first step that cannot proceed, waits settle by themselves), and use dsh_browser_assert to check a result instead of trusting a screenshot — dsh_browser_console/network explain what the page did when the screen does not. Keep the human informed of what you are doing on the page. If a snapshot or dsh_browser_challenge reports a human-verification challenge (CAPTCHA), stop retrying and ask the human to complete it in the browser window, then re-check.',
306
316
  });
307
317
  /**
308
318
  * Register one tool, turning a name collision into a warning instead of a dead apply.
@@ -316,6 +326,8 @@ export function apply(ctx, config = {}) {
316
326
  * A name this plugin cannot have is worth a sentence in the log, not the toolset.
317
327
  * @param definition - the tool to register.
318
328
  */
329
+ // One store for this apply: it caches by mtime, so reading it per download is a stat, not a parse.
330
+ const settingsStore = new SettingsStore();
319
331
  const registerSafely = (definition) => {
320
332
  try {
321
333
  ctx.tools.register(definition);
@@ -1686,8 +1698,24 @@ export function apply(ctx, config = {}) {
1686
1698
  savePath: { type: 'string', required: true, description: 'Absolute path of the file to write. Must resolve inside the configured downloadDir (default: the system Downloads folder, localized names such as ~/下载 included); an existing file is never overwritten.' },
1687
1699
  },
1688
1700
  output: {
1689
- schema: { type: 'object', additionalProperties: false, properties: { path: { type: 'string', required: true } } },
1690
- render: (_args, value) => [{ type: 'text', text: `Downloaded to ${value.path}.` }],
1701
+ schema: {
1702
+ type: 'object',
1703
+ additionalProperties: false,
1704
+ properties: {
1705
+ path: { type: 'string', required: true },
1706
+ handoff: { type: 'object', additionalProperties: true },
1707
+ remoteError: { type: 'string' },
1708
+ remoteResult: { type: 'object', additionalProperties: true },
1709
+ },
1710
+ },
1711
+ render: (_args, value) => {
1712
+ const lines = [`Downloaded to ${value.path}.`];
1713
+ if (value.handoff !== undefined)
1714
+ lines.push(`Handed to ${String(value.handoff.tool)}: ${String(value.handoff.result ?? 'ok')}`);
1715
+ if (value.remoteError !== undefined)
1716
+ lines.push(`The local file is intact; the remote side did not take it: ${String(value.remoteError)}`);
1717
+ return [{ type: 'text', text: lines.join('\n') }];
1718
+ },
1691
1719
  },
1692
1720
  timeoutMs,
1693
1721
  isConcurrencySafe: () => false,
@@ -1698,7 +1726,73 @@ export function apply(ctx, config = {}) {
1698
1726
  throw new Error('tool-browser: browser service unavailable');
1699
1727
  const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
1700
1728
  const result = await browser.download(session, { url: args.url, savePath: args.savePath }, exec.signal);
1701
- return { path: result.path };
1729
+ // Delivery is an attribute of the download: empty tool = the old behaviour, byte for byte.
1730
+ const plan = deliveryPlan(args.url, result.path);
1731
+ if (plan === undefined)
1732
+ return { path: result.path };
1733
+ let remoteValue;
1734
+ try {
1735
+ const tools = ctx.get?.('tools');
1736
+ if (tools?.execute === undefined)
1737
+ throw new Error('the tools service is not available on this surface');
1738
+ if (plan.tool === 'dsh_browser_download')
1739
+ throw new Error('the delivery tool must be a different tool from dsh_browser_download');
1740
+ exec.signal.throwIfAborted();
1741
+ const callId = 'handoff-' + globalThis.crypto.randomUUID();
1742
+ // DSH's executor service accepts raw batches. Earlier runtimes accept one parsed call.
1743
+ // Select the API before dispatch so a retry can never upload the same file twice.
1744
+ const batched = typeof tools.setExecutor === 'function';
1745
+ const answer = await tools.execute(batched ? {
1746
+ calls: [{ type: 'tool-call', id: callId, name: plan.tool, arguments: JSON.stringify(plan.args) }],
1747
+ agent: exec.agent,
1748
+ toolSet: exec.toolSet,
1749
+ signal: exec.signal,
1750
+ } : {
1751
+ callId,
1752
+ rootCallId: exec.rootCallId,
1753
+ parent: exec.token,
1754
+ name: plan.tool,
1755
+ arguments: plan.args,
1756
+ agent: exec.agent,
1757
+ signal: exec.signal,
1758
+ });
1759
+ let outcome = answer;
1760
+ let concluded = false;
1761
+ if (batched) {
1762
+ const batch = answer;
1763
+ if (!Array.isArray(batch?.results) || batch.results.length !== 1 || batch.results[0]?.callId !== callId) {
1764
+ throw new Error('the delivery executor returned no matching tool result');
1765
+ }
1766
+ for (const context of batch.additionalContexts ?? []) {
1767
+ exec.deferContext(context);
1768
+ }
1769
+ concluded = batch.concluded === true;
1770
+ outcome = batch.results[0].result;
1771
+ }
1772
+ const settled = outcome;
1773
+ remoteValue = settled?.value;
1774
+ const summary = summariseToolResult(outcome);
1775
+ if (!batched) {
1776
+ for (const context of settled?.additionalContexts ?? []) {
1777
+ exec.deferContext(context);
1778
+ }
1779
+ concluded = settled?.concludesTurn === true;
1780
+ }
1781
+ if (concluded)
1782
+ exec.concludeTurn();
1783
+ return { path: result.path, handoff: { tool: plan.tool, result: summary, value: remoteValue ?? null } };
1784
+ }
1785
+ catch (error) {
1786
+ exec.signal.throwIfAborted();
1787
+ const reason = error instanceof Error ? error.message : String(error);
1788
+ if (plan.onFail === 'stop')
1789
+ throw new Error(`dsh_browser_download: saved to ${result.path} locally, but the handoff to "${plan.tool}" failed: ${reason}`);
1790
+ return {
1791
+ path: result.path,
1792
+ remoteError: plan.tool + ': ' + reason,
1793
+ ...remoteValue === undefined ? {} : { remoteResult: { tool: plan.tool, value: remoteValue } },
1794
+ };
1795
+ }
1702
1796
  },
1703
1797
  }));
1704
1798
  registerSafely(defineTool({
@@ -1848,6 +1942,949 @@ export function apply(ctx, config = {}) {
1848
1942
  return { restored };
1849
1943
  },
1850
1944
  }));
1945
+ // ===========================================================================
1946
+ // Observation, assertion and batch work (0.5.7).
1947
+ //
1948
+ // Five capabilities were missing against the other browser plugins in this market: what the
1949
+ // console said, which responses arrived, what happened to a JavaScript dialog (an unanswered
1950
+ // `confirm()` used to hang a whole call), a way to assert a result instead of eyeballing a
1951
+ // screenshot, and a way to run several steps in one call. All of them come from one page-side
1952
+ // probe installed through `execute`, so they work identically on the self-hosted window, a driven
1953
+ // Chrome/Edge and the desktop sidebar — no host change, no bridge protocol version.
1954
+ // ===========================================================================
1955
+ /**
1956
+ * What to do with a saved file, from the settings document.
1957
+ *
1958
+ * Read here rather than threaded through the provider on purpose: delivery is a property of how
1959
+ * this deployment saves files, not of which browser carries the page, so every carrier gets it
1960
+ * for free and no seam grows a method for it.
1961
+ *
1962
+ * @param url - the downloaded address, used to pick a per-site override by host.
1963
+ * @param path - the absolute local path just written.
1964
+ * @returns the plan, or undefined when nothing is configured (the old behaviour).
1965
+ */
1966
+ function deliveryPlan(url, path) {
1967
+ let settings;
1968
+ try {
1969
+ settings = settingsStore.get();
1970
+ }
1971
+ catch {
1972
+ return undefined;
1973
+ }
1974
+ const delivery = settings.delivery;
1975
+ if (delivery === undefined)
1976
+ return undefined;
1977
+ let host = '';
1978
+ try {
1979
+ host = new URL(url).hostname.toLowerCase();
1980
+ }
1981
+ catch {
1982
+ host = '';
1983
+ }
1984
+ const override = host === '' ? undefined : (delivery.sites[host] ?? delivery.sites['*']);
1985
+ const tool = override ?? delivery.tool;
1986
+ if (typeof tool !== 'string' || tool.trim() === '')
1987
+ return undefined;
1988
+ const name = path.split(/[\\/]/).pop() ?? path;
1989
+ const size = (() => { try {
1990
+ return String(statSync(path).size);
1991
+ }
1992
+ catch {
1993
+ return '';
1994
+ } })();
1995
+ const args = {};
1996
+ for (const [key, value] of Object.entries(delivery.args)) {
1997
+ args[key] = String(value).split('{path}').join(path).split('{name}').join(name).split('{size}').join(size);
1998
+ }
1999
+ if (Object.keys(args).length === 0)
2000
+ args.file_path = path;
2001
+ return { tool: tool.trim(), args, onFail: delivery.onFail };
2002
+ }
2003
+ /** Check the canonical outcome before describing a completed delivery. */
2004
+ function summariseToolResult(answer) {
2005
+ const outcome = answer;
2006
+ if (outcome === null || typeof outcome !== 'object' || typeof outcome.isError !== 'boolean') {
2007
+ throw new Error('the delivery executor returned an invalid tool result');
2008
+ }
2009
+ if (outcome.isError) {
2010
+ throw new Error(outcome.error?.message || outcome.content?.map(block => block.text ?? '').join(' ') || 'the delivery tool failed');
2011
+ }
2012
+ if (!('value' in outcome))
2013
+ throw new Error('the delivery executor returned an invalid tool result');
2014
+ const failure = deliveryFailure(outcome.value);
2015
+ if (failure !== undefined)
2016
+ throw new Error(failure);
2017
+ const text = typeof outcome.value === 'string' ? outcome.value : JSON.stringify(outcome.value);
2018
+ return text.length > 200 ? text.slice(0, 200) + '…' : text;
2019
+ }
2020
+ /** Read explicit failure markers in common MCP structured or JSON text responses. */
2021
+ function deliveryFailure(value) {
2022
+ const object = (candidate) => {
2023
+ if (typeof candidate === 'string') {
2024
+ try {
2025
+ candidate = JSON.parse(candidate);
2026
+ }
2027
+ catch {
2028
+ return undefined;
2029
+ }
2030
+ }
2031
+ return candidate !== null && typeof candidate === 'object' && !Array.isArray(candidate)
2032
+ ? candidate : undefined;
2033
+ };
2034
+ const response = object(value);
2035
+ if (response === undefined)
2036
+ return undefined;
2037
+ const blocks = Array.isArray(response.content) ? response.content : [];
2038
+ const candidates = [
2039
+ response,
2040
+ object(response.structuredContent),
2041
+ ...blocks.map(block => {
2042
+ const content = object(block);
2043
+ return content?.type === 'text' ? object(content.text) : undefined;
2044
+ }),
2045
+ ];
2046
+ for (const candidate of candidates) {
2047
+ if (candidate === undefined)
2048
+ continue;
2049
+ if (candidate.isError !== true && candidate.ok !== false && candidate.success !== false
2050
+ && candidate.status !== 'error' && candidate.status !== 'failed')
2051
+ continue;
2052
+ const error = object(candidate.error);
2053
+ const detail = [candidate.message, candidate.error, error?.message].find(item => typeof item === 'string' && item !== '');
2054
+ return typeof detail === 'string' ? detail : 'the delivery tool reported a failed upload';
2055
+ }
2056
+ return undefined;
2057
+ }
2058
+ /** Run a script in the page and return its value as text. */
2059
+ async function pageValue(browser, session, script, signal) {
2060
+ const result = await browser.execute(session, { script }, signal);
2061
+ if (!result.ok)
2062
+ throw new Error(`page script failed: ${result.exception}`);
2063
+ const raw = result.value;
2064
+ return typeof raw === 'string' ? raw : JSON.stringify(raw ?? null);
2065
+ }
2066
+ /** Fixed operations keep their inputs as data and preserve arbitrary-script permissions. */
2067
+ async function pageOperationValue(browser, session, request, signal) {
2068
+ const result = typeof browser.pageOperation === 'function'
2069
+ ? await browser.pageOperation(session, request, signal)
2070
+ : await browser.execute(session, { script: pageOperationScript(request) }, signal);
2071
+ if (!result.ok)
2072
+ throw new Error('page operation failed: ' + result.exception);
2073
+ return typeof result.value === 'string' ? result.value : JSON.stringify(result.value ?? null);
2074
+ }
2075
+ /** Install the fixed probe and report page failures immediately. */
2076
+ async function installProbe(browser, session, signal) {
2077
+ await pageOperationValue(browser, session, { operation: 'install' }, signal);
2078
+ }
2079
+ /** One probe call, parsed. Throws when the probe is absent or the call failed. */
2080
+ async function probe(browser, session, method, args = [], signal) {
2081
+ const text = await pageOperationValue(browser, session, { operation: 'probe', method, args }, signal);
2082
+ let parsed;
2083
+ try {
2084
+ parsed = JSON.parse(text);
2085
+ }
2086
+ catch {
2087
+ throw new Error(`page probe returned unreadable JSON: ${text.slice(0, 120)}`);
2088
+ }
2089
+ if (parsed !== null && typeof parsed === 'object' && 'error' in parsed) {
2090
+ throw new Error(`page probe: ${String(parsed.error)}`);
2091
+ }
2092
+ return parsed;
2093
+ }
2094
+ /**
2095
+ * A probe call that survives a navigation inside a batch.
2096
+ *
2097
+ * Submitting a form replaces the document, and the probe with it, so a later step in the same
2098
+ * batch would fail with `probe-not-installed` — measured on the first real benchmark run. One
2099
+ * reinstall and one retry is enough: a second failure is a real absence, not a stale context.
2100
+ */
2101
+ async function probeLive(browser, session, method, args = [], signal) {
2102
+ try {
2103
+ return await probe(browser, session, method, args, signal);
2104
+ }
2105
+ catch (error) {
2106
+ if (!/probe-not-installed|probe-method-missing/.test(String(error)))
2107
+ throw error;
2108
+ await installProbe(browser, session, signal);
2109
+ return await probe(browser, session, method, args, signal);
2110
+ }
2111
+ }
2112
+ /** Sleep. Long waits are capped by the caller, and the tool timeout still applies. */
2113
+ async function pause(ms) {
2114
+ await new Promise(resolve => { setTimeout(resolve, ms); });
2115
+ }
2116
+ /** Poll until the callback returns something, or the budget runs out. */
2117
+ async function poll(check, budgetMs) {
2118
+ const deadline = Date.now() + budgetMs;
2119
+ for (;;) {
2120
+ const value = await check();
2121
+ if (value !== undefined)
2122
+ return value;
2123
+ if (Date.now() >= deadline)
2124
+ return undefined;
2125
+ await pause(200);
2126
+ }
2127
+ }
2128
+ /**
2129
+ * Run one `dsh_browser_check` specification against the page.
2130
+ *
2131
+ * Shared by the `check` tool and by the `{check: …}` step of `dsh_browser_do`, so a batch asserts
2132
+ * exactly what a standalone call asserts.
2133
+ */
2134
+ async function runChecks(browser, session, spec, signal) {
2135
+ const checks = [];
2136
+ if (spec.selector !== undefined) {
2137
+ const found = await probeLive(browser, session, 'find', [{ css: spec.selector }], signal);
2138
+ checks.push({ kind: 'selector', expected: spec.selector, actual: found === null ? 'not found' : String(found.described ?? 'found'), pass: found !== null });
2139
+ }
2140
+ if (spec.text !== undefined) {
2141
+ const present = await pageOperationValue(browser, session, { operation: 'text', text: spec.text }, signal);
2142
+ const ok = present === 'true';
2143
+ checks.push({ kind: 'text', expected: spec.text, actual: ok ? 'present' : 'absent', pass: ok });
2144
+ }
2145
+ if (spec.url !== undefined) {
2146
+ const href = await pageOperationValue(browser, session, { operation: 'url' }, signal).then(text => text.replace(/^"|"$/g, ''));
2147
+ const ok = href.includes(spec.url);
2148
+ checks.push({ kind: 'url', expected: spec.url, actual: href, pass: ok });
2149
+ }
2150
+ if (spec.js !== undefined) {
2151
+ try {
2152
+ const value = await pageValue(browser, session, `(() => { try { return JSON.stringify({ ok: !!(${spec.js}) }) } catch (error) { return JSON.stringify({ ok: false, error: String(error) }) } })()`, signal);
2153
+ const parsed = JSON.parse(value);
2154
+ checks.push({ kind: 'js', expected: spec.js, actual: parsed.ok === true ? 'truthy' : (parsed.error ?? 'falsy'), pass: parsed.ok === true });
2155
+ }
2156
+ catch (error) {
2157
+ checks.push({ kind: 'js', expected: spec.js, actual: String(error), pass: false });
2158
+ }
2159
+ }
2160
+ return { pass: checks.length > 0 && checks.every(check => check.pass), checks };
2161
+ }
2162
+ registerSafely(defineTool({
2163
+ name: 'dsh_browser_console',
2164
+ description: 'Read what the page has logged (console.log/info/warn/error/debug), newest last, capped at 200 lines. Use it when the screen does not explain a failure: a red toast, a form that silently refuses, a page that "just does nothing". Set clear:true first when you only want what happens next. A page that logs objects shows their JSON.',
2165
+ parameters: {
2166
+ limit: { type: 'number', description: 'How many lines, newest last (default 20, max 100).' },
2167
+ filter: { type: 'string', description: 'Only lines containing this text (case-insensitive).' },
2168
+ clear: { type: 'boolean', description: 'Clear the buffer before reading.' },
2169
+ },
2170
+ output: {
2171
+ schema: {
2172
+ type: 'object',
2173
+ additionalProperties: false,
2174
+ properties: { entries: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } },
2175
+ },
2176
+ render: (_args, value) => {
2177
+ const rows = value.entries;
2178
+ if (rows.length === 0)
2179
+ return [{ type: 'text', text: 'No console lines yet (nothing logged since the page probe was installed).' }];
2180
+ return [{ type: 'text', text: rows.map(row => `[${String(row.level)}] ${String(row.text)}`).join('\n') }];
2181
+ },
2182
+ },
2183
+ timeoutMs,
2184
+ isConcurrencySafe: () => true,
2185
+ async execute(args, exec) {
2186
+ const browser = ctx.get('browser');
2187
+ if (browser === undefined)
2188
+ throw new Error('tool-browser: browser service unavailable');
2189
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2190
+ await installProbe(browser, session, exec.signal);
2191
+ if (args.clear === true)
2192
+ await probe(browser, session, 'clear', ['console'], exec.signal);
2193
+ const entries = await probe(browser, session, 'read', ['console', args.filter ?? '', args.limit ?? 20], exec.signal);
2194
+ return { entries };
2195
+ },
2196
+ }));
2197
+ registerSafely(defineTool({
2198
+ name: 'dsh_browser_network',
2199
+ description: 'List the responses the page has received, newest last: method, status, type and address, for fetch, XHR and resource-timing entries. Use it when a page fills itself from the network and the screen does not say why, or to confirm a submit actually reached the server. onlyFailures keeps status 0 (blocked/aborted) and 4xx/5xx. Resource-timing rows carry no status (the browser never exposed it to the page) and show status 0.',
2200
+ parameters: {
2201
+ limit: { type: 'number', description: 'How many rows, newest last (default 20, max 100).' },
2202
+ filter: { type: 'string', description: 'Only rows whose address contains this text.' },
2203
+ onlyFailures: { type: 'boolean', description: 'Only rows with status 0, or status >= 400.' },
2204
+ clear: { type: 'boolean', description: 'Clear the buffer before reading.' },
2205
+ },
2206
+ output: {
2207
+ schema: {
2208
+ type: 'object',
2209
+ additionalProperties: false,
2210
+ properties: { entries: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } },
2211
+ },
2212
+ render: (_args, value) => {
2213
+ const rows = value.entries;
2214
+ if (rows.length === 0)
2215
+ return [{ type: 'text', text: 'No responses recorded yet.' }];
2216
+ return [{ type: 'text', text: rows.map(row => `${String(row.method)} ${String(row.status)} ${String(row.kind)} ${String(row.ms)}ms ${String(row.url)}`).join('\n') }];
2217
+ },
2218
+ },
2219
+ timeoutMs,
2220
+ isConcurrencySafe: () => true,
2221
+ async execute(args, exec) {
2222
+ const browser = ctx.get('browser');
2223
+ if (browser === undefined)
2224
+ throw new Error('tool-browser: browser service unavailable');
2225
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2226
+ await installProbe(browser, session, exec.signal);
2227
+ if (args.clear === true)
2228
+ await probe(browser, session, 'clear', ['network'], exec.signal);
2229
+ const rows = await probe(browser, session, 'read', ['network', args.filter ?? '', args.limit ?? 20], exec.signal);
2230
+ const entries = args.onlyFailures === true
2231
+ ? rows.filter(row => Number(row.status) === 0 || Number(row.status) >= 400)
2232
+ : rows;
2233
+ return { entries };
2234
+ },
2235
+ }));
2236
+ registerSafely(defineTool({
2237
+ name: 'dsh_browser_dialog',
2238
+ description: 'Report JavaScript dialogs (alert/confirm/prompt) the page raised, and choose how they are answered. Dialogs use the native browser UI by default. Setting policy "dismiss" answers alert/prompt with nothing and confirm with false, "accept" answers confirm with true and prompt with its current text. Policy "native" restores the original dialog functions. Reading preserves the current policy; changing it is an action. A dialog raised by the browser itself (beforeunload, HTTP auth) is not covered.',
2239
+ parameters: {
2240
+ policy: { type: 'string', enum: ['native', 'accept', 'dismiss'], description: 'Answer future dialogs this way.' },
2241
+ limit: { type: 'number', description: 'How many recent dialogs to return (default 10).' },
2242
+ },
2243
+ output: {
2244
+ schema: {
2245
+ type: 'object',
2246
+ additionalProperties: false,
2247
+ properties: {
2248
+ policy: { type: 'string', required: true },
2249
+ dialogs: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
2250
+ },
2251
+ },
2252
+ render: (_args, value) => {
2253
+ const rows = value.dialogs;
2254
+ const head = `Dialog policy: ${String(value.policy)} (${String(value.policy) === 'accept' ? 'confirm→true, prompt→its text' : 'confirm→false, prompt→null'}).`;
2255
+ if (rows.length === 0)
2256
+ return [{ type: 'text', text: `${head} No dialogs seen yet.` }];
2257
+ return [{ type: 'text', text: [head, ...rows.map(row => `${String(row.kind)} "${String(row.message)}" → ${String(row.answered)}`)].join('\n') }];
2258
+ },
2259
+ },
2260
+ timeoutMs,
2261
+ isConcurrencySafe: () => false, // the policy is task-wide state
2262
+ async execute(args, exec) {
2263
+ assertAllowed(state, 'dsh_browser_dialog', taskKey(exec));
2264
+ const browser = ctx.get('browser');
2265
+ if (browser === undefined)
2266
+ throw new Error('tool-browser: browser service unavailable');
2267
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2268
+ await installProbe(browser, session, exec.signal);
2269
+ const policy = args.policy === undefined
2270
+ ? await probe(browser, session, 'dialogStatus', [], exec.signal)
2271
+ : await probe(browser, session, 'setDialogPolicy', [args.policy], exec.signal);
2272
+ const dialogs = await probe(browser, session, 'read', ['dialogs', '', args.limit ?? 10], exec.signal);
2273
+ return { policy, dialogs };
2274
+ },
2275
+ }));
2276
+ registerSafely(defineTool({
2277
+ name: 'dsh_browser_wait_for_response',
2278
+ description: 'Wait until a response whose address contains `urlContains` has arrived AFTER this call started: optional status (e.g. 200, or 4xx), bounded by timeoutMs. Use it instead of sleeping before a snapshot when a click submits a form or starts a fetch — it returns as soon as the server answered, and says what arrived when it did not. This is the "did the submit reach the server" question that a screenshot cannot answer.',
2279
+ parameters: {
2280
+ urlContains: { type: 'string', required: true, description: 'Substring of the request address.' },
2281
+ status: { type: 'number', description: 'Require this exact status (a non-zero status is required to match).' },
2282
+ timeoutMs: { type: 'number', description: 'How long to wait (default 15000, capped by the tool timeout).' },
2283
+ },
2284
+ output: {
2285
+ schema: {
2286
+ type: 'object',
2287
+ additionalProperties: false,
2288
+ properties: {
2289
+ matched: { type: 'boolean', required: true },
2290
+ reason: { type: 'string', required: true },
2291
+ entry: { type: 'object', additionalProperties: true },
2292
+ },
2293
+ },
2294
+ render: (_args, value) => {
2295
+ const entry = value.entry;
2296
+ if (!value.matched)
2297
+ return [{ type: 'text', text: `No matching response: ${String(value.reason)}` }];
2298
+ return [{ type: 'text', text: `Matched: ${String(entry?.method)} ${String(entry?.status)} ${String(entry?.url)} (${String(entry?.ms)}ms)` }];
2299
+ },
2300
+ },
2301
+ timeoutMs,
2302
+ isConcurrencySafe: () => true,
2303
+ async execute(args, exec) {
2304
+ const browser = ctx.get('browser');
2305
+ if (browser === undefined)
2306
+ throw new Error('tool-browser: browser service unavailable');
2307
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2308
+ await installProbe(browser, session, exec.signal);
2309
+ const cursor = await probe(browser, session, 'networkCursor', [], exec.signal);
2310
+ const budget = Math.min(args.timeoutMs ?? 15_000, maxWaitMs);
2311
+ const found = await poll(async () => {
2312
+ const current = await probe(browser, session, 'networkCursor', [], exec.signal);
2313
+ if (current.startedAt !== cursor.startedAt)
2314
+ throw new Error('the page changed while waiting for a response; start a new wait on the current page');
2315
+ const rows = await probe(browser, session, 'read', ['network', args.urlContains, 100], exec.signal);
2316
+ const fresh = rows.filter(row => Number(row.sequence) > cursor.sequence && Number(row.status) > 0);
2317
+ const exact = args.status === undefined ? fresh : fresh.filter(row => Number(row.status) === args.status);
2318
+ return exact.length > 0 ? exact[exact.length - 1] : undefined;
2319
+ }, budget);
2320
+ if (found === undefined) {
2321
+ const rows = await probe(browser, session, 'read', ['network', args.urlContains, 60], exec.signal);
2322
+ const seen = rows.length === 0 ? 'nothing matched the address' : `${rows.length} older row(s) matched but none arrived after this call started`;
2323
+ return { matched: false, reason: `${seen} within ${Math.round(budget / 1000)}s` };
2324
+ }
2325
+ return { matched: true, reason: 'response arrived', entry: found };
2326
+ },
2327
+ }));
2328
+ registerSafely(defineTool({
2329
+ name: 'dsh_browser_assert',
2330
+ description: 'Assert facts about the page in one call and get a pass/fail per assertion with the evidence: a CSS selector exists, the body text contains something, the URL contains something, or a JavaScript expression is truthy. Use it to verify a step actually worked — "clicked" and "the form accepted it" are different claims — and before retrying anything that might have already taken effect.',
2331
+ parameters: {
2332
+ selector: { type: 'string', description: 'CSS selector that must match an element.' },
2333
+ text: { type: 'string', description: 'Text that must appear in the page body.' },
2334
+ url: { type: 'string', description: 'Substring the URL must contain.' },
2335
+ js: { type: 'string', description: 'Expression that must be truthy, e.g. document.querySelector("#ok") !== null.' },
2336
+ },
2337
+ output: {
2338
+ schema: {
2339
+ type: 'object',
2340
+ additionalProperties: false,
2341
+ properties: {
2342
+ pass: { type: 'boolean', required: true },
2343
+ checks: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
2344
+ },
2345
+ },
2346
+ render: (_args, value) => {
2347
+ const rows = value.checks;
2348
+ const lines = rows.map(row => `${row.pass === true ? 'PASS' : 'FAIL'} ${String(row.kind)}: ${String(row.expected)} → ${String(row.actual)}`);
2349
+ return [{ type: 'text', text: `${value.pass === true ? 'All checks passed.' : 'A check failed.'}\n${lines.join('\n')}` }];
2350
+ },
2351
+ },
2352
+ timeoutMs,
2353
+ isConcurrencySafe: () => true,
2354
+ async execute(args, exec) {
2355
+ const browser = ctx.get('browser');
2356
+ if (browser === undefined)
2357
+ throw new Error('tool-browser: browser service unavailable');
2358
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2359
+ await installProbe(browser, session, exec.signal);
2360
+ const spec = {
2361
+ ...args.selector !== undefined ? { selector: args.selector } : {},
2362
+ ...args.text !== undefined ? { text: args.text } : {},
2363
+ ...args.url !== undefined ? { url: args.url } : {},
2364
+ ...args.js !== undefined ? { js: args.js } : {},
2365
+ };
2366
+ if (Object.keys(spec).length === 0)
2367
+ throw new Error('dsh_browser_assert: give at least one of selector, text, url or js');
2368
+ return await runChecks(browser, session, spec, exec.signal);
2369
+ },
2370
+ }));
2371
+ registerSafely(defineTool({
2372
+ name: 'dsh_browser_drag',
2373
+ description: 'Drag from one viewport point to another using trusted browser pointer input. Coordinates are CSS pixels from the top-left of the current viewport. Use for sliders, sortable lists, HTML drag-and-drop and canvas drawing. Check the resulting control value or page state after the gesture.',
2374
+ parameters: {
2375
+ fromX: { type: 'number', required: true, description: 'Start x in viewport CSS pixels.' },
2376
+ fromY: { type: 'number', required: true, description: 'Start y in viewport CSS pixels.' },
2377
+ toX: { type: 'number', required: true, description: 'End x.' },
2378
+ toY: { type: 'number', required: true, description: 'End y.' },
2379
+ steps: { type: 'number', description: 'Intermediate moves (default 12, max 60); more steps make a slider follow the path.' },
2380
+ },
2381
+ output: {
2382
+ schema: {
2383
+ type: 'object',
2384
+ additionalProperties: false,
2385
+ properties: {
2386
+ ok: { type: 'boolean', required: true },
2387
+ reason: { type: 'string', required: true },
2388
+ },
2389
+ },
2390
+ render: (_args, value) => [{ type: 'text', text: value.ok === true ? 'Dragged.' : `Drag failed: ${String(value.reason)}` }],
2391
+ },
2392
+ timeoutMs,
2393
+ isConcurrencySafe: () => false, // a pointer gesture; exclusive within a task
2394
+ async execute(args, exec) {
2395
+ assertAllowed(state, 'dsh_browser_drag', taskKey(exec));
2396
+ const browser = ctx.get('browser');
2397
+ if (browser === undefined)
2398
+ throw new Error('tool-browser: browser service unavailable');
2399
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2400
+ const text = await pageOperationValue(browser, session, {
2401
+ operation: 'drag',
2402
+ from: { x: args.fromX, y: args.fromY },
2403
+ to: { x: args.toX, y: args.toY },
2404
+ steps: args.steps ?? 12,
2405
+ }, exec.signal);
2406
+ const parsed = JSON.parse(text);
2407
+ return { ok: parsed.ok === true, reason: parsed.ok === true ? `moved ${String(parsed.moved)} steps` : String(parsed.reason ?? 'unknown') };
2408
+ },
2409
+ }));
2410
+ registerSafely(defineTool({
2411
+ name: 'dsh_browser_doctor',
2412
+ description: 'Report the state of this task\'s browser: page URL, which tools the task restricted away, whether the page probe is installed, and what it has recorded (console lines, responses, dialogs, and how "settled" the page looks). Use it when something behaves oddly and the cause is not visible in the page — before guessing, or before telling the user the browser is broken.',
2413
+ parameters: {},
2414
+ output: {
2415
+ schema: { type: 'object', additionalProperties: false, properties: { report: { type: 'string', required: true } } },
2416
+ render: (_args, value) => [{ type: 'text', text: String(value.report) }],
2417
+ },
2418
+ timeoutMs,
2419
+ isConcurrencySafe: () => true,
2420
+ async execute(_args, exec) {
2421
+ const browser = ctx.get('browser');
2422
+ if (browser === undefined)
2423
+ throw new Error('tool-browser: browser service unavailable');
2424
+ const task = taskKey(exec);
2425
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2426
+ await installProbe(browser, session, exec.signal);
2427
+ const url = await pageOperationValue(browser, session, { operation: 'url' }, exec.signal).then(text => text.replace(/^"|"$/g, ''));
2428
+ const settle = await probe(browser, session, 'settle', [], exec.signal);
2429
+ const consoleRows = await probe(browser, session, 'read', ['console', '', 100], exec.signal);
2430
+ const networkRows = await probe(browser, session, 'read', ['network', '', 100], exec.signal);
2431
+ const dialogRows = await probe(browser, session, 'read', ['dialogs', '', 5], exec.signal);
2432
+ const restricted = state.restrictedByTask.get(task);
2433
+ const lines = [
2434
+ `session ${session}`,
2435
+ `url ${url || '(unknown)'}`,
2436
+ `page ${String(settle?.readyState ?? '?')}, ${String(settle?.pending ?? 0)} request(s) in flight, quiet for ${String(settle?.quietMs ?? 0)}ms`,
2437
+ `probe installed (console ${consoleRows.length}/100, network ${networkRows.length}/100, dialogs ${dialogRows.length}/5)`,
2438
+ restricted === undefined ? 'restricted: no (this task restricted nothing)' : `restricted: ${restricted.length === 0 ? 'everything' : restricted.join(', ')}`,
2439
+ state.configRestrictedTo === undefined ? 'deployment allow-list: none' : `deployment allow-list: ${state.configRestrictedTo.join(', ')}`,
2440
+ ];
2441
+ return { report: lines.join('\n') };
2442
+ },
2443
+ }));
2444
+ registerSafely(defineTool({
2445
+ name: 'dsh_browser_help',
2446
+ description: 'Look up how to use this browser: a short topic index (locate, wait, batch, dialogs, network, verify, recovery, limits) or one topic\'s text. Use it instead of guessing when a call failed for a reason the error message explains only briefly.',
2447
+ parameters: {
2448
+ topic: { type: 'string', description: 'One topic name; omit for the index.' },
2449
+ },
2450
+ output: {
2451
+ schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
2452
+ render: (_args, value) => [{ type: 'text', text: String(value.text) }],
2453
+ },
2454
+ timeoutMs,
2455
+ isConcurrencySafe: () => true,
2456
+ async execute(args) {
2457
+ const topics = {
2458
+ locate: 'Prefer dsh_browser_a11y (roles, names, states) or dsh_browser_snapshot (numbered elements), then click with {target:{by:"text"|css|xpath, value}}. Elements carry a stable CSS selector, so a click re-resolves the element instead of trusting an index that a re-render invalidates.',
2459
+ wait: 'dsh_browser_wait waits for load + an optional URL/selector. dsh_browser_wait_for_response waits for a server answer (that is the "did it submit" wait). dsh_browser_console/network then explain what the page did.',
2460
+ batch: 'dsh_browser_do runs several steps in one call: open/tap/field/type/key/scroll/sleep_ms/wait_text/wait_gone/wait_url/wait_idle/eval/check. It stops at the first step that cannot proceed and reports which one; a tap whose target is covered by a cookie banner dismisses the banner first.',
2461
+ dialogs: 'JavaScript dialogs are answered automatically (default: dismiss). dsh_browser_dialog reports them and can switch to "accept". A dialog from the browser itself (beforeunload, HTTP auth) is not covered — expect a stalled call there and reload.',
2462
+ network: 'dsh_browser_network lists fetch/XHR/resource rows. Status 0 means the page never saw a status (aborted, blocked, or a resource-timing row). Only fetch/XHR rows carry a real status.',
2463
+ verify: 'dsh_browser_assert asserts selector/text/url/js and returns evidence per assertion. Prefer it over reading a screenshot: "clicked" and "the form accepted it" are different claims, and a retry of an unverified submit can double it.',
2464
+ recovery: 'dsh_browser_reset_session closes this task\'s browser session without touching others. dsh_browser_refresh reloads the page. If a carrier was lost, the page context is gone: re-read the page before continuing, and never re-submit something whose result you did not verify.',
2465
+ limits: 'There is no CDP escape hatch and no network interception: the probe sees what the page sees. Downloads go through dsh_browser_download and a directory admission gate. Executing page JavaScript is a settings switch the model cannot lift.',
2466
+ deliver: 'The browser saves a file and returns an absolute path; sending it to Feishu drive, Baidu Netdisk or any MCP-connected storage is a separate tool call with that path. Report where it sits locally AND what the upload tool answered, never just one. If the upload tool is missing or fails, keep the local file and say so — do not retry somewhere else silently.',
2467
+ };
2468
+ if (args.topic === undefined) {
2469
+ return { text: `Topics: ${Object.keys(topics).join(', ')}\nAsk for one with topic=<name>.` };
2470
+ }
2471
+ const text = topics[args.topic];
2472
+ if (text === undefined)
2473
+ throw new Error(`dsh_browser_help: unknown topic "${args.topic}" (${Object.keys(topics).join(', ')})`);
2474
+ return { text };
2475
+ },
2476
+ }));
2477
+ registerSafely(defineTool({
2478
+ name: 'dsh_browser_do',
2479
+ description: 'Run several steps in ONE call and report one compact result: "click search, type a query, press Enter, wait for results" is one call instead of five. Steps run in order and stop at the first that cannot proceed. Each step is an object with exactly one key: open {url} | tap {target} | field {target, text} | type {text} | key {key} | scroll {deltaY} | sleep_ms {ms} | wait_text {text} | wait_gone {text} | wait_url {url} | wait_idle {} | eval {script} | check {selector|text|url|js}. A tap whose target is covered by a cookie banner or modal dismisses it first. Waits know when the page has settled and return as soon as the condition holds.',
2480
+ parameters: {
2481
+ steps: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true, description: 'Steps, in order (max 40).' },
2482
+ timeoutMs: { type: 'number', description: 'Budget for the whole batch (default 60000, capped by the tool timeout).' },
2483
+ autoDismiss: { type: 'boolean', description: 'Clear a covering banner before a tap (default true).' },
2484
+ },
2485
+ output: {
2486
+ schema: {
2487
+ type: 'object',
2488
+ additionalProperties: false,
2489
+ properties: {
2490
+ completed: { type: 'number', required: true },
2491
+ total: { type: 'number', required: true },
2492
+ ok: { type: 'boolean', required: true },
2493
+ stoppedAt: { type: 'number' },
2494
+ reason: { type: 'string' },
2495
+ sideEffectMayHaveHappened: { type: 'boolean' },
2496
+ log: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true },
2497
+ },
2498
+ },
2499
+ render: (_args, value) => {
2500
+ const rows = value.log;
2501
+ const head = value.ok === true
2502
+ ? `${String(value.completed)}/${String(value.total)} steps done.`
2503
+ : `Stopped at step ${String(value.stoppedAt)} (${String(value.completed)}/${String(value.total)} done): ${String(value.reason)}`;
2504
+ const warning = value.ok === false && value.sideEffectMayHaveHappened === true
2505
+ ? '\nA step that can change the page already ran: the site may have acted on it. Read the site\'s own record before retrying — do not repeat it on the assumption that it failed.'
2506
+ : '';
2507
+ return [{ type: 'text', text: [head + warning, ...rows.map(row => ` ${String(row.index)} ${String(row.kind)}: ${String(row.detail)}`)].join('\n') }];
2508
+ },
2509
+ },
2510
+ timeoutMs,
2511
+ isConcurrencySafe: () => false, // drives the page; exclusive within a task
2512
+ async execute(args, exec) {
2513
+ assertAllowed(state, 'dsh_browser_do', taskKey(exec));
2514
+ const browser = ctx.get('browser');
2515
+ if (browser === undefined)
2516
+ throw new Error('tool-browser: browser service unavailable');
2517
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2518
+ const steps = Array.isArray(args.steps) ? args.steps : [];
2519
+ if (steps.length === 0)
2520
+ throw new Error('dsh_browser_do: "steps" must be a non-empty array');
2521
+ if (steps.length > 40)
2522
+ throw new Error('dsh_browser_do: at most 40 steps per call — split the work');
2523
+ await installProbe(browser, session, exec.signal);
2524
+ const autoDismiss = args.autoDismiss !== false;
2525
+ const budget = Math.min(args.timeoutMs ?? timeoutMs, maxWaitMs);
2526
+ const deadline = Date.now() + budget;
2527
+ const log = [];
2528
+ // Set once a step that can change server state has run. A failure after that point must not
2529
+ // read like a failure before it: measured on the first real benchmark run, where a batch died
2530
+ // after the form had already been submitted and the message said nothing about it.
2531
+ let dispatched = false;
2532
+ const dispatchable = new Set(['tap', 'key', 'eval']);
2533
+ const kinds = ['open', 'tap', 'field', 'type', 'key', 'scroll', 'sleep_ms', 'wait_text', 'wait_gone', 'wait_url', 'wait_idle', 'eval', 'check'];
2534
+ /** Resolve a target: a string is visible text; an object passes through. */
2535
+ const asTarget = (value) => {
2536
+ if (typeof value === 'string' && value !== '')
2537
+ return { by: 'text', value };
2538
+ if (value !== null && typeof value === 'object') {
2539
+ const raw = value;
2540
+ if (typeof raw.value === 'string' && raw.value !== '') {
2541
+ const by = raw.by === 'css' || raw.by === 'xpath' || raw.by === 'text' ? raw.by : 'text';
2542
+ return { by, value: raw.value };
2543
+ }
2544
+ }
2545
+ return undefined;
2546
+ };
2547
+ for (let index = 0; index < steps.length; index += 1) {
2548
+ const step = steps[index] ?? {};
2549
+ const keys = Object.keys(step).filter(key => kinds.includes(key));
2550
+ if (keys.length !== 1) {
2551
+ return { ok: false, completed: index, total: steps.length, stoppedAt: index + 1, reason: `step ${index + 1} must have exactly one of: ${kinds.join(', ')}`, log };
2552
+ }
2553
+ const kind = keys[0];
2554
+ const value = step[kind];
2555
+ if (Date.now() > deadline) {
2556
+ return { ok: false, completed: index, total: steps.length, stoppedAt: index + 1, reason: `budget of ${Math.round(budget / 1000)}s exhausted`, log };
2557
+ }
2558
+ try {
2559
+ let detail = 'ok';
2560
+ if (kind === 'open') {
2561
+ const url = typeof value === 'string' ? value : value?.url;
2562
+ if (typeof url !== 'string')
2563
+ throw new Error('open needs a URL string or {url}');
2564
+ await browser.openUrl(session, { url }, exec.signal);
2565
+ detail = url;
2566
+ }
2567
+ else if (kind === 'tap') {
2568
+ const target = asTarget(value?.target ?? value);
2569
+ if (target === undefined)
2570
+ throw new Error('tap needs a target (text, or {by, value})');
2571
+ if (autoDismiss) {
2572
+ const rect = await probeLive(browser, session, 'find', [{ [target.by]: target.value }], exec.signal);
2573
+ if (rect && typeof rect.x === 'number' && typeof rect.y === 'number') {
2574
+ const cover = await probeLive(browser, session, 'overlayAt', [rect.x, rect.y], exec.signal);
2575
+ if (cover?.dismiss && typeof cover.dismiss.x === 'number' && typeof cover.dismiss.y === 'number') {
2576
+ await browser.click(session, { x: cover.dismiss.x, y: cover.dismiss.y }, exec.signal);
2577
+ detail = `dismissed "${String(cover.dismiss.label)}" first`;
2578
+ await pause(150);
2579
+ }
2580
+ else if (cover?.covers !== null && cover?.covers !== undefined && cover.covers !== rect.described) {
2581
+ // Measured on the fixture's human gate: a hidden form left the tap hitting `<html>`,
2582
+ // the step reported "ok", and nothing was submitted. A click that cannot land is a
2583
+ // FAILURE, not a note — a silent no-op is the worst result this tool can return.
2584
+ throw new Error(`the target is not reachable: ${String(cover.covers)} is at that point, not ${String(rect.described)} (hidden, or covered by an overlay that cannot be dismissed)`);
2585
+ }
2586
+ }
2587
+ }
2588
+ await browser.click(session, { target }, exec.signal);
2589
+ }
2590
+ else if (kind === 'field') {
2591
+ const spec = value;
2592
+ const target = asTarget(spec?.target);
2593
+ if (target === undefined || typeof spec?.text !== 'string')
2594
+ throw new Error('field needs {target, text}');
2595
+ await browser.setValue(session, { target, value: spec.text }, exec.signal);
2596
+ detail = `${target.value} ← ${spec.text.slice(0, 40)}`;
2597
+ }
2598
+ else if (kind === 'type') {
2599
+ const text = typeof value === 'string' ? value : value?.text;
2600
+ if (typeof text !== 'string')
2601
+ throw new Error('type needs a text string or {text}');
2602
+ await browser.type(session, { text }, exec.signal);
2603
+ detail = text.slice(0, 40);
2604
+ }
2605
+ else if (kind === 'key') {
2606
+ const key = typeof value === 'string' ? value : value?.key;
2607
+ if (typeof key !== 'string')
2608
+ throw new Error('key needs a key name or {key}');
2609
+ await browser.key(session, { key: key }, exec.signal);
2610
+ detail = key;
2611
+ }
2612
+ else if (kind === 'scroll') {
2613
+ const deltaY = typeof value === 'number' ? value : Number(value?.deltaY ?? Number.NaN);
2614
+ if (!Number.isFinite(deltaY))
2615
+ throw new Error('scroll needs a number or {deltaY}');
2616
+ await browser.scroll(session, { deltaY }, exec.signal);
2617
+ detail = String(deltaY);
2618
+ }
2619
+ else if (kind === 'sleep_ms') {
2620
+ const requestedMs = typeof value === 'number' ? value : value?.ms;
2621
+ if (typeof requestedMs !== 'number' || !Number.isFinite(requestedMs) || requestedMs < 0)
2622
+ throw new Error('sleep_ms needs a non-negative number or {ms}');
2623
+ const ms = Math.min(requestedMs, 10_000);
2624
+ await pause(ms);
2625
+ detail = `${ms}ms`;
2626
+ }
2627
+ else if (kind === 'wait_text' || kind === 'wait_gone') {
2628
+ const want = typeof value === 'string' ? value : value?.text;
2629
+ if (typeof want !== 'string')
2630
+ throw new Error('wait_text/wait_gone need text or {text}');
2631
+ const found = await poll(async () => {
2632
+ const present = (await pageOperationValue(browser, session, { operation: 'text', text: want }, exec.signal)) === 'true';
2633
+ return (kind === 'wait_text' ? present : !present) ? true : undefined;
2634
+ }, Math.max(1_000, Math.min(deadline - Date.now(), 30_000)));
2635
+ if (found === undefined)
2636
+ throw new Error(`timed out waiting for "${want}" to be ${kind === 'wait_text' ? 'present' : 'gone'}`);
2637
+ detail = want;
2638
+ }
2639
+ else if (kind === 'wait_url') {
2640
+ const want = typeof value === 'string' ? value : value?.url;
2641
+ if (typeof want !== 'string')
2642
+ throw new Error('wait_url needs a URL fragment or {url}');
2643
+ const budget = Math.max(1_000, Math.min(deadline - Date.now(), 30_000));
2644
+ const hit = await poll(async () => {
2645
+ const href = (await pageOperationValue(browser, session, { operation: 'url' }, exec.signal)).replace(/^"|"$/g, '');
2646
+ return href.includes(want) ? href : undefined;
2647
+ }, budget);
2648
+ if (hit === undefined)
2649
+ throw new Error(`timed out waiting for the URL to contain "${want}"`);
2650
+ detail = hit;
2651
+ }
2652
+ else if (kind === 'wait_idle') {
2653
+ const idle = await poll(async () => {
2654
+ const settle = await probeLive(browser, session, 'settle', [], exec.signal);
2655
+ const quiet = Number(settle?.quietMs ?? 0);
2656
+ return Number(settle?.pending ?? 0) === 0 && quiet >= 300 ? settle : undefined;
2657
+ }, Math.max(1_000, Math.min(deadline - Date.now(), 30_000)));
2658
+ if (idle === undefined)
2659
+ throw new Error('timed out waiting for the page to go quiet');
2660
+ detail = `quiet for ${String(idle.quietMs)}ms`;
2661
+ }
2662
+ else if (kind === 'eval') {
2663
+ const script = typeof value === 'string' ? value : value?.script;
2664
+ if (typeof script !== 'string')
2665
+ throw new Error('eval needs a script string or {script}');
2666
+ const text = await pageValue(browser, session, script, exec.signal);
2667
+ detail = text.slice(0, 80);
2668
+ }
2669
+ else if (kind === 'check') {
2670
+ const result = await runChecks(browser, session, value, exec.signal);
2671
+ if (!result.pass) {
2672
+ const failed = result.checks.filter(check => !check.pass).map(check => `${check.kind}: ${check.expected} → ${check.actual}`);
2673
+ throw new Error(`check failed (${failed.join('; ')})`);
2674
+ }
2675
+ detail = `${result.checks.length} check(s) passed`;
2676
+ }
2677
+ if (dispatchable.has(kind))
2678
+ dispatched = true;
2679
+ log.push({ index: index + 1, kind, detail });
2680
+ }
2681
+ catch (error) {
2682
+ return {
2683
+ ok: false,
2684
+ completed: index,
2685
+ total: steps.length,
2686
+ stoppedAt: index + 1,
2687
+ reason: error instanceof Error ? error.message : String(error),
2688
+ sideEffectMayHaveHappened: dispatched,
2689
+ log: [...log, { index: index + 1, kind, detail: `failed: ${error instanceof Error ? error.message : String(error)}` }],
2690
+ };
2691
+ }
2692
+ }
2693
+ return { ok: true, completed: steps.length, total: steps.length, log };
2694
+ },
2695
+ }));
2696
+ registerSafely(defineTool({
2697
+ name: 'dsh_browser_upload',
2698
+ description: 'Put a local file into a file input on the page (attachment, avatar, import form). The path must be a file INSIDE the current workspace, and only the bytes of that one file are read. The file is rebuilt in the page as a File and attached through a DataTransfer, so a form that reads input.files and a drop handler both see it; the change event is fired for you. Oversized files are refused rather than truncated.',
2699
+ parameters: {
2700
+ target: { type: 'object', required: true, additionalProperties: true, description: 'The input: {by: "css"|"text"|"xpath", value} — a text target is resolved to the element at that point and then to a nested input[type=file].' },
2701
+ path: { type: 'string', required: true, description: 'Absolute path of a file inside the workspace.' },
2702
+ mime: { type: 'string', description: 'MIME type (default guessed from the extension, else application/octet-stream).' },
2703
+ },
2704
+ output: {
2705
+ schema: {
2706
+ type: 'object',
2707
+ additionalProperties: false,
2708
+ properties: {
2709
+ ok: { type: 'boolean', required: true },
2710
+ name: { type: 'string' },
2711
+ size: { type: 'number' },
2712
+ reason: { type: 'string' },
2713
+ },
2714
+ },
2715
+ render: (_args, value) => [{ type: 'text', text: value.ok === true ? `Attached ${String(value.name)} (${String(value.size)} bytes).` : `Upload failed: ${String(value.reason)}` }],
2716
+ },
2717
+ timeoutMs,
2718
+ isConcurrencySafe: () => false,
2719
+ async execute(args, exec) {
2720
+ assertAllowed(state, 'dsh_browser_upload', taskKey(exec));
2721
+ const browser = ctx.get('browser');
2722
+ if (browser === undefined)
2723
+ throw new Error('tool-browser: browser service unavailable');
2724
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2725
+ const target = args.target;
2726
+ const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css';
2727
+ if (typeof target?.value !== 'string' || target.value === '')
2728
+ throw new Error('dsh_browser_upload: target.value is required');
2729
+ const { open, realpath, stat } = await import('node:fs/promises');
2730
+ const { resolve, relative, isAbsolute, extname, basename, sep } = await import('node:path');
2731
+ if (!isAbsolute(args.path))
2732
+ throw new Error('dsh_browser_upload: path must be absolute');
2733
+ const agent = agentOf(exec);
2734
+ const directory = (agent?.ctx?.get?.('workingDirectory') ?? ctx.get('workingDirectory'));
2735
+ const workspacePath = directory && agent
2736
+ ? await directory.ensure(agent, exec.signal)
2737
+ : agent?.session?.header?.cwd ?? process.cwd();
2738
+ if (!isAbsolute(workspacePath))
2739
+ throw new Error('dsh_browser_upload: the task workspace must be absolute');
2740
+ const workspace = await realpath(workspacePath);
2741
+ const resolved = await realpath(resolve(args.path));
2742
+ const offset = relative(workspace, resolved);
2743
+ if (offset === '..' || offset.startsWith('..' + sep) || isAbsolute(offset)) {
2744
+ throw new Error('dsh_browser_upload: refusing to read a file outside the task workspace');
2745
+ }
2746
+ const expected = await stat(resolved);
2747
+ const LIMIT = 20 * 1024 * 1024;
2748
+ if (!expected.isFile())
2749
+ throw new Error('dsh_browser_upload: path must name a regular file');
2750
+ if (expected.size > LIMIT)
2751
+ throw new Error('dsh_browser_upload: file is over the 20 MB limit');
2752
+ const file = await open(resolved, 'r');
2753
+ let bytes;
2754
+ try {
2755
+ const opened = await file.stat();
2756
+ if (opened.dev !== expected.dev || opened.ino !== expected.ino
2757
+ || opened.size !== expected.size || !opened.isFile()
2758
+ || await realpath(resolve(args.path)) !== resolved) {
2759
+ throw new Error('dsh_browser_upload: file changed while opening; retry');
2760
+ }
2761
+ const chunks = [];
2762
+ let length = 0;
2763
+ for await (const chunk of file.createReadStream({ autoClose: false, start: 0, end: LIMIT, signal: exec.signal })) {
2764
+ length += chunk.length;
2765
+ if (length > LIMIT)
2766
+ throw new Error('dsh_browser_upload: file grew over the 20 MB limit');
2767
+ chunks.push(chunk);
2768
+ }
2769
+ const after = await file.stat();
2770
+ if (after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || length !== opened.size
2771
+ || await realpath(resolve(args.path)) !== resolved) {
2772
+ throw new Error('dsh_browser_upload: file changed while reading; retry');
2773
+ }
2774
+ bytes = Buffer.concat(chunks, length);
2775
+ }
2776
+ finally {
2777
+ await file.close();
2778
+ }
2779
+ const guess = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.pdf': 'application/pdf', '.txt': 'text/plain', '.csv': 'text/csv', '.json': 'application/json', '.zip': 'application/zip' };
2780
+ const mime = args.mime ?? guess[extname(resolved).toLowerCase()] ?? 'application/octet-stream';
2781
+ await installProbe(browser, session, exec.signal);
2782
+ const text = await pageOperationValue(browser, session, {
2783
+ operation: 'upload',
2784
+ target: { by, value: target.value },
2785
+ file: { name: basename(resolved), mime, base64: bytes.toString('base64') },
2786
+ }, exec.signal);
2787
+ const parsed = JSON.parse(text);
2788
+ return parsed.ok === true
2789
+ ? { ok: true, name: String(parsed.name ?? ''), size: Number(parsed.size ?? 0) }
2790
+ : { ok: false, reason: String(parsed.reason ?? 'unknown') };
2791
+ },
2792
+ }));
2793
+ registerSafely(defineTool({
2794
+ name: 'dsh_browser_hover',
2795
+ description: 'Scroll an element into view and move the browser pointer to its centre. Supports CSS hover styles and JavaScript mouseover handlers. Use before reading or clicking a hover menu.',
2796
+ parameters: {
2797
+ target: { type: 'object', required: true, additionalProperties: true, description: 'The element: {by: "css"|"text"|"xpath", value}.' },
2798
+ settleMs: { type: 'number', description: 'How long to let the menu appear before returning (default 150).' },
2799
+ },
2800
+ output: {
2801
+ schema: { type: 'object', additionalProperties: false, properties: { hovered: { type: 'boolean', required: true }, at: { type: 'object', additionalProperties: true } } },
2802
+ render: (_args, value) => [{ type: 'text', text: value.hovered === true ? 'Pointer moved over the element.' : 'No element at that target.' }],
2803
+ },
2804
+ timeoutMs,
2805
+ isConcurrencySafe: () => false,
2806
+ async execute(args, exec) {
2807
+ assertAllowed(state, 'dsh_browser_hover', taskKey(exec));
2808
+ const browser = ctx.get('browser');
2809
+ if (browser === undefined)
2810
+ throw new Error('tool-browser: browser service unavailable');
2811
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2812
+ const target = args.target;
2813
+ const by = target?.by === 'css' || target?.by === 'xpath' || target?.by === 'text' ? target.by : 'css';
2814
+ if (typeof target?.value !== 'string' || target.value === '')
2815
+ throw new Error('dsh_browser_hover: target.value is required');
2816
+ await installProbe(browser, session, exec.signal);
2817
+ const where = await probe(browser, session, 'find', [{ [by]: target.value }, true], exec.signal);
2818
+ if (!where || typeof where.x !== 'number' || typeof where.y !== 'number')
2819
+ return { hovered: false, at: {} };
2820
+ const fired = await probe(browser, session, 'hoverAt', [where.x, where.y], exec.signal);
2821
+ await pause(Math.min(args.settleMs ?? 150, 2_000));
2822
+ const at = { x: where.x, y: where.y, described: String(where.described ?? '') };
2823
+ return { hovered: fired === true, at };
2824
+ },
2825
+ }));
2826
+ registerSafely(defineTool({
2827
+ name: 'dsh_browser_find',
2828
+ description: 'Find text on the page (the Ctrl+F equivalent) and get its position, so you can scroll to it or click near it without reading the whole page first. Returns up to 5 hits (all:true for up to 50), each with the surrounding snippet and the viewport point. Text inside shadow roots and iframes is not searched.',
2829
+ parameters: {
2830
+ text: { type: 'string', required: true, description: 'Text to look for (case-insensitive).' },
2831
+ all: { type: 'boolean', description: 'Return up to 50 hits instead of 5.' },
2832
+ },
2833
+ output: {
2834
+ schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'number', required: true }, hits: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } } },
2835
+ render: (_args, value) => {
2836
+ const hits = value.hits;
2837
+ if (hits.length === 0)
2838
+ return [{ type: 'text', text: 'Not found on the page.' }];
2839
+ return [{ type: 'text', text: [`${hits.length} hit(s):`, ...hits.map((hit, index) => ` ${index + 1}. ${String(hit.text)} @ ${String(hit.x)},${String(hit.y)}`)].join('\n') }];
2840
+ },
2841
+ },
2842
+ timeoutMs,
2843
+ isConcurrencySafe: () => true,
2844
+ async execute(args, exec) {
2845
+ const browser = ctx.get('browser');
2846
+ if (browser === undefined)
2847
+ throw new Error('tool-browser: browser service unavailable');
2848
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2849
+ await installProbe(browser, session, exec.signal);
2850
+ const hits = await probe(browser, session, 'findText', [args.text, args.all === true], exec.signal);
2851
+ return { count: hits.length, hits };
2852
+ },
2853
+ }));
2854
+ registerSafely(defineTool({
2855
+ name: 'dsh_browser_state',
2856
+ description: 'One compact answer to "what is on screen": URL, title, load state, requests still in flight and how long the page has been quiet, plus the counts of inputs/buttons/links, scroll position, current selection and the first 400 characters of visible text. Use it before a full snapshot when you only need to know where you are, and after an action to see whether the page moved at all.',
2857
+ parameters: {},
2858
+ output: {
2859
+ schema: {
2860
+ type: 'object',
2861
+ additionalProperties: false,
2862
+ properties: { summary: { type: 'object', additionalProperties: true, required: true } },
2863
+ },
2864
+ render: (_args, value) => {
2865
+ const row = value.summary;
2866
+ return [{ type: 'text', text: [
2867
+ `${String(row.url)}`,
2868
+ `${String(row.title)}`,
2869
+ `${String(row.readyState)}, ${String(row.pending)} in flight, quiet ${String(row.quietMs)}ms`,
2870
+ `${String(row.inputs)} input(s), ${String(row.buttons)} button(s), ${String(row.links)} link(s), scroll ${String(row.scrollY)}`,
2871
+ row.selection ? `selection: ${String(row.selection)}` : 'no selection',
2872
+ String(row.text ?? ''),
2873
+ ].join('\n') }];
2874
+ },
2875
+ },
2876
+ timeoutMs,
2877
+ isConcurrencySafe: () => true,
2878
+ async execute(_args, exec) {
2879
+ const browser = ctx.get('browser');
2880
+ if (browser === undefined)
2881
+ throw new Error('tool-browser: browser service unavailable');
2882
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec));
2883
+ await installProbe(browser, session, exec.signal);
2884
+ const summary = await probe(browser, session, 'summary', [], exec.signal);
2885
+ return { summary };
2886
+ },
2887
+ }));
1851
2888
  }
1852
2889
  /** Test hook: inspect and reset session mappings across every live plugin apply. */
1853
2890
  export const internals = {