dsh-builtin-browser 0.1.15 → 0.1.16

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.
@@ -6,7 +6,7 @@
6
6
  * shell that owns the `BrowserWindow`.
7
7
  * @module dsh-browser/browser-electron
8
8
  */
9
- import type { BrowserChallenge, BrowserContentRequest, BrowserContentResult, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserHistoryEntry, BrowserOpenRequest, BrowserProvider, BrowserSessionId, BrowserSnapshotResult, BrowserTab, ExportedCookie } from '../browser/types.ts';
9
+ import type { BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserContentRequest, BrowserContentResult, BrowserElementTarget, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserOpenRequest, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, ExportedCookie } from '../browser/types.js';
10
10
  /** Stable provider id registered with `ctx.browser`. */
11
11
  export declare const ELECTRON_BROWSER_PROVIDER_ID = "electron";
12
12
  /**
@@ -32,9 +32,70 @@ export interface ElectronBrowserViewHost {
32
32
  * Optional: a host without visible-tab switching treats every view as
33
33
  * always present (acceptable for headless/probe hosts).
34
34
  * @param handle - the handle to make visible.
35
+ * @param label - human-readable session/task label, when the provider knows
36
+ * one; the host may surface it (e.g. in the window title) so a human can
37
+ * tell which task's page is currently visible.
35
38
  */
36
- showView?(handle: ElectronViewHandle): void;
39
+ showView?(handle: ElectronViewHandle, label?: string): void;
40
+ /**
41
+ * Optional cheap usability probe (no network): whether the host can back
42
+ * views at all right now. The self-hosted host checks for a usable Electron
43
+ * binary; a host without the probe is assumed usable. Lets the seam's
44
+ * provider selection (BROWSER_PROVIDER_UNAVAILABLE etc.) be real instead
45
+ * of failing only at first use.
46
+ */
47
+ available?(): boolean;
48
+ /**
49
+ * Optional: associate a view with a window group. Views grouped under the
50
+ * same `windowId` share one window (one window per browser session); a host
51
+ * without this keeps a single shared window. Called right after
52
+ * `createView`, so the host may route the view to its own window even
53
+ * before the first command materializes it.
54
+ * @param handle - the view to group.
55
+ * @param windowId - the group (session) key.
56
+ * @param label - human-readable label for the window title.
57
+ */
58
+ groupView?(handle: ElectronViewHandle, windowId: string, label?: string): void;
59
+ /**
60
+ * Optional: receive user-initiated browser actions from the host's own UI
61
+ * (e.g. a toolbar address bar, back/forward buttons, tab strip). The
62
+ * provider routes them into the session model so the agent and the human
63
+ * always see the same tabs and navigation state.
64
+ * @param handler - called for every user action; must not throw.
65
+ */
66
+ onUserAction?(handler: (action: BrowserUserAction) => void): void;
37
67
  }
68
+ /**
69
+ * A user-initiated browser action from the host's own UI (toolbar). The
70
+ * `windowId` is the session id the view was grouped under, so the provider
71
+ * can route the action to the right session.
72
+ */
73
+ export type BrowserUserAction = {
74
+ readonly type: 'navigate';
75
+ readonly windowId: string;
76
+ readonly url: string;
77
+ } | {
78
+ readonly type: 'newTab';
79
+ readonly windowId: string;
80
+ readonly url?: string;
81
+ } | {
82
+ readonly type: 'activateTab';
83
+ readonly windowId: string;
84
+ readonly viewId: string;
85
+ } | {
86
+ readonly type: 'closeTab';
87
+ readonly windowId: string;
88
+ readonly viewId: string;
89
+ } | {
90
+ readonly type: 'back';
91
+ readonly windowId: string;
92
+ } | {
93
+ readonly type: 'forward';
94
+ readonly windowId: string;
95
+ } | {
96
+ readonly type: 'reload';
97
+ readonly windowId: string;
98
+ };
38
99
  /**
39
100
  * A CDP-capable view handle. This is the subset of Electron's
40
101
  * `WebContents`/`WebContentsView` the provider drives; the shell's real
@@ -60,6 +121,14 @@ export interface ElectronBrowserProviderConfig {
60
121
  readonly snapshotMaxElements?: number;
61
122
  /** Maximum content characters before truncation when no maxChars is given. Default 100_000. */
62
123
  readonly contentMaxChars?: number;
