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,1107 @@
|
|
|
1
|
+
import { DEFAULT_OPERATION_TIMEOUT_MS } from '../../assets/browser-policy.mjs'
|
|
2
|
+
import type { RawCaptureResult } from '../browser-reference/page-script.ts'
|
|
3
|
+
import { existsSync } from 'node:fs'
|
|
4
|
+
import { homedir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { HistoryStore } from './history-store.ts'
|
|
7
|
+
import type { BrowserSettings } from './settings-store.ts'
|
|
8
|
+
import type { DocumentIdentity } from './document-readiness.ts'
|
|
9
|
+
import type { BrowserExecuteRequest, BrowserExecuteResult, BrowserHistoryEntry, BrowserSessionId, ExportedCookie } from '../browser/types.ts'
|
|
10
|
+
import { BrowserError } from '../browser/types.ts'
|
|
11
|
+
import type { BrowserTabWireId } from '../browser/handles.ts'
|
|
12
|
+
import type { CarrierPage, CarrierLossReason } from '../browser/types.ts'
|
|
13
|
+
import type { BrowserReferenceTarget } from '../browser-reference/types.ts'
|
|
14
|
+
|
|
15
|
+
export const PROVIDER_TIMEOUTS = Object.freeze({
|
|
16
|
+
evaluation: 3_000,
|
|
17
|
+
interaction: 5_000,
|
|
18
|
+
lookup: 10_000,
|
|
19
|
+
action: 15_000,
|
|
20
|
+
prepare: DEFAULT_OPERATION_TIMEOUT_MS + 1_000,
|
|
21
|
+
download: 60_000,
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
/** Stable provider id registered with `ctx.browser`. */
|
|
25
|
+
export const ELECTRON_BROWSER_PROVIDER_ID = 'electron'
|
|
26
|
+
|
|
27
|
+
/** `until`: a hidden page waiting for the person's activation to come to the front stops waiting when this aborts (the takeover ended). */
|
|
28
|
+
export interface QuietRevealOptions { readonly select?: boolean; readonly until?: AbortSignal }
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The minimal Electron surface this provider needs. Implemented by the
|
|
32
|
+
* desktop shell with a real `WebContentsView`; a fake implements it in tests.
|
|
33
|
+
*/
|
|
34
|
+
export interface ElectronBrowserViewHost {
|
|
35
|
+
prepare?(scope?: BrowserSessionId): Promise<void>
|
|
36
|
+
readonly referenceOverlayOwner?: 'client'
|
|
37
|
+
referenceOverlayOwnerFor?(scope: BrowserSessionId): 'client' | undefined
|
|
38
|
+
retireSession?(scope: BrowserSessionId): Promise<void>
|
|
39
|
+
/** Move the view's window onto the screen if quiet mode parked it off-screen, without activating it; whether it moved. */
|
|
40
|
+
revealQuietWindow?(handle: ElectronViewHandle, options?: QuietRevealOptions): Promise<boolean>
|
|
41
|
+
/**
|
|
42
|
+
* Create a new browser view and return a handle to its webContents-like
|
|
43
|
+
* surface. The host owns windowing (adding the view to the window, sizing,
|
|
44
|
+
* removal); the provider owns CDP-driven behavior.
|
|
45
|
+
* @param owner - the conversation this view serves. A host shared by several conversations
|
|
46
|
+
* needs it to keep one conversation's page out of another's; a host with one conversation per
|
|
47
|
+
* process may ignore it. It is per VIEW and not per host on purpose: the desktop's host is a
|
|
48
|
+
* single instance that every conversation runs through, so an owner held there would be one
|
|
49
|
+
* conversation's id applied to all of them.
|
|
50
|
+
*/
|
|
51
|
+
createView(identity: BrowserTabWireId): ElectronViewHandle
|
|
52
|
+
/**
|
|
53
|
+
* Destroy a view created by this host. Called on session close; idempotent
|
|
54
|
+
* for an already-destroyed view.
|
|
55
|
+
* @param handle - the handle returned by {@link createView}.
|
|
56
|
+
*/
|
|
57
|
+
destroyView(handle: ElectronViewHandle, options?: { readonly keepPage?: boolean }): void
|
|
58
|
+
/**
|
|
59
|
+
* Show one view as the session's visible surface. The host keeps exactly
|
|
60
|
+
* one visible; switching tabs reorders visibility without losing state.
|
|
61
|
+
* Optional: a host without visible-tab switching treats every view as
|
|
62
|
+
* always present (acceptable for headless/probe hosts).
|
|
63
|
+
* @param handle - the handle to make visible.
|
|
64
|
+
* @param label - human-readable session/task label, when the provider knows
|
|
65
|
+
* one; the host may surface it (e.g. in the window title) so a human can
|
|
66
|
+
* tell which task's page is currently visible.
|
|
67
|
+
* @param options - presentation policy; `quiet` asks for a surface without taking
|
|
68
|
+
* over the screen (see {@link PresentOptions}).
|
|
69
|
+
*/
|
|
70
|
+
showView?(handle: ElectronViewHandle, label?: string, options?: PresentOptions): void
|
|
71
|
+
/**
|
|
72
|
+
* Optional: (re)present a view and WAIT until the host confirms it. Chromium
|
|
73
|
+
* silently drops CDP-synthesized input (`Input.*`) for a view that has no
|
|
74
|
+
* display surface, which made clicks/typing report success while the page
|
|
75
|
+
* received nothing (and made the first input after a navigation vanish,
|
|
76
|
+
* because the replaced renderer has no surface yet). Unlike
|
|
77
|
+
* {@link showView}, this round-trips an RPC barrier that is ordered AFTER
|
|
78
|
+
* the show on the same socket, so its reply means the view is on screen.
|
|
79
|
+
* Rejects when the view cannot be presented; a host without this method is
|
|
80
|
+
* assumed to present every view (headless/probe hosts).
|
|
81
|
+
* @param handle - the handle to present.
|
|
82
|
+
* @param label - human-readable session/task label, as in {@link showView}.
|
|
83
|
+
* @param options - presentation policy, as in {@link showView}.
|
|
84
|
+
*/
|
|
85
|
+
presentView?(handle: ElectronViewHandle, label?: string, options?: PresentOptions): Promise<void>
|
|
86
|
+
/**
|
|
87
|
+
* Optional: pages this carrier holds that the provider never created.
|
|
88
|
+
*
|
|
89
|
+
* A sidebar panel and an installed browser both own their own page creation. Clicking a link
|
|
90
|
+
* that opens a new page — or any `window.open` the page performs — produces a page the provider
|
|
91
|
+
* did not ask for and therefore never recorded. Those pages are real: they are what the human
|
|
92
|
+
* sees, they hold memory, and they persist until something closes them. Without this the tab
|
|
93
|
+
* model reports only what the provider itself made, so the extras are invisible to
|
|
94
|
+
* `dsh_browser_list_tabs` and unclosable through `dsh_browser_close_tab`, accumulating for the
|
|
95
|
+
* life of the browser.
|
|
96
|
+
*
|
|
97
|
+
* Views the host itself opened are NOT included. That exclusion belongs to the host, which is the
|
|
98
|
+
* only side that can make it: a provider tab is identified by the provider's own id and a carrier
|
|
99
|
+
* page by the carrier's, so a caller comparing the two matches nothing and reports every page
|
|
100
|
+
* twice. Measured on the sidebar carrier: three clicks produced three webview guests while
|
|
101
|
+
* `dsh_browser_list_tabs` reported one tab; on the installed-browser carrier the window held four
|
|
102
|
+
* pages and the tool reported one.
|
|
103
|
+
* @param owner - the calling task/conversation; shared sidebar hosts must scope to it.
|
|
104
|
+
* @param options - `requireRunning` lists only from a carrier that is already
|
|
105
|
+
* running. A background scan (the reference-bar pump) must use it: opening
|
|
106
|
+
* the human's installed browser just to look for a page is a side effect
|
|
107
|
+
* nobody asked for.
|
|
108
|
+
* @returns every page this conversation's carrier holds that this host did not open.
|
|
109
|
+
*/
|
|
110
|
+
listPages?(scope: BrowserSessionId, options?: { readonly requireRunning?: boolean }): Promise<readonly CarrierPage[]>
|
|
111
|
+
/**
|
|
112
|
+
* Optional: take over one page reported by {@link listPages}, so it becomes a page this provider
|
|
113
|
+
* drives rather than one it can only see.
|
|
114
|
+
*
|
|
115
|
+
* Reported as a defect: opening a window by hand, navigating it, and then asking a tool to read it
|
|
116
|
+
* produced a SECOND page — the human's own tab was listed (under `page:`) and closable, but not
|
|
117
|
+
* readable, which is the opposite of "the page you are looking at". A carrier that cannot do this
|
|
118
|
+
* must leave it undefined rather than pretend: a switch that reported success and then read
|
|
119
|
+
* nothing is the failure this removes.
|
|
120
|
+
* @param viewId - the view to bind the page to.
|
|
121
|
+
* @param id - the carrier's own page id, as {@link listPages} reported it.
|
|
122
|
+
* @returns a handle for that page, usable for commands like any other view's.
|
|
123
|
+
*/
|
|
124
|
+
adoptPage?(id: BrowserTabWireId, scope?: BrowserSessionId): Promise<ElectronViewHandle>
|
|
125
|
+
/**
|
|
126
|
+
* Optional: close one page reported by {@link listPages}.
|
|
127
|
+
*
|
|
128
|
+
* The pair exists because listing a page the caller cannot close is worse than not listing it:
|
|
129
|
+
* `dsh_browser_list_tabs` would report pages that `dsh_browser_close_tab` answers "not open in
|
|
130
|
+
* this session" about, which reads as a contradiction rather than a boundary.
|
|
131
|
+
* @param id - the carrier's own page id, as {@link listPages} reported it.
|
|
132
|
+
* @param owner - the same task/conversation used for listing; never a global fallback.
|
|
133
|
+
*/
|
|
134
|
+
closePage?(id: BrowserTabWireId, scope?: BrowserSessionId): Promise<void>
|
|
135
|
+
/**
|
|
136
|
+
* Optional cheap usability probe (no network): whether the host can back
|
|
137
|
+
* views at all right now. The self-hosted host checks for a usable Electron
|
|
138
|
+
* binary; a host without the probe is assumed usable. Lets the seam's
|
|
139
|
+
* provider selection (BROWSER_PROVIDER_UNAVAILABLE etc.) be real instead
|
|
140
|
+
* of failing only at first use.
|
|
141
|
+
*/
|
|
142
|
+
available?(): boolean
|
|
143
|
+
/**
|
|
144
|
+
* Tell the human that a toolbar action the agent could not complete has failed.
|
|
145
|
+
*
|
|
146
|
+
* Optional. Declared rather than reached through a cast because this is what issue #16 was:
|
|
147
|
+
* the call used to be unbound, so `this` inside the host's implementation was undefined and
|
|
148
|
+
* its first statement threw — inside an async catch, which turned it into an unhandled
|
|
149
|
+
* rejection that took the whole DSH process down. A declared member is checkable; a cast is
|
|
150
|
+
* not.
|
|
151
|
+
* @param windowId - the window the action came from.
|
|
152
|
+
* @param message - what to show the human.
|
|
153
|
+
*/
|
|
154
|
+
notifyUserActionError?(windowId: string, message: string): void
|
|
155
|
+
/**
|
|
156
|
+
* Optional: associate a view with a window group. Views grouped under the
|
|
157
|
+
* same `windowId` share one window (one window per browser session); a host
|
|
158
|
+
* without this keeps a single shared window. Called right after
|
|
159
|
+
* `createView`, so the host may route the view to its own window even
|
|
160
|
+
* before the first command materializes it.
|
|
161
|
+
* @param handle - the view to group.
|
|
162
|
+
* @param windowId - the group (session) key.
|
|
163
|
+
* @param label - human-readable label for the window title.
|
|
164
|
+
*/
|
|
165
|
+
groupView?(handle: ElectronViewHandle, windowId: string, label?: string): void
|
|
166
|
+
/**
|
|
167
|
+
* Optional: receive user-initiated browser actions from the host's own UI
|
|
168
|
+
* (e.g. a toolbar address bar, back/forward buttons, tab strip). The
|
|
169
|
+
* provider routes them into the session model so the agent and the human
|
|
170
|
+
* always see the same tabs and navigation state.
|
|
171
|
+
* @param handler - called for every user action; must not throw.
|
|
172
|
+
*/
|
|
173
|
+
onUserAction?(handler: (action: BrowserUserAction) => void): void
|
|
174
|
+
/**
|
|
175
|
+
* Optional: receive notice that the human closed a browser window. Closing the
|
|
176
|
+
* interface ends the session it showed — the next call opens a clean one —
|
|
177
|
+
* while browsing history and login state survive on disk.
|
|
178
|
+
* @param handler - called with the group (session) key; must not throw.
|
|
179
|
+
*/
|
|
180
|
+
onViewClosed?(handler: (windowId: string) => void): void
|
|
181
|
+
/**
|
|
182
|
+
* Release the service's page(s) without ending the plugin's own lifetime.
|
|
183
|
+
*
|
|
184
|
+
* Only carriers that outlive a browser session need this. A self-hosted window
|
|
185
|
+
* dies with its view, but the desktop shell's sidebar keeps running no matter
|
|
186
|
+
* what the plugin does — so "release the browser when the session ends"
|
|
187
|
+
* (settings: ui.closeWithSession) has to be asked for explicitly there.
|
|
188
|
+
* @returns a promise that settles once the release was attempted.
|
|
189
|
+
*/
|
|
190
|
+
/**
|
|
191
|
+
* Release this carrier's browser pages for one conversation.
|
|
192
|
+
* @param owner - the conversation whose pages to close. Omit to close every conversation's,
|
|
193
|
+
* which is only correct from a teardown that is itself global.
|
|
194
|
+
*/
|
|
195
|
+
releasePage?(scope?: BrowserSessionId): Promise<void>
|
|
196
|
+
/**
|
|
197
|
+
* Report that this carrier can no longer serve anything, so its owner may replace it.
|
|
198
|
+
*
|
|
199
|
+
* A carrier that borrows an outside process can lose it: the desktop shell exits, and every call
|
|
200
|
+
* after that would dial a port nobody owns. Without this signal the swap happens only at
|
|
201
|
+
* startup, so the choice made then is final for the process's life — which is what a user
|
|
202
|
+
* experiences as "the browser stopped working until I restart DSH". Optional: a carrier that
|
|
203
|
+
* owns its own lifetime has nothing to report.
|
|
204
|
+
*
|
|
205
|
+
* The listener receives WHY, because the fallback's message has to match what happened: a shell
|
|
206
|
+
* that exited and a shell whose panel cannot provide a page both reach the same fallback, and
|
|
207
|
+
* announcing "the shell has exited" for the second tells the user their desktop crashed when it
|
|
208
|
+
* did not.
|
|
209
|
+
* @param listener - called once, when the carrier concludes it is gone.
|
|
210
|
+
*/
|
|
211
|
+
onLost?(listener: (reason: CarrierLossReason) => void): void
|
|
212
|
+
/**
|
|
213
|
+
* Fold the carrier's presentation away while keeping the page alive.
|
|
214
|
+
*
|
|
215
|
+
* The desktop sidebar keeps running regardless of the plugin, so "do not take
|
|
216
|
+
* over the screen" (settings: ui.autoExpandOnce = false) can only be honoured by
|
|
217
|
+
* asking the shell to fold it. A self-hosted window has no such state and simply
|
|
218
|
+
* does not implement this.
|
|
219
|
+
* @returns a promise that settles once the fold was attempted.
|
|
220
|
+
*/
|
|
221
|
+
collapse?(): Promise<void>
|
|
222
|
+
/**
|
|
223
|
+
* Release everything the carrier owns (a spawned browser, a socket, a child).
|
|
224
|
+
* Called when the plugin stops using it, never while it is still in service.
|
|
225
|
+
*/
|
|
226
|
+
dispose?(): void
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* A user-initiated browser action from the host's own UI (toolbar). The
|
|
231
|
+
* `windowId` is the session id the view was grouped under, so the provider
|
|
232
|
+
* can route the action to the right session.
|
|
233
|
+
*/
|
|
234
|
+
export type BrowserUserAction =
|
|
235
|
+
| { readonly type: 'navigate'; readonly windowId: string; readonly url: string }
|
|
236
|
+
| { readonly type: 'newTab'; readonly windowId: string; readonly url?: string }
|
|
237
|
+
| { readonly type: 'activateTab'; readonly windowId: string; readonly viewId: string }
|
|
238
|
+
| { readonly type: 'closeTab'; readonly windowId: string; readonly viewId: string }
|
|
239
|
+
| { readonly type: 'back'; readonly windowId: string }
|
|
240
|
+
| { readonly type: 'forward'; readonly windowId: string }
|
|
241
|
+
| { readonly type: 'reload'; readonly windowId: string }
|
|
242
|
+
| {
|
|
243
|
+
readonly type: 'capture-reference'
|
|
244
|
+
readonly windowId: string
|
|
245
|
+
readonly entry: 'native-menu' | 'page-overlay'
|
|
246
|
+
readonly frameSelector?: string
|
|
247
|
+
/** The exact image/table the human right-clicked, if any. */
|
|
248
|
+
readonly target?: BrowserReferenceTarget
|
|
249
|
+
/** The note typed in the selection bar. */
|
|
250
|
+
readonly comment?: string
|
|
251
|
+
/**
|
|
252
|
+
* The selection text the bar froze before its comment field took focus.
|
|
253
|
+
* Used to locate the capture again when the live selection is gone.
|
|
254
|
+
*/
|
|
255
|
+
readonly selectionText?: string
|
|
256
|
+
/**
|
|
257
|
+
* The complete ordered capture the bar froze at that same moment (text
|
|
258
|
+
* runs, assets, table ranges, anchors). Preferred over `selectionText`.
|
|
259
|
+
*/
|
|
260
|
+
readonly capture?: RawCaptureResult
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* A CDP-capable view handle. This is the subset of Electron's
|
|
265
|
+
* `WebContents`/`WebContentsView` the provider drives; the shell's real
|
|
266
|
+
* implementation adapts `webContents.debugger` to it.
|
|
267
|
+
*/
|
|
268
|
+
export interface ElectronViewHandle {
|
|
269
|
+
/** Unique id of the backing view, used for diagnostics. */
|
|
270
|
+
readonly id: string
|
|
271
|
+
/**
|
|
272
|
+
* Send one CDP command and resolve with its result. Rejects when the
|
|
273
|
+
* debugger is not attached or the command fails.
|
|
274
|
+
* @param method - CDP method, e.g. `Page.navigate`.
|
|
275
|
+
* @param params - CDP command parameters.
|
|
276
|
+
* @returns the CDP `result` object.
|
|
277
|
+
*/
|
|
278
|
+
sendCommand(method: string, params?: Record<string, unknown>, options?: CommandOptions): Promise<Record<string, unknown>>
|
|
279
|
+
/**
|
|
280
|
+
* Whether this view's CDP can encode JPEG and honour a quality setting.
|
|
281
|
+
*
|
|
282
|
+
* Electron 43's CDP hangs on `Page.captureScreenshot` with `format: 'jpeg'`, so a view
|
|
283
|
+
* backed by Electron must leave this unset and the provider keeps to PNG. A view backed
|
|
284
|
+
* by an installed Chrome or Edge is the real browser, where JPEG works, and sets it so
|
|
285
|
+
* the requested format is not silently downgraded.
|
|
286
|
+
*/
|
|
287
|
+
readonly supportsCdpJpeg?: boolean
|
|
288
|
+
/**
|
|
289
|
+
* Give the backing view web focus so keyboard input reaches its page.
|
|
290
|
+
* Optional: an adapter that cannot focus a view omits it, and the provider
|
|
291
|
+
* then behaves exactly as before.
|
|
292
|
+
*/
|
|
293
|
+
focus?(options?: PresentOptions): Promise<void>
|
|
294
|
+
/**
|
|
295
|
+
* Save a URL straight to disk, when the backing view can do that itself.
|
|
296
|
+
*
|
|
297
|
+
* Optional. Declared here rather than reached through a structural cast at the call site:
|
|
298
|
+
* a cast tells the compiler nothing, so a host that implements the interface without this
|
|
299
|
+
* method compiles and then silently does nothing.
|
|
300
|
+
* @param url - the URL to fetch.
|
|
301
|
+
* @param savePath - where to write it.
|
|
302
|
+
*/
|
|
303
|
+
download?(url: string, savePath: string): Promise<void>
|
|
304
|
+
/**
|
|
305
|
+
* Export this view's cookies. Optional; see {@link download} for why it is declared.
|
|
306
|
+
* @returns the cookies, scoped to the view's own page.
|
|
307
|
+
*/
|
|
308
|
+
flushAuth?(): Promise<readonly ExportedCookie[]>
|
|
309
|
+
/**
|
|
310
|
+
* Import cookies into this view. Optional.
|
|
311
|
+
* @param cookies - the cookies to write.
|
|
312
|
+
* @returns how many were accepted.
|
|
313
|
+
*/
|
|
314
|
+
restoreAuth?(cookies: readonly ExportedCookie[]): Promise<number>
|
|
315
|
+
/**
|
|
316
|
+
* Capture this view natively, returning the image and its measured size.
|
|
317
|
+
*
|
|
318
|
+
* Optional. The size is part of the contract because the caller's own tool schema declares
|
|
319
|
+
* `width`/`height`; a host that can measure the image should say so here rather than leaving
|
|
320
|
+
* the provider to guess.
|
|
321
|
+
* @param opts - format, quality and downscale bounds.
|
|
322
|
+
* @returns the encoded image and the pixel size the caller will receive.
|
|
323
|
+
*/
|
|
324
|
+
capture?(opts?: ScreenshotOptions): Promise<{ base64: string; mime: string; width?: number; height?: number }>
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* One tab inside a session: its view, a stable id, and the last URL this provider accepted.
|
|
329
|
+
*
|
|
330
|
+
* `url` does two jobs. It separates "never navigated" from "navigated, but the URL could not be
|
|
331
|
+
* read" — the two used to collapse into the same empty string — and it lets `listTabs` skip
|
|
332
|
+
* probing a tab it already knows is blank, where a probe is a round trip on an uncommitted view
|
|
333
|
+
* that can only answer nothing.
|
|
334
|
+
*
|
|
335
|
+
* A failed guest stays attached to its tab until the caller explicitly closes or resets it.
|
|
336
|
+
*/
|
|
337
|
+
export interface Tab {
|
|
338
|
+
readonly id: BrowserTabWireId
|
|
339
|
+
readonly handle: ElectronViewHandle
|
|
340
|
+
url: string
|
|
341
|
+
navigation?: symbol
|
|
342
|
+
navigationAbort?: AbortController
|
|
343
|
+
failure?: BrowserError
|
|
344
|
+
/**
|
|
345
|
+
* Consecutive failed page evaluations, used only by the reference pump to tell
|
|
346
|
+
* "mid-navigation" (retried) from "this page is gone for now" (backed off).
|
|
347
|
+
*/
|
|
348
|
+
misses?: number
|
|
349
|
+
/** Earliest time the reference pump may try this page again. */
|
|
350
|
+
retryAt?: number
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** One live browser session: an ordered list of tabs, one active. */
|
|
354
|
+
export interface Session {
|
|
355
|
+
readonly id: BrowserSessionId
|
|
356
|
+
/** Human-readable label (usually the DSH task/session id) for the window title. */
|
|
357
|
+
readonly label?: string
|
|
358
|
+
readonly tabs: Tab[]
|
|
359
|
+
activeIndex: number
|
|
360
|
+
/** Chronological operation log (navigate/execute/click/type/fill/download/auth). */
|
|
361
|
+
readonly history: BrowserHistoryEntry[]
|
|
362
|
+
/** Monotonic sequence counter for history entries (survives truncation). */
|
|
363
|
+
nextSeq: number
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Provider config: navigation admission defaults and snapshot caps. */
|
|
367
|
+
export interface ElectronBrowserProviderConfig {
|
|
368
|
+
/** Allow navigation only to HTTP(S) URLs; reject anything else. Default true. */
|
|
369
|
+
readonly httpOnly?: boolean
|
|
370
|
+
/**
|
|
371
|
+
* Persistent browsing history (visited pages), independent of session
|
|
372
|
+
* lifetime. `enabled: false` keeps the browser working but records nothing;
|
|
373
|
+
* the retained limits ride along so a user's choice from the settings panel
|
|
374
|
+
* reaches the store without a second configuration path.
|
|
375
|
+
*/
|
|
376
|
+
readonly history?: {
|
|
377
|
+
readonly enabled?: boolean
|
|
378
|
+
readonly maxEntries?: number
|
|
379
|
+
readonly maxAgeDays?: number
|
|
380
|
+
/**
|
|
381
|
+
* Explicit history file path. Default: beside the browser profile
|
|
382
|
+
* (`$DSH_HOME/dsh-builtin-browser-host/history.jsonl`).
|
|
383
|
+
*/
|
|
384
|
+
readonly file?: string
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Live settings source (the settings panel's document). When present it wins
|
|
388
|
+
* over the static `history` config, so a switch flipped in the UI takes effect
|
|
389
|
+
* without restarting DSH.
|
|
390
|
+
*/
|
|
391
|
+
readonly settings?: () => BrowserSettings
|
|
392
|
+
/** Maximum snapshot elements before truncation. Default 60. */
|
|
393
|
+
readonly snapshotMaxElements?: number
|
|
394
|
+
/**
|
|
395
|
+
* Explicit content cap, overriding the per-format default when set.
|
|
396
|
+
*
|
|
397
|
+
* Honoured again, and it is worth saying why that is a fix rather than a feature: this was
|
|
398
|
+
* `config.contentMaxChars ?? 100_000`, one number for every format, and when the caps became
|
|
399
|
+
* per-format (html and json 50 000, otherwise 20 000) the field was left assigned and never
|
|
400
|
+
* read. A configuration knob that silently does nothing is worse than no knob — it is an
|
|
401
|
+
* operator's decision that quietly went nowhere. Leaving it unset means the per-format
|
|
402
|
+
* default; setting it means the operator meant it.
|
|
403
|
+
*/
|
|
404
|
+
readonly contentMaxChars?: number
|
|
405
|
+
/**
|
|
406
|
+
* Directory `dsh_browser_download` save paths must resolve inside (prevents a
|
|
407
|
+
* prompt-injected agent from writing arbitrary machine paths). Default:
|
|
408
|
+
* `~/Downloads`. NOTE: this default is a convenience, not a security
|
|
409
|
+
* boundary — on Windows it may resolve to OneDrive/redirected paths;
|
|
410
|
+
* a production deployment should set an explicit, verified path.
|
|
411
|
+
*/
|
|
412
|
+
readonly downloadDir?: string
|
|
413
|
+
/**
|
|
414
|
+
* The conversation this process serves, when the composition knows it.
|
|
415
|
+
*
|
|
416
|
+
* The reference entry needs it to find the page the human has open in THIS
|
|
417
|
+
* conversation's sidebar: the shell exposes a panel's pages by conversation id,
|
|
418
|
+
* and a page bound under the wrong id would either be refused or wired into
|
|
419
|
+
* another conversation's draft. Absent on hosts that do not name it (a plain
|
|
420
|
+
* `dsh web`), where the sidebar entry simply does not apply.
|
|
421
|
+
*/
|
|
422
|
+
readonly referenceLabel?: string | (() => string | undefined)
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* CDP method/params for `Page.navigate`, as sent to {@link ElectronViewHandle.sendCommand}.
|
|
427
|
+
*/
|
|
428
|
+
export interface CdpNavigateParams {
|
|
429
|
+
readonly url: string
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* CDP method/params for `Input.dispatchMouseEvent`: a pointer move, or one half
|
|
434
|
+
* of a click's press+release pair. `button`/`clickCount` belong to the press and
|
|
435
|
+
* release halves; a move carries only the position.
|
|
436
|
+
*
|
|
437
|
+
* `buttons` is a BITMASK of what is held down at the moment of the event, and it is not the same
|
|
438
|
+
* field as `button` — `button` says which one this event is about, `buttons` says which ones are
|
|
439
|
+
* down. Chromium needs both to recognise a synthesized press as a real button press: with
|
|
440
|
+
* `buttons` omitted (0), the event still reaches the page and a `click` listener still fires, but
|
|
441
|
+
* the element's DEFAULT ACTION does not run. Measured on the sidebar carrier: a click on an
|
|
442
|
+
* anchor sent `mousedown`/`mouseup`/`click` to the page with `isTrusted: true` and
|
|
443
|
+
* `defaultPrevented: false`, and the browser did not follow the link — including for an anchor
|
|
444
|
+
* injected by the test itself, so the page was not responsible.
|
|
445
|
+
*/
|
|
446
|
+
export interface CdpMouseParams {
|
|
447
|
+
readonly type: 'mouseMoved' | 'mousePressed' | 'mouseReleased'
|
|
448
|
+
readonly x: number
|
|
449
|
+
readonly y: number
|
|
450
|
+
readonly button?: 'left'
|
|
451
|
+
readonly clickCount?: number
|
|
452
|
+
/** Buttons held during the event: 1 = primary down. A move carries 0. */
|
|
453
|
+
readonly buttons?: number
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** CDP method/params for `Input.insertText`. */
|
|
457
|
+
export interface CdpInsertTextParams {
|
|
458
|
+
readonly text: string
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** CDP method/params for `Runtime.evaluate`. */
|
|
462
|
+
export interface CdpEvaluateParams {
|
|
463
|
+
readonly expression: string
|
|
464
|
+
readonly returnByValue: boolean
|
|
465
|
+
readonly awaitPromise?: boolean
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** CDP method for a full-page screenshot capture. */
|
|
469
|
+
export const CDP_PAGE_CAPTURE_SCREENSHOT = 'Page.captureScreenshot'
|
|
470
|
+
|
|
471
|
+
/** One cookie as CDP reports it (`Storage.getCookies`). */
|
|
472
|
+
export interface CdpCookie {
|
|
473
|
+
readonly name?: unknown
|
|
474
|
+
readonly value?: unknown
|
|
475
|
+
readonly domain?: unknown
|
|
476
|
+
readonly path?: unknown
|
|
477
|
+
readonly expires?: unknown
|
|
478
|
+
readonly httpOnly?: unknown
|
|
479
|
+
readonly secure?: unknown
|
|
480
|
+
readonly sameSite?: unknown
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* The document size out of a `Page.getLayoutMetrics` response.
|
|
485
|
+
*
|
|
486
|
+
* CDP returns `cssContentSize` (the whole document) and `cssLayoutViewport` (what is
|
|
487
|
+
* visible); the newer spellings `contentSize` / `layoutViewport` appear on some
|
|
488
|
+
* versions, so both are accepted. Returns undefined when neither is usable, leaving the
|
|
489
|
+
* caller to capture unscaled rather than guess.
|
|
490
|
+
* @param metrics - the raw CDP response.
|
|
491
|
+
* @returns the document and viewport size in CSS pixels.
|
|
492
|
+
*/
|
|
493
|
+
export function layoutSize(metrics: Record<string, unknown>): { width: number; height: number; viewportHeight: number; viewportWidth: number } | undefined {
|
|
494
|
+
const pick = (candidates: readonly unknown[]): { width: number; height: number } | undefined => {
|
|
495
|
+
for (const candidate of candidates) {
|
|
496
|
+
if (typeof candidate !== 'object' || candidate === null) continue
|
|
497
|
+
const box = candidate as { width?: unknown; height?: unknown }
|
|
498
|
+
if (typeof box.width === 'number' && typeof box.height === 'number' && box.width > 0 && box.height > 0) {
|
|
499
|
+
return { width: box.width, height: box.height }
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return undefined
|
|
503
|
+
}
|
|
504
|
+
const content = pick([metrics.cssContentSize, metrics.contentSize])
|
|
505
|
+
const viewport = pick([metrics.cssLayoutViewport, metrics.layoutViewport])
|
|
506
|
+
if (content === undefined) return undefined
|
|
507
|
+
return { width: content.width, height: content.height, viewportHeight: viewport?.height ?? content.height, viewportWidth: viewport?.width ?? content.width }
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Map CDP cookies onto the shape `dsh_browser_auth` exports.
|
|
512
|
+
*
|
|
513
|
+
* CDP reports a cookie as domain + path rather than a URL, and in seconds rather than
|
|
514
|
+
* milliseconds, so both are converted. Entries missing a name, value or domain are
|
|
515
|
+
* dropped rather than exported as broken cookies the caller cannot restore.
|
|
516
|
+
* @param raw - the `cookies` array from a CDP response, of unknown shape.
|
|
517
|
+
* @returns the mappable cookies.
|
|
518
|
+
*/
|
|
519
|
+
export function toExportedCookies(raw: unknown): ExportedCookie[] {
|
|
520
|
+
if (!Array.isArray(raw)) return []
|
|
521
|
+
const out: ExportedCookie[] = []
|
|
522
|
+
for (const entry of raw) {
|
|
523
|
+
if (typeof entry !== 'object' || entry === null) continue
|
|
524
|
+
const cookie = entry as CdpCookie
|
|
525
|
+
// An empty domain is as unusable as a missing one: it cannot form a cookie URL, so
|
|
526
|
+
// exporting it would hand the caller something that fails to restore.
|
|
527
|
+
if (typeof cookie.name !== 'string' || cookie.name === '') continue
|
|
528
|
+
if (typeof cookie.value !== 'string') continue
|
|
529
|
+
if (typeof cookie.domain !== 'string' || cookie.domain === '') continue
|
|
530
|
+
const path = typeof cookie.path === 'string' && cookie.path !== '' ? cookie.path : '/'
|
|
531
|
+
// A leading dot means "this domain and its subdomains"; a cookie URL must not keep it.
|
|
532
|
+
const host = cookie.domain.replace(/^\./, '')
|
|
533
|
+
out.push({
|
|
534
|
+
url: `${cookie.secure === true ? 'https' : 'http'}://${host}${path}`,
|
|
535
|
+
name: cookie.name,
|
|
536
|
+
value: cookie.value,
|
|
537
|
+
domain: cookie.domain,
|
|
538
|
+
path,
|
|
539
|
+
...cookie.secure === true ? { secure: true } : {},
|
|
540
|
+
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
541
|
+
...typeof cookie.expires === 'number' && cookie.expires > 0 ? { expirationDate: cookie.expires } : {},
|
|
542
|
+
})
|
|
543
|
+
}
|
|
544
|
+
return out
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* Map an exported cookie onto the fields `Storage.setCookies` expects.
|
|
549
|
+
*
|
|
550
|
+
* An exported cookie may carry only a URL, so the domain and path are recovered from it
|
|
551
|
+
* when they are absent; without either, CDP cannot place the cookie and it is skipped.
|
|
552
|
+
* @param cookie - the cookie to convert.
|
|
553
|
+
* @returns the CDP cookie, or undefined when it lacks a usable domain.
|
|
554
|
+
*/
|
|
555
|
+
export function toCdpCookie(cookie: ExportedCookie): Record<string, unknown> | undefined {
|
|
556
|
+
let domain = cookie.domain
|
|
557
|
+
let path = cookie.path
|
|
558
|
+
if (domain === undefined || domain === '') {
|
|
559
|
+
try {
|
|
560
|
+
const parsed = new URL(cookie.url)
|
|
561
|
+
domain = parsed.hostname
|
|
562
|
+
if (path === undefined || path === '') path = parsed.pathname === '' ? '/' : parsed.pathname
|
|
563
|
+
} catch {
|
|
564
|
+
return undefined
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (typeof domain !== 'string' || domain === '') return undefined
|
|
568
|
+
return {
|
|
569
|
+
name: cookie.name,
|
|
570
|
+
value: cookie.value,
|
|
571
|
+
domain,
|
|
572
|
+
path: path === undefined || path === '' ? '/' : path,
|
|
573
|
+
...cookie.secure === true ? { secure: true } : {},
|
|
574
|
+
...cookie.httpOnly === true ? { httpOnly: true } : {},
|
|
575
|
+
...typeof cookie.expirationDate === 'number' ? { expires: cookie.expirationDate } : {},
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* How the carrier should present a view before it is used.
|
|
581
|
+
*
|
|
582
|
+
* `quiet` is the resolved `ui.quiet` switch. It does not mean "invisible": Chromium drops
|
|
583
|
+
* synthesized `Input.*` for a view without a display surface, so input still needs one. It means
|
|
584
|
+
* the carrier must get that surface without taking the screen over — no application activation
|
|
585
|
+
* and no operating-system keyboard focus. New windows open inactive; a minimized window and the
|
|
586
|
+
* foreground window's selected page remain under the operator's control. DOM focus and CDP input
|
|
587
|
+
* still target the task's page. Explicit sidebar navigation can select the task's pane.
|
|
588
|
+
*/
|
|
589
|
+
export interface PresentOptions {
|
|
590
|
+
readonly quiet?: boolean
|
|
591
|
+
/** Explicit navigation or tab selection may change the task's sidebar tab without OS activation. */
|
|
592
|
+
readonly select?: boolean
|
|
593
|
+
/** A person's own selection, not the agent's: only this may reveal a window quiet mode parked off-screen. */
|
|
594
|
+
readonly user?: boolean
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* How a command should reach its page.
|
|
599
|
+
*
|
|
600
|
+
* Reported as issue #46: opening the live preview pushed the conversation's sidebar browser panel
|
|
601
|
+
* to the front — a read-only "look at it" action changing the reader's layout. The chain was
|
|
602
|
+
* `capturePassive` → `sendCommand('Page.captureScreenshot')` → the host's guest lookup → the bridge's
|
|
603
|
+
* `ensureSidebar` → a retry that asked the client half to `openSession`, which is exactly what a tool
|
|
604
|
+
* call is allowed to do and a preview is not.
|
|
605
|
+
*
|
|
606
|
+
* `present: false` says "this command must not make anything visible": use the page this
|
|
607
|
+
* conversation already has, and treat "not displayed" as a state to report rather than a condition
|
|
608
|
+
* to fix.
|
|
609
|
+
*/
|
|
610
|
+
export interface CommandOptions {
|
|
611
|
+
readonly deadline?: number
|
|
612
|
+
readonly signal?: AbortSignal
|
|
613
|
+
/** Present the view first (default), or only use a page that is already there. */
|
|
614
|
+
readonly present?: boolean
|
|
615
|
+
/** Only use a guest already attached to this handle, without sidebar initialization. */
|
|
616
|
+
readonly initialize?: boolean
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Native capture options the self-hosted view handle understands. */
|
|
620
|
+
export interface ScreenshotOptions {
|
|
621
|
+
readonly format?: 'png' | 'jpeg'
|
|
622
|
+
readonly quality?: number
|
|
623
|
+
readonly maxWidth?: number
|
|
624
|
+
readonly maxHeight?: number
|
|
625
|
+
/**
|
|
626
|
+
* Capture without presenting the window first (`ui.quiet`).
|
|
627
|
+
*
|
|
628
|
+
* The self-hosted host answers this by skipping its restore/show/focus step: a visible window
|
|
629
|
+
* still captures through `capturePage()`, and a minimized or hidden one falls through to the
|
|
630
|
+
* CDP path, which needs no display surface.
|
|
631
|
+
*/
|
|
632
|
+
readonly quiet?: boolean
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** CDP method for runtime evaluation (the execute path). */
|
|
636
|
+
export const CDP_RUNTIME_EVALUATE = 'Runtime.evaluate'
|
|
637
|
+
|
|
638
|
+
/** CDP method for navigation. */
|
|
639
|
+
export const CDP_PAGE_NAVIGATE = 'Page.navigate'
|
|
640
|
+
|
|
641
|
+
/** Named-key table for `key()`: CDP key/code names + Windows virtual key codes. */
|
|
642
|
+
export const KEY_SPECS: Readonly<Record<string, { readonly key: string; readonly code: string; readonly vk: number; readonly text?: string }>> = {
|
|
643
|
+
// `text` is what makes a key produce CHARACTER INPUT rather than only a key event, and form
|
|
644
|
+
// submission depends on the character: pressing Enter in a text field submits the form because
|
|
645
|
+
// the browser processes a carriage return, not because a key went down. Without `text` the event
|
|
646
|
+
// still reaches the page, a `keydown` listener still fires, and nothing happens — reported as
|
|
647
|
+
// issue #36, where `requestSubmit()` worked and this did not.
|
|
648
|
+
//
|
|
649
|
+
// The same omission is why Space used to pass only its key event; that one was already fixed and
|
|
650
|
+
// is the reason the table has a `text` column at all.
|
|
651
|
+
Enter: { key: 'Enter', code: 'Enter', vk: 13, text: '\r' },
|
|
652
|
+
Tab: { key: 'Tab', code: 'Tab', vk: 9 },
|
|
653
|
+
Escape: { key: 'Escape', code: 'Escape', vk: 27 },
|
|
654
|
+
Backspace: { key: 'Backspace', code: 'Backspace', vk: 8 },
|
|
655
|
+
Delete: { key: 'Delete', code: 'Delete', vk: 46 },
|
|
656
|
+
ArrowUp: { key: 'ArrowUp', code: 'ArrowUp', vk: 38 },
|
|
657
|
+
ArrowDown: { key: 'ArrowDown', code: 'ArrowDown', vk: 40 },
|
|
658
|
+
ArrowLeft: { key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 },
|
|
659
|
+
ArrowRight: { key: 'ArrowRight', code: 'ArrowRight', vk: 39 },
|
|
660
|
+
Home: { key: 'Home', code: 'Home', vk: 36 },
|
|
661
|
+
End: { key: 'End', code: 'End', vk: 35 },
|
|
662
|
+
PageUp: { key: 'PageUp', code: 'PageUp', vk: 33 },
|
|
663
|
+
PageDown: { key: 'PageDown', code: 'PageDown', vk: 34 },
|
|
664
|
+
// Space is the one printable key: CDP needs `text` on the keyDown for the
|
|
665
|
+
// character to land in a focused input; without it the key only scrolls.
|
|
666
|
+
Space: { key: ' ', code: 'Space', vk: 32, text: ' ' },
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** Supported key names, exported for the tool's enum and error messages. */
|
|
670
|
+
export const BROWSER_KEY_NAMES: readonly string[] = Object.keys(KEY_SPECS)
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Localized names a system Downloads folder may carry, in probe order: the
|
|
674
|
+
* English default first, then the Chinese spellings — a zh-CN desktop calls
|
|
675
|
+
* the folder `下载`, a zh-TW one `下載`, and neither is `Downloads`.
|
|
676
|
+
*/
|
|
677
|
+
export const DOWNLOAD_DIR_NAMES: readonly string[] = ['Downloads', '下载', '下載']
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Resolve the default download directory when the config names none: an
|
|
681
|
+
* existing `XDG_DOWNLOAD_DIR` wins (the freedesktop standard, which is what a
|
|
682
|
+
* localized Linux desktop writes), then the first localized `Downloads` folder
|
|
683
|
+
* that exists under the home directory, and finally the English name — created
|
|
684
|
+
* on first use — when none exists yet.
|
|
685
|
+
* @returns the absolute default download directory.
|
|
686
|
+
*/
|
|
687
|
+
export function defaultDownloadDir(): string {
|
|
688
|
+
const xdg = process.env.XDG_DOWNLOAD_DIR
|
|
689
|
+
if (typeof xdg === 'string' && xdg !== '' && existsSync(xdg)) return xdg
|
|
690
|
+
for (const name of DOWNLOAD_DIR_NAMES) {
|
|
691
|
+
const candidate = join(homedir(), name)
|
|
692
|
+
if (existsSync(candidate)) return candidate
|
|
693
|
+
}
|
|
694
|
+
return join(homedir(), DOWNLOAD_DIR_NAMES[0] ?? 'Downloads')
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/**
|
|
698
|
+
* Extra time the transport gets over an in-page locate script's own budget: the
|
|
699
|
+
* script polls for `timeoutMs` and answers only afterwards, so the outer wait
|
|
700
|
+
* must outlast it or its generic timeout hides the in-page reason.
|
|
701
|
+
*/
|
|
702
|
+
export const TARGET_SCRIPT_GRACE_MS = 2_000
|
|
703
|
+
|
|
704
|
+
/**
|
|
705
|
+
* Longest a single in-page wait may hold one `Runtime.evaluate` open. The desktop sidebar's bridge
|
|
706
|
+
* gives every CDP command 15 s and then refuses the guest for good, because a renderer command cannot
|
|
707
|
+
* be cancelled; a locate or scrape that polled its whole caller budget inside one evaluate (15 s on
|
|
708
|
+
* Baidu) crossed that limit while the page was healthy. Longer budgets are polled in slices instead.
|
|
709
|
+
*/
|
|
710
|
+
export const PAGE_POLL_SLICE_MS = 3_000
|
|
711
|
+
|
|
712
|
+
/**
|
|
713
|
+
* The next in-page poll slice before `deadline`: `last` when it reaches the deadline, so only that
|
|
714
|
+
* slice reports a miss and earlier ones answer `{ pending: true }` for the caller to poll again.
|
|
715
|
+
*/
|
|
716
|
+
export function pagePollSlice(deadline: number): { readonly sliceMs: number; readonly last: boolean } {
|
|
717
|
+
const remaining = Math.max(0, deadline - Date.now())
|
|
718
|
+
return remaining <= PAGE_POLL_SLICE_MS ? { sliceMs: remaining, last: true } : { sliceMs: PAGE_POLL_SLICE_MS, last: false }
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Abortable sleep used by the settle loop. */
|
|
722
|
+
export function delay(ms: number, signal?: AbortSignal): Promise<void> {
|
|
723
|
+
return new Promise<void>((resolve) => {
|
|
724
|
+
const timer = setTimeout(() => {
|
|
725
|
+
if (signal !== undefined) signal.removeEventListener('abort', onAbort)
|
|
726
|
+
resolve()
|
|
727
|
+
}, ms)
|
|
728
|
+
const onAbort = (): void => { clearTimeout(timer); resolve() }
|
|
729
|
+
if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
|
|
730
|
+
})
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Bound a promise so a wedged CDP call surfaces as an error instead of
|
|
735
|
+
* hanging the tool call forever. The caller's signal, when provided, wins
|
|
736
|
+
* over the timeout if it fires first.
|
|
737
|
+
* @param promise - the operation to bound.
|
|
738
|
+
* @param ms - the timeout budget.
|
|
739
|
+
* @param signal - optional caller signal.
|
|
740
|
+
* @param message - the timeout error message.
|
|
741
|
+
* @returns the promise's value, or a rejected promise on timeout/abort.
|
|
742
|
+
*/
|
|
743
|
+
export function withTimeout<T>(
|
|
744
|
+
promise: Promise<T>,
|
|
745
|
+
ms: number,
|
|
746
|
+
signal: AbortSignal | undefined,
|
|
747
|
+
message: string,
|
|
748
|
+
onCancel?: (timedOut: boolean) => void,
|
|
749
|
+
): Promise<T> {
|
|
750
|
+
return new Promise<T>((resolve, reject) => {
|
|
751
|
+
let done = false
|
|
752
|
+
const timer = setTimeout(() => {
|
|
753
|
+
if (done) return
|
|
754
|
+
done = true
|
|
755
|
+
// A fired timeout must also release the abort listener; { once: true }
|
|
756
|
+
// only releases it on the next abort, which may never come.
|
|
757
|
+
if (signal !== undefined) signal.removeEventListener('abort', onAbort)
|
|
758
|
+
const error = new Error(message)
|
|
759
|
+
error.name = 'TimeoutError'
|
|
760
|
+
reject(error)
|
|
761
|
+
// Best-effort interrupt of the underlying CDP call (see onCancel).
|
|
762
|
+
onCancel?.(true)
|
|
763
|
+
}, ms)
|
|
764
|
+
const finish = (fn: () => void): void => {
|
|
765
|
+
if (done) return
|
|
766
|
+
done = true
|
|
767
|
+
clearTimeout(timer)
|
|
768
|
+
if (signal !== undefined) signal.removeEventListener('abort', onAbort)
|
|
769
|
+
fn()
|
|
770
|
+
}
|
|
771
|
+
const onAbort = (): void => {
|
|
772
|
+
if (done) return
|
|
773
|
+
done = true
|
|
774
|
+
clearTimeout(timer)
|
|
775
|
+
reject(signal?.reason instanceof Error ? signal.reason : new Error('aborted'))
|
|
776
|
+
onCancel?.(false)
|
|
777
|
+
}
|
|
778
|
+
if (signal !== undefined) signal.addEventListener('abort', onAbort, { once: true })
|
|
779
|
+
promise.then(
|
|
780
|
+
value => finish(() => resolve(value)),
|
|
781
|
+
error => finish(() => reject(error)),
|
|
782
|
+
)
|
|
783
|
+
})
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Run a `Runtime.evaluate` through a view handle and normalize the result.
|
|
788
|
+
* Shared by execute, snapshot, content, and internal URL reads.
|
|
789
|
+
* @param handle - the view handle to evaluate in.
|
|
790
|
+
* @param expression - the JS expression.
|
|
791
|
+
* @param signal - optional abort signal; a fired signal rejects the call.
|
|
792
|
+
*/
|
|
793
|
+
/** Viewport point a target script reported, when it reported one. */
|
|
794
|
+
export function scriptPoint(out: Record<string, unknown> | undefined): { x: number; y: number } | undefined {
|
|
795
|
+
const point = out?.__point as { x?: unknown; y?: unknown } | undefined
|
|
796
|
+
const x = Number(point?.x)
|
|
797
|
+
const y = Number(point?.y)
|
|
798
|
+
return Number.isFinite(x) && Number.isFinite(y) ? { x, y } : undefined
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
export async function handleSendEvaluate(
|
|
802
|
+
handle: ElectronViewHandle,
|
|
803
|
+
expression: string,
|
|
804
|
+
signal?: AbortSignal,
|
|
805
|
+
options?: CommandOptions,
|
|
806
|
+
): Promise<BrowserExecuteResult> {
|
|
807
|
+
signal?.throwIfAborted()
|
|
808
|
+
const result = await handle.sendCommand(CDP_RUNTIME_EVALUATE, {
|
|
809
|
+
expression,
|
|
810
|
+
returnByValue: true,
|
|
811
|
+
awaitPromise: true,
|
|
812
|
+
} satisfies CdpEvaluateParams, options)
|
|
813
|
+
if (result.exceptionDetails !== undefined) {
|
|
814
|
+
const detail = result.exceptionDetails as { text?: string; exception?: { description?: string } }
|
|
815
|
+
return { ok: false, exception: detail.exception?.description ?? detail.text ?? 'unknown exception' }
|
|
816
|
+
}
|
|
817
|
+
return { ok: true, value: (result.result as { value?: unknown } | undefined)?.value ?? null }
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
export abstract class ProviderCore {
|
|
821
|
+
readonly id = ELECTRON_BROWSER_PROVIDER_ID
|
|
822
|
+
|
|
823
|
+
protected readonly sessions = new Map<BrowserSessionId, Session>()
|
|
824
|
+
protected carrierLaunchError: unknown
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* Tick that installs the selection bar in every live tab and collects what the
|
|
828
|
+
* human confirmed. The Desktop sidebar carrier is the shell's own <webview>:
|
|
829
|
+
* the page has no preload bridge and the bridge protocol carries no user-action
|
|
830
|
+
* channel, so the bar leaves its intent in `window.__dshRefIntents` and this
|
|
831
|
+
* pump takes it over CDP. Without it the sidebar has no reference entry.
|
|
832
|
+
*/
|
|
833
|
+
protected referencePump: ReturnType<typeof setInterval> | undefined
|
|
834
|
+
|
|
835
|
+
/** Guards against overlapping pump runs (setInterval keeps firing while one is slow). */
|
|
836
|
+
protected referencePumping = false
|
|
837
|
+
|
|
838
|
+
/**
|
|
839
|
+
* Set once the carrier swapped to a newer provider. `onUserAction` and
|
|
840
|
+
* `onViewClosed` return void and cannot be unsubscribed, so the callbacks
|
|
841
|
+
* themselves must go inert: otherwise one human click is handled by every
|
|
842
|
+
* old provider still retained by the view host, producing duplicate cards.
|
|
843
|
+
*/
|
|
844
|
+
protected disposed = false
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* The session bound to the page the human has open, created on first sight.
|
|
848
|
+
*
|
|
849
|
+
* A reference is captured from a browser SESSION, and a page the human opened from
|
|
850
|
+
* the sidebar's own address bar belongs to no session of ours. Adopting it into one
|
|
851
|
+
* is what makes the selection bar appear there at all — and it is done here, inside
|
|
852
|
+
* the pump, so it needs nothing from the human and nothing from the agent.
|
|
853
|
+
*/
|
|
854
|
+
protected referenceSession: BrowserSessionId | undefined
|
|
855
|
+
|
|
856
|
+
/** Ticks between sidebar page scans while nothing is adopted yet. */
|
|
857
|
+
protected referenceScanCountdown = 0
|
|
858
|
+
|
|
859
|
+
/** Last scan's diagnosis, surfaced by {@link referenceStatus}. */
|
|
860
|
+
protected readonly referenceScan: { label?: string; pages: number; lastError?: string } = { pages: 0 }
|
|
861
|
+
protected readonly httpOnly: boolean
|
|
862
|
+
protected readonly snapshotMaxElements: number
|
|
863
|
+
protected readonly contentMaxChars: number | undefined
|
|
864
|
+
protected readonly downloadDir: string | undefined
|
|
865
|
+
|
|
866
|
+
/**
|
|
867
|
+
* Persistent browsing history, or `undefined` when the user turned it off.
|
|
868
|
+
* Sessions come and go; this record outlives all of them.
|
|
869
|
+
*/
|
|
870
|
+
protected readonly historyStore: HistoryStore | undefined
|
|
871
|
+
|
|
872
|
+
/** Live settings source; absent when nothing owns a settings document. */
|
|
873
|
+
protected readonly settingsSource: (() => BrowserSettings) | undefined
|
|
874
|
+
protected readonly host: ElectronBrowserViewHost
|
|
875
|
+
protected readonly config: ElectronBrowserProviderConfig
|
|
876
|
+
constructor(
|
|
877
|
+
host: ElectronBrowserViewHost,
|
|
878
|
+
config: ElectronBrowserProviderConfig = {},
|
|
879
|
+
) {
|
|
880
|
+
this.host = host
|
|
881
|
+
this.config = config
|
|
882
|
+
this.httpOnly = config.httpOnly ?? true
|
|
883
|
+
this.snapshotMaxElements = config.snapshotMaxElements ?? 60
|
|
884
|
+
this.contentMaxChars = config.contentMaxChars
|
|
885
|
+
// Confine downloads AND screenshot saves to a dedicated directory by
|
|
886
|
+
// default: the OS Downloads folder is the human-visible, browser-natural
|
|
887
|
+
// place for written files, and it is the one directory the DSH file
|
|
888
|
+
// sandbox does not have to arbitrate. The localized name is probed so a
|
|
889
|
+
// Chinese desktop (`~/下载`) works without configuring `downloadDir`.
|
|
890
|
+
this.downloadDir = config.downloadDir ?? defaultDownloadDir()
|
|
891
|
+
this.settingsSource = config.settings
|
|
892
|
+
// Browsing history follows the browser profile's persistence rules (close
|
|
893
|
+
// the interface, lose nothing), and can be switched off from settings.
|
|
894
|
+
this.historyStore = config.history?.enabled === false
|
|
895
|
+
? undefined
|
|
896
|
+
: new HistoryStore(config.history?.file, {
|
|
897
|
+
...config.history?.maxEntries !== undefined ? { maxEntries: config.history.maxEntries } : {},
|
|
898
|
+
...config.history?.maxAgeDays !== undefined ? { maxAgeDays: config.history.maxAgeDays } : {},
|
|
899
|
+
})
|
|
900
|
+
// Route toolbar (host UI) actions into the session model: the human and
|
|
901
|
+
// the agent then always drive the same tabs, history, and navigation.
|
|
902
|
+
this.host.onUserAction?.(action => { if (!this.disposed) void this.handleUserAction(action) })
|
|
903
|
+
// A window the human closed ends the session it showed: the next call opens a
|
|
904
|
+
// clean one instead of driving a page nobody can see.
|
|
905
|
+
this.host.onViewClosed?.(windowId => { if (!this.disposed) void this.handleViewClosed(windowId) })
|
|
906
|
+
this.startReferenceEntryPump()
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* Evaluate one expression in a tab and return its value.
|
|
911
|
+
*
|
|
912
|
+
* Bounded on purpose: the pump runs on a timer, and an unresponsive renderer
|
|
913
|
+
* would otherwise hold the whole tick (and every later one) forever.
|
|
914
|
+
* Never initializes or launches a closed tab/browser (issue #105).
|
|
915
|
+
* @param tab - the tab to evaluate in.
|
|
916
|
+
* @param expression - the JS expression.
|
|
917
|
+
* @param timeoutMs - how long to wait before treating the page as not answering.
|
|
918
|
+
*/
|
|
919
|
+
protected async evaluateInTab(tab: Tab, expression: string, timeoutMs: number = PROVIDER_TIMEOUTS.evaluation): Promise<unknown> {
|
|
920
|
+
const raw = await withTimeout(
|
|
921
|
+
tab.handle.sendCommand('Runtime.evaluate', {
|
|
922
|
+
expression, returnByValue: true, awaitPromise: true,
|
|
923
|
+
}, { present: false, initialize: false }),
|
|
924
|
+
timeoutMs,
|
|
925
|
+
undefined,
|
|
926
|
+
`browser: reference probe timed out after ${timeoutMs}ms`,
|
|
927
|
+
)
|
|
928
|
+
const result = (raw as { result?: { value?: unknown } }).result
|
|
929
|
+
return result?.value
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/** Set by {@link openUrl}; read by the client through the HTTP surface. */
|
|
933
|
+
protected lastOpen: { readonly url: string; readonly at: number } | undefined
|
|
934
|
+
|
|
935
|
+
/**
|
|
936
|
+
* Refuse to send synthesized input to a view that is no longer the one it was located
|
|
937
|
+
* against.
|
|
938
|
+
*
|
|
939
|
+
* `locateHandle` was captured before a page-side locate that can consume its whole
|
|
940
|
+
* 10s budget; the session's active tab is re-read afterwards. If they differ, the human
|
|
941
|
+
* switched tabs mid-flight (the product's whole point is that they can take over), and
|
|
942
|
+
* the coordinates belong to one page while the dispatch would go to another. Comparing
|
|
943
|
+
* the handles turns that into a loud, retryable error instead of input the caller
|
|
944
|
+
* believes landed.
|
|
945
|
+
* @param session - the session id, for the message.
|
|
946
|
+
* @param locateHandle - the view the locate ran in.
|
|
947
|
+
* @param liveHandle - the view that is active now.
|
|
948
|
+
*/
|
|
949
|
+
protected assertSameView(session: BrowserSessionId, locateHandle: ElectronViewHandle, liveHandle: ElectronViewHandle): void {
|
|
950
|
+
if (locateHandle === liveHandle) return
|
|
951
|
+
throw new BrowserError(
|
|
952
|
+
`browser: the session's active view changed while the element was being located (session ${session}); the operation was not dispatched — retry it`,
|
|
953
|
+
'BROWSER_VIEW_CHANGED',
|
|
954
|
+
)
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* Give the view web focus before synthesizing keyboard input.
|
|
959
|
+
*
|
|
960
|
+
* A renderer only delivers key events to the view that holds web focus. A
|
|
961
|
+
* view that was created but never clicked holds none — and `Input` events
|
|
962
|
+
* injected over CDP do not grant it — so the FIRST `dsh_browser_key` of a fresh
|
|
963
|
+
* session vanished inside the renderer while the command still answered
|
|
964
|
+
* success. Hosts that cannot focus a view (a test double, a different shell
|
|
965
|
+
* adapter) simply have no `focus`, and nothing changes for them.
|
|
966
|
+
*/
|
|
967
|
+
protected async focusView(handle: ElectronViewHandle): Promise<void> {
|
|
968
|
+
if (handle.focus === undefined) return
|
|
969
|
+
const quiet = this.isQuiet()
|
|
970
|
+
try {
|
|
971
|
+
// Bounded, unlike the rest of this call: the child RPC has no timeout of its own,
|
|
972
|
+
// and this runs before typing, so an unresponsive child would hang dsh_browser_key for
|
|
973
|
+
// good. A timeout is caught below exactly like any other focus failure, so the
|
|
974
|
+
// best-effort contract is unchanged.
|
|
975
|
+
await withTimeout(handle.focus(quiet ? { quiet } : undefined), PROVIDER_TIMEOUTS.interaction, undefined, 'browser: focusing the view timed out')
|
|
976
|
+
} catch (error) {
|
|
977
|
+
if (quiet) throw error
|
|
978
|
+
// Best-effort: a view that refuses focus must not fail the caller's key
|
|
979
|
+
// press; the dispatch below reports a real channel failure itself.
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/** Execute JS in the active tab's page context. */
|
|
984
|
+
async execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
|
|
985
|
+
this.assertActionAllowed('execute')
|
|
986
|
+
return this.evaluatePage(session, request, signal)
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
protected async evaluatePage(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
|
|
990
|
+
const s = this.session(session)
|
|
991
|
+
const { handle } = this.activeTab(s)
|
|
992
|
+
signal?.throwIfAborted()
|
|
993
|
+
try {
|
|
994
|
+
// Wrap the script in a Function so `return` statements are legal and
|
|
995
|
+
// request.args arrive as `arguments[0..n]`. A bare script handed to CDP
|
|
996
|
+
// Runtime.evaluate is an expression context — a leading `return` would
|
|
997
|
+
// be a syntax error, and an object-literal script (`{...}`) would parse
|
|
998
|
+
// as a block. So: if the script already starts with `return`, use it as
|
|
999
|
+
// the body verbatim; otherwise wrap it as `return (expr)` so both
|
|
1000
|
+
// expression and object-literal forms evaluate to their value. Args are
|
|
1001
|
+
// embedded as a JSON array literal; unserializable members become null.
|
|
1002
|
+
const body = /^\s*return\b/.test(request.script)
|
|
1003
|
+
? request.script
|
|
1004
|
+
: `return (${request.script})`
|
|
1005
|
+
const hasArgs = request.args !== undefined && request.args.length > 0
|
|
1006
|
+
const expression = hasArgs
|
|
1007
|
+
? `(function(){ const __dshArgs = ${JSON.stringify(request.args)}; return Function(${JSON.stringify(body)}).apply(null, __dshArgs) })()`
|
|
1008
|
+
: `(function(){ return Function(${JSON.stringify(body)})() })()`
|
|
1009
|
+
// CDP Runtime.evaluate can hang indefinitely on a not-yet-loaded page
|
|
1010
|
+
// (navigate returned but the renderer has not committed). Bound it so a
|
|
1011
|
+
// stuck call surfaces as BROWSER_EXECUTE_TIMEOUT instead of wedging the
|
|
1012
|
+
// whole tool call. The caller's signal wins when it fires first.
|
|
1013
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS
|
|
1014
|
+
const result = await withTimeout(
|
|
1015
|
+
handle.sendCommand(CDP_RUNTIME_EVALUATE, {
|
|
1016
|
+
expression,
|
|
1017
|
+
returnByValue: true,
|
|
1018
|
+
awaitPromise: true,
|
|
1019
|
+
} satisfies CdpEvaluateParams),
|
|
1020
|
+
timeoutMs,
|
|
1021
|
+
signal,
|
|
1022
|
+
`browser: execute timed out after ${timeoutMs}ms`,
|
|
1023
|
+
// Best-effort: kill the wedged page script so the renderer (and the
|
|
1024
|
+
// debugger queue) is not stuck behind a busy loop forever.
|
|
1025
|
+
timedOut => { this.interrupt(handle, timedOut) },
|
|
1026
|
+
)
|
|
1027
|
+
if (result.exceptionDetails !== undefined) {
|
|
1028
|
+
const detail = result.exceptionDetails as { text?: string; exception?: { description?: string } }
|
|
1029
|
+
const exception = detail.exception?.description ?? detail.text ?? 'unknown exception'
|
|
1030
|
+
this.record(s, 'execute', { script: request.script }, false, { error: exception })
|
|
1031
|
+
return { ok: false, exception }
|
|
1032
|
+
}
|
|
1033
|
+
const value = (result.result as { value?: unknown } | undefined)?.value ?? null
|
|
1034
|
+
this.record(s, 'execute', {
|
|
1035
|
+
script: request.script,
|
|
1036
|
+
...request.args !== undefined && request.args.length > 0 ? { args: request.args } : {},
|
|
1037
|
+
}, true, { result: typeof value === 'string' ? value.slice(0, 500) : JSON.stringify(value).slice(0, 500) })
|
|
1038
|
+
return { ok: true, value }
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
// A caller that aborted is not a failure of the page: report its own reason, or the
|
|
1041
|
+
// cancellation surfaces as "execute failed: AbortError" and — if the caller's reason
|
|
1042
|
+
// happens to be named TimeoutError — as "timed out after 30000ms", quoting a budget
|
|
1043
|
+
// that belongs to the caller rather than to this call.
|
|
1044
|
+
if (signal?.aborted) throw signal.reason
|
|
1045
|
+
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
1046
|
+
throw new BrowserError(`browser: execute timed out after ${request.timeoutMs ?? DEFAULT_OPERATION_TIMEOUT_MS}ms`, 'BROWSER_EXECUTE_TIMEOUT', { cause: error })
|
|
1047
|
+
}
|
|
1048
|
+
throw new BrowserError(`browser: execute failed: ${String(error)}`, 'BROWSER_EXECUTE_FAILED', { cause: error })
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Refuse an action the settings have switched off.
|
|
1054
|
+
*
|
|
1055
|
+
* These switches belong to the OPERATOR. The settings document is written through the
|
|
1056
|
+
* plugin's own panel and no tool can reach it, so — unlike `dsh_browser_restrict`, which the
|
|
1057
|
+
* model owns and can lift at will — a refusal here stands for as long as the setting does.
|
|
1058
|
+
* That is the point of them: a deployment can take page-script execution, downloads, or
|
|
1059
|
+
* login-state writes off the table without relying on the model's cooperation.
|
|
1060
|
+
*
|
|
1061
|
+
* Read through `settingsSource` on every call rather than captured at construction, so
|
|
1062
|
+
* flipping a switch applies to the next command instead of the next restart — the same
|
|
1063
|
+
* rule the credentials gate follows.
|
|
1064
|
+
* @param action - which switch to consult.
|
|
1065
|
+
* @throws BrowserError when that switch is off.
|
|
1066
|
+
*/
|
|
1067
|
+
protected assertActionAllowed(action: 'execute' | 'download' | 'credentialWrite'): void {
|
|
1068
|
+
const settings = this.settingsSource?.()
|
|
1069
|
+
if (settings === undefined) return
|
|
1070
|
+
if (action === 'execute' && !settings.actions.allowExecute) {
|
|
1071
|
+
throw new BrowserError('browser: running page scripts is switched off in settings (Browser → actions)', 'BROWSER_EXECUTE_DISABLED')
|
|
1072
|
+
}
|
|
1073
|
+
if (action === 'download' && !settings.actions.allowDownload) {
|
|
1074
|
+
throw new BrowserError('browser: downloads are switched off in settings (Browser → actions)', 'BROWSER_DOWNLOAD_DISABLED')
|
|
1075
|
+
}
|
|
1076
|
+
if (action === 'credentialWrite' && !settings.actions.allowCredentialWrite) {
|
|
1077
|
+
throw new BrowserError('browser: writing cookies is switched off in settings (Browser → actions)', 'BROWSER_AUTH_WRITE_DISABLED')
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
protected abstract startReferenceEntryPump(): void
|
|
1082
|
+
protected abstract prepareCarrier(signal?: AbortSignal, scope?: BrowserSessionId): Promise<void>
|
|
1083
|
+
protected abstract checkNavigation(tab: Tab, navigation: symbol): void
|
|
1084
|
+
protected abstract documentIdentity(handle: ElectronViewHandle, signal?: AbortSignal, checkCurrent?: () => void,
|
|
1085
|
+
deadline?: number, allowErrorDocument?: boolean): Promise<DocumentIdentity>
|
|
1086
|
+
protected abstract settleDocument(handle: ElectronViewHandle, before: DocumentIdentity | undefined, signal?: AbortSignal,
|
|
1087
|
+
acknowledgement?: { readonly frameId?: string; readonly loaderId?: string }, checkCurrent?: () => void,
|
|
1088
|
+
historyEntry?: number, deadline?: number, allowErrorDocument?: boolean): Promise<void>
|
|
1089
|
+
protected abstract present(s: Session, signal?: AbortSignal): Promise<ElectronViewHandle>
|
|
1090
|
+
protected abstract record(
|
|
1091
|
+
s: Session,
|
|
1092
|
+
action: string,
|
|
1093
|
+
params: Record<string, unknown>,
|
|
1094
|
+
ok: boolean,
|
|
1095
|
+
detail?: { result?: string; error?: string },
|
|
1096
|
+
): void
|
|
1097
|
+
protected abstract recordVisit(s: Session, handle: ElectronViewHandle): void
|
|
1098
|
+
protected abstract session(session: BrowserSessionId): Session
|
|
1099
|
+
protected abstract activeTab(s: Session): Tab
|
|
1100
|
+
protected abstract interrupt(handle: ElectronViewHandle, timedOut: boolean): void
|
|
1101
|
+
protected abstract quarantine(handle: ElectronViewHandle): void
|
|
1102
|
+
protected abstract handleViewClosed(windowId: string): Promise<void>
|
|
1103
|
+
protected abstract handleUserAction(action: BrowserUserAction, propagate?: boolean): Promise<void>
|
|
1104
|
+
protected abstract isQuiet(): boolean
|
|
1105
|
+
protected abstract showActive(s: Session, select?: boolean, user?: boolean): void
|
|
1106
|
+
protected abstract currentUrl(handle: ElectronViewHandle): Promise<string>
|
|
1107
|
+
}
|