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,518 @@
1
+ import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs';
2
+ import { lstatSync, mkdirSync, realpathSync } from 'node:fs';
3
+ import { writeFileNoReplace } from './file-write.js';
4
+ import { dirname, isAbsolute, resolve, sep } from 'node:path';
5
+ import { BrowserError } from '../browser/types.js';
6
+ import { PROVIDER_TIMEOUTS, CDP_PAGE_CAPTURE_SCREENSHOT, layoutSize, toExportedCookies, toCdpCookie, withTimeout } from './provider-core.js';
7
+ import { ProviderInteraction } from './provider-interaction.js';
8
+ /**
9
+ * Whether a directory entry exists at `path`, judging the ENTRY rather than what it
10
+ * points at.
11
+ *
12
+ * `existsSync` follows links, so a DANGLING symlink — a link whose target does not
13
+ * exist — reads as "nothing here", and a write to that path creates the target
14
+ * instead: outside `downloadDir` whenever the link points out of it. `lstatSync`
15
+ * sees the link itself, which is the only correct answer to "is this name free".
16
+ * @param path - the path to judge.
17
+ * @returns true when any entry (file, directory, link) occupies the name.
18
+ */
19
+ function entryExists(path) {
20
+ try {
21
+ lstatSync(path);
22
+ return true;
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ /**
29
+ * The real path of the deepest existing ancestor of `path` — `path` itself when it
30
+ * exists, otherwise the nearest directory above it that does.
31
+ *
32
+ * `resolve()` normalizes `..` but never follows a link, so nothing textual can tell
33
+ * that `<downloadDir>/link/x.png` leaves the directory through `link`. The first
34
+ * ancestor that exists (judged by lstat, so a dangling link counts — the write would
35
+ * go through it) is the last component whose real location still determines where
36
+ * the bytes land, so that is the one to resolve and check.
37
+ * @param path - an absolute path that may not exist yet.
38
+ * @returns the resolved real path of its deepest existing ancestor.
39
+ */
40
+ function realAncestorOf(path) {
41
+ let current = path;
42
+ for (let depth = 0; depth < 64; depth += 1) {
43
+ if (entryExists(current)) {
44
+ try {
45
+ return realpathSync(current);
46
+ }
47
+ catch {
48
+ // The entry vanished between the two calls, or cannot be resolved: the
49
+ // textual path is the best available answer, and the write reports the rest.
50
+ return current;
51
+ }
52
+ }
53
+ const parent = dirname(current);
54
+ if (parent === current)
55
+ return current;
56
+ current = parent;
57
+ }
58
+ return current;
59
+ }
60
+ /**
61
+ * Bounds for one passive preview frame.
62
+ *
63
+ * The design's numbers (issue #34): viewport only, JPEG quality 70, fit inside 1280x720 without
64
+ * enlarging, and a 2 s capture ceiling so a stuck frame ends the viewer's wait instead of piling up
65
+ * behind the control queue. These are deliberately not configurable in v1 — one canonical spec per
66
+ * target is what lets several viewers share a single capture.
67
+ */
68
+ const PREVIEW_CAPTURE_MS = 2_000;
69
+ const PREVIEW_QUALITY = 70;
70
+ const PREVIEW_MAX_WIDTH = 1280;
71
+ const PREVIEW_MAX_HEIGHT = 720;
72
+ export class ProviderMedia extends ProviderInteraction {
73
+ /**
74
+ * Admit a caller-supplied save path for a file the browser writes to disk.
75
+ * ONE gate for both `dsh_browser_download` and `dsh_browser_screenshot`: the path
76
+ * must be absolute, must resolve inside `downloadDir`, and must not already
77
+ * exist. Without it a prompt-injected agent could write — or silently
78
+ * replace — any file the DSH process can reach, which also escapes the file
79
+ * sandbox every other tool in the set runs under.
80
+ * @param savePath - the caller's target path.
81
+ * @param kind - the operation, used in the error code and message.
82
+ * @returns the resolved absolute target path.
83
+ * @throws BrowserError when the path is relative, outside the directory, or occupied.
84
+ */
85
+ admitSavePath(savePath, kind) {
86
+ const code = kind === 'download' ? 'BROWSER_DOWNLOAD_BLOCKED' : 'BROWSER_SCREENSHOT_BLOCKED';
87
+ if (!isAbsolute(savePath)) {
88
+ throw new BrowserError(`browser: ${kind} savePath must be an absolute path`, code);
89
+ }
90
+ const file = resolve(savePath);
91
+ if (this.downloadDir !== undefined) {
92
+ const dir = resolve(this.downloadDir);
93
+ // Windows paths are case-insensitive and resolve() does not normalize case, so there
94
+ // the containment check folds case — otherwise %USERPROFILE%\Downloads and
95
+ // %userprofile%\downloads would read as different roots. Everywhere else the fold is
96
+ // REMOVED: a case-sensitive filesystem (Linux) treats /home/u/DOWNLOADS and
97
+ // /home/u/Downloads as different directories, so folding case there let a savePath
98
+ // that merely differed in case pass admission — a directory-confinement escape, and
99
+ // one that mkdirSync below would then happily create.
100
+ const fold = process.platform === 'win32' ? (value) => value.toLowerCase() : (value) => value;
101
+ const dirKey = fold(dir);
102
+ const fileKey = fold(file);
103
+ // The directory ITSELF is refused, not accepted: a save path that IS downloadDir names
104
+ // a directory, so there is no file to write — and mkdirSync would have created the
105
+ // directory when it did not exist. Two paths are "inside" only when the file path is
106
+ // strictly below the directory, which the separator check below already expresses.
107
+ if (!fileKey.startsWith(dirKey + fold(sep))) {
108
+ throw new BrowserError(`browser: ${kind} savePath must be inside downloadDir "${dir}"`, code);
109
+ }
110
+ // The check above is textual, and a symlink defeats it: resolve() normalizes `..`
111
+ // but never follows a link, so `<downloadDir>/out/x.png` passed every test above
112
+ // while `out` pointed at a directory outside the gate — and the write then landed
113
+ // there. Resolve the REAL location of the deepest existing ancestor (which is what
114
+ // decides where the bytes go) and require it to be inside the real directory too.
115
+ // A legitimate path is unaffected: its ancestor resolves to the directory itself.
116
+ //
117
+ // The directory is created first so that it can be resolved at all — mkdirSync is a
118
+ // no-op for one that already exists — and a directory that cannot be created or
119
+ // resolved falls back to its textual form, leaving the real filesystem error to the
120
+ // write instead of inventing one here.
121
+ let realDir;
122
+ try {
123
+ mkdirSync(dir, { recursive: true });
124
+ realDir = fold(realpathSync(dir));
125
+ }
126
+ catch {
127
+ realDir = fold(dir);
128
+ }
129
+ const realAncestor = fold(realAncestorOf(file));
130
+ if (realAncestor !== realDir && !realAncestor.startsWith(realDir + fold(sep))) {
131
+ throw new BrowserError(`browser: ${kind} savePath resolves outside downloadDir "${dir}" (a symlink leaves it)`, code);
132
+ }
133
+ }
134
+ // Never replace an existing file: its previous content is unrecoverable,
135
+ // and the admitted directory may hold files the human put there. A new
136
+ // name is one tool call away.
137
+ //
138
+ // Judged with lstat (see {@link entryExists}), not existsSync: existsSync FOLLOWS
139
+ // links, so a DANGLING symlink read as "nothing here" and the write below created
140
+ // its target — outside the directory whenever the link pointed out of it. It is the
141
+ // directory entry that has to be free, whatever that entry points at.
142
+ if (entryExists(file)) {
143
+ throw new BrowserError(`browser: refusing to overwrite existing file "${file}" — use another name`, code);
144
+ }
145
+ return file;
146
+ }
147
+ /**
148
+ * Download an HTTP(S) URL with the session's cookies to a local file.
149
+ * Admission is the shared {@link admitSavePath} gate. The carrier downloads
150
+ * with its own authenticated browser session. Both admitted paths and screenshots are confined
151
+ * to `downloadDir`, so a prompt-injected agent cannot write arbitrary
152
+ * machine paths.
153
+ * @param session - the session whose cookies are used.
154
+ * @param request - the URL plus the absolute target path.
155
+ * @param signal - optional cancellation.
156
+ * @returns the path the file was written to.
157
+ */
158
+ async download(session, request, signal) {
159
+ // Before admission, and before the session is even resolved: a switched-off action is
160
+ // not a path problem, and the caller should hear the real reason.
161
+ this.assertActionAllowed('download');
162
+ const s = this.session(session);
163
+ const { handle } = this.activeTab(s);
164
+ signal?.throwIfAborted();
165
+ // URL admission: HTTP(S) only (mirrors the navigation guard). The seam
166
+ // intentionally does not block private/localhost targets — a shared real
167
+ // browser legitimately reaches local dev servers.
168
+ let parsed;
169
+ try {
170
+ parsed = new URL(request.url);
171
+ }
172
+ catch {
173
+ throw new BrowserError(`browser: refusing download of unparseable URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED');
174
+ }
175
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
176
+ throw new BrowserError(`browser: refusing download of non-HTTP(S) URL "${request.url}"`, 'BROWSER_DOWNLOAD_BLOCKED');
177
+ }
178
+ // savePath admission: the shared gate — absolute, inside `downloadDir`,
179
+ // and never an existing file. Screenshots use the very same one.
180
+ const savePath = this.admitSavePath(request.savePath, 'download');
181
+ const downloadable = handle;
182
+ if (typeof downloadable.download !== 'function') {
183
+ throw new BrowserError('browser: the selected carrier does not provide file downloads', 'BROWSER_DOWNLOAD_UNSUPPORTED');
184
+ }
185
+ // The child fetches and writes the file; a slow/hung network can block
186
+ // it well past the tool budget, so bound it. NOTE: unlike CDP calls,
187
+ // there is no child-side abort mechanism for the RPC download — when the
188
+ // parent's timeout fires the child continues writing. The parent's pending
189
+ // entry is cleaned up (the promise settles) and the child's eventual
190
+ // reply is harmlessly consumed by the RPC layer.
191
+ const timeoutMs = PROVIDER_TIMEOUTS.download;
192
+ await withTimeout(downloadable.download(request.url, savePath), timeoutMs, signal, `browser: download timed out after ${timeoutMs}ms`);
193
+ this.record(s, 'download', { url: request.url, savePath }, true, { result: savePath });
194
+ return { path: savePath };
195
+ }
196
+ /**
197
+ * Export the session's cookies (login state) as serializable objects.
198
+ * Self-hosted only; the desktop shell's embedded views use the real profile.
199
+ */
200
+ async flushAuth(session) {
201
+ // The settings panel offers "allow the agent to read cookies / export login state".
202
+ // Until now nothing read that switch, so turning it off changed nothing at all —
203
+ // the tool exported every cookie regardless.
204
+ if (this.settingsSource?.().credentials.allowRead === false) {
205
+ throw new BrowserError('browser: reading cookies is switched off in settings (Browser → credentials)', 'BROWSER_AUTH_DISABLED');
206
+ }
207
+ const s = this.session(session);
208
+ const { handle } = this.activeTab(s);
209
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
210
+ // The self-hosted carrier has a native path (the child reads its own session), which
211
+ // is worth preferring: it reports exactly what the browser persisted.
212
+ const native = handle;
213
+ if (typeof native.flushAuth === 'function') {
214
+ const cookies = await withTimeout(native.flushAuth(), timeoutMs, undefined, `browser: auth export timed out after ${timeoutMs}ms`);
215
+ this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies` });
216
+ return cookies;
217
+ }
218
+ // Every other carrier drives a real browser over CDP, and cookies are part of CDP —
219
+ // the sidebar goes through the shell's webContents.debugger, an installed Chrome or
220
+ // Edge is the browser itself. So this works everywhere rather than only self-hosted.
221
+ // Scoped to the page this session is on. The jar itself is SHARED on purpose — every
222
+ // window and every task drives the same browser, so signing in once works everywhere,
223
+ // which is the whole point of "use your own browser". What must not be shared is the
224
+ // HANDING OVER: an unfiltered read puts every domain every task has visited, plus
225
+ // whatever the human is signed into, in front of one task's caller. Least exposure,
226
+ // not isolation.
227
+ //
228
+ // Two corrections to the previous attempt. It called Storage.getCookies with a `urls`
229
+ // parameter, but that method takes only browserContextId and ignores everything else, so
230
+ // the filter did nothing and the whole jar was still exported; `urls` belongs to
231
+ // Network.getCookies. And it silently fell back to an unfiltered read when the page URL
232
+ // was unavailable — an error path that asked for MORE than the normal one. Both are
233
+ // fixed: the method that honours the filter, and a failure that refuses instead of
234
+ // widening.
235
+ const cookiesUrl = await this.currentUrl(handle).catch(() => '');
236
+ if (cookiesUrl === '') {
237
+ throw new BrowserError('browser: cannot export cookies without knowing which page this session is on — the URL was unavailable, and reading the whole cookie jar would expose every other session\'s logins', 'BROWSER_AUTH_SCOPE_UNKNOWN');
238
+ }
239
+ const result = await withTimeout(handle.sendCommand('Network.getCookies', { urls: [cookiesUrl] }), timeoutMs, undefined, `browser: auth export timed out after ${timeoutMs}ms`);
240
+ const cookies = toExportedCookies(result.cookies);
241
+ this.record(s, 'flushAuth', {}, true, { result: `${cookies.length} cookies (CDP)` });
242
+ return cookies;
243
+ }
244
+ /** Import cookies into the session (restore login state). Self-hosted only. */
245
+ async restoreAuth(session, cookies) {
246
+ // Restore WRITES cookies, so it answers to the write switch — not to
247
+ // `credentials.allowRead`. It used to consult the read switch and report "reading
248
+ // cookies is switched off", which is both the wrong gate and the wrong sentence: an
249
+ // operator who allowed reading but wanted logins left alone had no switch at all,
250
+ // and one who turned reading off lost the restore path for the wrong reason.
251
+ this.assertActionAllowed('credentialWrite');
252
+ const s = this.session(session);
253
+ const { handle } = this.activeTab(s);
254
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
255
+ const native = handle;
256
+ if (typeof native.restoreAuth === 'function') {
257
+ const restored = await withTimeout(native.restoreAuth(cookies), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
258
+ this.record(s, 'restoreAuth', { count: cookies.length }, true, { result: `${restored} cookies` });
259
+ return restored;
260
+ }
261
+ // CDP again, for the same reason as the export: any carrier that drives a real
262
+ // browser can set cookies on it. Storage.setCookies needs the cookie fields spelled
263
+ // the CDP way, including the sameSite spelling and seconds rather than milliseconds.
264
+ //
265
+ // toCdpCookie returns undefined for a cookie it cannot place (no usable domain), and
266
+ // `cookies.map(...)` passed that undefined straight through: the array then held a
267
+ // JSON `null`, CDP rejected the WHOLE call, and every valid cookie failed with an error
268
+ // naming none of them. Filter the unusable ones out and say how many went.
269
+ const mapped = cookies.map(toCdpCookie);
270
+ const convertible = mapped.filter((cookie) => cookie !== undefined);
271
+ const dropped = mapped.length - convertible.length;
272
+ if (dropped > 0) {
273
+ process.stderr.write(`[dsh-browser] restoreAuth: dropped ${dropped} of ${mapped.length} cookie(s) with no usable domain; the rest were still restored\n`);
274
+ }
275
+ await withTimeout(handle.sendCommand('Storage.setCookies', { cookies: convertible }), timeoutMs, undefined, `browser: auth restore timed out after ${timeoutMs}ms`);
276
+ // Storage.setCookies returns nothing, so the count comes from what was actually sent.
277
+ // An earlier version read result.cookies here; it was always undefined and rendered as
278
+ // "Restored 0 cookies." even though the write had succeeded.
279
+ const restored = convertible.length;
280
+ this.record(s, 'restoreAuth', { count: cookies.length, dropped }, true, { result: `${restored} cookies (CDP)${dropped > 0 ? `; ${dropped} dropped` : ''}` });
281
+ return restored;
282
+ }
283
+ /**
284
+ * Capture the active page WITHOUT presenting it.
285
+ *
286
+ * `screenshot` calls `showActive()` before capturing, and that is right for a tool whose point is
287
+ * that the human sees what the model just captured. It is also what makes that path unusable for a
288
+ * live preview: presenting on every frame would move focus, switch tabs and expand windows on the
289
+ * host's screen — exactly the side effects a viewer must not cause (issue #34).
290
+ *
291
+ * So this does the capture and nothing else. Deliberately narrow: viewport only, JPEG at the
292
+ * preview defaults, a short timeout, no save path, no history entry, no carrier recovery. A
293
+ * preview that rebuilt a vanished carrier would make watching a way to start a browser, which the
294
+ * design forbids: no page means "nothing to watch", not "open one".
295
+ * @param session - the session whose active page to capture.
296
+ * @returns the encoded image and its dimensions; throws BROWSER_PREVIEW_UNAVAILABLE when the page
297
+ * is not painted, which the caller turns into a "paused" state rather than an error.
298
+ */
299
+ async capturePassive(session) {
300
+ const s = this.session(session);
301
+ const { handle } = this.activeTab(s);
302
+ const timeoutMs = PREVIEW_CAPTURE_MS;
303
+ const timeoutMessage = `browser: preview capture timed out after ${timeoutMs}ms`;
304
+ // The self-hosted carrier encodes in the child from a NativeImage; it is the only path that can
305
+ // produce JPEG under Electron 43, whose CDP JPEG encoder hangs.
306
+ if (typeof handle.capture === 'function') {
307
+ const shot = await withTimeout(handle.capture({
308
+ format: 'jpeg',
309
+ quality: PREVIEW_QUALITY,
310
+ maxWidth: PREVIEW_MAX_WIDTH,
311
+ maxHeight: PREVIEW_MAX_HEIGHT,
312
+ }), timeoutMs, undefined, timeoutMessage);
313
+ if (shot.base64 === '') {
314
+ // A hidden or minimized window is not a failure to report as one: the design says the
315
+ // viewer shows pause and does not open a window to fix it.
316
+ throw new BrowserError('browser: preview unavailable (the page is not painted; the window may be hidden or minimized)', 'BROWSER_PREVIEW_UNAVAILABLE');
317
+ }
318
+ return {
319
+ dataUrl: `data:${shot.mime};base64,${shot.base64}`,
320
+ ...shot.width !== undefined && shot.height !== undefined
321
+ ? { width: shot.width, height: shot.height }
322
+ : {},
323
+ };
324
+ }
325
+ // Real Chrome/Edge (and the sidebar): CDP. Viewport only — `captureBeyondViewport` would pull
326
+ // the whole document, which is neither what a viewer shows nor bounded in size.
327
+ //
328
+ // `present: false` is load-bearing (issue #46): a preview is read-only, so it must not reach the
329
+ // carrier's present path, which for the sidebar asks the shell to display this conversation —
330
+ // the reported symptom was the sidebar browser panel jumping to the front when someone opened
331
+ // the preview. A page that is not displayed now reads as "unavailable", which the route already
332
+ // turns into the panel's paused state.
333
+ const result = await withTimeout(handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, {
334
+ format: 'jpeg',
335
+ quality: PREVIEW_QUALITY,
336
+ fromSurface: true,
337
+ captureBeyondViewport: false,
338
+ }, { present: false }), timeoutMs, undefined, timeoutMessage);
339
+ const base64 = typeof result?.data === 'string' ? result.data : '';
340
+ if (base64 === '') {
341
+ throw new BrowserError('browser: preview unavailable (the carrier returned no image)', 'BROWSER_PREVIEW_UNAVAILABLE');
342
+ }
343
+ return { dataUrl: `data:image/jpeg;base64,${base64}` };
344
+ }
345
+ /** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
346
+ async screenshot(session, request, signal) {
347
+ const s = this.session(session);
348
+ const { handle } = this.activeTab(s);
349
+ signal?.throwIfAborted();
350
+ const format = request?.format ?? 'png';
351
+ // Native capturePage path (self-hosted): CDP Page.captureScreenshot can
352
+ // hang indefinitely on a view once another (hidden) WebContentsView exists
353
+ // in the window; capturePage is fast for visible views and resolves
354
+ // immediately (empty) for hidden ones. JPEG and downscaling are encoded
355
+ // in the child from the NativeImage, so this path is the only one that
356
+ // can produce JPEG (CDP JPEG hangs on Electron 43).
357
+ const capturable = handle;
358
+ // A region capture must go through CDP: the native NativeImage path has no
359
+ // clip and would present/activate the window (a quiet-mode violation).
360
+ if (request?.clip === undefined && request?.fullPage !== true && typeof capturable.capture === 'function') {
361
+ // Ensure the target view is the visible one before capturing — unless quiet mode is on.
362
+ // There, presenting the view is exactly what the user asked to avoid (it restores and
363
+ // raises the window); the host switches the visible tab inside the window and, if the
364
+ // window has no surface to capture, falls through to CDP.
365
+ if (!this.isQuiet())
366
+ this.showActive(s);
367
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
368
+ const shot = await withTimeout(capturable.capture({
369
+ ...format === 'jpeg' ? { format, quality: request?.quality } : {},
370
+ ...request?.maxWidth !== undefined ? { maxWidth: request.maxWidth } : {},
371
+ ...request?.maxHeight !== undefined ? { maxHeight: request.maxHeight } : {},
372
+ quiet: this.isQuiet(),
373
+ }), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
374
+ if (shot.base64 === '') {
375
+ throw new BrowserError('browser: capture returned an empty image (view not painted); retry shortly', 'BROWSER_SCREENSHOT_FAILED');
376
+ }
377
+ // The native capture describes the VIEW it was taken from, and that view is not always the
378
+ // page's own layout surface: an off-screen parked window answered a full-width capture with a
379
+ // 231×960 image while the page itself was 1254×707 (issue #140). A capture whose aspect ratio
380
+ // disagrees with the page's layout viewport was taken from another surface, so it is replaced
381
+ // by a CDP clip of the viewport below instead of being handed to the caller.
382
+ const nativeShape = await this.captureMatchesViewport(handle, shot.width, shot.height);
383
+ if (nativeShape)
384
+ return this.saveScreenshot(shot.base64, request?.savePath, shot.mime ?? 'image/png',
385
+ // The child measured these after applying any downscale, and they describe the image
386
+ // the caller receives. Without them this path — the default self-hosted one — could
387
+ // never answer the width/height its own tool schema declares.
388
+ shot.width !== undefined && shot.height !== undefined
389
+ ? { width: shot.width, height: shot.height }
390
+ : undefined);
391
+ }
392
+ // Fallback: a handle without a native capture() (the sidebar, or an installed Chrome
393
+ // or Edge) uses CDP; full-page needs `captureBeyondViewport`, which capturePage lacks.
394
+ //
395
+ // JPEG: Electron 43's CDP hangs on it, which is why the sidebar stays PNG. An
396
+ // installed Chrome or Edge is the real browser and has no such defect, so it says so
397
+ // through `supportsCdpJpeg` and gets the format it asked for, and the same for
398
+ // downscaling, which CDP performs through a full-document clip.
399
+ const timeoutMs = DEFAULT_OPERATION_TIMEOUT_MS;
400
+ const params = {};
401
+ const region = request?.clip;
402
+ if (region !== undefined) {
403
+ const valid = [region.x, region.y, region.width, region.height].every(value => typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 8192) && region.width > 0 && region.height > 0;
404
+ if (!valid)
405
+ throw new BrowserError('browser: screenshot region is out of range', 'BROWSER_SCREENSHOT_FAILED');
406
+ params.clip = { x: region.x, y: region.y, width: region.width, height: region.height, scale: 1 };
407
+ params.fromSurface = true;
408
+ params.captureBeyondViewport = false;
409
+ }
410
+ if (region === undefined && request?.fullPage === true) {
411
+ // `captureBeyondViewport` captures the full scrollable content; without
412
+ // a clip this yields the full-page image (CDP default is the viewport).
413
+ params.captureBeyondViewport = true;
414
+ }
415
+ // A viewport capture is defined by the PAGE's layout viewport, never by whatever surface the
416
+ // window happens to have when the screenshot is taken (issue #140).
417
+ if (region === undefined && request?.fullPage !== true && params.clip === undefined) {
418
+ const metrics = await withTimeout(handle.sendCommand('Page.getLayoutMetrics', {}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
419
+ const size = layoutSize(metrics);
420
+ if (size !== undefined && size.viewportWidth > 0 && size.viewportHeight > 0) {
421
+ params.clip = { x: 0, y: 0, width: size.viewportWidth, height: size.viewportHeight, scale: 1 };
422
+ params.fromSurface = true;
423
+ params.captureBeyondViewport = false;
424
+ }
425
+ }
426
+ const supportsJpeg = handle.supportsCdpJpeg === true;
427
+ if (format === 'jpeg' && supportsJpeg) {
428
+ params.format = 'jpeg';
429
+ // CDP range is 0-100 and defaults to 80 when omitted.
430
+ if (request?.quality !== undefined)
431
+ params.quality = request.quality;
432
+ }
433
+ // Downscaling on this path: CDP scales through `clip.scale`, and a clip only applies
434
+ // to the region it names, so it has to cover the whole document. The page's own size
435
+ // is read first; when that is unavailable the capture proceeds unscaled rather than
436
+ // failing — an image the caller can shrink itself beats no image at all.
437
+ let rendered;
438
+ if (region === undefined && (request?.maxWidth !== undefined || request?.maxHeight !== undefined)) {
439
+ const metrics = await withTimeout(handle.sendCommand('Page.getLayoutMetrics', {}), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
440
+ const size = layoutSize(metrics);
441
+ if (size !== undefined) {
442
+ const height = request.fullPage === true ? size.height : size.viewportHeight;
443
+ const byWidth = request.maxWidth !== undefined && size.width > 0 ? request.maxWidth / size.width : 1;
444
+ const byHeight = request.maxHeight !== undefined && height > 0 ? request.maxHeight / height : 1;
445
+ const scale = Math.min(1, byWidth, byHeight);
446
+ // What the caller will actually receive. Recorded before the branch below, because the
447
+ // size is worth reporting even when no scaling happened (scale 1).
448
+ rendered = { width: Math.round(size.width * scale), height: Math.round(height * scale) };
449
+ if (scale < 1) {
450
+ params.clip = { x: 0, y: 0, width: size.width, height, scale };
451
+ // The clip defines the captured area; captureBeyondViewport must not also apply.
452
+ delete params.captureBeyondViewport;
453
+ }
454
+ }
455
+ }
456
+ // A region capture is a read: it must never present the conversation or
457
+ // raise a window. Every other screenshot keeps the original call shape.
458
+ const result = await withTimeout(region === undefined
459
+ ? handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params)
460
+ : handle.sendCommand(CDP_PAGE_CAPTURE_SCREENSHOT, params, { present: false }), timeoutMs, signal, `browser: screenshot timed out after ${timeoutMs}ms`);
461
+ const data = result.data;
462
+ if (typeof data !== 'string') {
463
+ throw new BrowserError('browser: screenshot returned no image data', 'BROWSER_SCREENSHOT_FAILED');
464
+ }
465
+ // The mime must name the format that was ACTUALLY requested (params.format), not PNG
466
+ // unconditionally: a carrier that sets supportsCdpJpeg asks for `format: 'jpeg'`, so
467
+ // hardcoding the PNG mime announced a JPEG body as a PNG — the data URL then carried a
468
+ // mislabelled image, and a caller that decodes by mime wrote the wrong file.
469
+ const mime = params.format === 'jpeg' ? 'image/jpeg' : 'image/png';
470
+ return this.saveScreenshot(data, request?.savePath, mime, rendered);
471
+ }
472
+ /**
473
+ * Does a native capture describe the page's own layout viewport?
474
+ *
475
+ * Aspect ratio is the DPR-independent test: a correct capture keeps the viewport's shape whatever
476
+ * the device scale factor is, while a capture of another surface (an off-screen window's tiny
477
+ * backing store, a narrow panel view) does not. Absent metrics, the capture is trusted — this is a
478
+ * repair for a wrong surface, not a second guess at a right one.
479
+ */
480
+ async captureMatchesViewport(handle, width, height) {
481
+ if (width === undefined || height === undefined || width <= 0 || height <= 0)
482
+ return true;
483
+ try {
484
+ const size = layoutSize(await handle.sendCommand('Page.getLayoutMetrics', {}));
485
+ if (size === undefined || size.viewportWidth <= 0 || size.viewportHeight <= 0)
486
+ return true;
487
+ const captured = width / height;
488
+ const viewport = size.viewportWidth / size.viewportHeight;
489
+ return Math.abs(captured - viewport) / viewport <= 0.05;
490
+ }
491
+ catch {
492
+ return true;
493
+ }
494
+ }
495
+ /**
496
+ * Build the data URL and optionally write the image to disk. The caller's
497
+ * path goes through the SAME {@link admitSavePath} gate as a download — it
498
+ * must be absolute, resolve inside `downloadDir`, and not be an existing
499
+ * file — so a screenshot cannot be used to write to, or silently replace,
500
+ * files anywhere the DSH process happens to have permission (issue #13).
501
+ */
502
+ saveScreenshot(base64, savePath, mime, rendered) {
503
+ if (savePath !== undefined) {
504
+ // Admission failures propagate unchanged: they describe the caller's
505
+ // path, not a disk problem.
506
+ const target = this.admitSavePath(savePath, 'screenshot');
507
+ try {
508
+ writeFileNoReplace(target, Buffer.from(base64, 'base64'));
509
+ return { dataUrl: `data:${mime};base64,${base64}`, path: target, ...rendered };
510
+ }
511
+ catch (error) {
512
+ // Report the write problem but keep the capture usable.
513
+ throw new BrowserError(`browser: screenshot save to "${target}" failed: ${String(error)}`, 'BROWSER_SCREENSHOT_SAVE_FAILED', { cause: error });
514
+ }
515
+ }
516
+ return { dataUrl: `data:${mime};base64,${base64}`, ...rendered };
517
+ }
518
+ }