dsh-builtin-browser 1.0.1 → 1.0.4

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 (222) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/assets/browser-panel-locales.mjs +37 -5
  4. package/assets/browser-policy.d.mts +29 -0
  5. package/assets/browser-policy.mjs +40 -0
  6. package/desktop-bridge/desktop-discovery.d.mts +1 -1
  7. package/desktop-bridge/desktop-discovery.mjs +59 -9
  8. package/desktop-bridge/desktop-identity.json +12 -0
  9. package/desktop-bridge/install.mjs +14 -7
  10. package/desktop-bridge/plugin-browser-bridge.js +19 -7
  11. package/docs/acceptance-2026-11-27.md +67 -0
  12. package/docs/architecture.md +1 -1
  13. package/docs/development.md +33 -4
  14. package/docs/dsh-0.2.3-host-patch-task.md +34 -0
  15. package/docs/hardcoding-audit.md +28 -8
  16. package/docs/known-issues.md +26 -0
  17. package/docs/limitations.md +6 -2
  18. package/docs/tool-reference.md +1 -1
  19. package/docs/v1.1.0-bu-data-batching-task.md +66 -0
  20. package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
  21. package/dsh-host-patch/README.md +4 -0
  22. package/dsh-host-patch/apply.mjs +61 -13
  23. package/dsh-host-patch/rc3-revision9.json.gz +0 -0
  24. package/dsh-host-patch/rc5-revision9.json.gz +0 -0
  25. package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
  26. package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
  27. package/dsh-host-patch/tauri-revision1.json +39 -0
  28. package/dsh-host-patch/tauri.json +43 -0
  29. package/dsh-host-patch/v023-alpha2.json +153 -0
  30. package/lib/browser/anti-bot.js +215 -0
  31. package/lib/browser/deep-dom.js +39 -0
  32. package/lib/browser/runtime.js +15 -0
  33. package/lib/browser/takeover-target.js +13 -6
  34. package/lib/browser/types.js +30 -1
  35. package/lib/browser-electron/authenticated-route.js +16 -2
  36. package/lib/browser-electron/automatic-maintenance.js +16 -10
  37. package/lib/browser-electron/bridge-connection.js +3 -8
  38. package/lib/browser-electron/bridge-install.js +2 -1
  39. package/lib/browser-electron/bridge-status.js +55 -26
  40. package/lib/browser-electron/desktop-bridge-host.js +7 -6
  41. package/lib/browser-electron/desktop-identity.js +28 -5
  42. package/lib/browser-electron/desktop-shell.js +64 -0
  43. package/lib/browser-electron/electron-provision.js +105 -18
  44. package/lib/browser-electron/entry.js +129 -44
  45. package/lib/browser-electron/extension-browser.js +4 -4
  46. package/lib/browser-electron/foreground-watch.js +134 -0
  47. package/lib/browser-electron/guest-cookie-jar.js +13 -13
  48. package/lib/browser-electron/guest-route.js +181 -32
  49. package/lib/browser-electron/guest-runtime.js +61 -10
  50. package/lib/browser-electron/guest-storage.js +2 -2
  51. package/lib/browser-electron/history-store.js +1 -5
  52. package/lib/browser-electron/host-main.js +8 -4
  53. package/lib/browser-electron/host-patch-maintenance.js +14 -8
  54. package/lib/browser-electron/maintenance-route.js +2 -1
  55. package/lib/browser-electron/missing-system-browser.js +5 -9
  56. package/lib/browser-electron/preferred-browser.js +7 -3
  57. package/lib/browser-electron/preview-route.js +9 -13
  58. package/lib/browser-electron/process-ownership.js +1 -1
  59. package/lib/browser-electron/profile-command.js +2 -1
  60. package/lib/browser-electron/profile-extension.js +5 -0
  61. package/lib/browser-electron/profile-lease.js +152 -47
  62. package/lib/browser-electron/provider-core.js +527 -0
  63. package/lib/browser-electron/provider-interaction.js +963 -0
  64. package/lib/browser-electron/provider-media.js +518 -0
  65. package/lib/browser-electron/provider-navigation.js +301 -0
  66. package/lib/browser-electron/provider-observation.js +623 -0
  67. package/lib/browser-electron/provider-tabs.js +372 -0
  68. package/lib/browser-electron/provider.js +150 -3301
  69. package/lib/browser-electron/reference-route.js +9 -18
  70. package/lib/browser-electron/remote-host.js +79 -34
  71. package/lib/browser-electron/runtime-status.js +56 -6
  72. package/lib/browser-electron/settings-store.js +3 -6
  73. package/lib/browser-electron/sidebar-only-host.js +1 -1
  74. package/lib/browser-electron/system-browser.js +539 -172
  75. package/lib/browser-electron/tauri-host.js +208 -0
  76. package/lib/browser-electron/virtual-cursor.js +23 -13
  77. package/lib/browser-reference/service.js +22 -4
  78. package/lib/browser-reference/web-sources.js +1 -1
  79. package/lib/client.js +43409 -0
  80. package/lib/compat/host-features.js +75 -0
  81. package/lib/reference-source.js +1 -1
  82. package/lib/reference-text.js +23 -1
  83. package/lib/takeover-protocol.js +1 -1
  84. package/lib/tool-browser/block-recovery.js +69 -0
  85. package/lib/tool-browser/code-tool.js +170 -19
  86. package/lib/tool-browser/code-worker.js +115 -20
  87. package/lib/tool-browser/errors.js +34 -0
  88. package/lib/tool-browser/index.js +66 -3593
  89. package/lib/tool-browser/page-probe.js +227 -28
  90. package/lib/tool-browser/panel-page.js +2 -1
  91. package/lib/tool-browser/probe-client.js +157 -0
  92. package/lib/tool-browser/screenshot-annotations.js +108 -0
  93. package/lib/tool-browser/state.js +337 -0
  94. package/lib/tool-browser/takeover.js +1 -1
  95. package/lib/tool-browser/tools-debug.js +862 -0
  96. package/lib/tool-browser/tools-interaction.js +993 -0
  97. package/lib/tool-browser/tools-navigation.js +807 -0
  98. package/lib/tool-browser/tools-observation.js +461 -0
  99. package/lib/tool-browser/tools-reference.js +293 -0
  100. package/lib/web-guest.js +1 -0
  101. package/package.json +16 -36
  102. package/scripts/build-client.mjs +305 -0
  103. package/scripts/build.mjs +15 -12
  104. package/scripts/fix-exports.mjs +6 -16
  105. package/scripts/install-electron.mjs +55 -5
  106. package/scripts/pack.mjs +99 -0
  107. package/scripts/publish-manifest.mjs +56 -0
  108. package/scripts/verify-exports.mjs +26 -15
  109. package/skills/dsh-builtin-browser/SKILL.md +27 -2
  110. package/skills/dsh-builtin-browser/references/batch.md +15 -0
  111. package/src/browser/anti-bot.ts +251 -0
  112. package/src/browser/deep-dom.ts +40 -0
  113. package/src/browser/runtime.ts +18 -0
  114. package/src/browser/takeover-target.ts +16 -7
  115. package/src/browser/types.ts +56 -3
  116. package/src/browser-electron/authenticated-route.ts +29 -4
  117. package/src/browser-electron/automatic-maintenance.ts +23 -13
  118. package/src/browser-electron/bridge-connection.ts +11 -10
  119. package/src/browser-electron/bridge-install.ts +2 -1
  120. package/src/browser-electron/bridge-status.ts +61 -22
  121. package/src/browser-electron/desktop-bridge-host.ts +9 -7
  122. package/src/browser-electron/desktop-identity.ts +38 -5
  123. package/src/browser-electron/desktop-shell.ts +100 -0
  124. package/src/browser-electron/electron-provision.ts +104 -18
  125. package/src/browser-electron/entry.ts +1378 -1299
  126. package/src/browser-electron/extension-browser.ts +11 -4
  127. package/src/browser-electron/foreground-watch.ts +142 -0
  128. package/src/browser-electron/guest-cookie-jar.ts +3 -2
  129. package/src/browser-electron/guest-route.ts +180 -32
  130. package/src/browser-electron/guest-runtime.ts +61 -10
  131. package/src/browser-electron/guest-storage.ts +5 -2
  132. package/src/browser-electron/history-store.ts +3 -6
  133. package/src/browser-electron/host-main.ts +8 -4
  134. package/src/browser-electron/host-patch-maintenance.ts +18 -9
  135. package/src/browser-electron/maintenance-route.ts +2 -1
  136. package/src/browser-electron/missing-system-browser.ts +11 -10
  137. package/src/browser-electron/preferred-browser.ts +13 -3
  138. package/src/browser-electron/preview-route.ts +9 -12
  139. package/src/browser-electron/process-ownership.ts +9 -3
  140. package/src/browser-electron/profile-command.ts +2 -1
  141. package/src/browser-electron/profile-extension.ts +5 -0
  142. package/src/browser-electron/profile-lease.ts +131 -35
  143. package/src/browser-electron/provider-core.ts +1107 -0
  144. package/src/browser-electron/provider-interaction.ts +1034 -0
  145. package/src/browser-electron/provider-media.ts +589 -0
  146. package/src/browser-electron/provider-navigation.ts +323 -0
  147. package/src/browser-electron/provider-observation.ts +664 -0
  148. package/src/browser-electron/provider-tabs.ts +372 -0
  149. package/src/browser-electron/provider.ts +158 -4063
  150. package/src/browser-electron/reference-route.ts +598 -608
  151. package/src/browser-electron/remote-host.ts +118 -42
  152. package/src/browser-electron/runtime-status.ts +80 -13
  153. package/src/browser-electron/settings-store.ts +10 -6
  154. package/src/browser-electron/sidebar-only-host.ts +4 -2
  155. package/src/browser-electron/system-browser.ts +537 -184
  156. package/src/browser-electron/tauri-host.ts +194 -0
  157. package/src/browser-electron/virtual-cursor.ts +24 -14
  158. package/src/browser-reference/service.ts +38 -7
  159. package/src/browser-reference/web-sources.ts +4 -1
  160. package/src/client/apply-guard.ts +22 -0
  161. package/src/client/browser/BrowserController.ts +3 -3
  162. package/src/client/browser/IframeImpl.ts +182 -176
  163. package/src/client/browser/frame-history.ts +125 -0
  164. package/src/client/browser/frame-state.ts +27 -0
  165. package/src/client/browser/web-reference-source.ts +5 -1
  166. package/src/client/definition.tsx +36 -30
  167. package/src/client/electron/ElectronWebViewImpl.ts +20 -13
  168. package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
  169. package/src/client/electron/NativeChildPresentation.ts +11 -3
  170. package/src/client/electron/NativeViewPage.ts +19 -5
  171. package/src/client/index.ts +333 -293
  172. package/src/client/locales.ts +9 -6
  173. package/src/client/reference/client/plugin.ts +21 -2
  174. package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
  175. package/src/client/reference/client/production/assembly.ts +4 -28
  176. package/src/client/reference/client/production/availability.ts +0 -2
  177. package/src/client/reference/client/production/composer-attachments.ts +44 -0
  178. package/src/client/reference/client/production/draft-adapter.ts +4 -0
  179. package/src/client/reference/client/production/http-transport.ts +0 -5
  180. package/src/client/reference/client/production/production-submission.ts +50 -290
  181. package/src/client/reference/client/production/protocol.ts +7 -4
  182. package/src/client/reference/client/production/runtime.ts +41 -86
  183. package/src/client/reference/client/production/source-marker.ts +49 -13
  184. package/src/client/reference/client/production/user-text-rule.ts +10 -1
  185. package/src/client/reference/client/reveal.ts +3 -1
  186. package/src/client/reference/client/session-schedule.ts +36 -0
  187. package/src/client/settings/index.ts +8 -0
  188. package/src/client/settings/mount-guard.ts +31 -0
  189. package/src/client/settings/panel.ts +163 -52
  190. package/src/client/startpage/controller.ts +3 -6
  191. package/src/client/view/BrowserBody.tsx +2 -1
  192. package/src/client/view/IframePresentation.ts +37 -16
  193. package/src/client/view/StartPage.tsx +2 -1
  194. package/src/compat/host-features.ts +92 -0
  195. package/src/reference-source.ts +1 -1
  196. package/src/reference-text.ts +23 -1
  197. package/src/takeover-protocol.ts +11 -2
  198. package/src/tool-browser/block-recovery.ts +85 -0
  199. package/src/tool-browser/code-tool.ts +173 -19
  200. package/src/tool-browser/code-worker.ts +101 -15
  201. package/src/tool-browser/errors.ts +40 -0
  202. package/src/tool-browser/index.ts +66 -3534
  203. package/src/tool-browser/page-probe.ts +229 -28
  204. package/src/tool-browser/panel-page.ts +3 -1
  205. package/src/tool-browser/probe-client.ts +183 -0
  206. package/src/tool-browser/screenshot-annotations.ts +131 -0
  207. package/src/tool-browser/state.ts +375 -0
  208. package/src/tool-browser/takeover.ts +3 -2
  209. package/src/tool-browser/tools-debug.ts +806 -0
  210. package/src/tool-browser/tools-interaction.ts +956 -0
  211. package/src/tool-browser/tools-navigation.ts +786 -0
  212. package/src/tool-browser/tools-observation.ts +474 -0
  213. package/src/tool-browser/tools-reference.ts +294 -0
  214. package/src/web-guest.ts +35 -34
  215. package/dist/client.cjs +0 -43167
  216. package/dist/client.d.cts +0 -516
  217. package/dist/client.d.mts +0 -516
  218. package/dist/index.cjs +0 -92
  219. package/dist/index.d.mts +0 -2960
  220. package/dist/index.mjs +0 -24
  221. package/lib/browser-reference/submission-receipts.js +0 -139
  222. package/src/browser-reference/submission-receipts.ts +0 -122
