dsh-codex-style-computer-use 2.3.4 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +60 -5
  2. package/README.zh.md +50 -5
  3. package/client.js +1556 -32
  4. package/lib/browser/APACHE-2.0.txt +202 -0
  5. package/lib/browser/MIT-dsh-doyourweb.txt +21 -0
  6. package/lib/browser/NOTICE.md +53 -0
  7. package/lib/browser/README.md +139 -0
  8. package/lib/browser/access.js +540 -0
  9. package/lib/browser/approval.js +82 -0
  10. package/lib/browser/bridge.js +1048 -0
  11. package/lib/browser/engine.js +669 -0
  12. package/lib/browser/extension/background.js +474 -0
  13. package/lib/browser/extension/config.js +6 -0
  14. package/lib/browser/extension/manifest.json +25 -0
  15. package/lib/browser/extension/popup.css +89 -0
  16. package/lib/browser/extension/popup.html +35 -0
  17. package/lib/browser/extension/popup.js +99 -0
  18. package/lib/browser/host-protocol.js +132 -0
  19. package/lib/browser/host.js +1089 -0
  20. package/lib/browser/model.js +111 -0
  21. package/lib/browser/pairing.js +126 -0
  22. package/lib/browser/policy.js +131 -0
  23. package/lib/browser/protocol.js +171 -0
  24. package/lib/browser/schema.js +82 -0
  25. package/lib/browser/setup-page.js +145 -0
  26. package/lib/core/bin/dsh-computer-use-worker.exe +0 -0
  27. package/lib/core/bin/dsh-computer-use-worker.exe.json +2 -2
  28. package/lib/core/index.js +58 -1
  29. package/lib/core/worker.cs +32 -1
  30. package/lib/host-debug.js +3 -2
  31. package/lib/index.js +286 -4
  32. package/lib/references-apps.js +586 -0
  33. package/lib/references-files.js +77 -0
  34. package/lib/references.js +233 -0
  35. package/package.json +7 -2
  36. package/scripts/check-behavior.mjs +60 -0
  37. package/scripts/verify-browser-integration.mjs +807 -0
