import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
//#region src/gateway/agent-run-relay.ts
init_logger();
const log = createLogger("Gateway:AgentRunRelay");
const COMPLETE_TTL_MS = 5 * 6e4;
const MAX_EVENTS = 8e3;
var AgentRunRelay = class {
	runs = /* @__PURE__ */ new Map();
	ensureRun(runId, sessionKey) {
		if (this.runs.has(runId)) return;
		this.runs.set(runId, {
			sessionKey,
			events: [],
			done: false,
			waiters: []
		});
	}
	getSessionKey(runId) {
		return this.runs.get(runId)?.sessionKey;
	}
	hasRun(runId) {
		return this.runs.has(runId);
	}
	publish(runId, event) {
		const state = this.runs.get(runId);
		if (!state) return;
		if (state.events.length >= MAX_EVENTS) log.warn({
			runId,
			max: MAX_EVENTS,
			droppedType: event.type
		}, "Relay buffer full; dropping event (resume may miss tool_end/tokens)");
		else state.events.push(event);
		const waiters = state.waiters.splice(0);
		for (const w of waiters) w();
	}
	complete(runId) {
		const state = this.runs.get(runId);
		if (!state) return;
		state.done = true;
		const waiters = state.waiters.splice(0);
		for (const w of waiters) w();
		if (state.cleanupTimer) clearTimeout(state.cleanupTimer);
		state.cleanupTimer = setTimeout(() => {
			this.runs.delete(runId);
		}, COMPLETE_TTL_MS);
	}
	async *subscribe(runId) {
		const state = this.runs.get(runId);
		if (!state) throw new Error("UNKNOWN_RUN");
		let cursor = 0;
		while (true) {
			while (cursor < state.events.length) yield state.events[cursor++];
			if (state.done) break;
			await new Promise((resolve) => {
				state.waiters.push(resolve);
			});
		}
	}
};
//#endregion
export { AgentRunRelay };

//# sourceMappingURL=agent-run-relay.js.map