import type { AgentBrowserRun, AgentBrowserRunner } from './browser.js'; import { mkdir, readdir, rmdir, unlink, writeFile, rename, } from 'node:fs/promises'; import { randomUUID, createHash } from 'node:crypto'; import path from 'node:path'; import { agentStateDir } from '../../context/agentHome.js'; async function acquireProcessLock( sessionName: string, signal?: AbortSignal, ): Promise<() => Promise> { const lockPath = path.join( agentStateDir(), 'browser', 'locks', createHash('sha256').update(sessionName).digest('hex'), ); await mkdir(lockPath, { recursive: true }); // Each contender publishes its own immutable ticket atomically. Dead tickets // are removed by exact token, never by deleting a shared lock directory. const token = `${Date.now().toString().padStart(16, '0')}-${process.pid}-${randomUUID()}`; const ticket = path.join(lockPath, token); await mkdir(ticket); await writeFile(path.join(ticket, token), '', { flag: 'wx', mode: 0o600 }); const started = Date.now(); try { for (;;) { if (signal?.aborted) throw signal.reason instanceof Error ? signal.reason : new Error('Browser action cancelled'); // The gate is only released by its owner or after that process has died. // Its owner is encoded atomically in a directory name, avoiding partial metadata. const entries = await readdir(lockPath); for (const entry of entries) { const pid = Number(entry.split('-')[1]); if (!Number.isSafeInteger(pid) || pid <= 0) continue; try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ESRCH') { await unlink(path.join(lockPath, entry, entry)).catch(() => {}); await rmdir(path.join(lockPath, entry)).catch(() => {}); } } } // Atomic gate plus token-owned marker: contenders never remove a live gate. const gate = path.join(lockPath, 'gate'); try { // Rename publishes a nonempty owner directory atomically. An existing // nonempty gate cannot be replaced, even by simultaneous contenders. await rename(ticket, gate); return async () => { await unlink(path.join(gate, token)); await rmdir(gate).catch(() => {}); }; } catch (error) { if ( !['EEXIST', 'ENOTEMPTY', 'EPERM', 'EACCES'].includes( (error as NodeJS.ErrnoException).code ?? '', ) ) throw error; const owners = await readdir(gate).catch(() => []); for (const owner of owners) { const pid = Number(owner.split('-')[1]); if (!Number.isSafeInteger(pid) || pid <= 0) continue; try { process.kill(pid, 0); } catch (failure) { if ((failure as NodeJS.ErrnoException).code === 'ESRCH') { await unlink(path.join(gate, owner)).catch(() => {}); await rmdir(gate).catch(() => {}); } } } if (Date.now() - started > 120_000) throw new Error('浏览器动作锁等待超时'); await new Promise((resolve) => setTimeout(resolve, 50)); } } } catch (error) { await unlink(path.join(ticket, token)).catch(() => {}); await rmdir(ticket).catch(() => {}); throw error; } } /** * Process-wide action coordinator for the supervised browser. Desktop input, * Agent tools, TUI and workflows share the same daemon, so CDP mutations must * be serialized instead of racing through separate command adapters. */ export class BrowserService { private tails = new Map>(); private async waitForPrevious( previous: Promise, signal?: AbortSignal, ): Promise { if (!signal) return previous.catch(() => undefined); if (signal.aborted) throw signal.reason instanceof Error ? signal.reason : new Error('Browser action cancelled'); await new Promise((resolve, reject) => { let settled = false; const cleanup = () => signal.removeEventListener('abort', onAbort); const finish = (fn: () => void) => { if (settled) return; settled = true; cleanup(); fn(); }; const onAbort = () => finish(() => reject( signal.reason instanceof Error ? signal.reason : new Error('Browser action cancelled'), ), ); signal.addEventListener('abort', onAbort, { once: true }); void previous.then( () => finish(resolve), () => finish(resolve), ); }); } async exclusive( input: { sessionName: string; bin: string; runner: AgentBrowserRunner; signal?: AbortSignal; }, task: (run: (args: string[]) => Promise) => Promise, ): Promise { const previous = this.tails.get(input.sessionName) ?? Promise.resolve(); let release!: () => void; const current = new Promise((resolve) => { release = resolve; }); // 链上永远接一个已消化的 previous:任何一环 reject 都不能顺着队列传下去, // 否则后来者在 `await previous` 处抛出。 const tail = previous.catch(() => undefined).then(() => current); this.tails.set(input.sessionName, tail); // ⚠️ `await previous` **必须在 try 之内**。它曾经在 try 之外:previous 一旦 reject, // 函数在进入 try 之前就抛出 → `release()` 永不执行 → `current` 永不 resolve → // 后续所有该 session 的动作永久排队。症状是死锁而不是异常,排查起来极难。 // 当前 current 只 resolve 不 reject,所以实际安全 —— 但那是一条没写下来的不变量, // 谁往链上加一个 .then 都可能打破它。把 await 挪进来,安全性就不再依赖它。 try { await this.waitForPrevious(previous, input.signal); const releaseProcessLock = await acquireProcessLock( input.sessionName, input.signal, ); const run = async (args: string[]): Promise => { if (input.signal?.aborted) { return { code: -1, stdout: '', stderr: 'Browser action cancelled' }; } return input.runner(input.bin, args, input.signal); }; try { return await task(run); } finally { await releaseProcessLock(); } } finally { release(); if (this.tails.get(input.sessionName) === tail) this.tails.delete(input.sessionName); } } async run(input: { sessionName: string; bin: string; args: string[]; runner: AgentBrowserRunner; signal?: AbortSignal; }): Promise { return this.exclusive(input, (run) => run(input.args)); } } export const browserService = new BrowserService();