import { createLogger } from "../utils/logger/index.js";
import { init_logger } from "../utils/logger.js";
//#region src/gateway/clarify-bridge.ts
init_logger();
const log = createLogger("gateway:clarify");
/** User inactivity window before pending clarification is rejected (web/Telegram, etc.). */
const CLARIFY_USER_RESPONSE_TIMEOUT_MS = 300 * 1e3;
/**
* Pending user answers for the `clarify` tool (web UI, Telegram, etc.).
*/
var ClarifyBridge = class {
	pending = /* @__PURE__ */ new Map();
	/** sessionKey → requestId when waiting for a free-text reply (no multiple-choice). */
	pendingFreeTextBySession = /* @__PURE__ */ new Map();
	startRequest(opts) {
		const { sessionKey, runId, relay, publishSse, request, deliver } = opts;
		const requestId = crypto.randomUUID();
		const hasChoices = Array.isArray(request.choices) && request.choices.length >= 2;
		const needsFreeText = !hasChoices;
		return new Promise((resolve, reject) => {
			const failStart = (err) => {
				const e = this.deletePending(requestId);
				if (e) e.reject(err instanceof Error ? err : new Error(String(err)));
			};
			const timeout = setTimeout(() => {
				const entry = this.deletePending(requestId);
				if (entry) entry.reject(/* @__PURE__ */ new Error("Clarification timeout: user did not respond within 5 minutes"));
			}, CLARIFY_USER_RESPONSE_TIMEOUT_MS);
			this.pending.set(requestId, {
				runId: runId ?? "",
				sessionKey,
				choices: hasChoices ? request.choices : void 0,
				resolve,
				reject,
				timeout
			});
			if (needsFreeText) this.pendingFreeTextBySession.set(sessionKey, requestId);
			const payload = {
				type: "clarify_request",
				requestId,
				question: request.question,
				choices: request.choices,
				default: request.default
			};
			if (runId) relay.publish(runId, payload);
			try {
				publishSse?.(payload);
			} catch (err) {
				log.warn({
					err,
					requestId
				}, "clarify SSE publish failed");
			}
			if (deliver) deliver({
				sessionKey,
				requestId,
				request
			}).catch(failStart);
		});
	}
	deletePending(requestId) {
		const entry = this.pending.get(requestId);
		if (!entry) return void 0;
		clearTimeout(entry.timeout);
		this.pending.delete(requestId);
		this.clearFreeTextSlot(entry.sessionKey, requestId);
		return entry;
	}
	clearFreeTextSlot(sessionKey, requestId) {
		if (this.pendingFreeTextBySession.get(sessionKey) === requestId) this.pendingFreeTextBySession.delete(sessionKey);
	}
	/**
	* Consume the user's next text message as the clarify answer (Telegram DM/group).
	*/
	tryConsumeFreeTextReply(sessionKey, text) {
		const requestId = this.pendingFreeTextBySession.get(sessionKey);
		if (!requestId) return false;
		return this.handleResponse(requestId, text);
	}
	handleChoiceCallback(requestId, choiceIndex) {
		const entry = this.pending.get(requestId);
		if (!entry?.choices || choiceIndex < 0 || choiceIndex >= entry.choices.length) return false;
		return this.handleResponse(requestId, entry.choices[choiceIndex]);
	}
	handleResponse(requestId, answer) {
		const entry = this.deletePending(requestId);
		if (!entry) return false;
		entry.resolve(answer.trim());
		return true;
	}
	cancelForRun(runId) {
		for (const [id, entry] of [...this.pending]) if (entry.runId === runId) this.deletePending(id)?.reject(/* @__PURE__ */ new Error("Clarification cancelled: agent run aborted"));
	}
	dispose() {
		for (const [id, entry] of [...this.pending]) {
			clearTimeout(entry.timeout);
			entry.reject(/* @__PURE__ */ new Error("Gateway shutting down"));
			this.pending.delete(id);
		}
		this.pending.clear();
		this.pendingFreeTextBySession.clear();
	}
};
//#endregion
export { CLARIFY_USER_RESPONSE_TIMEOUT_MS, ClarifyBridge };

//# sourceMappingURL=clarify-bridge.js.map