/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ /** * @module bxc/mcp/page-sessions * * Session-keyed browser pages for the MCP server. * * Each session id owns one page created with an explicit profile. Asking for * a different profile on an existing session replaces its page instead of * silently reusing the old one, and sessions never share a page. Concurrent * acquisitions of the same session share one creation, idle sessions expire, * and the least recently used session is evicted beyond `maxSessions`. */ export type PageProfile = "static" | "fast" | "http" | "stealth" | "max"; /** Minimal page surface the registry needs. */ export interface SessionPage { close(): Promise; url(): string; } export interface PageSessionOptions

{ /** Creates a page for `profile`. */ factory: (profile: PageProfile) => Promise

; /** Profile used when a new session does not request one. Default: `stealth`. */ defaultProfile?: PageProfile; /** Maximum concurrent sessions before LRU eviction. Default: 8. */ maxSessions?: number; /** Idle time after which a session is closed. Default: 15 minutes. */ idleTtlMs?: number; /** Injectable clock for tests. */ now?: () => number; } interface SessionEntry

{ page: P; profile: PageProfile; lastUsedAt: number; } export interface SessionInfo { sessionId: string; profile: PageProfile; url: string; idleMs: number; } export const DEFAULT_SESSION = "default"; export class PageSessionRegistry

{ readonly #factory: (profile: PageProfile) => Promise

; readonly #defaultProfile: PageProfile; readonly #maxSessions: number; readonly #idleTtlMs: number; readonly #now: () => number; readonly #sessions = new Map>(); readonly #creating = new Map }>(); constructor(options: PageSessionOptions

) { this.#factory = options.factory; this.#defaultProfile = options.defaultProfile ?? "stealth"; this.#maxSessions = Math.max(1, options.maxSessions ?? 8); this.#idleTtlMs = options.idleTtlMs ?? 15 * 60_000; this.#now = options.now ?? Date.now; } /** * Page for `sessionId`. When `profile` is given and differs from the * session's current profile, the old page is closed and replaced. */ async acquire(sessionId: string = DEFAULT_SESSION, profile?: PageProfile): Promise

{ await this.#expireIdle(); const existing = this.#sessions.get(sessionId); if (existing && (profile === undefined || profile === existing.profile)) { existing.lastUsedAt = this.#now(); return existing.page; } const inFlight = this.#creating.get(sessionId); if (inFlight && (profile === undefined || profile === inFlight.profile)) { return inFlight.page; } if (existing) { this.#sessions.delete(sessionId); await existing.page.close().catch(() => {}); } const wanted = profile ?? this.#defaultProfile; const creation = this.#factory(wanted); this.#creating.set(sessionId, { profile: wanted, page: creation }); try { const page = await creation; this.#sessions.set(sessionId, { page, profile: wanted, lastUsedAt: this.#now() }); await this.#evictOverflow(sessionId); return page; } finally { if (this.#creating.get(sessionId)?.page === creation) { this.#creating.delete(sessionId); } } } /** Existing page for `sessionId` without creating one. */ peek(sessionId: string = DEFAULT_SESSION): P | undefined { return this.#sessions.get(sessionId)?.page; } /** Close one session. Returns `true` when a page was closed. */ async close(sessionId: string = DEFAULT_SESSION): Promise { const entry = this.#sessions.get(sessionId); if (!entry) return false; this.#sessions.delete(sessionId); await entry.page.close().catch(() => {}); return true; } /** Close every session. Returns the number of pages closed. */ async closeAll(): Promise { const ids = [...this.#sessions.keys()]; await Promise.all(ids.map((id) => this.close(id))); return ids.length; } list(): SessionInfo[] { const now = this.#now(); return [...this.#sessions.entries()].map(([sessionId, entry]) => ({ sessionId, profile: entry.profile, url: safeUrl(entry.page), idleMs: now - entry.lastUsedAt, })); } get size(): number { return this.#sessions.size; } async #expireIdle(): Promise { const now = this.#now(); const expired = [...this.#sessions.entries()].filter( ([, entry]) => now - entry.lastUsedAt > this.#idleTtlMs, ); await Promise.all(expired.map(([id]) => this.close(id))); } async #evictOverflow(keep: string): Promise { while (this.#sessions.size > this.#maxSessions) { let oldest: string | null = null; let oldestAt = Number.POSITIVE_INFINITY; for (const [id, entry] of this.#sessions) { if (id !== keep && entry.lastUsedAt < oldestAt) { oldest = id; oldestAt = entry.lastUsedAt; } } if (oldest === null) return; await this.close(oldest); } } } function safeUrl(page: SessionPage): string { try { return page.url(); } catch { return "about:blank"; } }