@agentium/browser 4.1.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,487 @@
1
+ import type { CostTracker, EventBus, LogLevel, ModelProvider, ToolDef, UnifiedMemoryConfig } from "@agentium/core";
2
+ import type { CredentialVault } from "./credential-vault.cjs";
3
+ /**
4
+ * The complete set of actions a `BrowserAgent` can take during a run.
5
+ *
6
+ * Click / type / scroll accept EITHER an `index` (preferred — resolved
7
+ * against the DOM tree we showed the model) OR `x`/`y` coordinates as a
8
+ * fallback. Indexed actions are far more reliable on dynamic pages because
9
+ * they survive layout shifts, devicePixelRatio mismatches, and "the
10
+ * sibling 4 pixels away" failure modes.
11
+ */
12
+ export type BrowserAction = {
13
+ action: "click";
14
+ /** Element index from the DOM snapshot. Preferred. */
15
+ index?: number;
16
+ /** Fallback x coordinate (CSS pixels). */
17
+ x?: number;
18
+ /** Fallback y coordinate (CSS pixels). */
19
+ y?: number;
20
+ /** Free-form description; if it contains a quoted label, used as a text-locator fallback. */
21
+ description?: string;
22
+ } | {
23
+ action: "type";
24
+ /** Element index from the DOM snapshot. Preferred. */
25
+ index?: number;
26
+ text: string;
27
+ /** Fallback x coordinate (CSS pixels). */
28
+ x?: number;
29
+ /** Fallback y coordinate (CSS pixels). */
30
+ y?: number;
31
+ /** If true (default), clear the field first. */
32
+ clear?: boolean;
33
+ /** If true (default), press Enter after typing when text ends with `\n`. */
34
+ submit?: boolean;
35
+ } | {
36
+ action: "scroll";
37
+ direction: "up" | "down";
38
+ /** Pixels to scroll. Default: 400. */
39
+ amount?: number;
40
+ /** If provided, scroll the element with this index into view instead. */
41
+ index?: number;
42
+ } | {
43
+ action: "navigate";
44
+ url: string /** Open the URL in a new tab, then switch to it. */;
45
+ newTab?: boolean;
46
+ } | {
47
+ action: "search";
48
+ query: string;
49
+ engine?: SearchEngine;
50
+ } | {
51
+ action: "new_tab";
52
+ url?: string;
53
+ } | {
54
+ action: "switch_tab";
55
+ tabId: string;
56
+ } | {
57
+ action: "close_tab";
58
+ tabId: string;
59
+ } | {
60
+ action: "search_page";
61
+ pattern: string;
62
+ regex?: boolean;
63
+ caseSensitive?: boolean;
64
+ maxResults?: number;
65
+ } | {
66
+ action: "find_elements";
67
+ selector: string;
68
+ maxResults?: number;
69
+ } | {
70
+ action: "back";
71
+ } | {
72
+ action: "wait";
73
+ ms: number;
74
+ } | {
75
+ action: "screenshot";
76
+ } | {
77
+ action: "send_keys";
78
+ keys: string;
79
+ } | {
80
+ action: "find_text";
81
+ text: string;
82
+ } | {
83
+ action: "evaluate";
84
+ code: string;
85
+ } | {
86
+ action: "dropdown_options";
87
+ index: number;
88
+ } | {
89
+ action: "select_dropdown";
90
+ index: number;
91
+ text: string;
92
+ } | {
93
+ action: "upload_file";
94
+ index: number;
95
+ path: string;
96
+ } | {
97
+ action: "extract";
98
+ /** Natural-language description of what to extract. */
99
+ query: string;
100
+ /** Include link hrefs in the extracted content. Default: false. */
101
+ extractLinks?: boolean;
102
+ } | {
103
+ action: "tool";
104
+ /** Name of a custom tool registered on the BrowserAgent. */
105
+ name: string;
106
+ args?: Record<string, unknown>;
107
+ } | {
108
+ action: "done";
109
+ result: string;
110
+ } | {
111
+ action: "fail";
112
+ reason: string;
113
+ };
114
+ /**
115
+ * One entry in the DOM snapshot the model sees. Returned by
116
+ * `BrowserProvider.extractDOM()` alongside the human-readable string form.
117
+ */
118
+ export interface DomElement {
119
+ /** Stable 1-based index for this step. Used by indexed actions. */
120
+ index: number;
121
+ /** Center coordinate in CSS pixels (fallback for the model if needed). */
122
+ cx: number;
123
+ cy: number;
124
+ /** ARIA role or tag name. */
125
+ role: string;
126
+ /** Input type, if applicable. */
127
+ type?: string;
128
+ /** Visible label (text / aria-label / placeholder / href / …). */
129
+ label: string;
130
+ /** Tag name. */
131
+ tag: string;
132
+ /** Whether it's an `<input>` / `<textarea>` / `[contenteditable]`. */
133
+ isInput: boolean;
134
+ /** Whether it's a `<select>`. */
135
+ isSelect: boolean;
136
+ /** Whether it's an `<input type="file">`. */
137
+ isFile: boolean;
138
+ /** Origin frame (`"main"` or the iframe `src`/path). */
139
+ frame?: string;
140
+ }
141
+ /**
142
+ * Scroll-context metadata returned alongside `DomElement[]`. Gives the
143
+ * model spatial awareness so it can decide when to scroll vs when more
144
+ * content is below / above the fold.
145
+ */
146
+ export interface DomScrollContext {
147
+ /** Approximate viewports of scrollable content above the current view. */
148
+ pagesAbove: number;
149
+ /** Approximate viewports of scrollable content below the current view. */
150
+ pagesBelow: number;
151
+ /** Total interactive elements found (visible + hidden combined). */
152
+ totalInteractive: number;
153
+ /** Count of interactive elements that exist on the page but aren't in the viewport. */
154
+ hiddenInteractive: number;
155
+ }
156
+ /** Combined return value of `BrowserProvider.extractDOM()`. */
157
+ export interface DomSnapshot {
158
+ /** Human-readable string fed to the model. */
159
+ text: string;
160
+ /** Structured list (stable indices) for runtime resolution. */
161
+ elements: DomElement[];
162
+ /** Spatial/scroll context. */
163
+ scroll: DomScrollContext;
164
+ }
165
+ export type SearchEngine = "duckduckgo" | "google" | "bing";
166
+ export type BrowserPlanner = "vision" | "jev";
167
+ export interface BrowserAgentConfig {
168
+ name: string;
169
+ /**
170
+ * Vision-capable model (GPT-4o, Gemini, etc.).
171
+ * When `planner` is `"jev"`, this model is only used to invent type/search
172
+ * strings (unless `pageExtractionLLM` is set).
173
+ */
174
+ model: ModelProvider;
175
+ /**
176
+ * Who picks the next action.
177
+ * - `"vision"` (default): the model writes JSON from screenshot + DOM.
178
+ * - `"jev"`: each step is a TypeSafe `choice` over this frame's controls
179
+ * (`click_12`, `back`, `done`, …). Needs `TYPESAFE_API_KEY`.
180
+ */
181
+ planner?: BrowserPlanner;
182
+ /** Jev model id when `planner` is `"jev"`. Default: `jev-latest`. */
183
+ jevModel?: string;
184
+ /**
185
+ * Max DOM elements offered as `click_N` / `type_N` choices (Jev or the
186
+ * observation list). Default: 40.
187
+ */
188
+ maxActionChoices?: number;
189
+ /** Default engine for the `search` action. Default: `duckduckgo`. */
190
+ searchEngine?: SearchEngine;
191
+ /**
192
+ * Optional secondary (usually cheaper) model used for the `extract`
193
+ * action and other text-only sub-tasks. Falls back to `model`.
194
+ */
195
+ pageExtractionLLM?: ModelProvider;
196
+ /**
197
+ * Fallback model used automatically when the primary `model` returns a
198
+ * rate-limit / auth / 5xx error or fails to produce valid JSON several
199
+ * times in a row. Failure-budget aware. Leave unset to disable.
200
+ */
201
+ fallbackModel?: ModelProvider;
202
+ /**
203
+ * Ask the model to emit a structured thinking/evaluation/memory/next_goal
204
+ * envelope around its action(s). Significantly improves accuracy and
205
+ * self-correction on multi-step tasks. Default: `true`. Set `false` for
206
+ * a `flash_mode` that just returns the raw action(s) — useful for very
207
+ * fast / cheap models that are bad at long outputs.
208
+ */
209
+ useThinking?: boolean;
210
+ /**
211
+ * Maximum number of recent step turns kept verbatim in the conversation
212
+ * history sent to the model. Older turns are compacted into a single
213
+ * summary line. Default: 6. Set 0 to disable conversation history
214
+ * entirely (each step rebuilt from scratch — v2.0 behaviour).
215
+ */
216
+ historyWindow?: number;
217
+ /** Extra instructions appended to the default system prompt. */
218
+ instructions?: string;
219
+ /**
220
+ * Append additional instructions to the default system prompt.
221
+ * Alias for `instructions` (browser-use parity). Both are concatenated.
222
+ */
223
+ extendSystemMessage?: string;
224
+ /**
225
+ * Completely replace the default system prompt with this string.
226
+ * The credentials / DOM / coordinate sections are still appended at the
227
+ * end automatically. Most users should use `instructions` instead.
228
+ */
229
+ overrideSystemMessage?: string;
230
+ /** Max vision loop iterations. Default: 30 */
231
+ maxSteps?: number;
232
+ /**
233
+ * Maximum number of consecutive step failures (action threw, invalid
234
+ * JSON from model, locator timeout) before the agent gives up. Default: 3.
235
+ */
236
+ maxFailures?: number;
237
+ /**
238
+ * Maximum number of actions the model can return in a single step.
239
+ * If the model returns an array, we execute them in order until the page
240
+ * navigates or the DOM changes substantially. Default: 3.
241
+ * Set to 1 to force one-action-per-step (the v2.0.x behaviour).
242
+ */
243
+ maxActionsPerStep?: number;
244
+ /**
245
+ * Actions to run before the LLM loop starts. Useful for boilerplate
246
+ * (cookie-banner click, login flow, scrolling) you already know the
247
+ * answer to — saves vision tokens.
248
+ */
249
+ initialActions?: BrowserAction[];
250
+ /**
251
+ * Vision mode. Default: `"auto"`.
252
+ * - `true`: always send a screenshot with every step (v2.0.x behaviour).
253
+ * - `false`: never send screenshots; DOM-only operation.
254
+ * - `"auto"`: send a screenshot on the first step and whenever the model
255
+ * used the `screenshot` action in the previous step. Saves vision
256
+ * tokens dramatically on DOM-only-suitable workloads.
257
+ */
258
+ useVision?: boolean | "auto";
259
+ /**
260
+ * If true (default), detect a URL in the task string and navigate to it
261
+ * before the first LLM call — saves one round trip on simple tasks.
262
+ */
263
+ directlyOpenUrl?: boolean;
264
+ /** Run browser without visible window. Default: true */
265
+ headless?: boolean;
266
+ /** Browser viewport size. Default: 1280x720 */
267
+ viewport?: {
268
+ width: number;
269
+ height: number;
270
+ };
271
+ /** Initial URL to navigate to before starting the task */
272
+ startUrl?: string;
273
+ /** Milliseconds to wait after each action for the page to settle. Default: 1500 */
274
+ waitAfterAction?: number;
275
+ /** Max consecutive identical actions before the agent auto-fails. Default: 3 */
276
+ maxRepeats?: number;
277
+ /**
278
+ * Include a simplified DOM/accessibility tree (each interactive element
279
+ * tagged with its exact center coordinates) alongside the screenshot.
280
+ * Dramatically improves click accuracy — strongly recommended.
281
+ * Default: true
282
+ */
283
+ useDOM?: boolean;
284
+ /**
285
+ * Allow the `evaluate` action to run arbitrary JavaScript inside the
286
+ * page. Default: false (security). Only enable if you trust the source
287
+ * of task strings — a malicious task could exfiltrate page contents.
288
+ */
289
+ allowEvaluate?: boolean;
290
+ /**
291
+ * Restrict navigation to specific domains. Wildcard patterns supported:
292
+ * `"example.com"`, `"*.example.com"`, `"http*://example.com"`.
293
+ * When set, any `navigate` action to a non-matching URL throws.
294
+ */
295
+ allowedDomains?: string[];
296
+ /**
297
+ * Block navigation to specific domains. Same pattern format as
298
+ * `allowedDomains`. Evaluated AFTER `allowedDomains`, so if both are
299
+ * set a URL must be in `allowedDomains` AND not in `prohibitedDomains`.
300
+ */
301
+ prohibitedDomains?: string[];
302
+ /**
303
+ * Path to a Playwright storageState JSON file.
304
+ * Restores cookies, localStorage, and sessionStorage from a previous session.
305
+ */
306
+ storageState?: string;
307
+ /**
308
+ * Connect to an existing browser via Chrome DevTools Protocol instead
309
+ * of launching one. Format: `"http://localhost:9222"`. When set,
310
+ * `headless`, `stealth.args`, `recordVideo`, etc. are ignored — the
311
+ * existing browser's configuration is used.
312
+ */
313
+ cdpUrl?: string;
314
+ /**
315
+ * Enable video recording of the browser session.
316
+ * Pass `true` for default dir (`./browser-videos`) or `{ dir: "/path" }`.
317
+ */
318
+ recordVideo?: boolean | {
319
+ dir: string;
320
+ };
321
+ /**
322
+ * Secure credential vault. The LLM never sees real values — only
323
+ * placeholders like `{{email}}`, `{{password}}`. Real values are
324
+ * injected at execution time and scrubbed from all logs.
325
+ */
326
+ credentials?: CredentialVault;
327
+ /**
328
+ * Enable stealth mode to avoid bot detection.
329
+ * Pass `true` for sensible defaults or a `StealthConfig` object for fine control.
330
+ * Patches navigator.webdriver, plugins, permissions, WebGL, and more.
331
+ */
332
+ stealth?: boolean | StealthConfig;
333
+ /**
334
+ * Simulate human-like behavior — jittered clicks, variable typing speed,
335
+ * mouse movement curves, random micro-pauses.
336
+ * Pass `true` for defaults or a `HumanizeConfig` for fine control.
337
+ */
338
+ humanize?: boolean | HumanizeConfig;
339
+ /**
340
+ * Unified memory config — persist browser sessions, decisions, and
341
+ * summaries of past runs. Same config as Agent and VoiceAgent.
342
+ */
343
+ memory?: UnifiedMemoryConfig;
344
+ /** Skills — pre-packaged or learned tool bundles. */
345
+ skills?: Array<import("@agentium/core").Skill | string>;
346
+ /**
347
+ * Custom tools that the BrowserAgent itself can invoke during a run.
348
+ * The agent emits `{ "action": "tool", "name": "<tool>", "args": {...} }`
349
+ * and we dispatch to the tool's `execute(args)`. Use this for 2FA codes,
350
+ * API calls, file I/O, calling out to other agents — anything the
351
+ * browser can't do alone.
352
+ */
353
+ tools?: ToolDef[];
354
+ /** Applies to custom tools. Native browser operations are unavailable in plan mode. */
355
+ executionPolicy?: import("@agentium/core").ExecutionPolicy;
356
+ approval?: import("@agentium/core").ApprovalConfig;
357
+ approvalManager?: import("@agentium/core").ApprovalManager;
358
+ /** Cost tracker — track vision model token usage and enforce budgets across browser runs. */
359
+ costTracker?: CostTracker;
360
+ logLevel?: LogLevel;
361
+ eventBus?: EventBus;
362
+ }
363
+ export interface BrowserRunOpts {
364
+ /** Inherit the calling Agent's identity, policy and cancellation. */
365
+ context?: import("@agentium/core").RunContext;
366
+ signal?: AbortSignal;
367
+ tenantId?: string;
368
+ runMode?: import("@agentium/core").RunMode;
369
+ /** Override startUrl from config */
370
+ startUrl?: string;
371
+ /** Per-run model API key override */
372
+ apiKey?: string;
373
+ /** Session identifier for memory persistence and event tracking */
374
+ sessionId?: string;
375
+ /** User identifier for memory personalization */
376
+ userId?: string;
377
+ /** Path to save storageState (cookies/auth) after the run completes */
378
+ saveStorageState?: string;
379
+ /** Per-run override of `maxSteps`. */
380
+ maxSteps?: number;
381
+ }
382
+ export interface BrowserRunOutput {
383
+ /** Final text result produced by the agent */
384
+ result: string;
385
+ /** Whether the task completed successfully (vs maxSteps exhausted or fail) */
386
+ success: boolean;
387
+ /** Full action history with screenshots */
388
+ steps: BrowserStep[];
389
+ /** URL at completion */
390
+ finalUrl: string;
391
+ /** Last screenshot captured */
392
+ finalScreenshot: Buffer;
393
+ /** Total time taken in milliseconds */
394
+ durationMs: number;
395
+ /** Video file path (if recordVideo was enabled) */
396
+ videoPath?: string;
397
+ /** Extracted content from every `extract` action, in chronological order. */
398
+ extractedContent?: string[];
399
+ }
400
+ export interface BrowserStep {
401
+ index: number;
402
+ action: BrowserAction;
403
+ /** Screenshot taken before this action was executed. May be empty if useVision=false. */
404
+ screenshot: Buffer;
405
+ pageUrl: string;
406
+ pageTitle: string;
407
+ timestamp: Date;
408
+ /** Simplified DOM snapshot (if useDOM is enabled) */
409
+ dom?: string;
410
+ /** Free-form result string produced by the action (e.g. extract output). */
411
+ output?: string;
412
+ /** Whether this step succeeded (vs threw / failed locator). Default: true. */
413
+ ok?: boolean;
414
+ /** Model's chain-of-thought reasoning (if `useThinking` was on). */
415
+ thinking?: string;
416
+ /** Model's evaluation of whether the previous action met its goal. */
417
+ evaluationPreviousGoal?: string;
418
+ /** Model's running memory of important state. */
419
+ memory?: string;
420
+ /** Model's stated next goal for this step. */
421
+ nextGoal?: string;
422
+ }
423
+ /**
424
+ * Structured envelope the model returns when `useThinking: true`. Inspired
425
+ * by browser-use's `AgentOutput`. Every field is optional from a runtime
426
+ * standpoint — only `action` is required for execution.
427
+ */
428
+ export interface AgentOutput {
429
+ thinking?: string;
430
+ evaluationPreviousGoal?: string;
431
+ memory?: string;
432
+ nextGoal?: string;
433
+ action: BrowserAction | BrowserAction[];
434
+ }
435
+ export interface StealthConfig {
436
+ /**
437
+ * Remove `navigator.webdriver` flag and patch common detection vectors
438
+ * (plugins, languages, permissions, WebGL, etc.). Default when stealth=true.
439
+ */
440
+ patchFingerprint?: boolean;
441
+ /** Custom User-Agent string. A realistic one is used by default. */
442
+ userAgent?: string;
443
+ /** Browser locale. Default: "en-US" */
444
+ locale?: string;
445
+ /** Timezone ID (IANA). Default: "America/New_York" */
446
+ timezone?: string;
447
+ /** Fake geolocation */
448
+ geolocation?: {
449
+ latitude: number;
450
+ longitude: number;
451
+ accuracy?: number;
452
+ };
453
+ /** Ignore HTTPS certificate errors. Default: false (secure). Only enable for local testing. */
454
+ ignoreHTTPSErrors?: boolean;
455
+ /**
456
+ * `window.devicePixelRatio` to emulate. Default: `1`. Set to `2` to mimic
457
+ * a Retina display (sharper screenshots at 2× cost). Setting to 2 on a
458
+ * non-Retina host display can cause the headed window to look zoomed-out
459
+ * or stretched because the OS compositor downsamples a 2× surface.
460
+ */
461
+ deviceScaleFactor?: number;
462
+ /** HTTP/SOCKS proxy. Format: "http://user:pass@host:port" */
463
+ proxy?: {
464
+ server: string;
465
+ username?: string;
466
+ password?: string;
467
+ };
468
+ }
469
+ export interface HumanizeConfig {
470
+ /** Per-character typing delay range in ms. Default: [40, 120] */
471
+ typingDelay?: [number, number];
472
+ /** Random pixel offset added to click coordinates. Default: 3 */
473
+ clickJitter?: number;
474
+ /** Extra random pause between actions in ms range. Default: [200, 800] */
475
+ actionDelay?: [number, number];
476
+ /** Simulate human-like mouse movement to target before clicking. Default: true */
477
+ mouseMovement?: boolean;
478
+ }
479
+ export interface PageInfo {
480
+ url: string;
481
+ title: string;
482
+ viewportSize: {
483
+ width: number;
484
+ height: number;
485
+ };
486
+ }
487
+ //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentium/browser",
3
- "version": "4.1.0",
3
+ "version": "4.5.0",
4
4
  "description": "Browser automation agent for Agentium using Playwright",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