124
+ /**
125
+ * Directory `browser_download` save paths must resolve inside (prevents a
126
+ * prompt-injected agent from writing arbitrary machine paths). Default:
127
+ * `~/Downloads`. NOTE: this default is a convenience, not a security
128
+ * boundary — on Windows it may resolve to OneDrive/redirected paths;
129
+ * a production deployment should set an explicit, verified path.
130
+ */
131
+ readonly downloadDir?: string;
63
132
  }
64
133
  /**
65
134
  * CDP method/params for `Page.navigate`, as sent to {@link ElectronViewHandle.sendCommand}.
@@ -89,10 +158,19 @@ export interface CdpEvaluateParams {
89
158
  }
90
159
  /** CDP method for a full-page screenshot capture. */
91
160
  export declare const CDP_PAGE_CAPTURE_SCREENSHOT = "Page.captureScreenshot";
161
+ /** Native capture options the self-hosted view handle understands. */
162
+ export interface ScreenshotOptions {
163
+ readonly format?: 'png' | 'jpeg';
164
+ readonly quality?: number;
165
+ readonly maxWidth?: number;
166
+ readonly maxHeight?: number;
167
+ }
92
168
  /** CDP method for runtime evaluation (the execute path). */
93
169
  export declare const CDP_RUNTIME_EVALUATE = "Runtime.evaluate";
94
170
  /** CDP method for navigation. */
95
171
  export declare const CDP_PAGE_NAVIGATE = "Page.navigate";
172
+ /** Supported key names, exported for the tool's enum and error messages. */
173
+ export declare const BROWSER_KEY_NAMES: readonly string[];
96
174
  /**
97
175
  * Browser provider over Electron views. Sessions hold an ordered list of
98
176
  * tabs; each tab is one view created by the host. The active tab receives
@@ -107,8 +185,12 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
107
185
  private readonly httpOnly;
108
186
  private readonly snapshotMaxElements;
109
187
  private readonly contentMaxChars;
188
+ private readonly downloadDir;
110
189
  constructor(host: ElectronBrowserViewHost, config?: ElectronBrowserProviderConfig);
111
- /** Usable whenever the host can create views (always in the desktop shell). */
190
+ /**
191
+ * Usable when the host says it can back views (the self-hosted host probes
192
+ * for a usable Electron binary; the desktop shell is assumed usable).
193
+ */
112
194
  available(): boolean;
113
195
  /**
114
196
  * Open a NEW browser session with its own view. Every call mints a fresh
@@ -116,8 +198,10 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
116
198
  * tool layer caches one session per DSH task). Sessions are isolated from
117
199
  * each other: each keeps its own tabs, active tab, and history, and only
118
200
  * the active tab of a session is made visible.
201
+ * @param label - optional human-readable label (e.g. the DSH task id) shown
202
+ * in the window title so a human can tell which task's page is visible.
119
203
  */
120
- open(): Promise<BrowserSessionId>;
204
+ open(label?: string): Promise<BrowserSessionId>;
121
205
  /** Open a URL in the active tab (default) or a new tab. */
122
206
  openUrl(session: BrowserSessionId, request: BrowserOpenRequest, signal?: AbortSignal): Promise<void>;
123
207
  /** List the session's tabs with their titles. */
@@ -126,6 +210,16 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
126
210
  switchTab(session: BrowserSessionId, tabId: string): Promise<void>;
127
211
  /** Close one tab; closing the active tab activates the next. */
128
212
  closeTab(session: BrowserSessionId, tabId: string): Promise<void>;
213
+ /**
214
+ * Find a tab by id, preferring the calling session. Tab ids are globally
215
+ * unique UUIDs, so when the calling session does not hold the tab (the tool
216
+ * layer's session resolution can drift from the session that opened it),
217
+ * fall back to locating it in any other session instead of failing — the
218
+ * caller explicitly named a tab, so acting on it is what they want. Throws
219
+ * BROWSER_TAB_UNKNOWN with the session's actual tabs when the id exists
220
+ * nowhere.
221
+ */
222
+ private locateTab;
129
223
  /** Close every tab and reset to one blank tab. */
130
224
  reset(session: BrowserSessionId): Promise<void>;
131
225
  /** Navigate the active tab's view to a URL, honoring HTTP(S)-only admission. */
@@ -134,21 +228,55 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
134
228
  }, signal?: AbortSignal): Promise<void>;
135
229
  /** Execute JS in the active tab's page context. */
136
230
  execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
