import { realpath } from 'node:fs/promises'; import { isAbsolute, relative, resolve, sep } from 'node:path'; import { CONFIG_LIMITS } from '../../config/numericLimits.js'; interface Waiter { owner: string; cwd: string; scopes: string[]; maxConcurrent: number; onStatus?: (status: LeaseStatus) => void; signal?: AbortSignal; onAbort?: () => void; resolve: (release: () => void) => void; reject: (error: Error) => void; } interface ActiveLease { cwd: string; scopes: string[] } const active: ActiveLease[] = []; const waiters: Waiter[] = []; let running = 0; let lastOwner: string | undefined; export interface LeaseStatus { phase: 'queued' | 'acquired'; queuePosition?: number; activeCount: number; maxConcurrent: number; } function overlaps(a: string, b: string): boolean { // realpath cannot canonicalize the spelling of a not-yet-created file. // Compare Windows lease keys conservatively; never widen write authorization. if (process.platform === 'win32') { a = a.toLowerCase(); b = b.toLowerCase(); } return a === b || a.startsWith(b.endsWith(sep) ? b : b + sep) || b.startsWith(a.endsWith(sep) ? a : a + sep); } function conflicts(cwd: string, scopes: string[]): boolean { return active.some((lease) => lease.scopes.some((left) => scopes.some((right) => overlaps(left, right)))); } function publishQueue(): void { waiters.forEach((waiter, index) => waiter.onStatus?.({ phase: 'queued', queuePosition: index + 1, activeCount: running, maxConcurrent: waiter.maxConcurrent, })); } function drain(): void { // Prefer another root when capacity becomes available; retain FIFO within roots. const nextOwner = waiters.find((w) => w.owner !== lastOwner && running < w.maxConcurrent && !conflicts(w.cwd, w.scopes))?.owner; if (nextOwner) waiters.sort((a, b) => Number(b.owner === nextOwner) - Number(a.owner === nextOwner)); for (let i = 0; i < waiters.length;) { const waiter = waiters[i]!; if (running >= waiter.maxConcurrent) { i++; continue; } if (conflicts(waiter.cwd, waiter.scopes)) { i++; continue; } waiters.splice(i, 1); if (waiter.onAbort) waiter.signal?.removeEventListener('abort', waiter.onAbort); running++; lastOwner = waiter.owner; const lease = { cwd: waiter.cwd, scopes: waiter.scopes }; active.push(lease); waiter.onStatus?.({ phase: 'acquired', activeCount: running, maxConcurrent: waiter.maxConcurrent }); waiter.resolve(() => { const index = active.indexOf(lease); if (index < 0) return; if (index >= 0) active.splice(index, 1); running = Math.max(0, running - 1); drain(); }); } publishQueue(); } export async function normalizeWriteScopes(cwd: string, rawScopes: readonly string[] | undefined): Promise { const lexicalRoot = resolve(cwd); const physicalRoot = await realpath(lexicalRoot).catch(() => lexicalRoot); if (!rawScopes?.length) return [physicalRoot]; const normalized = new Set(); for (const raw of rawScopes) { const value = raw.trim(); if (!value || isAbsolute(value)) throw new Error(`write_scopes 必须是工作目录内的相对路径:${raw}`); const lexical = resolve(lexicalRoot, value); const rel = relative(lexicalRoot, lexical); if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error(`write_scopes 越过工作目录:${raw}`); const physical = await realpath(lexical).catch(async () => { let ancestor = resolve(lexical, '..'); while (true) { const physicalAncestor = await realpath(ancestor).catch(() => undefined); if (physicalAncestor) return resolve(physicalAncestor, relative(ancestor, lexical)); const parent = resolve(ancestor, '..'); if (parent === ancestor) throw new Error(`无法解析路径:${raw}`); ancestor = parent; } }); const physicalRel = relative(physicalRoot, physical); if (physicalRel === '..' || physicalRel.startsWith(`..${sep}`) || isAbsolute(physicalRel)) throw new Error(`write_scopes 经过符号链接越过工作目录:${raw}`); normalized.add(physical); } return [...normalized].sort(); } export async function acquireSubagentLease( cwd: string, scopes: string[], maxConcurrent = 3, options: { signal?: AbortSignal; onStatus?: (status: LeaseStatus) => void; owner?: string } = {}, ): Promise<() => void> { // The configured ceiling is the only bound (numericLimits.ts); a second // hard-coded cap silently ignored values the settings page accepts. const safeMax = Math.max(1, Math.min(CONFIG_LIMITS.subagentMaxConcurrent.max, maxConcurrent)); return new Promise((resolveLease, reject) => { if (options.signal?.aborted) return reject(new DOMException('Aborted', 'AbortError')); const waiter: Waiter = { owner: options.owner ?? cwd, cwd, scopes, maxConcurrent: safeMax, onStatus: options.onStatus, signal: options.signal, resolve: resolveLease, reject }; waiter.onAbort = () => { const index = waiters.indexOf(waiter); if (index >= 0) waiters.splice(index, 1); publishQueue(); reject(new DOMException('Aborted', 'AbortError')); }; options.signal?.addEventListener('abort', waiter.onAbort, { once: true }); waiters.push(waiter); // 不在这里 publishQueue:立即拿到租约的 waiter 会被 drain 直接报 'acquired', // 抢先报一次 'queued' 会让每个子任务都闪一下幻影「排队中」;真排队者由 drain // 结尾的 publishQueue 覆盖。 drain(); }); }