/** * A minimal promise concurrency limiter (p-limit semantics) with zero deps. * Shared across a workflow and any nested workflow() so the global * min(16, cores-2) cap holds across nesting, matching Claude Code. */ export type Limiter = (fn: () => Promise) => Promise; export function createLimiter(concurrency: number): Limiter { const max = Math.max(1, Math.floor(concurrency)); let active = 0; const queue: Array<() => void> = []; const next = () => { if (active >= max) return; const run = queue.shift(); if (run) run(); }; return function limit(fn: () => Promise): Promise { return new Promise((resolve, reject) => { const run = () => { active++; // Run on a microtask so `active` is already incremented before fn starts. Promise.resolve() .then(fn) .then(resolve, reject) .finally(() => { active--; next(); }); }; queue.push(run); next(); }); }; }