-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathsessionManager.ts
More file actions
executable file
·484 lines (439 loc) · 16.1 KB
/
sessionManager.ts
File metadata and controls
executable file
·484 lines (439 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import { Stagehand } from "@browserbasehq/stagehand";
import type { Config } from "../config.d.ts";
import { clearScreenshotsForSession } from "./mcp/resources.js";
import type { BrowserSession, CreateSessionParams } from "./types/types.js";
import { randomUUID } from "crypto";
/**
* Create a configured Stagehand instance
* This is used internally by SessionManager to initialize browser sessions
*/
export const createStagehandInstance = async (
config: Config,
params: CreateSessionParams = {},
sessionId: string,
): Promise<Stagehand> => {
const apiKey = params.apiKey || config.browserbaseApiKey;
const projectId = params.projectId || config.browserbaseProjectId;
if (!apiKey || !projectId) {
throw new Error("Browserbase API Key and Project ID are required");
}
const modelName = params.modelName || config.modelName || "gemini-2.0-flash";
const modelApiKey =
config.modelApiKey ||
process.env.GEMINI_API_KEY ||
process.env.GOOGLE_API_KEY;
const stagehand = new Stagehand({
env: "BROWSERBASE",
apiKey,
projectId,
model: modelApiKey
? {
apiKey: modelApiKey,
modelName: modelName,
}
: modelName,
...(params.browserbaseSessionID && {
browserbaseSessionID: params.browserbaseSessionID,
}),
experimental: config.experimental ?? false,
browserbaseSessionCreateParams: {
projectId,
proxies: config.proxies,
keepAlive: config.keepAlive ?? false,
browserSettings: {
viewport: {
width: config.viewPort?.browserWidth ?? 1288,
height: config.viewPort?.browserHeight ?? 711,
},
context: config.context?.contextId
? {
id: config.context?.contextId,
persist: config.context?.persist ?? true,
}
: undefined,
advancedStealth: config.advancedStealth ?? undefined,
},
userMetadata: {
mcp: "true",
},
},
// Disable pino to prevent pino-pretty errors in production environments
// (pino-pretty is not available in serverless/bundled deployments)
disablePino: true,
logger: (logLine) => {
console.error(`Stagehand[${sessionId}]: ${logLine.message}`);
},
});
await stagehand.init();
return stagehand;
};
/**
* SessionManager manages browser sessions and tracks active/default sessions.
*
* Session ID Strategy:
* - Default session: Uses generated ID with timestamp and UUID for uniqueness
* - User sessions: Uses raw sessionId provided by user (no suffix added)
* - All sessions stored in this.browsers Map with their internal ID as key
*
* Note: Context.currentSessionId is a getter that delegates to this.getActiveSessionId()
* to ensure session tracking stays synchronized.
*/
export class SessionManager {
private browsers: Map<string, BrowserSession>;
private defaultBrowserSession: BrowserSession | null;
private readonly defaultSessionId: string;
private activeSessionId: string;
// Mutex to prevent race condition when multiple calls try to create default session simultaneously
private defaultSessionCreationPromise: Promise<BrowserSession> | null = null;
// Track sessions currently being cleaned up to prevent concurrent cleanup
private cleaningUpSessions: Set<string> = new Set();
constructor(contextId?: string) {
this.browsers = new Map();
this.defaultBrowserSession = null;
const uniqueId = randomUUID();
this.defaultSessionId = `browserbase_session_${contextId || "default"}_${Date.now()}_${uniqueId}`;
this.activeSessionId = this.defaultSessionId;
}
getDefaultSessionId(): string {
return this.defaultSessionId;
}
/**
* Sets the active session ID.
* @param id The ID of the session to set as active.
*/
setActiveSessionId(id: string): void {
if (this.browsers.has(id)) {
this.activeSessionId = id;
} else if (id === this.defaultSessionId) {
// Allow setting to default ID even if session doesn't exist yet
// (it will be created on first use via ensureDefaultSessionInternal)
this.activeSessionId = id;
} else {
process.stderr.write(
`[SessionManager] WARN - Set active session failed for non-existent ID: ${id}\n`,
);
}
}
/**
* Gets the active session ID.
* @returns The active session ID.
*/
getActiveSessionId(): string {
return this.activeSessionId;
}
/**
* Creates a new Browserbase session using Stagehand.
* @param newSessionId - Internal session ID for tracking in SessionManager
* @param config - Configuration object
* @param resumeSessionId - Optional Browserbase session ID to resume/reuse
*/
async createNewBrowserSession(
newSessionId: string,
config: Config,
resumeSessionId?: string,
): Promise<BrowserSession> {
if (!config.browserbaseApiKey) {
throw new Error("Browserbase API Key is missing in the configuration.");
}
if (!config.browserbaseProjectId) {
throw new Error(
"Browserbase Project ID is missing in the configuration.",
);
}
try {
process.stderr.write(
`[SessionManager] ${resumeSessionId ? "Resuming" : "Creating"} Stagehand session ${newSessionId}...\n`,
);
// Create and initialize Stagehand instance using shared function
const stagehand = await createStagehandInstance(
config,
{
...(resumeSessionId && { browserbaseSessionID: resumeSessionId }),
},
newSessionId,
);
const page = stagehand.context.pages()[0];
if (!page) {
throw new Error("No pages available in Stagehand context");
}
const browserbaseSessionId = stagehand.browserbaseSessionId;
if (!browserbaseSessionId) {
throw new Error(
"Browserbase session ID is required but was not returned by Stagehand",
);
}
process.stderr.write(
`[SessionManager] Stagehand initialized with Browserbase session: ${browserbaseSessionId}\n`,
);
process.stderr.write(
`[SessionManager] Browserbase Live Debugger URL: https://www.browserbase.com/sessions/${browserbaseSessionId}\n`,
);
const sessionObj: BrowserSession = {
page,
sessionId: browserbaseSessionId,
stagehand,
};
this.browsers.set(newSessionId, sessionObj);
if (newSessionId === this.defaultSessionId) {
this.defaultBrowserSession = sessionObj;
}
this.setActiveSessionId(newSessionId);
process.stderr.write(
`[SessionManager] Session created and active: ${newSessionId}\n`,
);
return sessionObj;
} catch (creationError) {
const errorMessage =
creationError instanceof Error
? creationError.message
: String(creationError);
process.stderr.write(
`[SessionManager] Creating session ${newSessionId} failed: ${errorMessage}\n`,
);
throw new Error(
`Failed to create/connect session ${newSessionId}: ${errorMessage}`,
);
}
}
private async closeBrowserGracefully(
session: BrowserSession | undefined | null,
sessionIdToLog: string,
): Promise<void> {
// Check if this session is already being cleaned up
if (this.cleaningUpSessions.has(sessionIdToLog)) {
process.stderr.write(
`[SessionManager] Session ${sessionIdToLog} is already being cleaned up, skipping.\n`,
);
return;
}
// Mark session as being cleaned up
this.cleaningUpSessions.add(sessionIdToLog);
try {
// Close Stagehand instance which handles browser cleanup
if (session?.stagehand) {
try {
process.stderr.write(
`[SessionManager] Closing Stagehand for session: ${sessionIdToLog}\n`,
);
await session.stagehand.close();
process.stderr.write(
`[SessionManager] Successfully closed Stagehand and browser for session: ${sessionIdToLog}\n`,
);
// After close, purge any screenshots associated with this session
try {
clearScreenshotsForSession(sessionIdToLog);
} catch (err) {
process.stderr.write(
`[SessionManager] WARN - Failed to clear screenshots after close for ${sessionIdToLog}: ${
err instanceof Error ? err.message : String(err)
}\n`,
);
}
} catch (closeError) {
process.stderr.write(
`[SessionManager] WARN - Error closing Stagehand for session ${sessionIdToLog}: ${
closeError instanceof Error
? closeError.message
: String(closeError)
}\n`,
);
}
}
} finally {
// Always remove from cleanup tracking set
this.cleaningUpSessions.delete(sessionIdToLog);
}
}
// Internal function to ensure default session
// Uses a mutex pattern to prevent race conditions when multiple calls happen concurrently
async ensureDefaultSessionInternal(config: Config): Promise<BrowserSession> {
// If a creation is already in progress, wait for it instead of starting a new one
if (this.defaultSessionCreationPromise) {
process.stderr.write(
`[SessionManager] Default session creation already in progress, waiting...\n`,
);
return await this.defaultSessionCreationPromise;
}
const sessionId = this.defaultSessionId;
let needsReCreation = false;
if (!this.defaultBrowserSession) {
needsReCreation = true;
process.stderr.write(
`[SessionManager] Default session ${sessionId} not found, creating.\n`,
);
} else {
try {
// Try a simple operation to validate the session is alive
const pages = this.defaultBrowserSession.stagehand.context.pages();
if (!pages || pages.length === 0) {
throw new Error("No pages available");
}
} catch {
needsReCreation = true;
process.stderr.write(
`[SessionManager] Default session ${sessionId} is stale, recreating.\n`,
);
await this.closeBrowserGracefully(
this.defaultBrowserSession,
sessionId,
);
this.defaultBrowserSession = null;
this.browsers.delete(sessionId);
}
}
if (needsReCreation) {
// Set the mutex promise before starting creation
this.defaultSessionCreationPromise = (async () => {
try {
this.defaultBrowserSession = await this.createNewBrowserSession(
sessionId,
config,
);
return this.defaultBrowserSession;
} catch (creationError) {
// Error during initial creation or recreation
process.stderr.write(
`[SessionManager] Initial/Recreation attempt for default session ${sessionId} failed. Error: ${
creationError instanceof Error
? creationError.message
: String(creationError)
}\n`,
);
// Attempt one more time after a failure
process.stderr.write(
`[SessionManager] Retrying creation of default session ${sessionId} after error...\n`,
);
try {
this.defaultBrowserSession = await this.createNewBrowserSession(
sessionId,
config,
);
return this.defaultBrowserSession;
} catch (retryError) {
const finalErrorMessage =
retryError instanceof Error
? retryError.message
: String(retryError);
process.stderr.write(
`[SessionManager] Failed to recreate default session ${sessionId} after retry: ${finalErrorMessage}\n`,
);
throw new Error(
`Failed to ensure default session ${sessionId} after initial error and retry: ${finalErrorMessage}`,
);
}
} finally {
// Clear the mutex after creation completes or fails
this.defaultSessionCreationPromise = null;
}
})();
return await this.defaultSessionCreationPromise;
}
// If we reached here, the existing default session is considered okay.
this.setActiveSessionId(sessionId); // Ensure default is marked active
return this.defaultBrowserSession!; // Non-null assertion: logic ensures it's not null here
}
// Get a specific session by ID
async getSession(
sessionId: string,
config: Config,
createIfMissing: boolean = true,
): Promise<BrowserSession | null> {
if (sessionId === this.defaultSessionId && createIfMissing) {
try {
return await this.ensureDefaultSessionInternal(config);
} catch {
process.stderr.write(
`[SessionManager] Failed to get default session due to error in ensureDefaultSessionInternal for ${sessionId}. See previous messages for details.\n`,
);
return null;
}
}
// For non-default sessions
process.stderr.write(`[SessionManager] Getting session: ${sessionId}\n`);
const sessionObj = this.browsers.get(sessionId);
if (!sessionObj) {
process.stderr.write(
`[SessionManager] WARN - Session not found in map: ${sessionId}\n`,
);
return null;
}
try {
const pages = sessionObj.stagehand.context.pages();
if (!pages || pages.length === 0) {
throw new Error("No pages available");
}
} catch {
process.stderr.write(
`[SessionManager] WARN - Found session ${sessionId} is stale, removing.\n`,
);
await this.closeBrowserGracefully(sessionObj, sessionId);
this.browsers.delete(sessionId);
if (this.activeSessionId === sessionId) {
process.stderr.write(
`[SessionManager] WARN - Invalidated active session ${sessionId}, resetting to default.\n`,
);
this.setActiveSessionId(this.defaultSessionId);
}
return null;
}
// Session appears valid, make it active
this.setActiveSessionId(sessionId);
process.stderr.write(
`[SessionManager] Using valid session: ${sessionId}\n`,
);
return sessionObj;
}
/**
* Clean up a session by closing the browser and removing it from tracking.
* This method handles both closing Stagehand and cleanup, and is idempotent.
*
* @param sessionId The session ID to clean up
*/
async cleanupSession(sessionId: string): Promise<void> {
process.stderr.write(
`[SessionManager] Cleaning up session: ${sessionId}\n`,
);
// Get the session to close it gracefully
const session = this.browsers.get(sessionId);
if (session) {
await this.closeBrowserGracefully(session, sessionId);
}
// Remove from browsers map
this.browsers.delete(sessionId);
// Clear default session reference if this was the default
if (sessionId === this.defaultSessionId && this.defaultBrowserSession) {
this.defaultBrowserSession = null;
}
// Reset active session to default if this was the active one
if (this.activeSessionId === sessionId) {
process.stderr.write(
`[SessionManager] Cleaned up active session ${sessionId}, resetting to default.\n`,
);
this.setActiveSessionId(this.defaultSessionId);
}
}
// Function to close all managed browser sessions gracefully
async closeAllSessions(): Promise<void> {
process.stderr.write(`[SessionManager] Closing all sessions...\n`);
const closePromises: Promise<void>[] = [];
for (const [id, session] of this.browsers.entries()) {
process.stderr.write(`[SessionManager] Closing session: ${id}\n`);
closePromises.push(
// Use the helper for consistent logging/error handling
this.closeBrowserGracefully(session, id),
);
}
try {
await Promise.all(closePromises);
} catch {
// Individual errors are caught and logged by closeBrowserGracefully
process.stderr.write(
`[SessionManager] WARN - Some errors occurred during batch session closing. See individual messages.\n`,
);
}
this.browsers.clear();
this.defaultBrowserSession = null;
this.setActiveSessionId(this.defaultSessionId); // Reset active session to default
process.stderr.write(`[SessionManager] All sessions closed and cleared.\n`);
}
}