import { randomUUID } from 'node:crypto'; // 这里曾 re-export `tools/computeruse/humanBoundary.js` 的 // `detectComputerHumanBoundary` —— 一个**通用**的人机接管模块 // (surface: 'browser' | 'computer')顶头挂一个具体工具的符号, // 是最容易被后人当成"通用能力"到处引的形状。已移除:需要它的消费方 // 直接从 `tools/computeruse/humanBoundary.js` 取,谁用谁依赖,路径如实。 export type HumanInterventionReason = | 'password' | 'otp' | 'captcha' | 'qr_login' | 'login' | 'permission' | 'security_warning' | 'blocked' | 'manual'; export type HumanInterventionSurface = 'browser' | 'computer'; export interface HumanInterventionIdentity { ownerId: string; conversationKey: string; runId: string; } export interface HumanInterventionTarget { tabId?: string; origin?: string; appId?: string; windowId?: string; } export interface HumanInterventionRequest extends HumanInterventionIdentity { surface: HumanInterventionSurface; reason: HumanInterventionReason; sanitizedSummary: string; target?: HumanInterventionTarget; expiresAt?: number; } export interface PendingHumanIntervention extends HumanInterventionRequest { id: string; resumeToken: string; requestedAt: number; } export type HumanInterventionResolutionStatus = 'resumed' | 'cancelled' | 'expired' | 'aborted'; export interface HumanInterventionResolution { status: HumanInterventionResolutionStatus; intervention: PendingHumanIntervention; resolvedAt: number; waitedMs: number; } export type HumanInterventionEvent = | { type: 'started'; intervention: PendingHumanIntervention } | { type: 'resolved'; resolution: HumanInterventionResolution }; export interface HumanInterventionCredential extends HumanInterventionIdentity { id: string; resumeToken: string; } type Waiter = { resolve: (resolution: HumanInterventionResolution) => void; reject: (error: unknown) => void; cleanup: () => void; }; type ActiveIntervention = { pending: PendingHumanIntervention; waiters: Set; expiryTimer?: ReturnType; }; function interventionKey(identity: HumanInterventionIdentity): string { return `${identity.ownerId}\u0000${identity.conversationKey}\u0000${identity.runId}`; } function sameIdentity( pending: PendingHumanIntervention, credential: HumanInterventionCredential, ): boolean { return pending.id === credential.id && pending.resumeToken === credential.resumeToken && pending.ownerId === credential.ownerId && pending.conversationKey === credential.conversationKey && pending.runId === credential.runId; } /** * Process-local coordination for sensitive handoffs. It deliberately stores no * secret input: only a sanitized reason and the run identity cross this boundary. */ export class HumanInterventionCoordinator { private readonly active = new Map(); private readonly byId = new Map(); private readonly listeners = new Set<(event: HumanInterventionEvent) => void>(); request(input: HumanInterventionRequest): PendingHumanIntervention { const key = interventionKey(input); const current = this.active.get(key); if (current) return current.pending; const requestedAt = Date.now(); const pending: PendingHumanIntervention = { ...input, id: randomUUID(), resumeToken: randomUUID(), requestedAt, }; const entry: ActiveIntervention = { pending, waiters: new Set() }; if (pending.expiresAt !== undefined) { const delay = Math.max(0, pending.expiresAt - requestedAt); entry.expiryTimer = setTimeout(() => { this.resolveEntry(entry, 'expired'); }, delay); entry.expiryTimer.unref?.(); } this.active.set(key, entry); this.byId.set(pending.id, entry); this.emit({ type: 'started', intervention: pending }); return pending; } get(identity: HumanInterventionIdentity): PendingHumanIntervention | undefined { return this.active.get(interventionKey(identity))?.pending; } subscribe(listener: (event: HumanInterventionEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } wait(id: string, signal?: AbortSignal): Promise { const entry = this.byId.get(id); if (!entry) return Promise.reject(new Error('人工介入请求不存在或已结束')); return new Promise((resolve, reject) => { let settled = false; const waiter: Waiter = { resolve: (resolution) => { if (settled) return; settled = true; waiter.cleanup(); resolve(resolution); }, reject: (error) => { if (settled) return; settled = true; waiter.cleanup(); reject(error); }, cleanup: () => signal?.removeEventListener('abort', onAbort), }; const onAbort = () => { entry.waiters.delete(waiter); waiter.reject(new DOMException('aborted', 'AbortError')); }; entry.waiters.add(waiter); signal?.addEventListener('abort', onAbort, { once: true }); if (signal?.aborted) onAbort(); }); } resume(credential: HumanInterventionCredential): boolean { return this.resolveCredential(credential, 'resumed'); } cancel(credential: HumanInterventionCredential): boolean { return this.resolveCredential(credential, 'cancelled'); } abort(identity: HumanInterventionIdentity): boolean { const entry = this.active.get(interventionKey(identity)); if (!entry) return false; this.resolveEntry(entry, 'aborted'); return true; } private resolveCredential( credential: HumanInterventionCredential, status: Extract, ): boolean { const entry = this.byId.get(credential.id); if (!entry || !sameIdentity(entry.pending, credential)) return false; this.resolveEntry(entry, status); return true; } private resolveEntry(entry: ActiveIntervention, status: HumanInterventionResolutionStatus): void { const key = interventionKey(entry.pending); if (this.active.get(key) !== entry || this.byId.get(entry.pending.id) !== entry) return; this.active.delete(key); this.byId.delete(entry.pending.id); if (entry.expiryTimer) clearTimeout(entry.expiryTimer); const resolvedAt = Date.now(); const resolution: HumanInterventionResolution = { status, intervention: entry.pending, resolvedAt, waitedMs: Math.max(0, resolvedAt - entry.pending.requestedAt), }; for (const waiter of [...entry.waiters]) waiter.resolve(resolution); entry.waiters.clear(); this.emit({ type: 'resolved', resolution }); } private emit(event: HumanInterventionEvent): void { for (const listener of this.listeners) listener(event); } }