@@ -0,0 +1,669 @@
1
+ // lib/browser/engine.js — DOM snapshot, paged reads and the bounded action batch.
2
+ //
3
+ // Adapted from DoYourWeb 0.2.6 (MIT) src/engine.js — the snapshot/act/extract/capture core — with
4
+ // the WebMCP, network-capture, annotation and upload-tool surfaces removed (they are explicitly out
5
+ // of scope for this partition) and the page-access guard made mandatory on every path.
6
+ //
7
+ // WHY A SNAPSHOT ID IS THE UNIT OF INSIGHT. A page's DOM moves under you: a click opens a dialog, a
8
+ // form submits, an SPA re-renders. Every readmints a random snapshot id, and every action call must
9
+ // present the CURRENT one for that tab. Acting on a stale id is refused before anything is
10
+ // dispatched — it is the difference between "the element I measured" and "whatever is at that
11
+ // position now". A cursor continues the SAME snapshot's text (so a long page can be read in pieces
12
+ // without minting a new id or invalidating the one being paged).
13
+ //
14
+ // WHY THE BATCH IS BOUNDED AT 12. One call is one model round trip, so batching is the main cost
15
+ // lever; but an unbounded list turns a single approval into an arbitrary program. Twelve is the
16
+ // number the skill and the tool description both state, and it is enforced here rather than
17
+ // trusted from the caller.
18
+ //
19
+ // WHY EVERY STEP RE-CHECKS THE PAGE. Navigation, a redirect or a page that moves ITSELF onto a
20
+ // DSH surface must stop the batch at the first step after the change. Before each step the engine
21
+ // calls `pageAccess.assertUrl(page.url())`; after a step it compares the document identity
22
+ // (url + performance.timeOrigin) and, when it changed, stops and reports `navigated: true` so the
23
+ // model reads the new page instead of replaying a step that may already have landed.
24
+ //
25
+ // WHY THE HOST'S CONTROL SURFACE IS REFUSED. `assertUrl` also refuses loopback pages on a port the
26
+ // HOST owns (the DSH web UI, this plugin's settings route, the bridge's pairing page). A browser tab
27
+ // that could read those would be a way around the desktop host guard — the model could approve its
28
+ // own approval cards through the browser instead of clicking them. That is one rule in one place
29
+ // (lib/browser/host-protocol.js `admitUrl`), and both the read and act paths ask it.
30
+
31
+ import { randomUUID } from 'node:crypto'
32
+ import path from 'node:path'
33
+ import { mkdir, stat, access, realpath, writeFile } from 'node:fs/promises'
34
+ import { constants } from 'node:fs'
35
+ import { clip, serialize } from './host-protocol.js'
36
+
37
+ export const MAX_STEPS = 12
38
+ export const MAX_STEP_FILES = 20
39
+
40
+ /** One page's text, sliced at a line boundary so a cursor never splits a line in half. */
41
+ export function pageChunk (snapshot, offset = 0, limit = 2400) {
42
+ if (!Number.isInteger(offset) || offset < 0 || offset > snapshot.text.length) throw new Error('Invalid snapshot cursor')
43
+ const end = Math.min(snapshot.text.length, offset + limit)
44
+ const newline = snapshot.text.lastIndexOf('\n', end - 1)
45
+ const boundary = end < snapshot.text.length && newline > offset ? newline + 1 : end
46
+ return {
47
+ snapshot: snapshot.id, url: snapshot.url, title: snapshot.title,
48
+ content: snapshot.text.slice(offset, boundary),
49
+ ...(boundary < snapshot.text.length ? { cursor: `${snapshot.id}:${boundary}`, omittedChars: snapshot.text.length - boundary } : {}),
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Fit a read into a byte budget.
55
+ *
56
+ * A limit that cannot even hold the metadata is an ERROR rather than a silent truncation: a caller
57
+ * that asked for 400 characters and got a title with no content has not been given a read.
58
+ */
59
+ function boundedChunk (state, offset, limit, extra) {
60
+ const metadata = { ...state, title: clip(state.title, Math.min(128, Math.floor(limit / 10))),
61
+ url: clip(state.url, Math.min(512, Math.floor(limit / 5))) }
62
+ let truncated = metadata.title !== state.title || metadata.url !== state.url
63
+ const result = length => ({ ...extra, ...pageChunk(metadata, offset, length),
64
+ ...(truncated ? { metadataTruncated: true } : {}) })
65
+ const minimum = offset < state.text.length ? 1 : 0
66
+ for (const field of ['title', 'url']) {
67
+ if (serialize(result(minimum)).length <= limit) break
68
+ metadata[field] = undefined
69
+ truncated = true
70
+ }
71
+ if (serialize(result(minimum)).length > limit) throw new Error('Output budget is too small for the action receipt; increase limit')
72
+ let low = minimum
73
+ let high = Math.min(state.text.length - offset, limit)
74
+ while (low < high) {
75
+ const middle = Math.ceil((low + high) / 2)
76
+ if (serialize(result(middle)).length <= limit) low = middle
77
+ else high = middle - 1
78
+ }
79
+ return result(low)
80
+ }
81
+
82
+ function checkpoint (signal) { signal?.throwIfAborted() }
83
+
84
+ /** Bound one batch receipt to its budget without ever dropping the evidence that it dispatched. */
85
+ function boundAction (result, cap = 1400) {
86
+ const budget = Math.max(400, Math.min(8000, cap))
87
+ for (const [object, key] of [[result.failure, 'error'], [result.expectation, 'error'], [result, 'readError'], [result, 'url']]) {
88
+ while (serialize(result).length > budget && object?.[key]?.length > 16) {
89
+ object[key] = clip(object[key], Math.floor(object[key].length / 2))
90
+ if (key === 'url') result.metadataTruncated = true
91
+ }
92
+ }
93
+ while (serialize(result).length > budget) {
94
+ const entry = result.results?.filter(item => item.rows?.length)
95
+ .sort((a, b) => serialize(b).length - serialize(a).length)[0]
96
+ if (!entry) {
97
+ const upload = result.results?.find(item => item.files?.length)
98
+ if (!upload) break
99
+ upload.files.pop()
100
+ upload.omittedFiles = (upload.omittedFiles || 0) + 1
101
+ continue
102
+ }
103
+ entry.rows.pop()
104
+ entry.omittedRows++
105
+ entry.truncated = true
106
+ }
107
+ // `completed` has no per-item cost to trade away: twelve steps is ~370 characters, which alone
108
+ // can exceed a small budget. Collapse it to a count rather than return an over-budget receipt.
109
+ if (Array.isArray(result.completed) && result.completed.length) {
110
+ while (serialize(result).length > budget && result.completed.length > 1) {
111
+ result.completed.pop()
112
+ result.completedTruncated = true
113
+ }
114
+ if (serialize(result).length > budget) {
115
+ result.completedCount = result.completed.length
116
+ result.completed = []
117
+ result.completedTruncated = true
118
+ }
119
+ }
120
+ return result
121
+ }
122
+
123
+ function boundedExtraction (index, data, limit) {
124
+ const result = { index, rows: data.rows, omittedRows: data.totalRows - data.rows.length,
125
+ ...(data.truncated ? { truncated: true } : {}) }
126
+ if (serialize(result).length <= limit) return result
127
+ result.truncated = true
128
+ const dropRow = () => { result.rows.pop(); result.omittedRows++ }
129
+ while (result.rows.length > 1 && serialize(result).length > limit) dropRow()
130
+ if (result.rows.length) {
131
+ for (let size = 100; serialize(result).length > limit && size >= 4; size = Math.floor(size / 2)) {
132
+ for (const key of Object.keys(result.rows[0])) result.rows[0][key] = clip(result.rows[0][key], size)
133
+ }
134
+ if (serialize(result).length > limit) dropRow()
135
+ }
136
+ return result
137
+ }
138
+
139
+ export class BrowserEngine {
140
+ /**
141
+ * @param {object} bridge a BrowserBridge ({page, release, on, off, cdp})
142
+ * @param {{snapshotChars?: number, artifactDir?: string}} options
143
+ */
144
+ constructor (bridge, { snapshotChars = 2400, artifactDir } = {}) {
145
+ this.bridge = bridge
146
+ this.snapshotChars = snapshotChars
147
+ this.artifactDir = artifactDir
148
+ this.states = new Map()
149
+ this.queues = new Map()
150
+ this.receipts = new Map()
151
+ this.actions = new Map()
152
+ // A released relay invalidates the snapshot, but an uncertain-effect receipt must survive it:
153
+ // it is the only evidence that a dispatched action may still land, and dropping it would let
154
+ // the next call replay the effect.
155
+ this.onRelease = ref => {
156
+ this.states.delete(ref)
157
+ if (!this.receipts.get(ref)?.mayHaveLateEffects) this.receipts.delete(ref)
158
+ }
159
+ this.onActivityStop = (ref, reply) => {
160
+ const controller = this.actions.get(ref)
161
+ const stopped = !!controller && !controller.signal.aborted
162
+ if (stopped) controller.abort(new Error('Stopped from the browser extension'))
163
+ reply(stopped)
164
+ }
165
+ try { this.bridge?.on?.('release', this.onRelease) } catch { /* stub bridge */ }
166
+ try { this.bridge?.on?.('activityStop', this.onActivityStop) } catch { /* stub bridge */ }
167
+ }
168
+
169
+ close () {
170
+ try { this.bridge?.off?.('release', this.onRelease) } catch { /* stub bridge */ }
171
+ try { this.bridge?.off?.('activityStop', this.onActivityStop) } catch { /* stub bridge */ }
172
+ this.states.clear()
173
+ this.receipts.clear()
174
+ this.actions.clear()
175
+ }
176
+
177
+ /**
178
+ * Attach to one tab, run `operation(page, signal)`, always release the debugger attachment.
179
+ *
180
+ * `pageAccess` is REQUIRED for every read and act: this is the point where the conversation's
181
+ * grant is turned into an enforced invariant instead of a caller's remembered promise.
182
+ */
183
+ async withPage (ref, operation, signal, active = false, pageAccess) {
184
+ checkpoint(signal)
185
+ const controller = active && this.bridge.cdp ? new AbortController() : undefined
186
+ const actionSignal = controller
187
+ ? (signal && AbortSignal.any ? AbortSignal.any([signal, controller.signal]) : controller.signal)
188
+ : signal
189
+ if (controller) this.actions.set(ref, controller)
190
+ try {
191
+ const page = await this.bridge.page(ref)
192
+ checkpoint(actionSignal)
193
+ pageAccess?.assertUrl(page.url())
194
+ const result = await operation(page, actionSignal)
195
+ if (!active) pageAccess?.assertUrl(page.url())
196
+ return result
197
+ } finally {
198
+ if (controller) this.actions.delete(ref)
199
+ this.bridge.release?.(ref)
200
+ }
201
+ }
202
+
203
+ /** One operation at a time per tab; a second call waits rather than interleaving with the first. */
204
+ async serial (ref, operation) {
205
+ const previous = this.queues.get(ref) || Promise.resolve()
206
+ const current = previous.catch(() => {}).then(operation)
207
+ this.queues.set(ref, current)
208
+ try { return await current } finally { if (this.queues.get(ref) === current) this.queues.delete(ref) }
209
+ }
210
+
211
+ async document (page) {
212
+ return page.evaluate(() => ({ url: location.href, epoch: performance.timeOrigin }))
213
+ }
214
+
215
+ /** The accessibility/AI snapshot of one read root, with the staleness checks a snapshot needs. */
216
+ async snapshot (ref, page, options = {}, signal) {
217
+ checkpoint(signal)
218
+ const before = await this.document(page)
219
+ options.pageAccess?.assertUrl(before.url)
220
+ let root = page.locator('xpath=/html/body')
221
+ if (options.scope === 'main') {
222
+ const main = page.locator("main, [role='main']")
223
+ if (await main.count() === 1 && await main.isVisible()) root = main
224
+ }
225
+ if (options.selector) root = page.locator(options.selector)
226
+ if (options.query) root = root.getByText(options.query, { exact: false })
227
+ let text
228
+ try {
229
+ // `ariaSnapshot` keeps role/name/level in the text, which is what element refs are made of.
230
+ text = await root.ariaSnapshot({ mode: 'ai', depth: options.depth || 8, timeout: 8000, signal })
231
+ } catch (error) {
232
+ if (!String(error?.message || '').includes('strict mode violation')) throw error
233
+ throw new Error('Read scope matches multiple elements. Choose one unique root (for example their common parent), or read each scope separately.', { cause: error })
234
+ }
235
+ const after = await this.document(page)
236
+ checkpoint(signal)
237
+ options.pageAccess?.assertUrl(after.url)
238
+ if (before.epoch !== after.epoch || before.url !== after.url) throw new Error('Page navigated while reading; read it again')
239
+ const state = { id: randomUUID().slice(0, 8), text, ...after, title: await page.title(), ref }
240
+ this.states.set(ref, state)
241
+ return state
242
+ }
243
+
244
+ async read (ref, options = {}, signal) {
245
+ return this.serial(ref, () => this.withPage(ref, async page => {
246
+ checkpoint(signal)
247
+ const limit = Math.max(400, Math.min(8000, options.limit || this.snapshotChars))
248
+ if (options.cursor) {
249
+ const [id, offset] = String(options.cursor).split(':')
250
+ const state = this.states.get(ref)
251
+ const document = await this.document(page)
252
+ options.pageAccess?.assertUrl(document.url)
253
+ if (!state || state.id !== id || document.epoch !== state.epoch || document.url !== state.url) {
254
+ throw new Error('Snapshot cursor is stale; read the page again without cursor')
255
+ }
256
+ checkpoint(signal)
257
+ const chunk = boundedChunk(state, Number(offset), limit, { tab: ref,
258
+ ...(this.receipts.has(ref) ? { lastAction: this.receipts.get(ref) } : {}) })
259
+ state.refsAvailable = true
260
+ return chunk
261
+ }
262
+ const state = await this.snapshot(ref, page, options, signal)
263
+ checkpoint(signal)
264
+ return boundedChunk(state, 0, limit, { tab: ref,
265
+ ...(this.receipts.has(ref) ? { lastAction: this.receipts.get(ref) } : {}) })
266
+ }, signal, false, options.pageAccess))
267
+ }
268
+
269
+ locator (page, step) {
270
+ if (step.ref) {
271
+ if (!/^(?:f\d+)?e\d+$/.test(step.ref)) throw new Error('Use an element ref from the latest browser read snapshot')
272
+ return page.locator(`aria-ref=${step.ref}`)
273
+ }
274
+ if (step.selector) return step.frame ? page.frameLocator(step.frame).locator(step.selector) : page.locator(step.selector)
275
+ throw new Error('Action requires ref or selector')
276
+ }
277
+
278
+ /**
279
+ * Validate every upload/drop path BEFORE the first step is dispatched.
280
+ *
281
+ * A batch that refuses at step 7 because file 3 does not exist has already performed six actions.
282
+ * Uploads are also the one step that DISCLOSES a local file to a website, so the caller's
283
+ * authorization for each exact path is checked by the tool layer (host.js) before this runs; here
284
+ * only the filesystem reality is established.
285
+ */
286
+ async prepareUploads (steps) {
287
+ const uploads = new Map()
288
+ for (const [index, step] of steps.entries()) {
289
+ if (step.op !== 'upload' && !(step.op === 'drop' && step.files)) continue
290
+ if (!Array.isArray(step.files) || !step.files.length || step.files.length > MAX_STEP_FILES) {
291
+ throw new Error(`Upload requires 1-${MAX_STEP_FILES} explicitly authorized absolute file paths`)
292
+ }
293
+ const files = []
294
+ for (const file of step.files) {
295
+ if (typeof file !== 'string' || !path.isAbsolute(file)) throw new Error('Upload paths must be absolute local files')
296
+ const resolved = await realpath(file)
297
+ if (!(await stat(resolved)).isFile()) throw new Error('Upload requires a regular file, not a directory')
298
+ await access(resolved, constants.R_OK)
299
+ files.push(resolved)
300
+ }
301
+ uploads.set(index, files)
302
+ }
303
+ return uploads
304
+ }
305
+
306
+ async act (ref, options, signal) {
307
+ return this.serial(ref, () => this.withPage(ref, async (page, actionSignal) => {
308
+ signal = actionSignal
309
+ checkpoint(signal)
310
+ const state = this.states.get(ref)
311
+ const actionId = randomUUID().slice(0, 8)
312
+ const steps = Array.isArray(options.steps) ? options.steps : []
313
+ if (!steps.length || steps.length > MAX_STEPS) throw new Error(`An action batch needs 1-${MAX_STEPS} steps`)
314
+ const pageAccess = options.pageAccess
315
+ let uploads
316
+ // THE DOCUMENT IDENTITY LIVES OUTSIDE THE PREFLIGHT try BLOCK ON PURPOSE (measured crash,
317
+ // 2026-11-28): it used to be declared with `let` INSIDE that block, so the step loop below
318
+ // read the enclosing scope's `document` — Node's global, which is undefined — and every batch
319
+ // died with `document is not defined` AFTER its first step had already been dispatched. The
320
+ // browser showed the fill, the receipt said `failure {index:0, dispatch:"sent"}`, and step 2
321
+ // never ran. A thrown ReferenceError there also skipped the honest failure record, which is
322
+ // exactly the "effect landed but the report denies it" shape that invites a duplicate replay.
323
+ // One buffer, assigned in preflight and updated when a soft (query/hash) navigation is seen.
324
+ let doc = await this.document(page)
325
+ try {
326
+ if (!state || options.snapshot !== state.id) {
327
+ throw new Error('Snapshot is stale. Use the latest read snapshot for this tab. Call the read tool before acting; no actions were performed.')
328
+ }
329
+ if (state.refsAvailable === false && steps.some(step => step.ref || step.toRef)) {
330
+ throw new Error('That receipt withheld element refs. Read its cursor before using refs, or continue with selectors; old refs must not be reused.')
331
+ }
332
+ pageAccess?.assertUrl(doc.url)
333
+ if (doc.epoch !== state.epoch || doc.url !== state.url) {
334
+ throw new Error('Snapshot is stale. Use the latest read snapshot for this tab. No actions were performed.')
335
+ }
336
+ for (const step of steps) {
337
+ if (step.op === 'navigate') {
338
+ if (!step.value?.trim()) throw new Error('navigate requires a URL in step.value, for example {"op":"navigate","value":"https://example.com"}. No actions were performed.')
339
+ pageAccess?.declareNavigation(step.value)
340
+ }
341
+ }
342
+ uploads = await this.prepareUploads(steps)
343
+ } catch (error) {
344
+ // A rejected retry must never destroy the evidence of a batch that may have dispatched
345
+ // something. Only a preflight failure that dispatched nothing may replace a `dispatch:none`
346
+ // receipt; otherwise the model would be told "nothing happened" and replay a landed action.
347
+ const existing = this.receipts.get(ref)
348
+ const dispatched = !!existing && (existing.mayHaveLateEffects === true || existing.cancelled === true ||
349
+ (Array.isArray(existing.completed) && existing.completed.length > 0) ||
350
+ (existing.failure !== undefined && existing.failure.dispatch !== 'none'))
351
+ if (!dispatched) this.receipts.set(ref, { actionId, snapshot: options.snapshot, completed: [], dispatch: 'none', rejected: true })
352
+ throw error
353
+ }
354
+ const completed = []
355
+ const results = []
356
+ const extractCount = steps.filter(step => step.op === 'extract').length
357
+ const extractLimit = Math.max(64, Math.floor(600 / Math.max(1, extractCount)))
358
+ let failure
359
+ let navigated = false
360
+ let cancelled = false
361
+ let uncertainStep
362
+ // Invalidate BEFORE dispatch: a cancellation must not leave an old snapshot reusable.
363
+ this.states.delete(ref)
364
+ this.receipts.delete(ref)
365
+ for (let index = 0; index < steps.length; index++) {
366
+ const step = steps[index]
367
+ let invoked = false
368
+ let sent = false
369
+ let phase
370
+ const invoke = operation => { invoked = true; return operation() }
371
+ const commandSent = (tab, command) => {
372
+ if (invoked && tab === ref && /^(?:Input\.(?:dispatchMouseEvent|dispatchKeyEvent|insertText|dispatchTouchEvent|dispatchDragEvent)|DOM\.setFileInputFiles|Page\.(?:navigate|navigateToHistoryEntry))$/.test(command)) sent = true
373
+ }
374
+ this.bridge.on?.('commandSent', commandSent)
375
+ try {
376
+ checkpoint(signal)
377
+ pageAccess?.assertUrl(page.url())
378
+ if (step.op === 'navigate') {
379
+ await invoke(() => page.goto(step.value, { waitUntil: 'domcontentloaded', signal }))
380
+ } else if (step.op === 'back') await invoke(() => page.goBack({ waitUntil: 'domcontentloaded', signal }))
381
+ else if (step.op === 'forward') await invoke(() => page.goForward({ waitUntil: 'domcontentloaded', signal }))
382
+ else if (step.op === 'scroll') {
383
+ await invoke(() => page.mouse.wheel(0, step.amount || 600))
384
+ } else {
385
+ const target = this.locator(page, step)
386
+ if (step.op === 'click') await invoke(() => target.click({ signal }))
387
+ else if (step.op === 'drag') {
388
+ const destination = this.locator(page, { ref: step.toRef, selector: step.toSelector, frame: step.frame })
389
+ await invoke(() => target.dragTo(destination, { timeout: 8000, signal }))
390
+ } else if (step.op === 'drop') {
391
+ await invoke(() => target.drop({
392
+ ...(uploads.has(index) ? { files: uploads.get(index) } : {}),
393
+ ...(step.data ? { data: step.data } : {}),
394
+ }, { timeout: 8000, signal }))
395
+ if (uploads.has(index)) results.push({ index, files: uploads.get(index).map(file => clip(path.basename(file), 40)) })
396
+ } else if (step.op === 'upload') {
397
+ const files = uploads.get(index)
398
+ const input = await target.evaluate(element => element.localName === 'input' && element.type === 'file', undefined, { timeout: 8000, signal })
399
+ phase = input ? 'selecting_files' : 'opening_chooser'
400
+ if (input) await invoke(() => target.setInputFiles(files, { timeout: 8000, signal }))
401
+ else {
402
+ // Cancel the chooser waiter when its triggering click fails as well.
403
+ const chooserController = new AbortController()
404
+ const chooserSignal = signal && AbortSignal.any ? AbortSignal.any([signal, chooserController.signal]) : chooserController.signal
405
+ const pending = page.waitForEvent('filechooser', { timeout: 8000, signal: chooserSignal })
406
+ pending.catch(() => {})
407
+ try {
408
+ await invoke(() => target.click({ timeout: 8000, signal }))
409
+ phase = 'button_clicked'
410
+ const chooser = await pending
411
+ phase = 'chooser_received'
412
+ checkpoint(signal)
413
+ await chooser.setFiles(files, { timeout: 8000, signal })
414
+ } finally { chooserController.abort() }
415
+ }
416
+ phase = 'files_selected'
417
+ results.push({ index, files: files.map(file => clip(path.basename(file), 40)) })
418
+ } else if (step.op === 'fill') await invoke(() => target.fill(step.value, { signal }))
419
+ else if (step.op === 'press') await invoke(() => target.press(step.value, { signal }))
420
+ else if (step.op === 'select') await invoke(() => target.selectOption(step.value, { signal }))
421
+ else if (step.op === 'check') await invoke(() => target.setChecked(step.checked ?? true, { signal }))
422
+ else if (step.op === 'hover') await invoke(() => target.hover({ signal }))
423
+ else if (step.op === 'wait') await target.waitFor({ state: step.state || 'visible', timeout: step.timeout || 8000, signal })
424
+ else if (step.op === 'extract') {
425
+ const fields = step.fields || ['text']
426
+ if (!fields.length || fields.some(field => !['text', 'value', 'href'].includes(field))) {
427
+ throw new Error('Extract fields must be text, value or href')
428
+ }
429
+ const data = await target.evaluateAll((nodes, options) => {
430
+ let truncated = false
431
+ const rows = nodes.slice(0, options.maxRows).map(node => {
432
+ const row = {}
433
+ for (const field of options.fields) {
434
+ const value = field === 'text' ? (node.innerText ?? node.textContent ?? '').replace(/\s+/g, ' ').trim()
435
+ : field === 'href' ? (node.href ?? '')
436
+ : node.type === 'password' ? '' : (node.value ?? '')
437
+ const text = String(value)
438
+ if (text.length > 200) truncated = true
439
+ row[field] = text.slice(0, 200)
440
+ }
441
+ return row
442
+ })
443
+ return { rows, totalRows: nodes.length, truncated }
444
+ }, { fields, maxRows: Math.max(1, Math.min(20, step.maxRows || 10)) })
445
+ results.push(boundedExtraction(index, data, extractLimit))
446
+ } else throw new Error(`Unknown action: ${step.op}`)
447
+ }
448
+ completed.push({ index, op: step.op })
449
+ checkpoint(signal)
450
+ const after = await this.document(page)
451
+ pageAccess?.assertUrl(after.url)
452
+ pageAccess?.commitNavigation?.(after.url)
453
+ if (after.epoch !== doc.epoch || after.url !== doc.url) {
454
+ const previous = new URL(doc.url)
455
+ const current = new URL(after.url)
456
+ const soft = after.epoch === doc.epoch && current.origin === previous.origin && current.pathname === previous.pathname
457
+ // A query/hash update does not prove DOM refs are still valid. Only selector-based or
458
+ // target-free observations may follow; a selector alone cannot prove a changed form safe.
459
+ if (soft && steps.slice(index + 1).every(next => !next.ref && ['wait', 'extract', 'scroll', 'navigate', 'back', 'forward'].includes(next.op))) {
460
+ doc = after
461
+ } else { navigated = true; break }
462
+ }
463
+ } catch (error) {
464
+ cancelled = signal?.aborted === true
465
+ if (invoked && completed.at(-1)?.index !== index) uncertainStep = index
466
+ failure = { index, op: step.op, error: clip(error.message || error, 200),
467
+ dispatch: sent ? 'sent' : invoked ? 'unknown' : 'none', ...(phase ? { phase } : {}) }
468
+ break
469
+ } finally { this.bridge.off?.('commandSent', commandSent) }
470
+ }
471
+ const budget = Math.max(400, Math.min(8000, this.snapshotChars))
472
+ const result = boundAction({ tab: ref, actionId, fromSnapshot: state.id, completed,
473
+ remaining: steps.length - completed.length,
474
+ ...(results.length ? { results } : {}),
475
+ ...(failure ? { failure, retry: 'Read current state first. Do not replay completed or uncertain actions.' } : {}),
476
+ ...(navigated ? { navigated: true, stopped: 'Navigation occurred; read the new page before remaining actions.' } : {}),
477
+ ...(cancelled ? { cancelled: true } : {}),
478
+ ...(uncertainStep !== undefined ? { uncertainStep, mayHaveLateEffects: true } : {}) }, budget)
479
+ const receipt = { actionId, snapshot: state.id, completed: completed.map(step => step.index),
480
+ ...(failure ? { failure: { index: failure.index, dispatch: failure.dispatch, ...(failure.phase ? { phase: failure.phase } : {}) } } : {}),
481
+ ...(cancelled ? { cancelled: true } : {}),
482
+ ...(navigated ? { navigated: true } : {}),
483
+ ...(uncertainStep !== undefined ? { uncertainStep, mayHaveLateEffects: true } : {}) }
484
+ this.receipts.set(ref, receipt)
485
+ if (cancelled) return result
486
+ // The optional expectation is a SEPARATE observation, never a claim that the actions worked:
487
+ // it reports `matched`/`unmet` on its own and leaves the executed-steps evidence untouched.
488
+ if (options.expect && !failure && completed.length === steps.length) {
489
+ const expected = options.expect
490
+ const wait = { timeout: expected.timeout || 8000, signal }
491
+ try {
492
+ checkpoint(signal)
493
+ pageAccess?.assertUrl(page.url())
494
+ if (expected.kind === 'url') await page.waitForURL(url => url.href === expected.value, { ...wait, waitUntil: 'commit' })
495
+ else {
496
+ const target = this.locator(page, expected)
497
+ if (expected.kind === 'visible') await target.waitFor({ state: 'visible', ...wait })
498
+ else await target.waitForFunction((element, spec) => spec.kind === 'text'
499
+ ? (element.innerText ?? element.textContent ?? '').includes(spec.value)
500
+ : element.type !== 'password' && element.value === spec.value,
501
+ { kind: expected.kind, value: expected.value }, wait)
502
+ }
503
+ checkpoint(signal)
504
+ pageAccess?.assertUrl(page.url())
505
+ pageAccess?.commitNavigation?.(page.url())
506
+ result.expectation = { kind: expected.kind, status: 'matched' }
507
+ } catch (error) {
508
+ result.expectation = { kind: expected.kind,
509
+ status: signal?.aborted ? 'cancelled' : error.name === 'TimeoutError' ? 'unmet' : 'error',
510
+ error: clip(error.message || error, 200) }
511
+ if (signal?.aborted) { result.cancelled = true; receipt.cancelled = true }
512
+ }
513
+ receipt.expectation = { kind: result.expectation.kind, status: result.expectation.status }
514
+ }
515
+ if (result.cancelled) return boundAction(result, budget)
516
+ if (options.observe === 'summary') return boundAction(result, budget)
517
+ try {
518
+ pageAccess?.assertUrl(page.url())
519
+ const next = await this.snapshot(ref, page, options.observation || {}, signal)
520
+ pageAccess?.assertUrl(next.url)
521
+ if (options.observe === 'handle') {
522
+ next.refsAvailable = false
523
+ return boundAction({ ...result, snapshot: next.id, cursor: `${next.id}:0`,
524
+ url: clip(next.url, 512), title: clip(next.title, 128), refs: 'read_required' }, budget)
525
+ }
526
+ return boundedChunk(next, 0, budget, result)
527
+ } catch (error) {
528
+ if (signal?.aborted) {
529
+ this.states.delete(ref)
530
+ receipt.cancelled = true
531
+ return { ...result, cancelled: true }
532
+ }
533
+ receipt.readError = true
534
+ return boundAction({ ...result, ...(pageAccess ? {} : { url: clip(page.url(), 256) }),
535
+ readError: clip(error.message, 200) }, budget)
536
+ }
537
+ }, signal, true, options.pageAccess))
538
+ }
539
+
540
+ /** A one-step upload through the same batch machinery, so nothing gains a private path. */
541
+ upload (ref, options, signal) {
542
+ return this.act(ref, {
543
+ snapshot: options.snapshot, observe: options.observe, observation: options.observation,
544
+ expect: options.expect, pageAccess: options.pageAccess,
545
+ steps: [{ op: 'upload', ref: options.ref, selector: options.selector, frame: options.frame, files: options.files }],
546
+ }, signal)
547
+ }
548
+
549
+ /**
550
+ * Full-page or viewport screenshot of the authorized tab, saved to a local PNG.
551
+ *
552
+ * WHY A FULL PAGE IS NOT `page.screenshot({fullPage:true})` HERE (measured 2026-11-28, branded
553
+ * Chrome 158, 175% DPI, real relayed tab): Playwright derived 1789×8603 for a document whose native
554
+ * capture is 1815×8603 — the right edge was cut by 26 CSS pixels, and both 6px magenta witness
555
+ * strips in the synthetic page disappeared. Playwright builds the full-page box from ITS viewport
556
+ * and scrollbar model; across this CDP relay that model lacks the real scrollbar width.
557
+ *
558
+ * So the geometry comes from the page itself, through the SAME debugger session the read/act engine
559
+ * already drives on this tab (`bridge.resolve` → `bridge.request` → the extension's
560
+ * `chrome.debugger`). Two FIXED commands, no session attach, no extra target, no DPR arithmetic:
561
+ *
562
+ * Page.getLayoutMetrics → cssContentSize, e.g. {x:0, y:0, width:1037, height:4916}
563
+ * (matches innerWidth=1037 / scrollHeight=4916 on the real tab)
564
+ * Page.captureScreenshot → clip exactly that CSS box at scale:1
565
+ * (measured 1815×8603, identical to native capture)
566
+ *
567
+ * `clip` is in CSS pixels and the browser rasterizes at the real DPR itself, so the size is used
568
+ * AS REPORTED; multiplying by 1.75 would clip almost twice the document.
569
+ *
570
+ * FALLBACK: unless BOTH commands answer with a usable size, the ordinary Playwright full-page
571
+ * screenshot is used — still a FULL page, never a viewport crop. A mock bridge or a page that
572
+ * cannot answer therefore behaves exactly as before.
573
+ */
574
+ async capture (ref, options = {}, signal) {
575
+ return this.serial(ref, () => this.withPage(ref, async page => {
576
+ checkpoint(signal)
577
+ const directory = this.artifactDir || path.join(process.cwd(), 'browser-captures')
578
+ await mkdir(directory, { recursive: true })
579
+ const output = path.join(directory, `browser-capture-${randomUUID()}.png`)
580
+ // The page may move while a screenshot is being taken; the URL is checked before AND after, so
581
+ // a capture can never be handed back as evidence for a page the user never cited.
582
+ options.pageAccess?.assertUrl(page.url())
583
+ let image = null
584
+ if (options.fullPage === true) image = await this.captureFullPage(ref, page, signal)
585
+ if (!image) {
586
+ image = await page.screenshot({ fullPage: options.fullPage === true,
587
+ animations: 'disabled', signal })
588
+ }
589
+ // CANCELLATION AND URL ARE RE-VERIFIED BEFORE THE BYTES ARE KEPT: a capture cancelled while the
590
+ // browser was rasterizing must not leave a file that looks like a completed one, and a page
591
+ // that navigated mid-capture must not be saved under the cited URL's evidence.
592
+ options.pageAccess?.assertUrl(page.url())
593
+ checkpoint(signal)
594
+ if (image) await writeFile(output, image)
595
+ return { tab: ref, url: clip(page.url(), 512), path: output, mediaType: 'image/png' }
596
+ }, signal, false, options.pageAccess))
597
+ }
598
+
599
+ /**
600
+ * The whole document through the tab's existing debugger session, or null when that is impossible.
601
+ *
602
+ * THE SCROLLBAR IS WHY `innerWidth` IS PART OF THE CLIP (measured in production, 2026-11-28). A
603
+ * full-page capture makes Chrome TEMPORARILY HIDE the page scrollbar to rasterize the whole
604
+ * document. Hiding it widens the layout by the scrollbar's 15 CSS pixels, but
605
+ * `Page.getLayoutMetrics` is asked BEFORE that switch and reports the NARROW layout:
606
+ *
607
+ * cssContentSize.width 1022
608
+ * cssLayoutViewport.width 1022
609
+ * cssVisualViewport.width 1022.28
610
+ * window.innerWidth 1037 ← includes the space the scrollbar occupies
611
+ *
612
+ * Clipping to 1022 therefore cut the right edge — the 26 device pixels / missing magenta strips.
613
+ * The page's own `window.innerWidth` is the ONLY number that already accounts for the scrollbar, so
614
+ * the clip width is `max(cssContentSize.width, innerWidth)`. Same for height, where `innerHeight` is
615
+ * the floor for a short document.
616
+ *
617
+ * NO new CDP session, no hard-coded scrollbar width and no DPR arithmetic: when the page cannot
618
+ * answer `innerWidth`, the metrics alone are used (the previous behaviour).
619
+ *
620
+ * The two method names are LITERALS in this file — never a tool argument — so this is not a
621
+ * protocol escape hatch, and `bridge.resolve` is the authorization boundary that refuses a closed
622
+ * tab, an unsupported URL or a protected host port before anything is sent.
623
+ */
624
+ async captureFullPage (ref, page, signal) {
625
+ if (typeof this.bridge?.request !== 'function' || typeof this.bridge?.resolve !== 'function') return null
626
+ let target
627
+ try { target = this.bridge.resolve(ref) } catch { return null }
628
+ checkpoint(signal)
629
+ const send = (method, params) => this.bridge.request(target.profile,
630
+ 'chrome.debugger.sendCommand', [{ tabId: target.tabId }, method, params])
631
+ // THE PAGE'S OWN VIEWPORT, read concurrently with the metrics: `innerWidth` includes the 15 CSS
632
+ // pixels the hidden scrollbar occupies, which no layout metric reports. A failure here is not
633
+ // fatal — the metrics alone still produce a usable clip.
634
+ const innerViewport = Promise.resolve()
635
+ .then(() => page?.evaluate?.(() => ({ width: window.innerWidth, height: window.innerHeight })))
636
+ .catch(() => null)
637
+ try {
638
+ const [metrics, inner] = await Promise.all([send('Page.getLayoutMetrics', {}), innerViewport])
639
+ checkpoint(signal)
640
+ // CSS content size ONLY. `contentSize` is the pre-DPR box; a visual viewport would describe the
641
+ // visible area, which is the wrong thing to clip a whole document to.
642
+ const size = metrics?.cssContentSize ?? metrics?.contentSize
643
+ const metricsWidth = Number(size?.width)
644
+ const metricsHeight = Number(size?.height)
645
+ if (!Number.isFinite(metricsWidth) || !Number.isFinite(metricsHeight) ||
646
+ metricsWidth <= 0 || metricsHeight <= 0) return null
647
+ const finite = value => {
648
+ const number = Number(value)
649
+ return Number.isFinite(number) && number > 0 ? number : 0
650
+ }
651
+ // The floor that fixes the right edge; `max` so a page with NO scrollbar (innerWidth == layout
652
+ // width) is unaffected, and so a taller-than-viewport document keeps its content height.
653
+ const width = Math.max(metricsWidth, finite(inner?.width))
654
+ const height = Math.max(metricsHeight, finite(inner?.height))
655
+ const shot = await send('Page.captureScreenshot', {
656
+ format: 'png',
657
+ fromSurface: true,
658
+ captureBeyondViewport: true,
659
+ // `ceil` is a rounding safety for a fractional CSS size, NOT a DPR conversion.
660
+ clip: { x: 0, y: 0, width: Math.ceil(width), height: Math.ceil(height), scale: 1 },
661
+ })
662
+ checkpoint(signal)
663
+ return typeof shot?.data === 'string' && shot.data ? Buffer.from(shot.data, 'base64') : null
664
+ } catch (error) {
665
+ if (signal?.aborted) throw error
666
+ return null
667
+ }
668
+ }
669
+ }