@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,42 @@
1
+ import type { BrowserAction, DomElement, SearchEngine } from "./types.cjs";
2
+ export declare const DEFAULT_MAX_ACTION_CHOICES = 40;
3
+ export interface TabInfo {
4
+ id: string;
5
+ url: string;
6
+ active: boolean;
7
+ }
8
+ export interface ActionSpace {
9
+ /** Jev / TypeSafe choice criteria: label → description. */
10
+ criteria: Record<string, string>;
11
+ toAction(label: string): BrowserAction | undefined;
12
+ }
13
+ export declare function searchUrl(query: string, engine?: SearchEngine): string;
14
+ export declare function isSearchResultsUrl(url: string): boolean;
15
+ /** Bot-block / challenge pages (DDG 418, Google sorry, Cloudflare, …). */
16
+ export declare function isBlockedPageUrl(url: string): boolean;
17
+ export declare function isBotChallengeText(text: string): boolean;
18
+ export declare function isResultTitle(label: string): boolean;
19
+ export declare function looksLikeResultList(text: string): boolean;
20
+ /** Longest non-chrome link labels — search result titles, not "email us". */
21
+ export declare function titlesFromElements(elements: DomElement[], max?: number): string;
22
+ export declare const SERP_TITLE_SELECTORS: string[];
23
+ export declare function guessSearchQuery(task: string): string;
24
+ /**
25
+ * Closed action list for this frame: chrome (back, scroll, done, …) plus
26
+ * `click_N` / `type_N` from the DOM snapshot. Used by the Jev planner and
27
+ * as documentation of what `executeAction` can run without free-form JSON.
28
+ */
29
+ export declare function buildActionSpace(elements: DomElement[], tabs?: TabInfo[], opts?: {
30
+ max?: number;
31
+ pagesBelow?: number;
32
+ pagesAbove?: number;
33
+ allowSearch?: boolean;
34
+ allowDone?: boolean;
35
+ allowWait?: boolean;
36
+ }): ActionSpace;
37
+ export declare function labelToAction(label: string, extras?: {
38
+ typeText?: string;
39
+ searchQuery?: string;
40
+ doneResult?: string;
41
+ }): BrowserAction | undefined;
42
+ //# sourceMappingURL=action-space.d.ts.map
@@ -0,0 +1,134 @@
1
+ import type { ToolDef } from "@agentium/core";
2
+ import { ApprovalManager, EventBus, MemoryManager } from "@agentium/core";
3
+ import type { BrowserAgentConfig, BrowserRunOpts, BrowserRunOutput } from "./types.cjs";
4
+ export declare class BrowserAgent {
5
+ readonly name: string;
6
+ readonly eventBus: EventBus;
7
+ private model;
8
+ private pageExtractionLLM;
9
+ private fallbackModel;
10
+ private useThinking;
11
+ private historyWindow;
12
+ private instructions?;
13
+ private extendSystemMessage?;
14
+ private overrideSystemMessage?;
15
+ private maxSteps;
16
+ private maxFailures;
17
+ private maxActionsPerStep;
18
+ private initialActions;
19
+ private useVision;
20
+ private directlyOpenUrl;
21
+ private headless;
22
+ private viewport;
23
+ private defaultStartUrl?;
24
+ private waitAfterAction;
25
+ private maxRepeats;
26
+ private useDOM;
27
+ private allowEvaluate;
28
+ private allowedDomains?;
29
+ private prohibitedDomains?;
30
+ private storageState?;
31
+ private cdpUrl?;
32
+ private recordVideo?;
33
+ private credentials?;
34
+ private stealth?;
35
+ private humanize?;
36
+ private tools;
37
+ readonly approvalManager: ApprovalManager | null;
38
+ private executionPolicy?;
39
+ private planner;
40
+ private jevModel;
41
+ private maxActionChoices;
42
+ private searchEngine;
43
+ private jevProvider;
44
+ private costTracker;
45
+ private memoryManager;
46
+ private logger;
47
+ /** Access the MemoryManager (if memory is configured). */
48
+ get memory(): MemoryManager | null;
49
+ constructor(config: BrowserAgentConfig);
50
+ run(task: string, opts?: BrowserRunOpts): Promise<BrowserRunOutput>;
51
+ private runAccounted;
52
+ /**
53
+ * Returns a ToolDef that lets a regular Agent delegate browser tasks
54
+ * to this BrowserAgent.
55
+ */
56
+ asTool(config?: {
57
+ name?: string;
58
+ description?: string;
59
+ }): ToolDef;
60
+ private shouldCaptureVision;
61
+ private detectUrlInTask;
62
+ private assertDomainAllowed;
63
+ /**
64
+ * Build the message array sent to the model: system prompt + a compact
65
+ * summary of older turns (if any) + the most recent `historyWindow`
66
+ * turns verbatim + the current step's user message.
67
+ *
68
+ * Inspired by browser-use's history compaction. Keeps tokens bounded
69
+ * while giving the model meaningful context about what it already
70
+ * tried.
71
+ */
72
+ private buildMessages;
73
+ /**
74
+ * Call the primary model, retrying once with `fallbackModel` on
75
+ * transient errors (5xx, 429, network). Returns the response or
76
+ * `null` if both models failed.
77
+ */
78
+ private callModelWithFallback;
79
+ private isTransientError;
80
+ private getJev;
81
+ /**
82
+ * Ask Jev to pick one label from this frame's action space, then map it
83
+ * to a BrowserAction. Type/search strings come from a text model or the task.
84
+ */
85
+ private planWithJev;
86
+ private pageLooksBlocked;
87
+ private scrapeSerpTitles;
88
+ private inferTypeText;
89
+ /**
90
+ * Parse the model's raw response into an `AgentOutput`. Tolerant to
91
+ * three shapes:
92
+ * - Full envelope: { thinking, evaluation_previous_goal, action, ... }
93
+ * - Raw action object (legacy / `useThinking: false`)
94
+ * - Raw action array
95
+ *
96
+ * Also strips ```json fences the model occasionally adds.
97
+ */
98
+ private parseEnvelope;
99
+ /**
100
+ * Quick post-navigation health check. If the page came back blank
101
+ * (no body text and no interactive elements), reload once and wait
102
+ * for stable. This catches the "FreightOS half-loaded font test" class
103
+ * of failure before the LLM ever sees it.
104
+ */
105
+ private navigationHealthCheck;
106
+ /**
107
+ * Force-finalize the run with whatever partial data the agent has.
108
+ * Called when:
109
+ * - `maxSteps` is exhausted without an explicit `done`,
110
+ * - `maxFailures` is exceeded,
111
+ * - the model can't produce parseable JSON enough times to make
112
+ * forward progress.
113
+ * The result is composed from `extractedContent` + the last few
114
+ * action summaries so the caller gets something useful instead of
115
+ * just a one-line error.
116
+ */
117
+ private forceDone;
118
+ private finalize;
119
+ /**
120
+ * Execute a single action. Returns `{ output?, didNavigate? }` for the
121
+ * caller's state tracking. May throw — the loop handles failure-budget
122
+ * accounting in that case.
123
+ */
124
+ private executeAction;
125
+ private sleep;
126
+ /**
127
+ * Parse a quoted target keyword from a click action's `description`.
128
+ * Returns `undefined` for generic / ambiguous labels (login buttons,
129
+ * close, OK, etc.) where a substring text match could fire on the
130
+ * wrong element.
131
+ */
132
+ private extractClickKeyword;
133
+ }
134
+ //# sourceMappingURL=browser-agent.d.ts.map
@@ -48,6 +48,7 @@ export declare class BrowserAgent {
48
48
  get memory(): MemoryManager | null;
49
49
  constructor(config: BrowserAgentConfig);
50
50
  run(task: string, opts?: BrowserRunOpts): Promise<BrowserRunOutput>;
51
+ private runAccounted;
51
52
  /**
52
53
  * Returns a ToolDef that lets a regular Agent delegate browser tasks
53
54
  * to this BrowserAgent.
@@ -1 +1 @@
1
- {"version":3,"file":"browser-agent.d.ts","sourceRoot":"","sources":["../src/browser-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAuD,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACnG,OAAO,EACL,eAAe,EAEf,QAAQ,EAGR,aAAa,EAGd,MAAM,gBAAgB,CAAC;AAoBxB,OAAO,KAAK,EAGV,kBAAkB,EAElB,cAAc,EACd,gBAAgB,EAKjB,MAAM,YAAY,CAAC;AAEpB,qBAAa,YAAY;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAE5B,OAAO,CAAC,KAAK,CAAgB;IAC7B,OAAO,CAAC,iBAAiB,CAAuB;IAChD,OAAO,CAAC,aAAa,CAAuB;IAC5C,OAAO,CAAC,WAAW,CAAU;IAC7B,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,mBAAmB,CAAC,CAAS;IACrC,OAAO,CAAC,qBAAqB,CAAC,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,cAAc,CAAkB;IACxC,OAAO,CAAC,SAAS,CAAmB;IACpC,OAAO,CAAC,eAAe,CAAU;IACjC,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,QAAQ,CAAoC;I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,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO;IAsBjE,OAAO,CAAC,mBAAmB;IAa3B,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,mBAAmB;IAgB3B;;;;;;;;OAQG;IACH,OAAO,CAAC,aAAa;IA2CrB;;;;OAIG;YACW,qBAAqB;IAkCnC,OAAO,CAAC,gBAAgB;IAUxB,OAAO,CAAC,MAAM;IAKd;;;OAGG;YACW,WAAW;YA0FX,gBAAgB;YAUhB,gBAAgB;YAqBhB,aAAa;IAwB3B;;;;;;;;OAQG;IACH,OAAO,CAAC,aAAa;IAoCrB;;;;;OAKG;YACW,qBAAqB;IAiBnC;;;;;;;;;;OAUG;YACW,SAAS;YAwBT,QAAQ;IA6EtB;;;;OAIG;YACW,aAAa;IAwO3B,OAAO,CAAC,KAAK;IAIb;;;;;OAKG;IACH,OAAO,CAAC,mBAAmB;CAmC5B"}
@@ -0,0 +1,242 @@
1
+ import type { DomElement, DomSnapshot, HumanizeConfig, PageInfo, StealthConfig } from "./types.cjs";
2
+ /**
3
+ * Playwright wrapper with stealth anti-detection, human-like behavior,
4
+ * indexed DOM element resolution, and a rich action vocabulary.
5
+ *
6
+ * The `BrowserProvider` is intentionally LLM-agnostic — it exposes the
7
+ * primitives that `BrowserAgent` orchestrates via vision+DOM reasoning.
8
+ */
9
+ export declare class BrowserProvider {
10
+ private browser;
11
+ private context;
12
+ private page;
13
+ private pages;
14
+ private activeTabId;
15
+ private tabCounter;
16
+ private _viewport;
17
+ private _videoDir?;
18
+ private _humanize?;
19
+ /**
20
+ * Most recent DOM snapshot (one per `extractDOM` call). Indexed actions
21
+ * (`clickByIndex`, `inputByIndex`, …) resolve their `index` against this.
22
+ */
23
+ private _lastDom;
24
+ /** True if we connected over CDP (don't tear down the browser on close). */
25
+ private _attached;
26
+ constructor();
27
+ launch(opts?: {
28
+ headless?: boolean;
29
+ viewport?: {
30
+ width: number;
31
+ height: number;
32
+ };
33
+ storageState?: string;
34
+ recordVideo?: boolean | {
35
+ dir: string;
36
+ };
37
+ stealth?: boolean | StealthConfig;
38
+ humanize?: boolean | HumanizeConfig;
39
+ cdpUrl?: string;
40
+ }): Promise<void>;
41
+ saveStorageState(path: string): Promise<void>;
42
+ navigate(url: string): Promise<void>;
43
+ back(): Promise<void>;
44
+ screenshot(): Promise<Buffer>;
45
+ /** Viewport size in CSS pixels (matches screenshot dimensions). */
46
+ get viewport(): {
47
+ width: number;
48
+ height: number;
49
+ };
50
+ /** Most recent DOM snapshot. Each entry has a stable `index`. */
51
+ get lastDom(): DomElement[];
52
+ click(x: number, y: number): Promise<void>;
53
+ type(text: string): Promise<void>;
54
+ clickAndType(x: number, y: number, text: string): Promise<void>;
55
+ pressKey(key: string): Promise<void>;
56
+ /**
57
+ * Send arbitrary keyboard keys / shortcuts. Accepts a single
58
+ * Playwright key spec (`"Enter"`, `"Control+l"`, `"Shift+ArrowDown"`)
59
+ * or a space-separated sequence (`"Tab Tab Enter"`).
60
+ */
61
+ sendKeys(keys: string): Promise<void>;
62
+ scroll(direction: "up" | "down", amount?: number): Promise<void>;
63
+ /**
64
+ * Build a Playwright locator for a DOM-snapshot index. Each `extractDOM`
65
+ * call tags surviving elements with `data-bua-idx="<n>"`; we resolve by
66
+ * that attribute. Returns null if the index is unknown.
67
+ */
68
+ private locatorForIndex;
69
+ /**
70
+ * Click an element by its DOM-snapshot index. The most reliable click
71
+ * path on dynamic pages — survives layout shifts and DPR oddities.
72
+ */
73
+ clickByIndex(index: number, opts?: {
74
+ timeout?: number;
75
+ }): Promise<boolean>;
76
+ /**
77
+ * Focus an indexed input, optionally clear it, and type. Returns false
78
+ * if the index couldn't be resolved or the input couldn't be focused.
79
+ */
80
+ inputByIndex(index: number, text: string, opts?: {
81
+ clear?: boolean;
82
+ submit?: boolean;
83
+ timeout?: number;
84
+ }): Promise<boolean>;
85
+ uploadFileByIndex(index: number, path: string): Promise<boolean>;
86
+ /** Scroll the indexed element into view (no click). */
87
+ scrollIntoViewByIndex(index: number): Promise<boolean>;
88
+ /**
89
+ * Deterministic, DOM-based click using Playwright's text locator.
90
+ *
91
+ * Returns `true` if a matching, visible, clickable element was found and
92
+ * clicked within `timeout` ms; `false` otherwise (so the caller can fall
93
+ * back to coordinate clicking). Substring-matches by default — e.g.
94
+ * `clickByText("Cheapest")` matches "Cheapest · 23-28 days · $2,550".
95
+ */
96
+ clickByText(keyword: string, opts?: {
97
+ timeout?: number;
98
+ }): Promise<boolean>;
99
+ /**
100
+ * Scroll the first occurrence of `text` into view. Returns false if no
101
+ * match was found within the timeout.
102
+ */
103
+ findText(text: string, opts?: {
104
+ timeout?: number;
105
+ }): Promise<boolean>;
106
+ /**
107
+ * Read the options of a native `<select>` at the given DOM-snapshot
108
+ * index. Returns `[]` if the element is not a `<select>`.
109
+ */
110
+ dropdownOptions(index: number): Promise<{
111
+ value: string;
112
+ label: string;
113
+ selected: boolean;
114
+ }[]>;
115
+ /**
116
+ * Select an option in a native `<select>` by its visible text or value.
117
+ * Returns false if the element isn't a `<select>` or no option matched.
118
+ */
119
+ selectDropdown(index: number, text: string): Promise<boolean>;
120
+ /**
121
+ * Run arbitrary JS in the page context. The caller is responsible for
122
+ * gating this behind a config flag — the BrowserAgent only routes the
123
+ * `evaluate` action here when `allowEvaluate: true`.
124
+ *
125
+ * The code is wrapped in `(async () => { ... })()` and the return value
126
+ * is coerced to a string for the model.
127
+ */
128
+ evaluate(code: string): Promise<string>;
129
+ /**
130
+ * Returns a clean text representation of the visible page body, with
131
+ * optional link extraction. Used by the BrowserAgent's `extract` action
132
+ * — the text is passed to a (usually cheap) LLM with the user's query.
133
+ */
134
+ pageText(opts?: {
135
+ extractLinks?: boolean;
136
+ maxChars?: number;
137
+ }): Promise<string>;
138
+ /**
139
+ * Snapshot the interactive elements visible in the viewport, tag each
140
+ * with a `data-bua-idx="<n>"` attribute (used by indexed actions), and
141
+ * return:
142
+ * - `text`: a human-readable string fed to the model
143
+ * - `elements`: the structured list with stable indices
144
+ * - `scroll`: spatial context (pages above/below, hidden interactive count)
145
+ *
146
+ * Five properties matter for accuracy:
147
+ * - **Hit-tested**: each listed coordinate / index actually reaches the
148
+ * labeled element (overlays / occlusion skip the entry).
149
+ * - **Visibility filtered (with parent chain)**: an element is dropped
150
+ * if itself OR any ancestor is `display:none`, `visibility:hidden`,
151
+ * `pointer-events:none`, or near-zero opacity.
152
+ * - **Shadow DOM piercing**: traverses open shadow roots so custom
153
+ * elements / web components are visible to the agent.
154
+ * - **Same-origin iframes**: walks into each accessible iframe and
155
+ * includes its interactive elements (offset by the iframe's screen
156
+ * position so the coordinates the model sees are still viewport-
157
+ * relative).
158
+ * - **`cursor: pointer` fallback pass**: catches custom React widgets
159
+ * that have no semantic role/href/onclick but are clickable.
160
+ */
161
+ extractDOM(opts?: {
162
+ maxElements?: number;
163
+ }): Promise<DomSnapshot>;
164
+ /**
165
+ * Install the `__buaExtract` global on the main page. Idempotent —
166
+ * subsequent calls are no-ops.
167
+ */
168
+ private installExtractorScript;
169
+ /**
170
+ * The extractor source. Lives in its own method so we can also inject
171
+ * it into iframes that haven't yet had it loaded.
172
+ *
173
+ * This function intentionally runs entirely in the page context. It:
174
+ * - traverses the regular DOM + open shadow roots (deep)
175
+ * - applies a parent-chain visibility filter
176
+ * - applies a `cursor:pointer` second pass for custom widgets
177
+ * - hit-tests each candidate at its center to avoid overlay collisions
178
+ * - returns scroll context (pages above/below, hidden counts)
179
+ * - tags survivors with `data-bua-idx` for indexed actions
180
+ */
181
+ private extractorScriptSource;
182
+ getPageInfo(): Promise<PageInfo>;
183
+ waitForStable(minWait?: number): Promise<void>;
184
+ newTab(url?: string): Promise<string>;
185
+ switchTab(tabId: string): Promise<void>;
186
+ closeTab(tabId: string): Promise<void>;
187
+ visibleText(maxChars?: number): Promise<string>;
188
+ /**
189
+ * Grep visible page text. No LLM. Used by `search_page`.
190
+ */
191
+ searchPage(opts: {
192
+ pattern: string;
193
+ regex?: boolean;
194
+ caseSensitive?: boolean;
195
+ maxResults?: number;
196
+ contextChars?: number;
197
+ }): Promise<Array<{
198
+ match: string;
199
+ context: string;
200
+ index: number;
201
+ }>>;
202
+ /**
203
+ * querySelectorAll over the page. No LLM. Used by `find_elements`.
204
+ */
205
+ findElements(selector: string, opts?: {
206
+ maxResults?: number;
207
+ }): Promise<Array<{
208
+ tag: string;
209
+ text: string;
210
+ href?: string;
211
+ }>>;
212
+ listTabs(): {
213
+ id: string;
214
+ url: string;
215
+ active: boolean;
216
+ }[];
217
+ get currentTabId(): string;
218
+ getVideoPath(tabId?: string): Promise<string | null>;
219
+ get videoDir(): string | undefined;
220
+ close(): Promise<void>;
221
+ /** Add small random offset to coordinates to avoid pixel-perfect bot patterns. */
222
+ private jitter;
223
+ /**
224
+ * Safety net: clamp coordinates returned by the vision model to the actual
225
+ * viewport. If a model occasionally returns image-space coordinates from a
226
+ * 2x screenshot (despite our `scale: "css"` fix), this prevents Playwright
227
+ * from clicking at e.g. (2200, 1300) and either erroring or landing on a
228
+ * random off-screen element.
229
+ */
230
+ private clampToViewport;
231
+ /**
232
+ * Simulate human mouse movement using smoothstep interpolation.
233
+ */
234
+ private humanMouseMove;
235
+ /** Small random pause after an interaction. */
236
+ private humanPause;
237
+ private randInt;
238
+ private ensurePage;
239
+ private ensureContext;
240
+ private sleep;
241
+ }
242
+ //# sourceMappingURL=browser-provider.d.ts.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Secure credential store for BrowserAgent.
3
+ *
4
+ * Secrets are stored in memory and NEVER sent to the LLM.
5
+ * The model works with placeholders (e.g. `{{email}}`, `{{password}}`),
6
+ * and the agent resolves them to real values only at execution time.
7
+ */
8
+ export declare class CredentialVault {
9
+ private secrets;
10
+ constructor(initial?: Record<string, string>);
11
+ /** Store a credential. Key names become the placeholder: `{{key}}`. */
12
+ set(key: string, value: string): this;
13
+ /** Retrieve a credential value. Returns undefined if not found. */
14
+ get(key: string): string | undefined;
15
+ has(key: string): boolean;
16
+ /** List available placeholder names (never exposes values). */
17
+ keys(): string[];
18
+ /**
19
+ * Load credentials from environment variables.
20
+ * Maps env var names to placeholder keys.
21
+ *
22
+ * @example
23
+ * vault.fromEnv({ email: "LOGIN_EMAIL", password: "LOGIN_PASS" });
24
+ */
25
+ fromEnv(mapping: Record<string, string>): this;
26
+ /**
27
+ * Replace `{{key}}` placeholders in text with actual credential values.
28
+ * Used internally by BrowserAgent right before executing a type action.
29
+ */
30
+ resolve(text: string): string;
31
+ /**
32
+ * Replace any occurrence of real credential values in text with
33
+ * their `{{key}}` placeholder. Used to sanitize logs and action history.
34
+ */
35
+ mask(text: string): string;
36
+ }
37
+ //# sourceMappingURL=credential-vault.d.ts.map
package/dist/index.cjs CHANGED
@@ -1622,6 +1622,35 @@ var BrowserAgent = class {
1622
1622
  if (config.memory) this.memoryManager = new _agentium_core.MemoryManager(config.memory);
1623
1623
  }
1624
1624
  async run(task, opts) {
1625
+ const parent = (0, _agentium_core.getAccountingContext)();
1626
+ const tracker = this.costTracker ?? parent?.tracker;
1627
+ if (!tracker) return this.runAccounted(task, opts);
1628
+ const ctx = opts?.context ?? new _agentium_core.RunContext({
1629
+ sessionId: opts?.sessionId ?? `browser_${Date.now()}`,
1630
+ userId: opts?.userId,
1631
+ tenantId: opts?.tenantId,
1632
+ signal: opts?.signal,
1633
+ runMode: opts?.runMode,
1634
+ executionPolicy: this.executionPolicy,
1635
+ eventBus: this.eventBus
1636
+ });
1637
+ return (0, _agentium_core.withAccountingContext)({
1638
+ ...parent,
1639
+ tracker,
1640
+ runId: ctx.runId,
1641
+ rootRunId: parent?.rootRunId ?? parent?.runId ?? ctx.runId,
1642
+ parentRunId: parent?.runId,
1643
+ sessionId: ctx.sessionId,
1644
+ tenantId: ctx.tenantId,
1645
+ userId: ctx.userId,
1646
+ agentName: this.name,
1647
+ eventBus: this.eventBus
1648
+ }, () => this.runAccounted(task, {
1649
+ ...opts,
1650
+ context: ctx
1651
+ }));
1652
+ }
1653
+ async runAccounted(task, opts) {
1625
1654
  const startTime = Date.now();
1626
1655
  const maxSteps = opts?.maxSteps ?? this.maxSteps;
1627
1656
  const sessionId = opts?.context?.sessionId ?? opts?.sessionId ?? `browser_${startTime}`;
@@ -1752,49 +1781,28 @@ var BrowserAgent = class {
1752
1781
  vision: wantVision
1753
1782
  });
1754
1783
  let envelope = null;
1755
- let modelUsed = this.model;
1756
- if (this.planner === "jev") {
1757
- const planned = await this.planWithJev({
1758
- task,
1759
- url: pageInfo.url,
1760
- title: pageInfo.title,
1761
- elements,
1762
- tabs,
1763
- actionHistory,
1764
- lastExtract: lastExtractResult,
1765
- pagesBelow: scrollCtx?.pagesBelow,
1766
- pagesAbove: scrollCtx?.pagesAbove,
1767
- apiKey: opts?.apiKey,
1768
- signal: ctx.signal
1769
- });
1770
- envelope = planned.envelope;
1771
- modelUsed = planned.modelUsed;
1772
- if (this.costTracker && planned.usage) this.costTracker.track({
1773
- runId: sessionId,
1774
- agentName: this.name,
1775
- modelId: modelUsed.modelId,
1776
- usage: planned.usage,
1777
- sessionId,
1778
- userId
1779
- });
1780
- } else {
1784
+ if (this.planner === "jev") envelope = (await this.planWithJev({
1785
+ task,
1786
+ url: pageInfo.url,
1787
+ title: pageInfo.title,
1788
+ elements,
1789
+ tabs,
1790
+ actionHistory,
1791
+ lastExtract: lastExtractResult,
1792
+ pagesBelow: scrollCtx?.pagesBelow,
1793
+ pagesAbove: scrollCtx?.pagesAbove,
1794
+ apiKey: opts?.apiKey,
1795
+ signal: ctx.signal
1796
+ })).envelope;
1797
+ else {
1781
1798
  const messages = this.buildMessages(systemPrompt, historyTurns, userText, wantVision ? screenshot : null);
1782
- const { response, modelUsed: used } = await this.callModelWithFallback(messages, opts?.apiKey, ctx.signal);
1783
- modelUsed = used;
1799
+ const { response } = await this.callModelWithFallback(messages, opts?.apiKey, ctx.signal);
1784
1800
  if (!response) {
1785
1801
  consecutiveFailures++;
1786
1802
  actionHistory.push(`(model call failed — retrying, ${consecutiveFailures}/${this.maxFailures})`);
1787
1803
  if (consecutiveFailures > this.maxFailures) return await this.forceDone(browser, steps, startTime, opts, extractedContent, actionHistory, "model");
1788
1804
  continue;
1789
1805
  }
1790
- if (this.costTracker && response.usage) this.costTracker.track({
1791
- runId: sessionId,
1792
- agentName: this.name,
1793
- modelId: modelUsed.modelId,
1794
- usage: response.usage,
1795
- sessionId,
1796
- userId
1797
- });
1798
1806
  const raw = typeof response.message.content === "string" ? response.message.content : "";
1799
1807
  envelope = this.parseEnvelope(raw);
1800
1808
  }
@@ -2027,7 +2035,7 @@ var BrowserAgent = class {
2027
2035
  };
2028
2036
  try {
2029
2037
  signal?.throwIfAborted();
2030
- const r = await this.model.generate(messages, reqOpts);
2038
+ const r = await (0, _agentium_core.meteredGenerate)(this.model, messages, reqOpts);
2031
2039
  signal?.throwIfAborted();
2032
2040
  return {
2033
2041
  response: r,
@@ -2042,7 +2050,7 @@ var BrowserAgent = class {
2042
2050
  fallback: this.fallbackModel.modelId
2043
2051
  });
2044
2052
  try {
2045
- const r = await this.fallbackModel.generate(messages, reqOpts);
2053
+ const r = await (0, _agentium_core.meteredGenerate)(this.fallbackModel, messages, reqOpts);
2046
2054
  signal?.throwIfAborted();
2047
2055
  return {
2048
2056
  response: r,
@@ -2096,7 +2104,7 @@ var BrowserAgent = class {
2096
2104
  const provider = this.getJev();
2097
2105
  args.signal?.throwIfAborted();
2098
2106
  try {
2099
- const response = await provider.generate([{
2107
+ const response = await (0, _agentium_core.meteredGenerate)(provider, [{
2100
2108
  role: "user",
2101
2109
  content: JSON.stringify({
2102
2110
  task: args.task,
@@ -2183,7 +2191,7 @@ var BrowserAgent = class {
2183
2191
  const model = this.pageExtractionLLM ?? (this.model.providerId === "jev" ? null : this.model);
2184
2192
  if (!model) return guessSearchQuery(task);
2185
2193
  try {
2186
- const response = await model.generate([{
2194
+ const response = await (0, _agentium_core.meteredGenerate)(model, [{
2187
2195
  role: "user",
2188
2196
  content: `Task: ${task}\nThe next browser action is ${pick}. Reply with ONLY the text to type into that field. No quotes.`
2189
2197
  }], { signal });
@@ -2480,7 +2488,7 @@ var BrowserAgent = class {
2480
2488
  role: "user",
2481
2489
  content: `Query: ${action.query}\n\nPage content:\n${pageText}`
2482
2490
  }];
2483
- const response = await model.generate(messages, {
2491
+ const response = await (0, _agentium_core.meteredGenerate)(model, messages, {
2484
2492
  temperature: 0,
2485
2493
  maxTokens: 2048,
2486
2494
  signal: ctx.signal
@@ -0,0 +1,7 @@
1
+ export type { ActionSpace, TabInfo } from "./action-space.cjs";
2
+ export { buildActionSpace, guessSearchQuery, isBlockedPageUrl, isBotChallengeText, isResultTitle, isSearchResultsUrl, labelToAction, looksLikeResultList, searchUrl, titlesFromElements, } from "./action-space.cjs";
3
+ export { BrowserAgent } from "./browser-agent.cjs";
4
+ export { BrowserProvider } from "./browser-provider.cjs";
5
+ export { CredentialVault } from "./credential-vault.cjs";
6
+ export type { AgentOutput, BrowserAction, BrowserAgentConfig, BrowserPlanner, BrowserRunOpts, BrowserRunOutput, BrowserStep, DomElement, DomScrollContext, DomSnapshot, HumanizeConfig, PageInfo, SearchEngine, StealthConfig, } from "./types.cjs";
7
+ //# sourceMappingURL=index.d.ts.map