231
+ /**
232
+ * Poll until the active tab's page is ready (and optional URL/selector
233
+ * match), or the budget runs out. Returns a verdict instead of throwing on
234
+ * timeout — the caller (model) decides what a miss means. Polling evaluates
235
+ * in the CURRENT document, so after a navigation the old document may
236
+ * briefly answer; pass the expected `url` to disambiguate.
237
+ */
238
+ waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult>;
137
239
  /** Produce an AI-friendly snapshot of the active tab. */
138
240
  snapshot(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserSnapshotResult>;
241
+ /**
242
+ * Read the active tab's accessibility tree: semantic roles/names/states for
243
+ * every interactive node (Chrome's `computedRole`/`computedName` when
244
+ * available, tag/attribute inference otherwise). Pierces same-origin
245
+ * iframes and shadow roots like the snapshot; cross-origin frames stay
246
+ * opaque. Coordinates are top-document viewport-relative, so a node can
247
+ * also be driven by click/type.
248
+ */
249
+ a11y(session: BrowserSessionId, request: BrowserA11yRequest, signal?: AbortSignal): Promise<BrowserA11yResult>;
139
250
  /** Check whether a human-verification challenge is blocking the active tab. */
140
251
  detectChallenge(session: BrowserSessionId, signal?: AbortSignal): Promise<BrowserChallenge>;
141
252
  /** Fetch page content in a requested format. */
142
253
  content(session: BrowserSessionId, request: BrowserContentRequest, signal?: AbortSignal): Promise<BrowserContentResult>;
143
- /** Click at viewport coordinates (CDP mousePressed + mouseReleased). */
144
- click(session: BrowserSessionId, request: {
145
- readonly x: number;
146
- readonly y: number;
254
+ /**
255
+ * Click at viewport coordinates, or at a located element's center when a
256
+ * `target` (css/text/xpath) is given. CDP mousePressed + mouseReleased.
257
+ */
258
+ click(session: BrowserSessionId, request: BrowserClickRequest | {
259
+ readonly target: BrowserElementTarget;
147
260
  }, signal?: AbortSignal): Promise<void>;
148
- /** Type into the focused element. */
149
- type(session: BrowserSessionId, request: {
150
- readonly text: string;
261
+ /**
262
+ * Type into the focused element, or focus a located element (css/text/xpath)
263
+ * first and then insert the text.
264
+ */
265
+ type(session: BrowserSessionId, request: BrowserTypeRequest | {
266
+ readonly target: BrowserElementTarget;
151
267
  }, signal?: AbortSignal): Promise<void>;
268
+ /** Scroll the page: by deltas, to a selector, or to top/bottom. */
269
+ scroll(session: BrowserSessionId, request: BrowserScrollRequest, signal?: AbortSignal): Promise<void>;
270
+ /** Go back (-1) or forward (+1) in the active tab's navigation history. */
271
+ private historyStep;
272
+ /** Go back in the active tab's history. */
273
+ back(session: BrowserSessionId, signal?: AbortSignal): Promise<void>;
274
+ /** Go forward in the active tab's history. */
275
+ forward(session: BrowserSessionId, signal?: AbortSignal): Promise<void>;
276
+ /** Reload the active tab. */
277
+ reload(session: BrowserSessionId, signal?: AbortSignal): Promise<void>;
278
+ /** Press one named key (Enter/Tab/arrows/…) via CDP key events. */
279
+ key(session: BrowserSessionId, request: BrowserKeyRequest, signal?: AbortSignal): Promise<void>;
152
280
  /**
153
281
  * Fill a form's fields in one batch. Runs one page-context script that
154
282
  * resolves each field (selector, or name/label/placeholder among visible
@@ -157,10 +285,48 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
157
285
  * select/checkbox/radio/contenteditable, and optionally submits the form.
158
286
  */
159
287
  fillForm(session: BrowserSessionId, request: BrowserFillRequest, signal?: AbortSignal): Promise<BrowserFillResult>;
288
+ /**
289
+ * Build an in-page async IIFE that locates ONE element by css/text/xpath
290
+ * (polling until it appears or the budget runs out) and then runs `body`
291
+ * with `el` in scope. Shared by the target-based tools: click/type (②),
292
+ * setValue/check/select/clear/getValue (③), and the scrape item wait.
293
+ */
294
+ private buildTargetScript;
295
+ /**
296
+ * Shared evaluate wrapper for the target-based tools. Runs the in-page
297
+ * script and returns its result object; throws a typed BrowserError on
298
+ * evaluation failure or an in-page `{ ok: false, error }` verdict.
299
+ */
300
+ private runTargetScript;
301
+ /** Set one element's value (native setter + input/change, React-friendly). */
302
+ setValue(session: BrowserSessionId, request: BrowserSetValueRequest, signal?: AbortSignal): Promise<BrowserSetValueResult>;
303
+ /** Check or uncheck one checkbox/radio. */
304
+ check(session: BrowserSessionId, request: BrowserCheckRequest, signal?: AbortSignal): Promise<{
305
+ readonly checked: boolean;
306
+ }>;
307
+ /** Select one option of a <select>, by value, visible text, or index. */
308
+ selectOption(session: BrowserSessionId, request: BrowserSelectRequest, signal?: AbortSignal): Promise<BrowserSelectResult>;
309
+ /** Clear one input/textarea/contenteditable (or uncheck a checkbox/radio). */
310
+ clearField(session: BrowserSessionId, request: BrowserClearRequest, signal?: AbortSignal): Promise<{
311
+ readonly cleared: boolean;
312
+ }>;
313
+ /** Read one element's current value (for verification). */
314
+ getValue(session: BrowserSessionId, request: BrowserGetValueRequest, signal?: AbortSignal): Promise<BrowserGetValueResult>;
315
+ /**
316
+ * Extract structured data from repeated DOM items (static CSS, CSP-safe —
317
+ * no arbitrary code runs). Waits for the item selector, then maps each item
318
+ * through the field selectors; `selector@attr` reads an attribute instead
319
+ * of text (`a@href` yields an absolute URL).
320
+ */
321
+ scrape(session: BrowserSessionId, request: BrowserScrapeRequest, signal?: AbortSignal): Promise<BrowserScrapeResult>;
160
322
  /**
161
323
  * Download a URL to a local file, keeping the session's cookies/login.
162
324
  * Requires the self-hosted host (which implements view-level download); the
163
325
  * desktop shell's embedded views delegate downloads to the real browser UI.
326
+ * Admission: only HTTP(S) targets (the in-page fetch cannot meaningfully
327
+ * fetch anything else), and the save path must be absolute — confined to
328
+ * `downloadDir` when one is configured, so a prompt-injected agent cannot
329
+ * write arbitrary machine paths.
164
330
  */
165
331
  download(session: BrowserSessionId, request: {
166
332
  readonly url: string;
@@ -175,15 +341,12 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
175
341
  flushAuth(session: BrowserSessionId): Promise<readonly ExportedCookie[]>;
176
342
  /** Import cookies into the session (restore login state). Self-hosted only. */
177
343
  restoreAuth(session: BrowserSessionId, cookies: readonly ExportedCookie[]): Promise<number>;
178
- /** Capture the current page, optionally full-page. PNG only (CDP JPEG hangs on Electron 43). */
179
- screenshot(session: BrowserSessionId, request?: {
180
- readonly fullPage?: boolean;
181
- readonly savePath?: string;
182
- }, signal?: AbortSignal): Promise<{
344
+ /** Capture the current page, optionally full-page, PNG or JPEG, scalable. */
345
+ screenshot(session: BrowserSessionId, request?: BrowserScreenshotRequest, signal?: AbortSignal): Promise<{
183
346
  readonly dataUrl: string;
184
347
  readonly path?: string;
185
348
  }>;
186
- /** Build the data URL and optionally write the PNG to disk. */
349
+ /** Build the data URL and optionally write the image to disk. */
187
350
  private saveScreenshot;
188
351
  /** Append one operation to the session's history. */
189
352
  private record;
@@ -205,7 +368,18 @@ export declare class ElectronBrowserProvider implements BrowserProvider {
205
368
  private activeTab;
206
369
  /** Append a fresh tab and make it active. */
207
370
  private newTab;
208
- /** Ask the host to show the active tab's view. */
371
+ /** Find a session's tab by its backing view id (toolbar actions carry view ids). */
372
+ private tabByViewId;
373
+ /**
374
+ * Route a user-initiated action from the host's UI into the session model.
375
+ * Fire-and-forget by design: a user action failing (e.g. an unreachable
376
+ * URL typed into the address bar) must never crash the host UI loop — it
377
+ * is reported to the host (toolbar) when the host supports it, else logged.
378
+ */
379
+ private handleUserAction;
380
+ /** Report a failed user action to the host UI (toolbar), when supported. */
381
+ private notifyUserActionError;
382
+ /** Ask the host to show the active tab's view, carrying the session label. */
209
383
  private showActive;
210
384
  /** Read the current URL of a view through CDP. */
211
385
  private currentUrl;