@@ -0,0 +1,474 @@
1
+ /**
2
+ * Observation tools: snapshots, accessibility, content, scrape, screenshot, state, find, challenge.
3
+ * @module dsh-browser/tool-browser/tools-observation
4
+ */
5
+
6
+ import { annotationLines, clearAnnotations, drawAnnotations, type ScreenshotAnnotation } from './screenshot-annotations.ts'
7
+ import type { ImageBlock } from '@deepseek-ai/dsh-llm'
8
+ import { SCREENSHOT_MAX_WIDTH, SCREENSHOT_MAX_HEIGHT, screenshotDimension, screenshotBytes, screenshotVisionEnabled, saveScreenshotImage } from './screenshot-image.ts'
9
+ import { defineTool } from '@deepseek-ai/dsh-tools'
10
+ import { CHALLENGE_SCHEMA, challengeBanner, reportChallenge, type ChallengeReport } from './block-recovery.ts'
11
+ import { NODE_ITEM_SCHEMA, projectElement, projectNode } from './element-fields.ts'
12
+ import { assertCapability } from '../browser/types.ts'
13
+ import { assertAllowed, agentOf, taskKey, ensureSession, carrierCapabilities, type ToolScope, type ToolDefinition } from './state.ts'
14
+ import { installProbe, probe, type ProbeRow } from './probe-client.ts'
15
+
16
+ /**
17
+ * Format a snapshot element list for the model.
18
+ *
19
+ * Coordinates are opt-in. They are only meaningful to a caller that intends to
20
+ * click a pixel position, which means a vision pass; for the far more common case
21
+ * of locating an element by role/label and passing a semantic target, they are the
22
+ * bulkiest and least useful part of every line. Omitting them keeps the listing
23
+ * readable — which is exactly what a model without image input has to work from.
24
+ * @param snapshot - the snapshot payload.
25
+ * @param options - `coords: true` to include each element's viewport position.
26
+ */
27
+ export function formatSnapshot(snapshot: {
28
+ url: string
29
+ title?: string
30
+ elements: readonly { ref: number; kind: string; label: string; x: number; y: number; frame?: boolean; selector?: string }[]
31
+ truncated?: boolean
32
+ challenge?: ChallengeReport
33
+ blank?: boolean
34
+ note?: string
35
+ canvas?: boolean
36
+ }, options: { coords?: boolean } = {}): string {
37
+ const showCoords = options.coords === true
38
+ const lines = snapshot.elements.map(el => `[${el.ref}] ${el.kind}: ${el.label}${el.selector !== undefined && el.selector !== '' ? ` {${el.selector}}` : ''}${el.frame === true ? ' (iframe)' : ''}${showCoords ? ` (${el.x},${el.y})` : ''}`)
39
+ const header = `URL: ${snapshot.url}${snapshot.title !== undefined ? `\nTitle: ${snapshot.title}` : ''}`
40
+ // A blank page, a canvas page and a page with nothing interactive are three different facts, and
41
+ // the old wording reported all of them as "no interactive elements found" — which reads as a
42
+ // successful look. Each now says what it is and what to do next.
43
+ const body = snapshot.blank === true
44
+ ? `BLANK PAGE: ${snapshot.note ?? 'nothing has been opened in this browser'}. `
45
+ + 'Do not drive this page — open a URL first (`dsh_browser_open`).'
46
+ : snapshot.canvas === true
47
+ ? `CANVAS PAGE: ${snapshot.note ?? 'this page draws its interface on a canvas'}. `
48
+ + 'A DOM snapshot cannot describe it; use `dsh_browser_screenshot` and coordinate clicks.'
49
+ : lines.length > 0 ? lines.join('\n') : '(no interactive elements found)'
50
+ const tail = snapshot.truncated === true ? '\n(snapshot truncated)' : ''
51
+ const banner = challengeBanner(snapshot.challenge)
52
+ return `${header}\n\n${body}${tail}${banner}`
53
+ }
54
+
55
+ /**
56
+ * Define this module's tools for one apply.
57
+ * @param scope - the apply's context, settings and per-apply state.
58
+ * @returns the tool definitions, for the entry to register.
59
+ */
60
+ export function observationTools(scope: ToolScope): ToolDefinition[] {
61
+ const { ctx, state, timeoutMs } = scope
62
+ const tools: ToolDefinition[] = []
63
+
64
+ tools.push(defineTool({
65
+ name: 'dsh_browser_snapshot',
66
+ description: 'Return an AI-friendly snapshot of the current shared-browser page: numbered interactive elements (inputs, buttons, links) the model can cite. This is the primary way to understand a page, and it needs no image input — every listed element can afterwards be addressed by a semantic target (dsh_browser_click, dsh_browser_type, dsh_browser_check, …) rather than by coordinates.',
67
+ parameters: {
68
+ coords: { type: 'boolean', description: 'Also print each element\'s viewport coordinates. Off by default; only useful when a vision pass is going to click a pixel position.' },
69
+ },
70
+ output: {
71
+ schema: {
72
+ type: 'object',
73
+ additionalProperties: false,
74
+ properties: {
75
+ url: { type: 'string', required: true },
76
+ title: { type: 'string' },
77
+ truncated: { type: 'boolean' },
78
+ elements: {
79
+ type: 'array',
80
+ required: true,
81
+ items: {
82
+ type: 'object',
83
+ additionalProperties: false,
84
+ properties: {
85
+ ref: { type: 'number', required: true },
86
+ kind: { type: 'string', required: true },
87
+ label: { type: 'string', required: true },
88
+ x: { type: 'number', required: true },
89
+ y: { type: 'number', required: true },
90
+ frame: { type: 'boolean' },
91
+ // The page-side script computes this for every element and the tool layer
92
+ // passes it through. Without it in the schema, a declared
93
+ // additionalProperties: false rejects the whole result at run time — which is
94
+ // how this was found, on the very first real call, after a static review had
95
+ // called the change verified.
96
+ selector: { type: 'string' },
97
+ },
98
+ },
99
+ },
100
+ challenge: CHALLENGE_SCHEMA,
101
+ },
102
+ },
103
+ render: (args, value) => [{ type: 'text', text: formatSnapshot(value, { coords: args.coords === true }) }],
104
+ },
105
+ timeoutMs,
106
+ isConcurrencySafe: () => true,
107
+ async execute(_args, exec) {
108
+ const browser = ctx.get('browser')
109
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
110
+ const key = taskKey(exec)
111
+ const session = await ensureSession(browser, state, key, agentOf(exec))
112
+ const snapshot = await browser.snapshot(session, exec.signal)
113
+ return {
114
+ url: snapshot.url,
115
+ ...snapshot.title !== undefined ? { title: snapshot.title } : {},
116
+ elements: snapshot.elements.map(el => projectElement(el)),
117
+ truncated: snapshot.truncated,
118
+ ...snapshot.challenge !== undefined ? { challenge: reportChallenge(snapshot.challenge, snapshot.url) } : {},
119
+ }
120
+ },
121
+ }))
122
+
123
+ tools.push(defineTool({
124
+ name: 'dsh_browser_a11y',
125
+ description: 'Read the accessibility tree: every interactive node with its role (button/link/textbox/checkbox/…), accessible name, value, and states (enabled/checked/expanded/…); coordinates only with coords: true. Prefer this over dsh_browser_snapshot to understand structure and find the right element — roles and names say WHAT each node is, and the name is what dsh_browser_click matches when targeting by text. Penetrates same-origin iframes and shadow roots.',
126
+ parameters: {
127
+ includeHidden: { type: 'boolean', description: 'Include hidden elements (default false).' },
128
+ maxNodes: { type: 'number', description: 'Maximum nodes (default 150, range 10-5000).' },
129
+ coords: { type: 'boolean', description: 'Include each element\'s viewport coordinates. Off by default: a semantic target needs no coordinates, and they are pure noise unless a vision pass is going to click a pixel position.' },
130
+ },
131
+ output: {
132
+ schema: {
133
+ type: 'object',
134
+ additionalProperties: false,
135
+ properties: {
136
+ url: { type: 'string', required: true },
137
+ title: { type: 'string' },
138
+ count: { type: 'number', required: true },
139
+ truncated: { type: 'boolean' },
140
+ nodes: {
141
+ type: 'array',
142
+ required: true,
143
+ // Same shared table as the node projection.
144
+ items: NODE_ITEM_SCHEMA,
145
+ },
146
+ },
147
+ },
148
+ render: (args, value) => {
149
+ const nodes = value.nodes as Array<{ ref: number; role: string; name: string; value?: string | null; states: string[]; depth: number; tag: string; x: number; y: number; frame?: boolean; selector?: string }>
150
+ // Built for reading, not for imaging: containment is shown as indentation
151
+ // (the depth was already collected and simply thrown away), an empty state
152
+ // list adds nothing, and coordinates appear only when asked for — a model
153
+ // working from the DOM never needs them, and they are the bulkiest part of
154
+ // every line.
155
+ const showCoords = args.coords === true
156
+ const lines = nodes.map(n => {
157
+ const valuePart = n.value !== undefined && n.value !== null ? ` value="${String(n.value).slice(0, 60)}"` : ''
158
+ // One space per level, not two: indentation was 19.7% of a measured 38,953-character
159
+ // result, and DOM depth is not a11y depth — deep wrapper divs push it to the cap.
160
+ const indent = ' '.repeat(Math.max(0, Math.min(8, Number(n.depth) || 0)))
161
+ const coordsPart = showCoords ? ` (${n.x},${n.y})` : ''
162
+ // Only states that are not the default. `states=[enabled]` was printed on 405 of 500
163
+ // nodes whose state WAS the default — 22% of the output for no information. Absence
164
+ // now means "enabled", which the description states.
165
+ const notableStates = Array.isArray(n.states) ? n.states.filter((state: string) => state !== 'enabled') : []
166
+ const statePart = notableStates.length > 0 ? ` states=[${notableStates.join(',')}]` : ''
167
+ // The provider computes this for a node with an id or a name; printing it is what
168
+ // makes the node something the caller can point at instead of guessing at its text.
169
+ const selectorPart = typeof n.selector === 'string' && n.selector !== '' ? ` {${n.selector}}` : ''
170
+ return `${indent}[${n.ref}] ${n.role} "${n.name}"${valuePart}${coordsPart}${statePart}${selectorPart}${n.frame === true ? ' (iframe)' : ''}`
171
+ })
172
+ const header = `URL: ${value.url}${value.title !== undefined ? `\nTitle: ${value.title}` : ''}`
173
+ // The "coords: true" hint used to be appended to EVERY a11y result. It already lives in
174
+ // the parameter description, so repeating it in each model turn was pure token cost.
175
+ return [{ type: 'text', text: `${header}\n\n${lines.length > 0 ? lines.join('\n') : '(no accessible interactive nodes)'}${value.truncated === true ? '\n(truncated)' : ''}` }]
176
+ },
177
+ },
178
+ timeoutMs,
179
+ isConcurrencySafe: () => true,
180
+ async execute(args, exec) {
181
+ const browser = ctx.get('browser')
182
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
183
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
184
+ const result = await browser.a11y(session, {
185
+ ...args.includeHidden === true ? { includeHidden: true } : {},
186
+ ...args.maxNodes !== undefined ? { maxNodes: args.maxNodes } : {},
187
+ }, exec.signal)
188
+ return {
189
+ url: result.url,
190
+ ...result.title !== undefined ? { title: result.title } : {},
191
+ count: result.count,
192
+ truncated: result.truncated,
193
+ // The projection drops `value: null` (the schema declares a string, and the contract is
194
+ // that an absent value means "not applicable"), so the run-time shape and the inferred
195
+ // type differ by exactly that. The field table is what keeps the schema and the
196
+ // projection in agreement; this assertion is the type-level echo of that.
197
+ // The projection and the schema are now generated from one field table, so the shape
198
+ // they agree on is guaranteed at run time. TypeScript cannot see that agreement — it
199
+ // infers the output type from the schema object and compares it against the provider's
200
+ // interface, which describes the provider's internal shape rather than the contract
201
+ // (`value` nullable internally, absent on the wire; `selector` required by the
202
+ // interface, optional in the inferred schema). The assertion bridges that last gap; the
203
+ // test that walks every registered tool is what checks the agreement for real.
204
+ nodes: result.nodes.map(n => projectNode(n)) as never,
205
+ }
206
+ },
207
+ }))
208
+
209
+ tools.push(defineTool({
210
+ name: 'dsh_browser_challenge',
211
+ description: 'Check whether the current page is a bot wall: a human verification (CAPTCHA, slider, press-and-hold, Cloudflare Turnstile), a "Just a moment" interstitial, an access-denied/429 refusal, or a network (IP) block. Returns the kind, what to do (recovery: takeover | wait | retry | environment) and public fallback routes (site API, search results, archives). Never solve or retry a human verification: call dsh_browser_request_takeover. A blocked page (403, access denied, bot wall) is not the end of the task: try other pages of the site, its JSON/API endpoints or sitemap, search results, or archived/reader copies first, keep each value tied to its source, and report a blocker only once those routes are exhausted while delivering everything found.',
212
+ parameters: {},
213
+ output: {
214
+ schema: CHALLENGE_SCHEMA,
215
+ render: (_args, value) => [{
216
+ type: 'text',
217
+ text: value.blocked ? challengeBanner(value).trimStart() : 'No challenge or block detected.',
218
+ }],
219
+ },
220
+ timeoutMs,
221
+ isConcurrencySafe: () => true,
222
+ async execute(_args, exec) {
223
+ const browser = ctx.get('browser')
224
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
225
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
226
+ const challenge = await browser.detectChallenge(session, exec.signal)
227
+ const tabs = await browser.listTabs(session).catch(() => [])
228
+ return reportChallenge(challenge, tabs.find(tab => tab.active)?.url ?? '')
229
+ },
230
+ }))
231
+
232
+ tools.push(defineTool({
233
+ name: 'dsh_browser_content',
234
+ description: 'Fetch the current shared-browser page content in a chosen format: html (raw DOM), markdown (structured reading), txt (plain text), or json. Optionally scope to a CSS selector and cap the length. Use this to read page content, not to interact.',
235
+ parameters: {
236
+ format: { type: 'string', required: true, enum: ['html', 'markdown', 'txt', 'json'], description: 'Output format.' },
237
+ selector: { type: 'string', description: 'CSS selector limiting the fetch to one region (e.g. #main).' },
238
+ maxChars: { type: 'number', description: 'Maximum characters of returned content.' },
239
+ timeoutMs: { type: 'number', description: 'Evaluation timeout in ms (default 30000).' },
240
+ },
241
+ output: {
242
+ schema: {
243
+ type: 'object',
244
+ additionalProperties: false,
245
+ properties: {
246
+ content: { type: 'string', required: true },
247
+ truncated: { type: 'boolean', required: true },
248
+ },
249
+ },
250
+ render: (_args, value) => [{ type: 'text', text: value.content + (value.truncated ? `\n(content truncated — narrow it with selector= or raise maxChars)` : '') }],
251
+ },
252
+ timeoutMs,
253
+ isConcurrencySafe: () => true,
254
+ async execute(args, exec) {
255
+ const browser = ctx.get('browser')
256
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
257
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
258
+ const result = await browser.content(session, {
259
+ format: args.format,
260
+ ...args.selector !== undefined ? { selector: args.selector } : {},
261
+ ...args.maxChars !== undefined ? { maxChars: args.maxChars } : {},
262
+ ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
263
+ }, exec.signal)
264
+ return { content: result.content, truncated: result.truncated }
265
+ },
266
+ }))
267
+
268
+ tools.push(defineTool({
269
+ name: 'dsh_browser_scrape',
270
+ description: 'Extract structured data from a page: give the container CSS selector (item) and a field map (name -> selector, optionally selector@attr to take an attribute; a@href yields the absolute URL). Returns one object per item. Static CSS queries only — no arbitrary code runs — so it is safe on any page. Use for list pages (search results, cards, tables) instead of hand-writing dsh_browser_execute.',
271
+ parameters: {
272
+ item: { type: 'string', required: true, description: 'CSS selector of each result container (e.g. "div.card").' },
273
+ fields: {
274
+ type: 'object',
275
+ required: true,
276
+ additionalProperties: true,
277
+ description: 'Field map: name -> selector[@attr] (e.g. {"title": "h3", "url": "a@href"}).',
278
+ },
279
+ timeoutMs: { type: 'number', description: 'Wait budget for the item selector in ms (default 5000).' },
280
+ },
281
+ output: {
282
+ schema: {
283
+ type: 'object',
284
+ additionalProperties: false,
285
+ properties: {
286
+ count: { type: 'number', required: true },
287
+ items: {
288
+ type: 'array',
289
+ required: true,
290
+ items: { type: 'object', additionalProperties: true },
291
+ },
292
+ },
293
+ },
294
+ render: (_args, value) => [{
295
+ type: 'text',
296
+ // Compact, unlike the pretty-printed form this used to emit: two-space indentation
297
+ // carries no information a model can use and cost 13.7% of a measured 39,559-character
298
+ // result. The count leads so the caller can tell a short list from a capped one.
299
+ text: `${value.count} item(s):\n${JSON.stringify(value.items)}`,
300
+ }],
301
+ },
302
+ timeoutMs,
303
+ isConcurrencySafe: () => true,
304
+ async execute(args, exec) {
305
+ assertAllowed(state, 'dsh_browser_scrape', taskKey(exec))
306
+ const browser = ctx.get('browser')
307
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
308
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
309
+ const fields = (args.fields ?? {}) as Record<string, string>
310
+ const result = await browser.scrape(session, {
311
+ item: args.item,
312
+ fields: Object.entries(fields).map(([name, selector]) => ({ name, selector })),
313
+ ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
314
+ }, exec.signal)
315
+ return { count: result.count, items: result.items.map(it => ({ ...it })) as never }
316
+ },
317
+ }))
318
+
319
+ tools.push(defineTool({
320
+ name: 'dsh_browser_screenshot',
321
+ description: 'Screenshot the Desktop browser (PNG default, JPEG where supported). Vision-capable active models receive the image directly; non-vision or unknown models receive text metadata only. Images are downscaled to at most 1280x960 and limited to 4 MiB; retry with smaller dimensions if encoding exceeds the limit. Supports fullPage and savePath. Web iframe screenshots are unavailable. Never solve CAPTCHAs automatically; request human takeover instead.',
322
+ parameters: {
323
+ fullPage: { type: 'boolean', description: 'Capture the full scrollable page instead of the viewport (default false).' },
324
+ savePath: { type: 'string', description: 'Absolute file path to also save the image to. Must resolve inside the configured downloadDir (default: the system Downloads folder, localized names such as ~/下载 included); an existing file is never overwritten.' },
325
+ format: { type: 'string', enum: ['png', 'jpeg'], description: 'Image format (default png; jpeg needs the self-hosted browser or an installed Chrome/Edge; the desktop sidebar returns PNG because the Electron CDP JPEG encoder hangs).' },
326
+ quality: { type: 'number', description: 'JPEG quality 1-100 (default 80); ignored for PNG.' },
327
+ maxWidth: { type: 'number', description: 'Downscale to fit within this width (aspect preserved).' },
328
+ maxHeight: { type: 'number', description: 'Downscale to fit within this height (aspect preserved).' },
329
+ annotate: { type: 'boolean', description: 'Draw numbered boxes on the visible interactive elements (open shadow roots and same-origin iframes included) for this capture only, and return them as elements: [{ id, x, y, role, label }] with x/y the centre in viewport CSS pixels (what click {x, y} takes). Viewport only; not with fullPage.' },
330
+ },
331
+ output: {
332
+ schema: {
333
+ type: 'object',
334
+ additionalProperties: false,
335
+ properties: {
336
+ bytes: { type: 'number', required: true, description: 'Encoded screenshot byte count.' },
337
+ attachment: {
338
+ type: 'object', additionalProperties: false,
339
+ properties: {
340
+ attachmentId: { type: 'string', required: true },
341
+ mediaType: { type: 'string', required: true },
342
+ bytes: { type: 'number', required: true },
343
+ width: { type: 'number', required: true },
344
+ height: { type: 'number', required: true },
345
+ },
346
+ },
347
+ width: { type: 'number', description: 'Pixel width of the returned image, when the capture was measured (present with maxWidth/maxHeight).' },
348
+ height: { type: 'number', description: 'Pixel height of the returned image, when the capture was measured.' },
349
+ path: { type: 'string', description: 'The file path the screenshot was saved to, when savePath was given.' },
350
+ elements: {
351
+ type: 'array',
352
+ description: 'The numbered elements drawn on an annotated screenshot.',
353
+ items: {
354
+ type: 'object', additionalProperties: false,
355
+ properties: {
356
+ id: { type: 'number', required: true },
357
+ x: { type: 'number', required: true },
358
+ y: { type: 'number', required: true },
359
+ role: { type: 'string', required: true },
360
+ label: { type: 'string', required: true },
361
+ },
362
+ },
363
+ },
364
+ },
365
+ },
366
+ render: (_args, value) => [
367
+ { type: 'text', text: [`Screenshot captured (${Math.round(value.bytes / 1024)} KiB${value.width !== undefined && value.height !== undefined ? `, ${value.width}x${value.height}` : ''})${value.path !== undefined ? ` saved to ${value.path}` : ''}.`, ...value.elements === undefined ? [] : [`${value.elements.length} annotated element(s):`, ...annotationLines(value.elements as ScreenshotAnnotation[])]].join('\n') },
368
+ ...value.attachment === undefined ? [] : [{ type: 'image' as const, attachment: value.attachment as ImageBlock['attachment'] }],
369
+ ],
370
+ },
371
+ timeoutMs,
372
+ isConcurrencySafe: () => true,
373
+ async execute(args, exec) {
374
+ const browser = ctx.get('browser')
375
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
376
+ const key = taskKey(exec)
377
+ await state.pendingPanelOpens.get(key)
378
+ const existing = state.sessionsByTask.get(key)
379
+ assertCapability(carrierCapabilities(browser, state, key), 'screenshot',
380
+ 'Web 侧栏暂不支持截图:iframe 无法被网页静默截图 (panel surface unavailable). Use the CDP-backed DSH desktop sidebar with a connected desktop bridge for screenshots.')
381
+ if (args.annotate === true && args.fullPage === true) throw new Error('annotate marks the viewport; drop fullPage or annotate')
382
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
383
+ const vision = await screenshotVisionEnabled(ctx, exec, exec.signal)
384
+ const maxWidth = screenshotDimension(args.maxWidth, SCREENSHOT_MAX_WIDTH)
385
+ const maxHeight = screenshotDimension(args.maxHeight, SCREENSHOT_MAX_HEIGHT)
386
+ const elements = args.annotate === true ? await drawAnnotations(browser, session, exec.signal) : undefined
387
+ const shot = await browser.screenshot(session, {
388
+ ...args.fullPage === true ? { fullPage: true } : {},
389
+ ...args.savePath !== undefined ? { savePath: args.savePath } : {},
390
+ ...args.format !== undefined ? { format: args.format } : {},
391
+ ...args.quality !== undefined ? { quality: args.quality } : {},
392
+ maxWidth,
393
+ maxHeight,
394
+ }, exec.signal).finally(() => elements !== undefined ? clearAnnotations(browser, session) : undefined)
395
+ exec.signal?.throwIfAborted()
396
+ const image = screenshotBytes(shot.dataUrl)
397
+ const attachment = vision ? await saveScreenshotImage(ctx, image, maxWidth, maxHeight) : undefined
398
+ exec.signal?.throwIfAborted()
399
+ return {
400
+ bytes: image.data.length,
401
+ ...attachment === undefined ? {} : { attachment },
402
+ ...shot.path !== undefined ? { path: shot.path } : {},
403
+ ...shot.width !== undefined ? { width: shot.width } : {},
404
+ ...shot.height !== undefined ? { height: shot.height } : {},
405
+ ...elements !== undefined ? { elements: elements.map(row => ({ ...row })) } : {},
406
+ }
407
+ },
408
+ }))
409
+
410
+ tools.push(defineTool({
411
+ name: 'dsh_browser_find',
412
+ 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. Searches open shadow roots and same-origin iframes too; cross-origin frames stay opaque.',
413
+ parameters: {
414
+ text: { type: 'string', required: true, description: 'Text to look for (case-insensitive).' },
415
+ all: { type: 'boolean', description: 'Return up to 50 hits instead of 5.' },
416
+ },
417
+ output: {
418
+ schema: { type: 'object', additionalProperties: false, properties: { count: { type: 'number', required: true }, hits: { type: 'array', items: { type: 'object', additionalProperties: true }, required: true } } },
419
+ render: (_args, value) => {
420
+ const hits = value.hits as ProbeRow[]
421
+ if (hits.length === 0) return [{ type: 'text', text: 'Not found on the page.' }]
422
+ 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') }]
423
+ },
424
+ },
425
+ timeoutMs,
426
+ isConcurrencySafe: () => true,
427
+ async execute(args, exec) {
428
+ const browser = ctx.get('browser')
429
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
430
+ const session = await ensureSession(browser, state, taskKey(exec), agentOf(exec))
431
+ await installProbe(browser, session, exec.signal)
432
+ const hits = await probe<ProbeRow[]>(browser, session, 'findText', [args.text, args.all === true], exec.signal)
433
+ return { count: hits.length, hits }
434
+ },
435
+ }))
436
+
437
+ tools.push(defineTool({
438
+ name: 'dsh_browser_state',
439
+ 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, the viewport size and device pixel ratio, 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.',
440
+ parameters: {},
441
+ output: {
442
+ schema: {
443
+ type: 'object',
444
+ additionalProperties: false,
445
+ properties: { summary: { type: 'object', additionalProperties: true, required: true } },
446
+ },
447
+ render: (_args, value) => {
448
+ const row = value.summary as ProbeRow
449
+ return [{ type: 'text', text: [
450
+ `${String(row.url)}`,
451
+ `${String(row.title)}`,
452
+ `${String(row.readyState)}, ${String(row.pending)} in flight, quiet ${String(row.quietMs)}ms`,
453
+ `${String(row.inputs)} input(s), ${String(row.buttons)} button(s), ${String(row.links)} link(s), scroll ${String(row.scrollY)}`,
454
+ `viewport ${String(row.vpWidth)}×${String(row.vpHeight)} @${String(row.dpr)} (window ${String(row.winWidth)}×${String(row.winHeight)})`,
455
+ row.selection ? `selection: ${String(row.selection)}` : 'no selection',
456
+ String(row.text ?? ''),
457
+ ].join('\n') }]
458
+ },
459
+ },
460
+ timeoutMs,
461
+ isConcurrencySafe: () => true,
462
+ async execute(_args, exec) {
463
+ const browser = ctx.get('browser')
464
+ if (browser === undefined) throw new Error('tool-browser: browser service unavailable')
465
+ const key = taskKey(exec)
466
+ const session = await ensureSession(browser, state, key, agentOf(exec))
467
+ await installProbe(browser, session, exec.signal)
468
+ const summary = await probe<ProbeRow>(browser, session, 'summary', [], exec.signal)
469
+ return { summary }
470
+ },
471
+ }))
472
+
473
+ return tools
474
+ }