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.
- package/CHANGELOG.md +55 -0
- package/README.md +1 -1
- package/assets/browser-panel-locales.mjs +37 -5
- package/assets/browser-policy.d.mts +29 -0
- package/assets/browser-policy.mjs +40 -0
- package/desktop-bridge/desktop-discovery.d.mts +1 -1
- package/desktop-bridge/desktop-discovery.mjs +59 -9
- package/desktop-bridge/desktop-identity.json +12 -0
- package/desktop-bridge/install.mjs +14 -7
- package/desktop-bridge/plugin-browser-bridge.js +19 -7
- package/docs/acceptance-2026-11-27.md +67 -0
- package/docs/architecture.md +1 -1
- package/docs/development.md +33 -4
- package/docs/dsh-0.2.3-host-patch-task.md +34 -0
- package/docs/hardcoding-audit.md +28 -8
- package/docs/known-issues.md +26 -0
- package/docs/limitations.md +6 -2
- package/docs/tool-reference.md +1 -1
- package/docs/v1.1.0-bu-data-batching-task.md +66 -0
- package/docs/v1.1.0-compat-hardcoding-task.md +85 -0
- package/dsh-host-patch/README.md +4 -0
- package/dsh-host-patch/apply.mjs +61 -13
- package/dsh-host-patch/rc3-revision9.json.gz +0 -0
- package/dsh-host-patch/rc5-revision9.json.gz +0 -0
- package/dsh-host-patch/tauri/desktop-main.cjs +62 -0
- package/dsh-host-patch/tauri/sidebar-session.cjs +104 -0
- package/dsh-host-patch/tauri-revision1.json +39 -0
- package/dsh-host-patch/tauri.json +43 -0
- package/dsh-host-patch/v023-alpha2.json +153 -0
- package/lib/browser/anti-bot.js +215 -0
- package/lib/browser/deep-dom.js +39 -0
- package/lib/browser/runtime.js +15 -0
- package/lib/browser/takeover-target.js +13 -6
- package/lib/browser/types.js +30 -1
- package/lib/browser-electron/authenticated-route.js +16 -2
- package/lib/browser-electron/automatic-maintenance.js +16 -10
- package/lib/browser-electron/bridge-connection.js +3 -8
- package/lib/browser-electron/bridge-install.js +2 -1
- package/lib/browser-electron/bridge-status.js +55 -26
- package/lib/browser-electron/desktop-bridge-host.js +7 -6
- package/lib/browser-electron/desktop-identity.js +28 -5
- package/lib/browser-electron/desktop-shell.js +64 -0
- package/lib/browser-electron/electron-provision.js +105 -18
- package/lib/browser-electron/entry.js +129 -44
- package/lib/browser-electron/extension-browser.js +4 -4
- package/lib/browser-electron/foreground-watch.js +134 -0
- package/lib/browser-electron/guest-cookie-jar.js +13 -13
- package/lib/browser-electron/guest-route.js +181 -32
- package/lib/browser-electron/guest-runtime.js +61 -10
- package/lib/browser-electron/guest-storage.js +2 -2
- package/lib/browser-electron/history-store.js +1 -5
- package/lib/browser-electron/host-main.js +8 -4
- package/lib/browser-electron/host-patch-maintenance.js +14 -8
- package/lib/browser-electron/maintenance-route.js +2 -1
- package/lib/browser-electron/missing-system-browser.js +5 -9
- package/lib/browser-electron/preferred-browser.js +7 -3
- package/lib/browser-electron/preview-route.js +9 -13
- package/lib/browser-electron/process-ownership.js +1 -1
- package/lib/browser-electron/profile-command.js +2 -1
- package/lib/browser-electron/profile-extension.js +5 -0
- package/lib/browser-electron/profile-lease.js +152 -47
- package/lib/browser-electron/provider-core.js +527 -0
- package/lib/browser-electron/provider-interaction.js +963 -0
- package/lib/browser-electron/provider-media.js +518 -0
- package/lib/browser-electron/provider-navigation.js +301 -0
- package/lib/browser-electron/provider-observation.js +623 -0
- package/lib/browser-electron/provider-tabs.js +372 -0
- package/lib/browser-electron/provider.js +150 -3301
- package/lib/browser-electron/reference-route.js +9 -18
- package/lib/browser-electron/remote-host.js +79 -34
- package/lib/browser-electron/runtime-status.js +56 -6
- package/lib/browser-electron/settings-store.js +3 -6
- package/lib/browser-electron/sidebar-only-host.js +1 -1
- package/lib/browser-electron/system-browser.js +539 -172
- package/lib/browser-electron/tauri-host.js +208 -0
- package/lib/browser-electron/virtual-cursor.js +23 -13
- package/lib/browser-reference/service.js +22 -4
- package/lib/browser-reference/web-sources.js +1 -1
- package/lib/client.js +43409 -0
- package/lib/compat/host-features.js +75 -0
- package/lib/reference-source.js +1 -1
- package/lib/reference-text.js +23 -1
- package/lib/takeover-protocol.js +1 -1
- package/lib/tool-browser/block-recovery.js +69 -0
- package/lib/tool-browser/code-tool.js +170 -19
- package/lib/tool-browser/code-worker.js +115 -20
- package/lib/tool-browser/errors.js +34 -0
- package/lib/tool-browser/index.js +66 -3593
- package/lib/tool-browser/page-probe.js +227 -28
- package/lib/tool-browser/panel-page.js +2 -1
- package/lib/tool-browser/probe-client.js +157 -0
- package/lib/tool-browser/screenshot-annotations.js +108 -0
- package/lib/tool-browser/state.js +337 -0
- package/lib/tool-browser/takeover.js +1 -1
- package/lib/tool-browser/tools-debug.js +862 -0
- package/lib/tool-browser/tools-interaction.js +993 -0
- package/lib/tool-browser/tools-navigation.js +807 -0
- package/lib/tool-browser/tools-observation.js +461 -0
- package/lib/tool-browser/tools-reference.js +293 -0
- package/lib/web-guest.js +1 -0
- package/package.json +16 -36
- package/scripts/build-client.mjs +305 -0
- package/scripts/build.mjs +15 -12
- package/scripts/fix-exports.mjs +6 -16
- package/scripts/install-electron.mjs +55 -5
- package/scripts/pack.mjs +99 -0
- package/scripts/publish-manifest.mjs +56 -0
- package/scripts/verify-exports.mjs +26 -15
- package/skills/dsh-builtin-browser/SKILL.md +27 -2
- package/skills/dsh-builtin-browser/references/batch.md +15 -0
- package/src/browser/anti-bot.ts +251 -0
- package/src/browser/deep-dom.ts +40 -0
- package/src/browser/runtime.ts +18 -0
- package/src/browser/takeover-target.ts +16 -7
- package/src/browser/types.ts +56 -3
- package/src/browser-electron/authenticated-route.ts +29 -4
- package/src/browser-electron/automatic-maintenance.ts +23 -13
- package/src/browser-electron/bridge-connection.ts +11 -10
- package/src/browser-electron/bridge-install.ts +2 -1
- package/src/browser-electron/bridge-status.ts +61 -22
- package/src/browser-electron/desktop-bridge-host.ts +9 -7
- package/src/browser-electron/desktop-identity.ts +38 -5
- package/src/browser-electron/desktop-shell.ts +100 -0
- package/src/browser-electron/electron-provision.ts +104 -18
- package/src/browser-electron/entry.ts +1378 -1299
- package/src/browser-electron/extension-browser.ts +11 -4
- package/src/browser-electron/foreground-watch.ts +142 -0
- package/src/browser-electron/guest-cookie-jar.ts +3 -2
- package/src/browser-electron/guest-route.ts +180 -32
- package/src/browser-electron/guest-runtime.ts +61 -10
- package/src/browser-electron/guest-storage.ts +5 -2
- package/src/browser-electron/history-store.ts +3 -6
- package/src/browser-electron/host-main.ts +8 -4
- package/src/browser-electron/host-patch-maintenance.ts +18 -9
- package/src/browser-electron/maintenance-route.ts +2 -1
- package/src/browser-electron/missing-system-browser.ts +11 -10
- package/src/browser-electron/preferred-browser.ts +13 -3
- package/src/browser-electron/preview-route.ts +9 -12
- package/src/browser-electron/process-ownership.ts +9 -3
- package/src/browser-electron/profile-command.ts +2 -1
- package/src/browser-electron/profile-extension.ts +5 -0
- package/src/browser-electron/profile-lease.ts +131 -35
- package/src/browser-electron/provider-core.ts +1107 -0
- package/src/browser-electron/provider-interaction.ts +1034 -0
- package/src/browser-electron/provider-media.ts +589 -0
- package/src/browser-electron/provider-navigation.ts +323 -0
- package/src/browser-electron/provider-observation.ts +664 -0
- package/src/browser-electron/provider-tabs.ts +372 -0
- package/src/browser-electron/provider.ts +158 -4063
- package/src/browser-electron/reference-route.ts +598 -608
- package/src/browser-electron/remote-host.ts +118 -42
- package/src/browser-electron/runtime-status.ts +80 -13
- package/src/browser-electron/settings-store.ts +10 -6
- package/src/browser-electron/sidebar-only-host.ts +4 -2
- package/src/browser-electron/system-browser.ts +537 -184
- package/src/browser-electron/tauri-host.ts +194 -0
- package/src/browser-electron/virtual-cursor.ts +24 -14
- package/src/browser-reference/service.ts +38 -7
- package/src/browser-reference/web-sources.ts +4 -1
- package/src/client/apply-guard.ts +22 -0
- package/src/client/browser/BrowserController.ts +3 -3
- package/src/client/browser/IframeImpl.ts +182 -176
- package/src/client/browser/frame-history.ts +125 -0
- package/src/client/browser/frame-state.ts +27 -0
- package/src/client/browser/web-reference-source.ts +5 -1
- package/src/client/definition.tsx +36 -30
- package/src/client/electron/ElectronWebViewImpl.ts +20 -13
- package/src/client/electron/ElectronWebviewPresentation.ts +4 -2
- package/src/client/electron/NativeChildPresentation.ts +11 -3
- package/src/client/electron/NativeViewPage.ts +19 -5
- package/src/client/index.ts +333 -293
- package/src/client/locales.ts +9 -6
- package/src/client/reference/client/plugin.ts +21 -2
- package/src/client/reference/client/production/ReferenceCapsules.tsx +3 -3
- package/src/client/reference/client/production/assembly.ts +4 -28
- package/src/client/reference/client/production/availability.ts +0 -2
- package/src/client/reference/client/production/composer-attachments.ts +44 -0
- package/src/client/reference/client/production/draft-adapter.ts +4 -0
- package/src/client/reference/client/production/http-transport.ts +0 -5
- package/src/client/reference/client/production/production-submission.ts +50 -290
- package/src/client/reference/client/production/protocol.ts +7 -4
- package/src/client/reference/client/production/runtime.ts +41 -86
- package/src/client/reference/client/production/source-marker.ts +49 -13
- package/src/client/reference/client/production/user-text-rule.ts +10 -1
- package/src/client/reference/client/reveal.ts +3 -1
- package/src/client/reference/client/session-schedule.ts +36 -0
- package/src/client/settings/index.ts +8 -0
- package/src/client/settings/mount-guard.ts +31 -0
- package/src/client/settings/panel.ts +163 -52
- package/src/client/startpage/controller.ts +3 -6
- package/src/client/view/BrowserBody.tsx +2 -1
- package/src/client/view/IframePresentation.ts +37 -16
- package/src/client/view/StartPage.tsx +2 -1
- package/src/compat/host-features.ts +92 -0
- package/src/reference-source.ts +1 -1
- package/src/reference-text.ts +23 -1
- package/src/takeover-protocol.ts +11 -2
- package/src/tool-browser/block-recovery.ts +85 -0
- package/src/tool-browser/code-tool.ts +173 -19
- package/src/tool-browser/code-worker.ts +101 -15
- package/src/tool-browser/errors.ts +40 -0
- package/src/tool-browser/index.ts +66 -3534
- package/src/tool-browser/page-probe.ts +229 -28
- package/src/tool-browser/panel-page.ts +3 -1
- package/src/tool-browser/probe-client.ts +183 -0
- package/src/tool-browser/screenshot-annotations.ts +131 -0
- package/src/tool-browser/state.ts +375 -0
- package/src/tool-browser/takeover.ts +3 -2
- package/src/tool-browser/tools-debug.ts +806 -0
- package/src/tool-browser/tools-interaction.ts +956 -0
- package/src/tool-browser/tools-navigation.ts +786 -0
- package/src/tool-browser/tools-observation.ts +474 -0
- package/src/tool-browser/tools-reference.ts +294 -0
- package/src/web-guest.ts +35 -34
- package/dist/client.cjs +0 -43167
- package/dist/client.d.cts +0 -516
- package/dist/client.d.mts +0 -516
- package/dist/index.cjs +0 -92
- package/dist/index.d.mts +0 -2960
- package/dist/index.mjs +0 -24
- package/lib/browser-reference/submission-receipts.js +0 -139
- package/src/browser-reference/submission-receipts.ts +0 -122
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { HistoryStore } from './history-store.js';
|
|
6
|
+
import { BrowserError } from '../browser/types.js';
|
|
7
|
+
export const PROVIDER_TIMEOUTS = Object.freeze({
|
|
8
|
+
evaluation: 3_000,
|
|
9
|
+
interaction: 5_000,
|
|
10
|
+
lookup: 10_000,
|
|
11
|
+
action: 15_000,
|
|
12
|
+
prepare: DEFAULT_OPERATION_TIMEOUT_MS + 1_000,
|
|
13
|
+
download: 60_000,
|
|
14
|
+
});
|
|
15
|
+
/** Stable provider id registered with `ctx.browser`. */
|
|
16
|
+
export const ELECTRON_BROWSER_PROVIDER_ID = 'electron';
|
|
17
|
+
/** CDP method for a full-page screenshot capture. */
|
|
18
|
+
export const CDP_PAGE_CAPTURE_SCREENSHOT = 'Page.captureScreenshot';
|
|
19
|
+
/**
|
|
20
|
+
* The document size out of a `Page.getLayoutMetrics` response.
|
|
21
|
+
*
|
|
22
|
+
* CDP returns `cssContentSize` (the whole document) and `cssLayoutViewport` (what is
|
|
23
|
+
* visible); the newer spellings `contentSize` / `layoutViewport` appear on some
|
|
24
|
+
* versions, so both are accepted. Returns undefined when neither is usable, leaving the
|
|
25
|
+
* caller to capture unscaled rather than guess.
|
|
26
|
+
* @param metrics - the raw CDP response.
|
|
27
|
+
* @returns the document and viewport size in CSS pixels.
|
|
28
|
+
*/
|
|
29
|
+
export function layoutSize(metrics) {
|
|
30
|
+
const pick = (candidates) => {
|
|
31
|
+
for (const candidate of candidates) {
|
|
32
|
+
if (typeof candidate !== 'object' || candidate === null)
|
|
33
|
+
continue;
|
|
34
|
+
const box = candidate;
|
|
35
|
+
if (typeof box.width === 'number' && typeof box.height === 'number' && box.width > 0 && box.height > 0) {
|
|
36
|
+
return { width: box.width, height: box.height };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
};
|
|
41
|
+
const content = pick([metrics.cssContentSize, metrics.contentSize]);
|
|
42
|
+
const viewport = pick([metrics.cssLayoutViewport, metrics.layoutViewport]);
|
|
43
|
+
if (content === undefined)
|
|
44
|
+
return undefined;
|
|
45
|
+
return { width: content.width, height: content.height, viewportHeight: viewport?.height ?? content.height, viewportWidth: viewport?.width ?? content.width };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Map CDP cookies onto the shape `dsh_browser_auth` exports.
|
|
49
|
+
*
|
|
50
|
+
* CDP reports a cookie as domain + path rather than a URL, and in seconds rather than
|
|
51
|
+
* milliseconds, so both are converted. Entries missing a name, value or domain are
|
|
52
|
+
* dropped rather than exported as broken cookies the caller cannot restore.
|
|
53
|
+
* @param raw - the `cookies` array from a CDP response, of unknown shape.
|
|
54
|
+
* @returns the mappable cookies.
|
|
55
|
+
*/
|
|
56
|
+
export function toExportedCookies(raw) {
|
|
57
|
+
if (!Array.isArray(raw))
|
|
58
|
+
return [];
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const entry of raw) {
|
|
61
|
+
if (typeof entry !== 'object' || entry === null)
|
|
62
|
+
continue;
|
|
63
|
+
const cookie = entry;
|
|
64
|
+
// An empty domain is as unusable as a missing one: it cannot form a cookie URL, so
|
|
65
|
+
// exporting it would hand the caller something that fails to restore.
|
|
66
|
+
if (typeof cookie.name !== 'string' || cookie.name === '')
|
|
67
|
+
continue;
|
|
68
|
+
if (typeof cookie.value !== 'string')
|
|
69
|
+
continue;
|
|
70
|
+
if (typeof cookie.domain !== 'string' || cookie.domain === '')
|
|
71
|
+
continue;
|
|
72
|
+
const path = typeof cookie.path === 'string' && cookie.path !== '' ? cookie.path : '/';
|
|
73
|
+
// A leading dot means "this domain and its subdomains"; a cookie URL must not keep it.
|
|
74
|
+
const host = cookie.domain.replace(/^\./, '');
|
|
75
|
+
out.push({
|
|
76
|
+
url: `${cookie.secure === true ? 'https' : 'http'}://${host}${path}`,
|
|
77
|
+
name: cookie.name,
|
|
78
|
+
value: cookie.value,
|
|
79
|
+
domain: cookie.domain,
|
|
80
|
+
path,
|
|
81
|
+
...cookie.secure === true ? { secure: true } : {},
|
|
82
|
+
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
83
|
+
...typeof cookie.expires === 'number' && cookie.expires > 0 ? { expirationDate: cookie.expires } : {},
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Map an exported cookie onto the fields `Storage.setCookies` expects.
|
|
90
|
+
*
|
|
91
|
+
* An exported cookie may carry only a URL, so the domain and path are recovered from it
|
|
92
|
+
* when they are absent; without either, CDP cannot place the cookie and it is skipped.
|
|
93
|
+
* @param cookie - the cookie to convert.
|
|
94
|
+
* @returns the CDP cookie, or undefined when it lacks a usable domain.
|
|
95
|
+
*/
|
|
96
|
+
export function toCdpCookie(cookie) {
|
|
97
|
+
let domain = cookie.domain;
|
|
98
|
+
let path = cookie.path;
|
|
99
|
+
if (domain === undefined || domain === '') {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = new URL(cookie.url);
|
|
102
|
+
domain = parsed.hostname;
|
|
103
|
+
if (path === undefined || path === '')
|
|
104
|
+
path = parsed.pathname === '' ? '/' : parsed.pathname;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (typeof domain !== 'string' || domain === '')
|
|
111
|
+
return undefined;
|
|
112
|
+
return {
|
|
113
|
+
name: cookie.name,
|
|
114
|
+
value: cookie.value,
|
|
115
|
+
domain,
|
|
116
|
+
path: path === undefined || path === '' ? '/' : path,
|
|
117
|
+
...cookie.secure === true ? { secure: true } : {},
|
|
118
|
+
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
119
|
+
...typeof cookie.expirationDate === 'number' ? { expires: cookie.expirationDate } : {},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/** CDP method for runtime evaluation (the execute path). */
|
|
123
|
+
export const CDP_RUNTIME_EVALUATE = 'Runtime.evaluate';
|
|
124
|
+
/** CDP method for navigation. */
|
|
125
|
+
export const CDP_PAGE_NAVIGATE = 'Page.navigate';
|
|
126
|
+
/** Named-key table for `key()`: CDP key/code names + Windows virtual key codes. */
|
|
127
|
+
export const KEY_SPECS = {
|
|
128
|
+
// `text` is what makes a key produce CHARACTER INPUT rather than only a key event, and form
|
|
129
|
+
// submission depends on the character: pressing Enter in a text field submits the form because
|
|
130
|
+
// the browser processes a carriage return, not because a key went down. Without `text` the event
|
|
131
|
+
// still reaches the page, a `keydown` listener still fires, and nothing happens — reported as
|
|
132
|
+
// issue #36, where `requestSubmit()` worked and this did not.
|
|
133
|
+
//
|
|
134
|
+
// The same omission is why Space used to pass only its key event; that one was already fixed and
|
|
135
|
+
// is the reason the table has a `text` column at all.
|
|
136
|
+
Enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
|
|
137
|
+
Tab: { key: 'Tab', code: 'Tab', vk: 9 },
|
|
138
|
+
Escape: { key: 'Escape', code: 'Escape', vk: 27 },
|
|
139
|
+
Backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
|
|
140
|
+
Delete: { key: 'Delete', code: 'Delete', vk: 46 },
|
|
141
|
+
ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', vk: 38 },
|
|
142
|
+
ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', vk: 40 },
|
|
143
|
+
ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 },
|
|
144
|
+
ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', vk: 39 },
|
|
145
|
+
Home: { key: 'Home', code: 'Home', vk: 36 },
|
|
146
|
+
End: { key: 'End', code: 'End', vk: 35 },
|
|
147
|
+
PageUp: { key: 'PageUp', code: 'PageUp', vk: 33 },
|
|
148
|
+
PageDown: { key: 'PageDown', code: 'PageDown', vk: 34 },
|
|
149
|
+
// Space is the one printable key: CDP needs `text` on the keyDown for the
|
|
150
|
+
// character to land in a focused input; without it the key only scrolls.
|
|
151
|
+
Space: { key: ' ', code: 'Space', vk: 32, text: ' ' },
|
|
152
|
+
};
|
|
153
|
+
/** Supported key names, exported for the tool's enum and error messages. */
|
|
154
|
+
export const BROWSER_KEY_NAMES = Object.keys(KEY_SPECS);
|
|
155
|
+
/**
|
|
156
|
+
* Localized names a system Downloads folder may carry, in probe order: the
|
|
157
|
+
* English default first, then the Chinese spellings — a zh-CN desktop calls
|
|
158
|
+
* the folder `下载`, a zh-TW one `下載`, and neither is `Downloads`.
|
|
159
|
+
*/
|
|
160
|
+
export const DOWNLOAD_DIR_NAMES = ['Downloads', '下载', '下載'];
|
|
161
|
+
/**
|
|
162
|
+
* Resolve the default download directory when the config names none: an
|
|
163
|
+
* existing `XDG_DOWNLOAD_DIR` wins (the freedesktop standard, which is what a
|
|
164
|
+
* localized Linux desktop writes), then the first localized `Downloads` folder
|
|
165
|
+
* that exists under the home directory, and finally the English name — created
|
|
166
|
+
* on first use — when none exists yet.
|
|
167
|
+
* @returns the absolute default download directory.
|
|
168
|
+
*/
|
|
169
|
+
export function defaultDownloadDir() {
|
|
170
|
+
const xdg = process.env.XDG_DOWNLOAD_DIR;
|
|
171
|
+
if (typeof xdg === 'string' && xdg !== '' && existsSync(xdg))
|
|
172
|
+
return xdg;
|
|
173
|
+
for (const name of DOWNLOAD_DIR_NAMES) {
|
|
174
|
+
const candidate = join(homedir(), name);
|
|
175
|
+
if (existsSync(candidate))
|
|
176
|
+
return candidate;
|
|
177
|
+
}
|
|
178
|
+
return join(homedir(), DOWNLOAD_DIR_NAMES[0] ?? 'Downloads');
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Extra time the transport gets over an in-page locate script's own budget: the
|
|
182
|
+
* script polls for `timeoutMs` and answers only afterwards, so the outer wait
|
|
183
|
+
* must outlast it or its generic timeout hides the in-page reason.
|
|
184
|
+
*/
|
|
185
|
+
export const TARGET_SCRIPT_GRACE_MS = 2_000;
|
|
186
|
+
/**
|
|
187
|
+
* Longest a single in-page wait may hold one `Runtime.evaluate` open. The desktop sidebar's bridge
|
|
188
|
+
* gives every CDP command 15 s and then refuses the guest for good, because a renderer command cannot
|
|
189
|
+
* be cancelled; a locate or scrape that polled its whole caller budget inside one evaluate (15 s on
|
|
190
|
+
* Baidu) crossed that limit while the page was healthy. Longer budgets are polled in slices instead.
|
|
191
|
+
*/
|
|
192
|
+
export const PAGE_POLL_SLICE_MS = 3_000;
|
|
193
|
+
/**
|
|
194
|
+
* The next in-page poll slice before `deadline`: `last` when it reaches the deadline, so only that
|
|
195
|
+
* slice reports a miss and earlier ones answer `{ pending: true }` for the caller to poll again.
|
|
196
|
+
*/
|
|
197
|
+
export function pagePollSlice(deadline) {
|
|
198
|
+
const remaining = Math.max(0, deadline - Date.now());
|
|
199
|
+
return remaining <= PAGE_POLL_SLICE_MS ? { sliceMs: remaining, last: true } : { sliceMs: PAGE_POLL_SLICE_MS, last: false };
|
|
200
|
+
}
|
|
201
|
+
/** Abortable sleep used by the settle loop. */
|
|
202
|
+
export function delay(ms, signal) {
|
|
203
|
+
return new Promise((resolve) => {
|
|
204
|
+
const timer = setTimeout(() => {
|
|
205
|
+
if (signal !== undefined)
|
|
206
|
+
signal.removeEventListener('abort', onAbort);
|
|
207
|
+
resolve();
|
|
208
|
+
}, ms);
|
|
209
|
+
const onAbort = () => { clearTimeout(timer); resolve(); };
|
|
210
|
+
if (signal !== undefined)
|
|
211
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Bound a promise so a wedged CDP call surfaces as an error instead of
|
|
216
|
+
* hanging the tool call forever. The caller's signal, when provided, wins
|
|
217
|
+
* over the timeout if it fires first.
|
|
218
|
+
* @param promise - the operation to bound.
|
|
219
|
+
* @param ms - the timeout budget.
|
|
220
|
+
* @param signal - optional caller signal.
|
|
221
|
+
* @param message - the timeout error message.
|
|
222
|
+
* @returns the promise's value, or a rejected promise on timeout/abort.
|
|
223
|
+
*/
|
|
224
|
+
export function withTimeout(promise, ms, signal, message, onCancel) {
|
|
225
|
+
return new Promise((resolve, reject) => {
|
|
226
|
+
let done = false;
|
|
227
|
+
const timer = setTimeout(() => {
|
|
228
|
+
if (done)
|
|
229
|
+
return;
|
|
230
|
+
done = true;
|
|
231
|
+
// A fired timeout must also release the abort listener; { once: true }
|
|
232
|
+
// only releases it on the next abort, which may never come.
|
|
233
|
+
if (signal !== undefined)
|
|
234
|
+
signal.removeEventListener('abort', onAbort);
|
|
235
|
+
const error = new Error(message);
|
|
236
|
+
error.name = 'TimeoutError';
|
|
237
|
+
reject(error);
|
|
238
|
+
// Best-effort interrupt of the underlying CDP call (see onCancel).
|
|
239
|
+
onCancel?.(true);
|
|
240
|
+
}, ms);
|
|
241
|
+
const finish = (fn) => {
|
|
242
|
+
if (done)
|
|
243
|
+
return;
|
|
244
|
+
done = true;
|
|
245
|
+
clearTimeout(timer);
|
|
246
|
+
if (signal !== undefined)
|
|
247
|
+
signal.removeEventListener('abort', onAbort);
|
|
248
|
+
fn();
|
|
249
|
+
};
|
|
250
|
+
const onAbort = () => {
|
|
251
|
+
if (done)
|
|
252
|
+
return;
|
|
253
|
+
done = true;
|
|
254
|
+
clearTimeout(timer);
|
|
255
|
+
reject(signal?.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
256
|
+
onCancel?.(false);
|
|
257
|
+
};
|
|
258
|
+
if (signal !== undefined)
|
|
259
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
260
|
+
promise.then(value => finish(() => resolve(value)), error => finish(() => reject(error)));
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Run a `Runtime.evaluate` through a view handle and normalize the result.
|
|
265
|
+
* Shared by execute, snapshot, content, and internal URL reads.
|
|
266
|
+
* @param handle - the view handle to evaluate in.
|
|
267
|
+
* @param expression - the JS expression.
|
|
268
|
+
* @param signal - optional abort signal; a fired signal rejects the call.
|
|
269
|
+
*/
|
|
270
|
+
/** Viewport point a target script reported, when it reported one. */
|
|
271
|
+
export function scriptPoint(out) {
|
|
272
|
+
const point = out?.__point;
|
|
273
|
+
const x = Number(point?.x);
|
|
274
|
+
const y = Number(point?.y);
|
|
275
|
+
return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : undefined;
|
|
276
|
+
}
|
|
277
|
+
export async function handleSendEvaluate(handle, expression, signal, options) {
|
|
278
|
+
signal?.throwIfAborted();
|
|
279
|
+
const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
|
|
280
|
+
expression,
|
|
281
|
+
returnByValue: true,
|
|
282
|
+
awaitPromise: true,
|
|
283
|
+
}, options);
|
|
284
|
+
if (result.exceptionDetails !== undefined) {
|
|
285
|
+
const detail = result.exceptionDetails;
|
|
286
|
+
return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' };
|
|
287
|
+
}
|
|
288
|
+
return { ok: true, value: result.result?.value ?? null };
|
|
289
|
+
}
|
|
290
|
+
export class ProviderCore {
|
|
291
|
+
id = ELECTRON_BROWSER_PROVIDER_ID;
|
|
292
|
+
sessions = new Map();
|
|
293
|
+
carrierLaunchError;
|
|
294
|
+
/**
|
|
295
|
+
* Tick that installs the selection bar in every live tab and collects what the
|
|
296
|
+
* human confirmed. The Desktop sidebar carrier is the shell's own <webview>:
|
|
297
|
+
* the page has no preload bridge and the bridge protocol carries no user-action
|
|
298
|
+
* channel, so the bar leaves its intent in `window.__dshRefIntents` and this
|
|
299
|
+
* pump takes it over CDP. Without it the sidebar has no reference entry.
|
|
300
|
+
*/
|
|
301
|
+
referencePump;
|
|
302
|
+
/** Guards against overlapping pump runs (setInterval keeps firing while one is slow). */
|
|
303
|
+
referencePumping = false;
|
|
304
|
+
/**
|
|
305
|
+
* Set once the carrier swapped to a newer provider. `onUserAction` and
|
|
306
|
+
* `onViewClosed` return void and cannot be unsubscribed, so the callbacks
|
|
307
|
+
* themselves must go inert: otherwise one human click is handled by every
|
|
308
|
+
* old provider still retained by the view host, producing duplicate cards.
|
|
309
|
+
*/
|
|
310
|
+
disposed = false;
|
|
311
|
+
/**
|
|
312
|
+
* The session bound to the page the human has open, created on first sight.
|
|
313
|
+
*
|
|
314
|
+
* A reference is captured from a browser SESSION, and a page the human opened from
|
|
315
|
+
* the sidebar's own address bar belongs to no session of ours. Adopting it into one
|
|
316
|
+
* is what makes the selection bar appear there at all — and it is done here, inside
|
|
317
|
+
* the pump, so it needs nothing from the human and nothing from the agent.
|
|
318
|
+
*/
|
|
319
|
+
referenceSession;
|
|
320
|
+
/** Ticks between sidebar page scans while nothing is adopted yet. */
|
|
321
|
+
referenceScanCountdown = 0;
|
|
322
|
+
/** Last scan's diagnosis, surfaced by {@link referenceStatus}. */
|
|
323
|
+
referenceScan = { pages: 0 };
|
|
324
|
+
httpOnly;
|
|
325
|
+
snapshotMaxElements;
|
|
326
|
+
contentMaxChars;
|
|
327
|
+
downloadDir;
|
|
328
|
+
/**
|
|
329
|
+
* Persistent browsing history, or `undefined` when the user turned it off.
|
|
330
|
+
* Sessions come and go; this record outlives all of them.
|
|
331
|
+
*/
|
|
332
|
+
historyStore;
|
|
333
|
+
/** Live settings source; absent when nothing owns a settings document. */
|
|
334
|
+
settingsSource;
|
|
335
|
+
host;
|
|
336
|
+
config;
|
|
337
|
+
constructor(host, config = {}) {
|
|
338
|
+
this.host = host;
|
|
339
|
+
this.config = config;
|
|
340
|
+
this.httpOnly = config.httpOnly ?? true;
|
|
341
|
+
this.snapshotMaxElements = config.snapshotMaxElements ?? 60;
|
|
342
|
+
this.contentMaxChars = config.contentMaxChars;
|
|
343
|
+
// Confine downloads AND screenshot saves to a dedicated directory by
|
|
344
|
+
// default: the OS Downloads folder is the human-visible, browser-natural
|
|
345
|
+
// place for written files, and it is the one directory the DSH file
|
|
346
|
+
// sandbox does not have to arbitrate. The localized name is probed so a
|
|
347
|
+
// Chinese desktop (`~/下载`) works without configuring `downloadDir`.
|
|
348
|
+
this.downloadDir = config.downloadDir ?? defaultDownloadDir();
|
|
349
|
+
this.settingsSource = config.settings;
|
|
350
|
+
// Browsing history follows the browser profile's persistence rules (close
|
|
351
|
+
// the interface, lose nothing), and can be switched off from settings.
|
|
352
|
+
this.historyStore = config.history?.enabled === false
|
|
353
|
+
? undefined
|
|
354
|
+
: new HistoryStore(config.history?.file, {
|
|
355
|
+
...config.history?.maxEntries !== undefined ? { maxEntries: config.history.maxEntries } : {},
|
|
356
|
+
...config.history?.maxAgeDays !== undefined ? { maxAgeDays: config.history.maxAgeDays } : {},
|
|
357
|
+
});
|
|
358
|
+
// Route toolbar (host UI) actions into the session model: the human and
|
|
359
|
+
// the agent then always drive the same tabs, history, and navigation.
|
|
360
|
+
this.host.onUserAction?.(action => { if (!this.disposed)
|
|
361
|
+
void this.handleUserAction(action); });
|
|
362
|
+
// A window the human closed ends the session it showed: the next call opens a
|
|
363
|
+
// clean one instead of driving a page nobody can see.
|
|
364
|
+
this.host.onViewClosed?.(windowId => { if (!this.disposed)
|
|
365
|
+
void this.handleViewClosed(windowId); });
|
|
366
|
+
this.startReferenceEntryPump();
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Evaluate one expression in a tab and return its value.
|
|
370
|
+
*
|
|
371
|
+
* Bounded on purpose: the pump runs on a timer, and an unresponsive renderer
|
|
372
|
+
* would otherwise hold the whole tick (and every later one) forever.
|
|
373
|
+
* Never initializes or launches a closed tab/browser (issue #105).
|
|
374
|
+
* @param tab - the tab to evaluate in.
|
|
375
|
+
* @param expression - the JS expression.
|
|
376
|
+
* @param timeoutMs - how long to wait before treating the page as not answering.
|
|
377
|
+
*/
|
|
378
|
+
async evaluateInTab(tab, expression, timeoutMs = PROVIDER_TIMEOUTS.evaluation) {
|
|
379
|
+
const raw = await withTimeout(tab.handle.sendCommand('Runtime.evaluate', {
|
|
380
|
+
expression, returnByValue: true, awaitPromise: true,
|
|
381
|
+
}, { present: false, initialize: false }), timeoutMs, undefined, `browser: reference probe timed out after ${timeoutMs}ms`);
|
|
382
|
+
const result = raw.result;
|
|
383
|
+
return result?.value;
|
|
384
|
+
}
|
|
385
|
+
/** Set by {@link openUrl}; read by the client through the HTTP surface. */
|
|
386
|
+
lastOpen;
|
|
387
|
+
/**
|
|
388
|
+
* Refuse to send synthesized input to a view that is no longer the one it was located
|
|
389
|
+
* against.
|
|
390
|
+
*
|
|
391
|
+
* `locateHandle` was captured before a page-side locate that can consume its whole
|
|
392
|
+
* 10s budget; the session's active tab is re-read afterwards. If they differ, the human
|
|
393
|
+
* switched tabs mid-flight (the product's whole point is that they can take over), and
|
|
394
|
+
* the coordinates belong to one page while the dispatch would go to another. Comparing
|
|
395
|
+
* the handles turns that into a loud, retryable error instead of input the caller
|
|
396
|
+
* believes landed.
|
|
397
|
+
* @param session - the session id, for the message.
|
|
398
|
+
* @param locateHandle - the view the locate ran in.
|
|
399
|
+
* @param liveHandle - the view that is active now.
|
|
400
|
+
*/
|
|
401
|
+
assertSameView(session, locateHandle, liveHandle) {
|
|
402
|
+
if (locateHandle === liveHandle)
|
|
403
|
+
return;
|
|
404
|
+
throw new BrowserError(`browser: the session's active view changed while the element was being located (session ${session}); the operation was not dispatched — retry it`, 'BROWSER_VIEW_CHANGED');
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Give the view web focus before synthesizing keyboard input.
|
|
408
|
+
*
|
|
409
|
+
* A renderer only delivers key events to the view that holds web focus. A
|
|
410
|
+
* view that was created but never clicked holds none — and `Input` events
|
|
411
|
+
* injected over CDP do not grant it — so the FIRST `dsh_browser_key` of a fresh
|
|
412
|
+
* session vanished inside the renderer while the command still answered
|
|
413
|
+
* success. Hosts that cannot focus a view (a test double, a different shell
|
|
414
|
+
* adapter) simply have no `focus`, and nothing changes for them.
|
|
415
|
+
*/
|
|
416
|
+
async focusView(handle) {
|
|
417
|
+
if (handle.focus === undefined)
|
|
418
|
+
return;
|
|
419
|
+
const quiet = this.isQuiet();
|
|
420
|
+
try {
|
|
421
|
+
// Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
|
|
422
|
+
// and this runs before typing, so an unresponsive child would hang dsh_browser_key for
|
|
423
|
+
// good. A timeout is caught below exactly like any other focus failure, so the
|
|
424
|
+
// best-effort contract is unchanged.
|
|
425
|
+
await withTimeout(handle.focus(quiet ? { quiet } : undefined), PROVIDER_TIMEOUTS.interaction, undefined, 'browser: focusing the view timed out');
|
|
426
|
+
}
|
|
427
|
+
catch (error) {
|
|
428
|
+
if (quiet)
|
|
429
|
+
throw error;
|
|
430
|
+
// Best-effort: a view that refuses focus must not fail the caller's key
|
|
431
|
+
// press; the dispatch below reports a real channel failure itself.
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
/** Execute JS in the active tab's page context. */
|
|
435
|
+
async execute(session, request, signal) {
|
|
436
|
+
this.assertActionAllowed('execute');
|
|
437
|
+
return this.evaluatePage(session, request, signal);
|
|
438
|
+
}
|
|
439
|
+
async evaluatePage(session, request, signal) {
|
|
440
|
+
const s = this.session(session);
|
|
441
|
+
const { handle } = this.activeTab(s);
|
|
442
|
+
signal?.throwIfAborted();
|
|
443
|
+
try {
|
|
444
|
+
// Wrap the script in a Function so `return` statements are legal and
|
|
445
|
+
// request.args arrive as `arguments[0..n]`. A bare script handed to CDP
|
|
446
|
+
// Runtime.evaluate is an expression context — a leading `return` would
|
|
447
|
+
// be a syntax error, and an object-literal script (`{...}`) would parse
|
|
448
|
+
// as a block. So: if the script already starts with `return`, use it as
|
|
449
|
+
// the body verbatim; otherwise wrap it as `return (expr)` so both
|
|
450
|
+
// expression and object-literal forms evaluate to their value. Args are
|
|
451
|
+
// embedded as a JSON array literal; unserializable members become null.
|
|
452
|
+
const body = /^\s*return\b/.test(request.script)
|
|
453
|
+
? request.script
|
|
454
|
+
: `return (${request.script})`;
|
|
455
|
+
const hasArgs = request.args !== undefined && request.args.length > 0;
|
|
456
|
+
const expression = hasArgs
|
|
457
|
+
? `(function(){ const __dshArgs = ${JSON.stringify(request.args)}; return Function(${JSON.stringify(body)}).apply(null, __dshArgs) })()`
|
|
458
|
+
: `(function(){ return Function(${JSON.stringify(body)})() })()`;
|
|
459
|
+
// CDP Runtime.evaluate can hang indefinitely on a not-yet-loaded page
|
|
460
|
+
// (navigate returned but the renderer has not committed). Bound it so a
|
|
461
|
+
// stuck call surfaces as BROWSER_EXECUTE_TIMEOUT instead of wedging the
|
|
462
|
+
// whole tool call. The caller's signal wins when it fires first.
|
|
463
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS;
|
|
464
|
+
const result = await withTimeout(handle.sendCommand(CDP_RUNTIME_EVALUATE, {
|
|
465
|
+
expression,
|
|
466
|
+
returnByValue: true,
|
|
467
|
+
awaitPromise: true,
|
|
468
|
+
}), timeoutMs, signal, `browser: execute timed out after ${timeoutMs}ms`,
|
|
469
|
+
// Best-effort: kill the wedged page script so the renderer (and the
|
|
470
|
+
// debugger queue) is not stuck behind a busy loop forever.
|
|
471
|
+
timedOut => { this.interrupt(handle, timedOut); });
|
|
472
|
+
if (result.exceptionDetails !== undefined) {
|
|
473
|
+
const detail = result.exceptionDetails;
|
|
474
|
+
const exception = detail.exception?.description ?? detail.text ?? 'unknown exception';
|
|
475
|
+
this.record(s, 'execute', { script: request.script }, false, { error: exception });
|
|
476
|
+
return { ok: false, exception };
|
|
477
|
+
}
|
|
478
|
+
const value = result.result?.value ?? null;
|
|
479
|
+
this.record(s, 'execute', {
|
|
480
|
+
script: request.script,
|
|
481
|
+
...request.args !== undefined && request.args.length > 0 ? { args: request.args } : {},
|
|
482
|
+
}, true, { result: typeof value === 'string' ? value.slice(0, 500) : JSON.stringify(value).slice(0, 500) });
|
|
483
|
+
return { ok: true, value };
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
// A caller that aborted is not a failure of the page: report its own reason, or the
|
|
487
|
+
// cancellation surfaces as "execute failed: AbortError" and — if the caller's reason
|
|
488
|
+
// happens to be named TimeoutError — as "timed out after 30000ms", quoting a budget
|
|
489
|
+
// that belongs to the caller rather than to this call.
|
|
490
|
+
if (signal?.aborted)
|
|
491
|
+
throw signal.reason;
|
|
492
|
+
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
493
|
+
throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error });
|
|
494
|
+
}
|
|
495
|
+
throw new BrowserError(`browser: execute failed: ${String(error)}`, 'BROWSER_EXECUTE_FAILED', { cause: error });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Refuse an action the settings have switched off.
|
|
500
|
+
*
|
|
501
|
+
* These switches belong to the OPERATOR. The settings document is written through the
|
|
502
|
+
* plugin's own panel and no tool can reach it, so — unlike `dsh_browser_restrict`, which the
|
|
503
|
+
* model owns and can lift at will — a refusal here stands for as long as the setting does.
|
|
504
|
+
* That is the point of them: a deployment can take page-script execution, downloads, or
|
|
505
|
+
* login-state writes off the table without relying on the model's cooperation.
|
|
506
|
+
*
|
|
507
|
+
* Read through `settingsSource` on every call rather than captured at construction, so
|
|
508
|
+
* flipping a switch applies to the next command instead of the next restart — the same
|
|
509
|
+
* rule the credentials gate follows.
|
|
510
|
+
* @param action - which switch to consult.
|
|
511
|
+
* @throws BrowserError when that switch is off.
|
|
512
|
+
*/
|
|
513
|
+
assertActionAllowed(action) {
|
|
514
|
+
const settings = this.settingsSource?.();
|
|
515
|
+
if (settings === undefined)
|
|
516
|
+
return;
|
|
517
|
+
if (action === 'execute' && !settings.actions.allowExecute) {
|
|
518
|
+
throw new BrowserError('browser: running page scripts is switched off in settings (Browser → actions)', 'BROWSER_EXECUTE_DISABLED');
|
|
519
|
+
}
|
|
520
|
+
if (action === 'download' && !settings.actions.allowDownload) {
|
|
521
|
+
throw new BrowserError('browser: downloads are switched off in settings (Browser → actions)', 'BROWSER_DOWNLOAD_DISABLED');
|
|
522
|
+
}
|
|
523
|
+
if (action === 'credentialWrite' && !settings.actions.allowCredentialWrite) {
|
|
524
|
+
throw new BrowserError('browser: writing cookies is switched off in settings (Browser → actions)', 'BROWSER_AUTH_WRITE_DISABLED');
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|