/** Bounded scheduling, not an authorization limit. Results retain input order. */ export async function orderedPool(items: readonly T[], concurrency: number, run: (item: T, index: number) => Promise): Promise { if (!Number.isSafeInteger(concurrency) || concurrency < 1) { throw new Error('toolConcurrency must be a positive safe integer'); } const results = new Array(items.length); let next = 0; const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => { while (next < items.length) { const index = next++; results[index] = await run(items[index]!, index); } }); // Drain active workers even when a host callback fails. const outcomes = await Promise.allSettled(workers); const failure = outcomes.find(result => result.status === 'rejected'); if (failure?.status === 'rejected') throw failure.reason; return results; }