export class ConversationTurnRuntime {
    session;
    abortController;
    constructor(session) {
        this.session = session;
    }
    get isRunning() {
        return this.abortController !== undefined;
    }
    async run(options) {
        if (this.abortController) {
            throw new Error("conversation turn is already running");
        }
        const abortController = new AbortController();
        this.abortController = abortController;
        try {
            let result;
            try {
                const stream = this.session.events(abortController.signal);
                while (true) {
                    const next = await stream.next();
                    if (next.done) {
                        result = next.value;
                        break;
                    }
                    options?.onEvent?.(next.value);
                    if (abortController.signal.aborted) {
                        await stream.return?.({ aborted: true });
                        break;
                    }
                }
            }
            catch (err) {
                if (!abortController.signal.aborted) {
                    throw err;
                }
            }
            return {
                aborted: abortController.signal.aborted || Boolean(result?.aborted),
                ...(result?.blocked ? { blocked: result.blocked } : {}),
            };
        }
        finally {
            if (this.abortController === abortController) {
                this.abortController = undefined;
            }
        }
    }
    interrupt() {
        const abortController = this.abortController;
        if (!abortController || abortController.signal.aborted) {
            return false;
        }
        abortController.abort();
        return true;
    }
}
//# sourceMappingURL=conversation_turn_runtime.js.map