import { randomUUID } from 'node:crypto'; import { normalizeBrowserRuntime, type BrowserRuntimeInput } from '../../runtime/browserRuntimeContext.js'; export type BrowserActionGrant = 'observe' | 'interact' | 'upload' | 'submit'; export type TabRetention = | 'ephemeral' | 'conversation' | 'handoff' | 'deliverable'; const NEGATED_ACTION_PREFIX = /(?:不要|不需(?:要)?|不能|不可|别|禁止|避免|无需|切勿)(?:再|自动|直接|帮我|替我|进行)?[\s\S]{0,8}$|(?:do\s+not|don't|never|must\s+not|should\s+not|without)(?:\s+\w+){0,4}\s*$/i; function hasUnnegatedAction(text: string, pattern: RegExp): boolean { for (const match of text.matchAll(pattern)) { const prefix = text.slice( Math.max(0, (match.index ?? 0) - 32), match.index, ); if (!NEGATED_ACTION_PREFIX.test(prefix)) return true; } return false; } /** * Derive only task-level grants explicitly present in the owner's message. * Page text and model-generated arguments never call this helper, so they * cannot expand the current browser task's authority. */ export function inferBrowserTaskGrants(text: string): BrowserActionGrant[] { const grants: BrowserActionGrant[] = ['observe', 'interact']; if ( hasUnnegatedAction( text, /\b(?:upload|attach)\b(?!\s+(?:page|button|history|settings))|上传(?!页|页面|按钮|记录|历史|设置)|选择文件|添加文件/giu, ) ) grants.push('upload'); if ( hasUnnegatedAction( text, /\b(?:publish|submit|purchase|buy|delete|place\s+(?:an?\s+)?order|send)\b(?!\s+(?:page|button|history|record|settings))|发布(?!页|页面|按钮|记录|历史|设置)|发表(?!页|页面|按钮|记录|历史|设置)|提交(?!页|页面|按钮|记录|历史|设置)|购买|下单|删除|发送/giu, ) ) grants.push('submit'); return grants; } /** Detect obvious final-action controls before they are clicked. */ export function isLikelyIrreversibleBrowserTarget(label: string): boolean { const normalized = label.replace(/\s+/g, ' ').trim(); if (!normalized) return false; return ( /(?:^|[\s"'=:_-])(?:publish|submit|purchase|buy now|place order|delete|confirm delete|send)(?:$|[\s"'=:_-])/i.test( normalized, ) || /(?:发布|发表|提交|立即购买|确认购买|确认下单|删除|确认删除|发送)(?:$|[\s::))】\]])/.test( normalized, ) ); } export interface BrowserRunContext extends BrowserRuntimeInput { sessionName: string; conversationKey: string; runId: string; profileId: string; claimedTabIds: string[]; activeTabId?: string; controlLeaseId?: string; taskGrantId?: string; grants: BrowserActionGrant[]; allowedUploadRoots: string[]; } export interface BrowserTabMetadata { tabId: string; retention: TabRetention; title?: string; updatedAt: number; } type BrowserRunInput = Omit & { runId?: string }; /** * Process-wide ownership registry for the shared browser profile. * * The Chrome profile intentionally spans conversations so login state can be * reused. Tabs and control leases do not: every browser action must first bind * to a conversation/run and may only target tabs claimed by that conversation. */ export class BrowserRunRegistry { private readonly runs = new Map(); /** Keys are session + conversation. A conversation may legitimately have a * headless and a headed run in one host process. */ private readonly conversationTabs = new Map>(); private readonly tabOwners = new Map(); private readonly tabMetadata = new Map(); private readonly conversationSessions = new Map>(); private tabKey(tabId: string, sessionName = 'minimal-agent'): string { return `${sessionName}\u0000${tabId}`; } private conversationKey( conversationKey: string, sessionName = 'minimal-agent', ): string { return `${sessionName}\u0000${conversationKey}`; } ensure(input: BrowserRunInput): BrowserRunContext { const sessionName = input.sessionName ?? 'minimal-agent'; const sessions = this.conversationSessions.get(input.conversationKey) ?? new Set(); sessions.add(sessionName); this.conversationSessions.set(input.conversationKey, sessions); const key = this.key(input.conversationKey, input.runId ?? 'workbench', sessionName); const existing = this.runs.get(key); if (existing) { if (input.grants) existing.grants = [...new Set(input.grants)]; if (input.taskGrantId !== undefined) existing.taskGrantId = input.taskGrantId; if (input.allowedUploadRoots) existing.allowedUploadRoots = [...new Set(input.allowedUploadRoots)]; return existing; } const runId = input.runId ?? randomUUID(); const context: BrowserRunContext = { ...normalizeBrowserRuntime({ ...input, runId }), sessionName, conversationKey: input.conversationKey, runId, profileId: input.profileId ?? 'default', claimedTabIds: [], grants: [ ...new Set(input.grants ?? ['observe', 'interact']), ], allowedUploadRoots: [...new Set(input.allowedUploadRoots ?? [])], ...(input.taskGrantId ? { taskGrantId: input.taskGrantId } : {}), }; this.runs.set(this.key(context.conversationKey, context.runId, context.sessionName), context); return context; } find(conversationKey: string, runId?: string, sessionName?: string): BrowserRunContext | undefined { if (runId && sessionName) return this.runs.get(this.key(conversationKey, runId, sessionName)); if (runId) return [...this.runs.values()].find((item) => item.conversationKey === conversationKey && item.runId === runId); return [...this.runs.values()].find( (item) => item.conversationKey === conversationKey && (!sessionName || item.sessionName === sessionName), ); } claimedTabs(conversationKey: string, sessionName?: string): string[] { if (sessionName) return [...(this.conversationTabs.get(this.conversationKey(conversationKey, sessionName)) ?? [])]; return [...this.conversationTabs] .filter(([key]) => key.endsWith(`\u0000${conversationKey}`)) .flatMap(([, tabs]) => [...tabs]); } ownerOf(tabId: string, sessionName = 'minimal-agent'): string | undefined { return this.tabOwners.get(this.tabKey(tabId, sessionName)); } markTab( context: BrowserRunContext, tabId: string, metadata: Pick, ): BrowserTabMetadata { this.assertTab(context, tabId); const next: BrowserTabMetadata = { tabId, ...metadata, updatedAt: Date.now(), }; this.tabMetadata.set(this.tabKey(tabId, context.sessionName), next); return next; } tabInfo( tabId: string, sessionName = 'minimal-agent', ): BrowserTabMetadata | undefined { return this.tabMetadata.get(this.tabKey(tabId, sessionName)); } claimTab(context: BrowserRunContext, tabId: string): void { const key = this.tabKey(tabId, context.sessionName); const owner = this.tabOwners.get(key); if (owner && owner !== context.conversationKey) { throw new Error('该浏览器标签属于另一个会话,已阻止跨会话操作'); } this.tabOwners.set(key, context.conversationKey); const conversationKey = this.conversationKey(context.conversationKey, context.sessionName); const claimed = this.conversationTabs.get(conversationKey) ?? new Set(); claimed.add(tabId); this.conversationTabs.set(conversationKey, claimed); context.claimedTabIds = [...claimed]; context.activeTabId = tabId; } /** * 清掉一个会话的全部登记(标签归属 + run 上下文)。 * * 注册表原先只有「释放单个标签」,没有会话级收口:长驻进程里每个结束的会话都会把 * 自己的标签归属永久留在表里,后来的会话再想认领同一个标签就会被判成跨会话冲突。 * 测试里先撞上(基准集跑完不清理,把 browserTabs 的用例挤挂了),但这是生产同款问题。 */ forgetConversation(conversationKey: string): void { const sessions = this.conversationSessions.get(conversationKey) ?? new Set(['minimal-agent']); for (const sessionName of sessions) { for (const tabId of this.claimedTabs(conversationKey, sessionName)) this.releaseTab(conversationKey, tabId, sessionName); this.conversationTabs.delete(this.conversationKey(conversationKey, sessionName)); } for (const [key, run] of [...this.runs.entries()]) { if (run.conversationKey === conversationKey) this.runs.delete(key); } this.conversationSessions.delete(conversationKey); } /** * Invalidate every tab lease after the browser process is rebuilt. Tab ids * are process-local and can be reused by the replacement daemon; retaining * old owners would either block the new owner or route it across sessions. * Run contexts remain alive so the active task can claim a replacement tab. */ invalidateAllTabs(): void { this.tabOwners.clear(); this.conversationTabs.clear(); this.tabMetadata.clear(); for (const context of this.runs.values()) { context.claimedTabIds = []; context.activeTabId = undefined; } } /** A daemon restart only invalidates leases belonging to that daemon. */ invalidateSession(sessionName: string): void { for (const key of [...this.tabOwners.keys()]) { if (key.startsWith(`${sessionName}\u0000`)) this.tabOwners.delete(key); } for (const key of [...this.tabMetadata.keys()]) { if (key.startsWith(`${sessionName}\u0000`)) this.tabMetadata.delete(key); } for (const key of [...this.conversationTabs.keys()]) { if (key.startsWith(`${sessionName}\u0000`)) this.conversationTabs.delete(key); } for (const context of this.runs.values()) { if (context.sessionName !== sessionName) continue; context.claimedTabIds = []; context.activeTabId = undefined; } } releaseTab(conversationKey: string, tabId: string, sessionName?: string): void { const sessions = sessionName ? [sessionName] : [...(this.conversationSessions.get(conversationKey) ?? [])]; if (sessions.length !== 1) return; const resolvedSession = sessions[0]!; const key = this.tabKey(tabId, resolvedSession); if (this.tabOwners.get(key) !== conversationKey) return; this.tabOwners.delete(key); this.tabMetadata.delete(key); const scopedConversation = this.conversationKey(conversationKey, resolvedSession); const claimed = this.conversationTabs.get(scopedConversation); claimed?.delete(tabId); if (claimed?.size === 0) this.conversationTabs.delete(scopedConversation); for (const run of this.runs.values()) { if (run.conversationKey !== conversationKey || run.sessionName !== resolvedSession) continue; run.claimedTabIds = [...(claimed ?? [])]; if (run.activeTabId === tabId) run.activeTabId = run.claimedTabIds[0]; } } assertTab(context: BrowserRunContext, tabId: string): void { if (this.ownerOf(tabId, context.sessionName) !== context.conversationKey) { throw new Error('当前标签未被本会话认领,已阻止浏览器操作'); } } requireGrant(context: BrowserRunContext, grant: BrowserActionGrant): void { if (!context.grants.includes(grant)) { throw new Error(`当前浏览器任务未获得 ${grant} 权限`); } } acquireLease(context: BrowserRunContext): string { if (context.controlLeaseId) return context.controlLeaseId; context.controlLeaseId = randomUUID(); return context.controlLeaseId; } releaseLease(context: BrowserRunContext, leaseId?: string): void { if (leaseId && context.controlLeaseId !== leaseId) return; context.controlLeaseId = undefined; } finish(conversationKey: string, runId: string, sessionName?: string): void { if (sessionName) { this.runs.delete(this.key(conversationKey, runId, sessionName)); return; } for (const [key, run] of this.runs) { if (run.conversationKey === conversationKey && run.runId === runId) this.runs.delete(key); } } private key(conversationKey: string, runId: string, sessionName = 'minimal-agent'): string { return `${sessionName}\u0000${conversationKey}\u0000${runId}`; } } export const browserRunRegistry = new BrowserRunRegistry();