import { buildPromptEventData } from './interactiveTaskKinds.js';
import { SystemTaskExecutionError } from './runSystemTask.js';
class AsyncQueue {
    items = [];
    waiters = [];
    push(value) {
        const waiter = this.waiters.shift();
        if (waiter) {
            waiter(value);
            return;
        }
        this.items.push(value);
    }
    async shift() {
        const next = this.items.shift();
        if (typeof next !== 'undefined') {
            return next;
        }
        return await new Promise((resolve) => {
            this.waiters.push(resolve);
        });
    }
}
export function createExecutionRunnerFromKind(kind) {
    return async function* runKind(params, context) {
        const queue = new AsyncQueue();
        void kind.run({
            params: params,
            signal: context.signal,
            emit(event) {
                queue.push({
                    type: 'event',
                    value: event,
                });
            },
            async prompt(prompt) {
                queue.push({
                    type: 'event',
                    value: {
                        type: 'prompt',
                        ...(prompt.stepId ? { stepId: prompt.stepId } : {}),
                        message: prompt.message,
                        data: buildPromptEventData(prompt),
                    },
                });
                throw new SystemTaskExecutionError('prompt_required', prompt.message);
            },
        }).then((value) => {
            queue.push({
                type: 'return',
                value,
            });
        }, (error) => {
            queue.push({
                type: 'error',
                error,
            });
        });
        while (true) {
            const item = await queue.shift();
            if (item.type === 'event') {
                yield item.value;
                continue;
            }
            if (item.type === 'error') {
                throw item.error;
            }
            return item.value;
        }
    };
}
//# sourceMappingURL=createExecutionRunnerFromKind.js.map