/** Bridge callback progress to a generator, draining events before returning or throwing. */ export async function* progressStream( run: (emit: (event: Event) => void) => Promise, ): AsyncGenerator { const queue: Event[] = []; let wake: (() => void) | undefined; let finished = false; const notify = () => { wake?.(); wake = undefined; }; const result = Promise.resolve().then(() => run((event) => { queue.push(event); notify(); }), ); const settled = result .then( (value) => ({ ok: true as const, value }), (error) => ({ ok: false as const, error }), ) .then((outcome) => { finished = true; notify(); return outcome; }); try { while (!finished || queue.length) { while (queue.length) yield queue.shift()!; if (!finished) await new Promise((resolve) => { wake = resolve; }); } const outcome = await settled; if (!outcome.ok) throw outcome.error; return outcome.value; } finally { // Generator disposal must not orphan a still-running tool. Cancellation is // owned by the caller's AbortSignal; this boundary only drains settlement. await settled; } }