import { c as normalizeOptionalString } from "./string-coerce-DyL154ka.js";
import { t as formatCliCommand } from "./command-format-BPjMauol.js";
import "./agent-scope-cDU1X4Nx.js";
import { c as normalizeAgentId } from "./session-key-BAP1m9Ju.js";
import { n as listAgentIds } from "./agent-scope-config-jq9Xbh_R.js";
import { r as writeRuntimeJson } from "./runtime-yzlkhCoS.js";
import { a as routeLogsToStderr } from "./console-C88cURjL.js";
import { i as getRuntimeConfig } from "./io-8Mkqsky4.js";
import "./config-BZW6i8j3.js";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-BVWE_ra1.js";
import { u as normalizeMessageChannel } from "./message-channel-2-EtCWOg.js";
import { t as ADMIN_SCOPE } from "./operator-scopes-DGvgHuOd.js";
import { l as isGatewayTransportError, r as callGateway, u as randomIdempotencyKey } from "./call-fnd9xGwB.js";
import { m as resolveSendableOutboundReplyParts } from "./reply-payload-Bslhx7AA.js";
import { r as resolveSessionKeyForRequest, t as buildExplicitSessionIdSessionKey } from "./session-DkMeiV71.js";
import { r as withProgress } from "./progress-CE2g1zbv.js";
import { t as agentCommand } from "./agent-command-DEooEi05.js";
import "./agent-DrEiBnFg.js";
import { randomUUID } from "node:crypto";
//#region src/commands/agent-via-gateway.ts
const NO_GATEWAY_TIMEOUT_MS = 2147e6;
const EMBEDDED_FALLBACK_META = {
	transport: "embedded",
	fallbackFrom: "gateway"
};
const GATEWAY_TIMEOUT_FALLBACK_SESSION_PREFIX = "gateway-fallback-";
function protectJsonStdout(opts) {
	if (opts.json === true) routeLogsToStderr();
}
function parseTimeoutSeconds(opts) {
	const raw = opts.timeout !== void 0 ? Number.parseInt(opts.timeout, 10) : opts.cfg.agents?.defaults?.timeoutSeconds ?? 600;
	if (Number.isNaN(raw) || raw < 0) throw new Error(`Invalid --timeout. Use seconds as a non-negative integer, for example --timeout 600. Use --timeout 0 to disable the timeout.`);
	return raw;
}
function formatPayloadForLog(payload) {
	const parts = resolveSendableOutboundReplyParts({
		text: payload.text,
		mediaUrls: payload.mediaUrls,
		mediaUrl: typeof payload.mediaUrl === "string" ? payload.mediaUrl : void 0
	});
	const lines = [];
	if (parts.text) lines.push(parts.text.trimEnd());
	for (const url of parts.mediaUrls) lines.push(`MEDIA:${url}`);
	return lines.join("\n").trimEnd();
}
function isGatewayAgentTimeoutError(err) {
	if (isGatewayTransportError(err)) return err.kind === "timeout";
	return err instanceof Error && err.message.includes("gateway request timeout for agent");
}
function isGatewayAgentEmbeddedFallbackError(err) {
	return isGatewayTransportError(err);
}
function createGatewayTimeoutFallbackSessionId() {
	return `${GATEWAY_TIMEOUT_FALLBACK_SESSION_PREFIX}${randomUUID()}`;
}
function createGatewayTimeoutFallbackSession(agentId) {
	const sessionId = createGatewayTimeoutFallbackSessionId();
	return {
		sessionId,
		sessionKey: buildExplicitSessionIdSessionKey({
			sessionId,
			agentId
		})
	};
}
function buildGatewayJsonResponse(response) {
	const deliveryStatus = response.result?.deliveryStatus;
	if (deliveryStatus === void 0) return response;
	return {
		...response,
		deliveryStatus
	};
}
async function agentViaGatewayCommand(opts, runtime) {
	protectJsonStdout(opts);
	const body = (opts.message ?? "").trim();
	if (!body) throw new Error(`Missing message. Use ${formatCliCommand("openclaw agent --message \"...\" --agent <id>")} or pass --to/--session-id for an existing conversation.`);
	if (!opts.to && !opts.sessionId && !opts.agent) throw new Error(`No target session selected. Use --agent <id>, --session-id <id>, or --to <E.164>. Run ${formatCliCommand("openclaw agents list")} to see agents.`);
	const cfg = getRuntimeConfig();
	const agentIdRaw = opts.agent?.trim();
	const agentId = agentIdRaw ? normalizeAgentId(agentIdRaw) : void 0;
	if (agentId) {
		if (!listAgentIds(cfg).includes(agentId)) throw new Error(`Unknown agent id "${agentIdRaw}". Use "${formatCliCommand("openclaw agents list")}" to see configured agents.`);
	}
	const timeoutSeconds = parseTimeoutSeconds({
		cfg,
		timeout: opts.timeout
	});
	const gatewayTimeoutMs = timeoutSeconds === 0 ? NO_GATEWAY_TIMEOUT_MS : Math.max(1e4, (timeoutSeconds + 30) * 1e3);
	const sessionKey = resolveSessionKeyForRequest({
		cfg,
		agentId,
		to: opts.to,
		sessionId: opts.sessionId
	}).sessionKey;
	const channel = normalizeMessageChannel(opts.channel);
	const idempotencyKey = normalizeOptionalString(opts.runId) || randomIdempotencyKey();
	const modelOverride = normalizeOptionalString(opts.model);
	const hasModelOverride = Boolean(modelOverride);
	const response = await withProgress({
		label: "Waiting for agent reply…",
		indeterminate: true,
		enabled: opts.json !== true
	}, async () => await callGateway({
		method: "agent",
		params: {
			message: body,
			agentId,
			model: modelOverride,
			to: opts.to,
			replyTo: opts.replyTo,
			sessionId: opts.sessionId,
			sessionKey,
			thinking: opts.thinking,
			deliver: Boolean(opts.deliver),
			channel,
			replyChannel: opts.replyChannel,
			replyAccountId: opts.replyAccount,
			bestEffortDeliver: opts.bestEffortDeliver,
			timeout: timeoutSeconds,
			lane: opts.lane,
			extraSystemPrompt: opts.extraSystemPrompt,
			idempotencyKey
		},
		expectFinal: true,
		timeoutMs: gatewayTimeoutMs,
		clientName: hasModelOverride ? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT : GATEWAY_CLIENT_NAMES.CLI,
		mode: hasModelOverride ? GATEWAY_CLIENT_MODES.BACKEND : GATEWAY_CLIENT_MODES.CLI,
		...hasModelOverride ? { scopes: [ADMIN_SCOPE] } : {}
	}));
	if (opts.json) {
		writeRuntimeJson(runtime, buildGatewayJsonResponse(response));
		return response;
	}
	const payloads = (response?.result)?.payloads ?? [];
	if (payloads.length === 0) {
		if (response?.status !== "ok") runtime.log(response?.summary ? response.summary : "No reply from agent.");
		return response;
	}
	for (const payload of payloads) {
		const out = formatPayloadForLog(payload);
		if (out) runtime.log(out);
	}
	return response;
}
async function agentCliCommand(opts, runtime, deps) {
	protectJsonStdout(opts);
	const localOpts = {
		...opts,
		agentId: opts.agent,
		replyAccountId: opts.replyAccount,
		cleanupBundleMcpOnRunEnd: true,
		cleanupCliLiveSessionOnRunEnd: true
	};
	if (opts.local === true) return await agentCommand(localOpts, runtime, deps);
	try {
		return await agentViaGatewayCommand(opts, runtime);
	} catch (err) {
		if (isGatewayAgentTimeoutError(err)) {
			const fallbackSession = createGatewayTimeoutFallbackSession(opts.agent);
			runtime.error?.(`EMBEDDED FALLBACK: Gateway agent timed out; running embedded agent with fresh session ${fallbackSession.sessionId}: ${String(err)}`);
			return await agentCommand({
				...localOpts,
				sessionId: fallbackSession.sessionId,
				sessionKey: fallbackSession.sessionKey,
				runId: fallbackSession.sessionId,
				resultMetaOverrides: {
					...EMBEDDED_FALLBACK_META,
					fallbackReason: "gateway_timeout",
					fallbackSessionId: fallbackSession.sessionId,
					fallbackSessionKey: fallbackSession.sessionKey
				}
			}, runtime, deps);
		}
		if (!isGatewayAgentEmbeddedFallbackError(err)) throw err;
		runtime.error?.(`EMBEDDED FALLBACK: Gateway agent failed; running embedded agent: ${String(err)}`);
		return await agentCommand({
			...localOpts,
			resultMetaOverrides: EMBEDDED_FALLBACK_META
		}, runtime, deps);
	}
}
//#endregion
export { agentCliCommand };
