import { StreamMux } from "../stream/mux.js";
import { GraphRunStream } from "../stream/run-stream.js";
//#region src/pregel/remote-run-stream.ts
const REMOTE_V3_CHANNELS = [
	"values",
	"updates",
	"messages",
	"tools",
	"custom",
	"tasks",
	"checkpoints",
	"lifecycle",
	"input"
];
/**
* Adapts the SDK's remote ThreadStream to the local GraphRunStream shape.
*/
var RemoteGraphRunStream = class extends GraphRunStream {
	#client;
	#thread;
	#runId;
	#abortController;
	constructor(params) {
		const abortController = params.abortController ?? new AbortController();
		super([], new StreamMux(), 0, 0, params.thread.extensions, abortController);
		this.#client = params.client;
		this.#thread = params.thread;
		this.#runId = params.runId;
		this.#abortController = abortController;
	}
	[Symbol.asyncIterator]() {
		return this.#iterateEvents()[Symbol.asyncIterator]();
	}
	get subgraphs() {
		return this.#thread.subgraphs;
	}
	get values() {
		return this.#thread.values;
	}
	get messages() {
		return this.#thread.messages;
	}
	get lifecycle() {
		return this.#iterateLifecycle();
	}
	messagesFrom(node) {
		const messages = this.messages;
		return { async *[Symbol.asyncIterator]() {
			for await (const message of messages) if (message.node === node) yield message;
		} };
	}
	get output() {
		return this.#thread.output;
	}
	get interrupted() {
		return this.#thread.interrupted;
	}
	get interrupts() {
		return this.#thread.interrupts;
	}
	abort(reason) {
		if (this.#abortController.signal.aborted) return;
		this.#abortController.abort(reason);
		this.#cancelAndClose();
	}
	get signal() {
		return this.#abortController.signal;
	}
	get thread() {
		return this.#thread;
	}
	async #cancelAndClose() {
		try {
			if (this.#runId != null) await this.#client.runs.cancel(this.#thread.threadId, this.#runId, false);
		} catch {}
		try {
			await this.#thread.close();
		} catch {}
	}
	async *#iterateEvents() {
		const subscription = await this.#thread.subscribe({ channels: REMOTE_V3_CHANNELS });
		try {
			for await (const event of subscription) yield event;
		} finally {
			await subscription.unsubscribe();
		}
	}
	async *#iterateLifecycle() {
		const subscription = await this.#thread.subscribe({ channels: ["lifecycle"] });
		try {
			for await (const event of subscription) yield eventToLifecycleEntry(event);
		} finally {
			await subscription.unsubscribe();
		}
	}
};
function eventToLifecycleEntry(event) {
	return {
		...event.params.data,
		namespace: event.params.namespace,
		timestamp: event.params.timestamp
	};
}
//#endregion
export { RemoteGraphRunStream };

//# sourceMappingURL=remote-run-stream.js.map