@mastra/stagehand 0.0.0-async-hooks-fix-20260405144639

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,524 @@
1
+ import { Stagehand } from '@browserbasehq/stagehand';
2
+ import { ThreadManager, ThreadSession, ThreadManagerConfig, BrowserConfigBase, BrowserScope, CdpUrlProvider, MastraBrowser, BrowserToolError, BrowserState, BrowserTabState, ScreencastOptions, ScreencastStream, MouseEventParams, KeyboardEventParams } from '@mastra/core/browser';
3
+ import { Tool } from '@mastra/core/tools';
4
+ import { z } from 'zod';
5
+
6
+ /**
7
+ * Stagehand Tool Schemas
8
+ *
9
+ * AI-powered browser tools using natural language instructions.
10
+ * These are fundamentally different from the deterministic AgentBrowser tools.
11
+ */
12
+
13
+ /**
14
+ * stagehand_act - Perform an action using natural language
15
+ */
16
+ declare const actInputSchema: z.ZodObject<{
17
+ instruction: z.ZodString;
18
+ variables: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
19
+ useVision: z.ZodOptional<z.ZodBoolean>;
20
+ timeout: z.ZodOptional<z.ZodNumber>;
21
+ }, z.core.$strip>;
22
+ type ActInput = z.output<typeof actInputSchema>;
23
+ /**
24
+ * stagehand_extract - Extract structured data from a page
25
+ */
26
+ declare const extractInputSchema: z.ZodObject<{
27
+ instruction: z.ZodString;
28
+ schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
29
+ timeout: z.ZodOptional<z.ZodNumber>;
30
+ }, z.core.$strip>;
31
+ type ExtractInput = z.output<typeof extractInputSchema>;
32
+ /**
33
+ * stagehand_observe - Discover actionable elements on a page
34
+ */
35
+ declare const observeInputSchema: z.ZodObject<{
36
+ instruction: z.ZodOptional<z.ZodString>;
37
+ onlyVisible: z.ZodOptional<z.ZodBoolean>;
38
+ timeout: z.ZodOptional<z.ZodNumber>;
39
+ }, z.core.$strip>;
40
+ type ObserveInput = z.output<typeof observeInputSchema>;
41
+ /**
42
+ * stagehand_navigate - Navigate to a URL
43
+ */
44
+ declare const navigateInputSchema: z.ZodObject<{
45
+ url: z.ZodString;
46
+ waitUntil: z.ZodOptional<z.ZodEnum<{
47
+ load: "load";
48
+ domcontentloaded: "domcontentloaded";
49
+ networkidle: "networkidle";
50
+ }>>;
51
+ }, z.core.$strip>;
52
+ type NavigateInput = z.output<typeof navigateInputSchema>;
53
+ /**
54
+ * stagehand_close - Close the browser
55
+ */
56
+ declare const closeInputSchema: z.ZodObject<{}, z.core.$strip>;
57
+ type CloseInput = z.output<typeof closeInputSchema>;
58
+ /**
59
+ * stagehand_tabs - Manage browser tabs
60
+ */
61
+ declare const tabsInputSchema: z.ZodObject<{
62
+ action: z.ZodEnum<{
63
+ list: "list";
64
+ new: "new";
65
+ switch: "switch";
66
+ close: "close";
67
+ }>;
68
+ index: z.ZodOptional<z.ZodNumber>;
69
+ url: z.ZodOptional<z.ZodString>;
70
+ }, z.core.$strip>;
71
+ type TabsInput = z.output<typeof tabsInputSchema>;
72
+ declare const stagehandSchemas: {
73
+ readonly act: z.ZodObject<{
74
+ instruction: z.ZodString;
75
+ variables: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
76
+ useVision: z.ZodOptional<z.ZodBoolean>;
77
+ timeout: z.ZodOptional<z.ZodNumber>;
78
+ }, z.core.$strip>;
79
+ readonly extract: z.ZodObject<{
80
+ instruction: z.ZodString;
81
+ schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
82
+ timeout: z.ZodOptional<z.ZodNumber>;
83
+ }, z.core.$strip>;
84
+ readonly observe: z.ZodObject<{
85
+ instruction: z.ZodOptional<z.ZodString>;
86
+ onlyVisible: z.ZodOptional<z.ZodBoolean>;
87
+ timeout: z.ZodOptional<z.ZodNumber>;
88
+ }, z.core.$strip>;
89
+ readonly navigate: z.ZodObject<{
90
+ url: z.ZodString;
91
+ waitUntil: z.ZodOptional<z.ZodEnum<{
92
+ load: "load";
93
+ domcontentloaded: "domcontentloaded";
94
+ networkidle: "networkidle";
95
+ }>>;
96
+ }, z.core.$strip>;
97
+ readonly tabs: z.ZodObject<{
98
+ action: z.ZodEnum<{
99
+ list: "list";
100
+ new: "new";
101
+ switch: "switch";
102
+ close: "close";
103
+ }>;
104
+ index: z.ZodOptional<z.ZodNumber>;
105
+ url: z.ZodOptional<z.ZodString>;
106
+ }, z.core.$strip>;
107
+ readonly close: z.ZodObject<{}, z.core.$strip>;
108
+ };
109
+
110
+ /**
111
+ * StagehandThreadManager - Thread scope management for StagehandBrowser
112
+ *
113
+ * Supports two scope modes:
114
+ * - 'shared': All threads share the same Stagehand instance and page
115
+ * - 'thread': Each thread gets its own Stagehand instance (separate browser)
116
+ *
117
+ * @see AgentBrowserThreadManager for the equivalent implementation.
118
+ */
119
+
120
+ type V3 = Stagehand;
121
+ type V3Page$1 = NonNullable<ReturnType<NonNullable<Stagehand['context']>['activePage']>>;
122
+ /**
123
+ * Extended session info for Stagehand threads.
124
+ */
125
+ interface StagehandThreadSession extends ThreadSession {
126
+ /** For 'thread' mode: dedicated Stagehand instance */
127
+ stagehand?: V3;
128
+ }
129
+ /**
130
+ * Configuration for StagehandThreadManager.
131
+ */
132
+ interface StagehandThreadManagerConfig extends ThreadManagerConfig {
133
+ /** Function to create a new Stagehand instance (for 'thread' mode) */
134
+ createStagehand?: () => Promise<V3>;
135
+ /** Callback when a new browser/Stagehand instance is created for a thread */
136
+ onBrowserCreated?: (stagehand: V3, threadId: string) => void;
137
+ }
138
+ /**
139
+ * Thread manager for StagehandBrowser.
140
+ *
141
+ * Supports two scope modes:
142
+ * - 'shared': All threads share the shared Stagehand instance
143
+ * - 'thread': Each thread gets a dedicated Stagehand instance
144
+ */
145
+ declare class StagehandThreadManager extends ThreadManager<V3> {
146
+ protected sessions: Map<string, StagehandThreadSession>;
147
+ private createStagehand?;
148
+ private onBrowserCreated?;
149
+ constructor(config: StagehandThreadManagerConfig);
150
+ /**
151
+ * Set the factory function for creating new Stagehand instances.
152
+ * Required for 'thread' scope mode.
153
+ */
154
+ setCreateStagehand(factory: () => Promise<V3>): void;
155
+ /**
156
+ * Get the page for a specific thread, creating session if needed.
157
+ */
158
+ getPageForThread(threadId?: string): Promise<V3Page$1 | null>;
159
+ /**
160
+ * Create a new session for a thread.
161
+ */
162
+ protected createSession(threadId: string): Promise<StagehandThreadSession>;
163
+ /**
164
+ * Restore browser state (multiple tabs) to a Stagehand instance.
165
+ */
166
+ private restoreBrowserState;
167
+ /**
168
+ * Get the manager (Stagehand instance) for a specific session.
169
+ */
170
+ protected getManagerForSession(session: StagehandThreadSession): V3;
171
+ /**
172
+ * Destroy a session and clean up resources.
173
+ */
174
+ protected doDestroySession(session: StagehandThreadSession): Promise<void>;
175
+ /**
176
+ * Destroy all sessions (called during browser close).
177
+ * doDestroySession handles closing individual Stagehand instances.
178
+ */
179
+ destroyAllSessions(): Promise<void>;
180
+ }
181
+
182
+ /**
183
+ * Stagehand Browser Types
184
+ */
185
+
186
+ /**
187
+ * Model configuration for Stagehand AI operations
188
+ */
189
+ type ModelConfiguration = string | {
190
+ modelName: string;
191
+ apiKey?: string;
192
+ baseURL?: string;
193
+ };
194
+ /**
195
+ * Stagehand-specific configuration fields.
196
+ */
197
+ interface StagehandConfigExtensions {
198
+ /**
199
+ * Environment to run the browser in
200
+ * - 'LOCAL': Run browser locally
201
+ * - 'BROWSERBASE': Use Browserbase cloud
202
+ * @default 'LOCAL'
203
+ */
204
+ env?: 'LOCAL' | 'BROWSERBASE';
205
+ /**
206
+ * Browserbase API key (required when env = 'BROWSERBASE')
207
+ */
208
+ apiKey?: string;
209
+ /**
210
+ * Browserbase project ID (required when env = 'BROWSERBASE')
211
+ */
212
+ projectId?: string;
213
+ /**
214
+ * Model configuration for AI operations
215
+ * @default 'openai/gpt-4o'
216
+ */
217
+ model?: ModelConfiguration;
218
+ /**
219
+ * Enable self-healing selectors.
220
+ * When enabled, Stagehand uses AI to find elements even when selectors fail.
221
+ * @default true
222
+ */
223
+ selfHeal?: boolean;
224
+ /**
225
+ * Timeout for DOM to settle after actions (ms)
226
+ * @default 5000
227
+ */
228
+ domSettleTimeout?: number;
229
+ /**
230
+ * Logging verbosity level
231
+ * - 0: Silent
232
+ * - 1: Errors only
233
+ * - 2: Verbose
234
+ * @default 1
235
+ */
236
+ verbose?: 0 | 1 | 2;
237
+ /**
238
+ * Custom system prompt for AI operations (act, extract, observe)
239
+ */
240
+ systemPrompt?: string;
241
+ }
242
+ /**
243
+ * Configuration for StagehandBrowser with compile-time enforcement of cdpUrl/scope compatibility.
244
+ *
245
+ * This type enforces that `cdpUrl` and `scope: 'thread'` cannot be used together:
246
+ * - When `cdpUrl` is provided, `scope` must be `'shared'` or omitted
247
+ * - When `scope: 'thread'` is used, `cdpUrl` must not be provided
248
+ */
249
+ type StagehandBrowserConfig = (BrowserConfigBase & StagehandConfigExtensions & {
250
+ cdpUrl?: undefined;
251
+ scope?: BrowserScope;
252
+ }) | (BrowserConfigBase & StagehandConfigExtensions & {
253
+ cdpUrl: CdpUrlProvider;
254
+ scope?: 'shared';
255
+ });
256
+ /**
257
+ * Action returned from observe()
258
+ */
259
+ interface StagehandAction {
260
+ /** XPath selector to locate element */
261
+ selector: string;
262
+ /** Human-readable description */
263
+ description: string;
264
+ /** Suggested action method */
265
+ method?: string;
266
+ /** Additional action parameters */
267
+ arguments?: string[];
268
+ }
269
+ /**
270
+ * Result from act()
271
+ */
272
+ interface ActResult {
273
+ success: boolean;
274
+ message?: string;
275
+ action?: string;
276
+ url?: string;
277
+ hint?: string;
278
+ }
279
+ /**
280
+ * Result from extract()
281
+ */
282
+ interface ExtractResult<T = unknown> {
283
+ success: boolean;
284
+ data?: T;
285
+ error?: string;
286
+ url?: string;
287
+ hint?: string;
288
+ }
289
+ /**
290
+ * Result from observe()
291
+ */
292
+ interface ObserveResult {
293
+ success: boolean;
294
+ actions: StagehandAction[];
295
+ url?: string;
296
+ hint?: string;
297
+ }
298
+
299
+ /**
300
+ * StagehandBrowser - AI-powered browser automation using Stagehand v3
301
+ *
302
+ * Uses natural language instructions for browser interactions.
303
+ * Fundamentally different from AgentBrowser's deterministic refs approach.
304
+ *
305
+ * Stagehand v3 is CDP-native and provides direct CDP access for screencast/input injection.
306
+ */
307
+
308
+ type V3Page = NonNullable<ReturnType<NonNullable<Stagehand['context']>['activePage']>>;
309
+ /**
310
+ * StagehandBrowser - AI-powered browser using Stagehand v3
311
+ *
312
+ * Unlike AgentBrowser which uses refs ([ref=e1]), StagehandBrowser uses
313
+ * natural language instructions for all interactions.
314
+ *
315
+ * Supports thread scope via the scope config:
316
+ * - 'shared': All threads share the same Stagehand instance
317
+ * - 'thread': Each thread gets its own Stagehand instance (separate browser)
318
+ */
319
+ declare class StagehandBrowser extends MastraBrowser {
320
+ readonly id: string;
321
+ readonly name = "StagehandBrowser";
322
+ readonly provider = "browserbase/stagehand";
323
+ /** Shared Stagehand instance (for 'shared' scope) - narrowed type from base class */
324
+ protected sharedManager: Stagehand | null;
325
+ private stagehandConfig;
326
+ /** Thread manager - narrowed type from base class */
327
+ protected threadManager: StagehandThreadManager;
328
+ /** Debounce timers per thread for tab change reconnection */
329
+ private tabChangeDebounceTimers;
330
+ constructor(config?: StagehandBrowserConfig);
331
+ /**
332
+ * Ensure browser is ready and thread session exists.
333
+ * For 'thread' scope, this creates a dedicated Stagehand instance for the thread.
334
+ */
335
+ ensureReady(): Promise<void>;
336
+ /**
337
+ * Build Stagehand options from config.
338
+ * Returns the configuration object expected by Stagehand constructor.
339
+ */
340
+ private buildStagehandOptions;
341
+ /**
342
+ * Create a new Stagehand instance with the current config.
343
+ * Used by thread manager for 'thread' scope.
344
+ */
345
+ private createStagehandInstance;
346
+ protected doLaunch(): Promise<void>;
347
+ /**
348
+ * Set up close event listener for a shared Stagehand instance.
349
+ * Listens to both context and page close events for robust detection.
350
+ */
351
+ private setupCloseListenerForSharedScope;
352
+ /**
353
+ * Set up close event listener for a thread's Stagehand instance.
354
+ * Uses CDP Target.targetDestroyed events to detect when all pages are gone.
355
+ */
356
+ private setupCloseListenerForThread;
357
+ protected doClose(): Promise<void>;
358
+ /**
359
+ * Check if the browser is still alive by verifying the context and pages exist.
360
+ * Called by base class ensureReady() to detect externally closed browsers.
361
+ */
362
+ protected checkBrowserAlive(): Promise<boolean>;
363
+ /**
364
+ * Create an error response from an exception.
365
+ * Extends base class to add Stagehand-specific error handling.
366
+ */
367
+ protected createErrorFromException(error: unknown, context: string): BrowserToolError;
368
+ /**
369
+ * Get the Stagehand instance for a thread, creating it if needed.
370
+ * For 'thread' scope, this creates a dedicated Stagehand instance.
371
+ * For 'shared' scope, returns the shared instance.
372
+ */
373
+ getManagerForThread(threadId?: string): Promise<Stagehand | null>;
374
+ /**
375
+ * Require a Stagehand instance for the given or current thread.
376
+ * Throws if no instance is available.
377
+ * @param explicitThreadId - Optional thread ID to use instead of getCurrentThread()
378
+ * Use this to avoid race conditions in concurrent tool calls.
379
+ */
380
+ private requireStagehand;
381
+ /**
382
+ * Get the current page from Stagehand v3, respecting thread scope.
383
+ * @param explicitThreadId - Optional thread ID to use instead of getCurrentThread()
384
+ * Use this to avoid race conditions in concurrent tool calls.
385
+ */
386
+ private getPage;
387
+ /**
388
+ * Get the active page for a thread (implements abstract method from base class).
389
+ */
390
+ protected getActivePage(threadId?: string): Promise<V3Page | null>;
391
+ /**
392
+ * Get a CDP session for a specific page.
393
+ */
394
+ private getCdpSessionForPage;
395
+ getTools(): Record<string, Tool<any, any>>;
396
+ /**
397
+ * Perform an action using natural language instruction
398
+ * @param input - Action input
399
+ * @param threadId - Optional thread ID for thread-safe operation
400
+ */
401
+ act(input: ActInput, threadId?: string): Promise<{
402
+ success: true;
403
+ message?: string;
404
+ action?: string;
405
+ url: string;
406
+ hint: string;
407
+ } | BrowserToolError>;
408
+ /**
409
+ * Extract structured data from a page using natural language
410
+ * @param input - Extract input
411
+ * @param threadId - Optional thread ID for thread-safe operation
412
+ */
413
+ extract(input: ExtractInput, threadId?: string): Promise<{
414
+ success: true;
415
+ data: unknown;
416
+ url: string;
417
+ hint: string;
418
+ } | BrowserToolError>;
419
+ /**
420
+ * Discover actionable elements on a page
421
+ * @param input - Observe input
422
+ * @param threadId - Optional thread ID for thread-safe operation
423
+ */
424
+ observe(input: ObserveInput, threadId?: string): Promise<{
425
+ success: true;
426
+ actions: StagehandAction[];
427
+ url: string;
428
+ hint: string;
429
+ } | BrowserToolError>;
430
+ /**
431
+ * Navigate to a URL
432
+ * @param input - Navigate input
433
+ * @param threadId - Optional thread ID for thread-safe operation
434
+ */
435
+ navigate(input: NavigateInput, threadId?: string): Promise<{
436
+ success: true;
437
+ url: string;
438
+ title: string;
439
+ hint: string;
440
+ } | BrowserToolError>;
441
+ /**
442
+ * Manage browser tabs - list, create, switch, close
443
+ * @param input - Tabs input
444
+ * @param threadId - Optional thread ID for thread-safe operation
445
+ */
446
+ tabs(input: TabsInput, threadId?: string): Promise<{
447
+ success: true;
448
+ tabs?: Array<{
449
+ index: number;
450
+ url: string;
451
+ title: string;
452
+ active: boolean;
453
+ }>;
454
+ hint: string;
455
+ } | {
456
+ success: true;
457
+ index?: number;
458
+ url?: string;
459
+ title?: string;
460
+ remaining?: number;
461
+ hint: string;
462
+ } | BrowserToolError>;
463
+ getCurrentUrl(threadId?: string): Promise<string | null>;
464
+ /**
465
+ * Navigate to a URL (simple version). Used internally for restoring state on relaunch.
466
+ */
467
+ navigateTo(url: string): Promise<void>;
468
+ /**
469
+ * Get the current browser state (all tabs and active tab index).
470
+ */
471
+ getBrowserState(threadId?: string): Promise<BrowserState | null>;
472
+ /**
473
+ * Get browser state for a thread (implements abstract method from base class).
474
+ * Sync version that uses existing manager lookup without creating sessions.
475
+ */
476
+ protected getBrowserStateForThread(threadId?: string): BrowserState | null;
477
+ /**
478
+ * Get browser state from a specific Stagehand instance.
479
+ */
480
+ private getBrowserStateFromStagehand;
481
+ /**
482
+ * Get all open tabs with their URLs and titles.
483
+ */
484
+ getTabState(threadId?: string): Promise<BrowserTabState[]>;
485
+ /**
486
+ * Get the active tab index.
487
+ */
488
+ getActiveTabIndex(threadId?: string): Promise<number>;
489
+ startScreencast(options?: ScreencastOptions): Promise<ScreencastStream>;
490
+ /**
491
+ * Set up listeners to detect tab changes and reconnect the screencast.
492
+ * Uses CDP Target events since Stagehand doesn't expose page lifecycle events.
493
+ */
494
+ private setupTabChangeDetection;
495
+ injectMouseEvent(event: MouseEventParams, threadId?: string): Promise<void>;
496
+ injectKeyboardEvent(event: KeyboardEventParams, threadId?: string): Promise<void>;
497
+ }
498
+
499
+ /**
500
+ * Stagehand Tool Constants
501
+ */
502
+ declare const STAGEHAND_TOOLS: {
503
+ readonly ACT: "stagehand_act";
504
+ readonly EXTRACT: "stagehand_extract";
505
+ readonly OBSERVE: "stagehand_observe";
506
+ readonly NAVIGATE: "stagehand_navigate";
507
+ readonly TABS: "stagehand_tabs";
508
+ readonly CLOSE: "stagehand_close";
509
+ };
510
+ type StagehandToolName = (typeof STAGEHAND_TOOLS)[keyof typeof STAGEHAND_TOOLS];
511
+
512
+ /**
513
+ * Stagehand Tools
514
+ *
515
+ * Creates AI-powered browser tools bound to a StagehandBrowser instance.
516
+ */
517
+
518
+ /**
519
+ * Creates all Stagehand tools bound to a StagehandBrowser instance.
520
+ * The browser is lazily initialized on first tool use.
521
+ */
522
+ declare function createStagehandTools(browser: StagehandBrowser): Record<string, Tool<any, any>>;
523
+
524
+ export { type ActInput, type ActResult, type CloseInput, type ExtractInput, type ExtractResult, type ModelConfiguration, type NavigateInput, type ObserveInput, type ObserveResult, STAGEHAND_TOOLS, type StagehandAction, StagehandBrowser, type StagehandBrowserConfig, type StagehandToolName, type TabsInput, actInputSchema, closeInputSchema, createStagehandTools, extractInputSchema, navigateInputSchema, observeInputSchema, stagehandSchemas, tabsInputSchema };