@@ -25,9 +25,14 @@
25
25
  "types": "./dist/index.d.ts",
26
26
  "exports": {
27
27
  ".": {
28
- "types": "./dist/index.d.ts",
29
- "import": "./dist/index.js",
30
- "require": "./dist/index.cjs",
28
+ "import": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "require": {
33
+ "types": "./dist/index.d.cts",
34
+ "default": "./dist/index.cjs"
35
+ },
31
36
  "default": "./dist/index.js"
32
37
  }
33
38
  },
@@ -35,7 +40,7 @@
35
40
  "dist"
36
41
  ],
37
42
  "scripts": {
38
- "build": "tsdown --config ../../tsdown.config.ts && tsc -p tsconfig.build.json --emitDeclarationOnly --declaration --pretty false",
43
+ "build": "tsdown --config ../../tsdown.config.ts && tsc -p tsconfig.build.json --emitDeclarationOnly --declaration --pretty false && node ../../scripts/cjs-declarations.mjs",
39
44
  "dev": "tsdown --config ../../tsdown.config.ts --watch",
40
45
  "prepublishOnly": "npm run build"
41
46
  },
@@ -49,7 +54,7 @@
49
54
  "tsdown": "0.23.0"
50
55
  },
51
56
  "peerDependencies": {
52
- "@agentium/core": "^4.1.0",
57
+ "@agentium/core": "^4.5.0",
53
58
  "playwright": ">=1.40.0"
54
59
  },
55
60
  "peerDependenciesMeta": {