@mastra/stagehand 0.3.7 → 0.4.0-alpha.1

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/dist/index.cjs CHANGED
@@ -17,10 +17,12 @@ var StagehandThreadManager = class extends _mastra_core_browser.ThreadManager {
17
17
  sessions = /* @__PURE__ */ new Map();
18
18
  createStagehand;
19
19
  onBrowserCreated;
20
+ onBrowserOpened;
20
21
  constructor(config) {
21
22
  super(config);
22
23
  this.createStagehand = config.createStagehand;
23
24
  this.onBrowserCreated = config.onBrowserCreated;
25
+ this.onBrowserOpened = config.onBrowserOpened;
24
26
  }
25
27
  /**
26
28
  * Set the factory function for creating new Stagehand instances.
@@ -51,6 +53,14 @@ var StagehandThreadManager = class extends _mastra_core_browser.ThreadManager {
51
53
  const stagehand = await this.createStagehand();
52
54
  session.stagehand = stagehand;
53
55
  this.threadManagers.set(threadId, stagehand);
56
+ try {
57
+ await this.onBrowserOpened?.(threadId);
58
+ } catch (error) {
59
+ this.threadManagers.delete(threadId);
60
+ session.stagehand = void 0;
61
+ await stagehand.close().catch(() => {});
62
+ throw error;
63
+ }
54
64
  if (savedState && savedState.tabs.length > 0) {
55
65
  this.logger?.debug?.(`Restoring browser state for thread ${threadId}: ${savedState.tabs.length} tabs`);
56
66
  await this.restoreBrowserState(stagehand, savedState);
@@ -416,6 +426,8 @@ function getStagehandChromePid(stagehand) {
416
426
  *
417
427
  * Stagehand v3 is CDP-native and provides direct CDP access for screencast/input injection.
418
428
  */
429
+ /** How long to wait for a Chrome started after retire() to close before killing it. */
430
+ const RETIRED_CLOSE_TIMEOUT_MS = 5e3;
419
431
  /**
420
432
  * StagehandBrowser - AI-powered browser using Stagehand v3
421
433
  *
@@ -447,7 +459,8 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
447
459
  },
448
460
  onBrowserCreated: (stagehand, threadId) => {
449
461
  this.setupCloseListener(stagehand, () => this.handleThreadBrowserDisconnected(threadId), threadId);
450
- }
462
+ },
463
+ onBrowserOpened: (threadId) => this.addPendingCookies(threadId)
451
464
  });
452
465
  }
453
466
  /**
@@ -460,6 +473,7 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
460
473
  const scope = this.getScope();
461
474
  const threadId = this.getCurrentThread();
462
475
  if (scope === "thread" && threadId && threadId !== _mastra_core_browser.DEFAULT_THREAD_ID) await this.getManagerForThread(threadId);
476
+ await this.addPendingCookies(threadId);
463
477
  }
464
478
  /**
465
479
  * Build Stagehand options from config.
@@ -508,9 +522,24 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
508
522
  * Used by thread manager for 'thread' scope.
509
523
  */
510
524
  async createStagehandInstance() {
525
+ this.assertNotRetired();
526
+ if (this.getScope() === "thread") await this.prepareLocalProfile();
511
527
  const stagehandOptions = await this.buildStagehandOptions();
528
+ this.assertNotRetired();
512
529
  const stagehand = new _browserbasehq_stagehand.Stagehand(stagehandOptions);
513
530
  await stagehand.init();
531
+ try {
532
+ this.assertNotRetired();
533
+ } catch (error) {
534
+ const pid = this.isConnectedToRemoteBrowser() ? void 0 : getStagehandChromePid(stagehand);
535
+ let timer;
536
+ const closed = await Promise.race([stagehand.close().then(() => true, () => false), new Promise((resolve) => {
537
+ timer = setTimeout(() => resolve(false), RETIRED_CLOSE_TIMEOUT_MS);
538
+ })]);
539
+ clearTimeout(timer);
540
+ if (!closed) this.killBrowserProcessGroup(pid);
541
+ throw error;
542
+ }
514
543
  return stagehand;
515
544
  }
516
545
  async doLaunch() {
@@ -532,6 +561,9 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
532
561
  const config = this.stagehandConfig;
533
562
  return config.env === "BROWSERBASE" || config.cdpUrl != null;
534
563
  }
564
+ getLocalProfilePath() {
565
+ return this.isConnectedToRemoteBrowser() ? void 0 : this.stagehandConfig.profile;
566
+ }
535
567
  /**
536
568
  * Set up close event listener for a shared Stagehand instance.
537
569
  * Listens to both context and page close events for robust detection.
@@ -542,7 +574,8 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
542
574
  * Tracks page targets via CDP `Target.targetCreated` / `Target.targetDestroyed`.
543
575
  * When all page targets are gone the `onDisconnect` callback fires. This is more
544
576
  * reliable than Playwright's `context.close` / `page.close` events which don't
545
- * fire when Chrome is killed externally (SIGTERM/SIGKILL).
577
+ * fire when Chrome is killed externally (SIGTERM/SIGKILL). A CDP transport close
578
+ * that we did not cause is also treated as a disconnect.
546
579
  */
547
580
  setupCloseListener(stagehand, onDisconnect, threadId) {
548
581
  if (!this.isConnectedToRemoteBrowser()) {
@@ -577,6 +610,15 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
577
610
  if (pageTargets.size === 0) handleDisconnect();
578
611
  }
579
612
  });
613
+ let closingOnPurpose = false;
614
+ const close = stagehand.close.bind(stagehand);
615
+ stagehand.close = (opts) => {
616
+ if (!opts?.force) closingOnPurpose = true;
617
+ return close(opts);
618
+ };
619
+ conn.onTransportClosed?.(() => {
620
+ if (!closingOnPurpose) handleDisconnect();
621
+ });
580
622
  } catch {}
581
623
  }
582
624
  async doClose() {
@@ -664,15 +706,24 @@ var StagehandBrowser = class extends _mastra_core_browser.MastraBrowser {
664
706
  * For 'shared' scope, returns the shared instance.
665
707
  */
666
708
  async getManagerForThread(threadId) {
667
- if (this.getScope() === "shared") return this.sharedManager;
668
- if (!threadId || threadId === _mastra_core_browser.DEFAULT_THREAD_ID) return this.sharedManager;
709
+ if (this.getScope() === "shared" || !threadId || threadId === _mastra_core_browser.DEFAULT_THREAD_ID) {
710
+ await this.addPendingCookies(threadId ?? this.getCurrentThread());
711
+ return this.sharedManager;
712
+ }
669
713
  let stagehand = this.threadManager.getExistingManagerForThread(threadId);
670
714
  if (!stagehand) {
671
715
  await this.threadManager.getManagerForThread(threadId);
672
716
  stagehand = this.threadManager.getExistingManagerForThread(threadId);
673
717
  }
718
+ await this.addPendingCookies(threadId);
674
719
  return stagehand ?? null;
675
720
  }
721
+ async addCookiesToOpenBrowser(cookies, threadId) {
722
+ const context = (this.getScope() === "shared" || threadId === _mastra_core_browser.DEFAULT_THREAD_ID ? this.sharedManager : this.threadManager.getExistingManagerForThread(threadId))?.context;
723
+ if (!context) return false;
724
+ await context.addCookies(cookies);
725
+ return true;
726
+ }
676
727
  /**
677
728
  * Require a Stagehand instance for the given or current thread.
678
729
  * Throws if no instance is available.