import "./paths-D4_LjrY7.js";
import "./utils-BnlaT0eO.js";
import "./theme-CG-K7m8u.js";
import { t as createSubsystemLogger } from "./subsystem-ocBR131w.js";
import "./runtime-CRvfzclG.js";
import "./exec-CZr_EJHt.js";
import "./agent-scope-CVnlY0oG.js";
import "./model-selection-p6J3l4qF.js";
import "./github-copilot-token-CjSKohyA.js";
import "./emitter-oHo8y9ow.js";
import "./sqlite-wYNyDR1B.js";
import "./reliability-Dl7hbRzF.js";
import "./boolean-DGGu1sGA.js";
import "./env-CvUd308i.js";
import "./validation-p1IK70TM.js";
import { u as resolveConfigSnapshotHash } from "./config-DJ3A5x_1.js";
import "./manifest-registry-U2EDFVP4.js";
import "./image-ops-C0D77XHD.js";
import { t as extractDeliveryInfo } from "./sessions-Ct2d_bGl.js";
import "./message-channel-DSU96OKy.js";
import "./dock-DY0TWaYa.js";
import "./normalize-DgwtBdm-.js";
import "./accounts-BZv5WxME.js";
import "./accounts-DFaskvEN.js";
import "./accounts-T7o73ZSN.js";
import "./bindings-BbaWTQJM.js";
import "./logging-wfRfbMvt.js";
import "./plugins-DYgcd4QJ.js";
import "./paths-DRyRQF9o.js";
import "./tool-images-CRPqucMe.js";
import { a as jsonResult, u as readStringParam } from "./common-oaZdjdal.js";
import "./client-DNPnFy4E.js";
import "./call-C206Z-zx.js";
import { t as callGatewayTool } from "./gateway-DKSm1BrZ.js";
import { o as scheduleGatewaySigusr1Restart } from "./restart-BWS6jdP3.js";
import { i as stringEnum } from "./typebox-BNGTpPE2.js";
import { n as formatDoctorNonInteractiveHint, s as writeRestartSentinel } from "./restart-sentinel-U-T5uwcW.js";
import { Type } from "@sinclair/typebox";

//#region src/agents/tools/automation/gateway-tool.ts
const log = createSubsystemLogger("tools/gateway");
const DEFAULT_UPDATE_TIMEOUT_MS = 20 * 6e4;
function resolveBaseHashFromSnapshot(snapshot) {
	if (!snapshot || typeof snapshot !== "object") return;
	const hashValue = snapshot.hash;
	const rawValue = snapshot.raw;
	return resolveConfigSnapshotHash({
		hash: typeof hashValue === "string" ? hashValue : void 0,
		raw: typeof rawValue === "string" ? rawValue : void 0
	}) ?? void 0;
}
const GatewayToolSchema = Type.Object({
	action: stringEnum([
		"restart",
		"config.get",
		"config.schema",
		"config.apply",
		"config.patch",
		"update.run"
	]),
	delayMs: Type.Optional(Type.Number()),
	reason: Type.Optional(Type.String()),
	gatewayUrl: Type.Optional(Type.String()),
	gatewayToken: Type.Optional(Type.String()),
	timeoutMs: Type.Optional(Type.Number()),
	raw: Type.Optional(Type.String()),
	baseHash: Type.Optional(Type.String()),
	sessionKey: Type.Optional(Type.String()),
	note: Type.Optional(Type.String()),
	restartDelayMs: Type.Optional(Type.Number())
});
function createGatewayTool(opts) {
	return {
		label: "Gateway",
		name: "gateway",
		description: "Restart, apply config, or update the gateway in-place (SIGUSR1). Use config.patch for safe partial config updates (merges with existing). Use config.apply only when replacing entire config. Both trigger restart after writing. Always pass a human-readable completion message via the `note` parameter so the system can deliver it to the user after restart.",
		parameters: GatewayToolSchema,
		execute: async (_toolCallId, args) => {
			const params = args;
			const action = readStringParam(params, "action", { required: true });
			if (action === "restart") {
				if (opts?.config?.commands?.restart !== true) throw new Error("Gateway restart is disabled. Set commands.restart=true to enable.");
				const sessionKey = typeof params.sessionKey === "string" && params.sessionKey.trim() ? params.sessionKey.trim() : opts?.agentSessionKey?.trim() || void 0;
				const delayMs = typeof params.delayMs === "number" && Number.isFinite(params.delayMs) ? Math.floor(params.delayMs) : void 0;
				const reason = typeof params.reason === "string" && params.reason.trim() ? params.reason.trim().slice(0, 200) : void 0;
				const note = typeof params.note === "string" && params.note.trim() ? params.note.trim() : void 0;
				const { deliveryContext, threadId } = extractDeliveryInfo(sessionKey);
				const payload = {
					kind: "restart",
					status: "ok",
					ts: Date.now(),
					sessionKey,
					deliveryContext,
					threadId,
					message: note ?? reason ?? null,
					doctorHint: formatDoctorNonInteractiveHint(),
					stats: {
						mode: "gateway.restart",
						reason
					}
				};
				try {
					await writeRestartSentinel(payload);
				} catch {}
				log.info(`Restart requested (delayMs=${delayMs ?? "default"}, reason=${reason ?? "none"})`);
				return jsonResult(scheduleGatewaySigusr1Restart({
					delayMs,
					reason
				}));
			}
			const gatewayUrl = typeof params.gatewayUrl === "string" && params.gatewayUrl.trim() ? params.gatewayUrl.trim() : void 0;
			const gatewayToken = typeof params.gatewayToken === "string" && params.gatewayToken.trim() ? params.gatewayToken.trim() : void 0;
			const timeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) ? Math.max(1, Math.floor(params.timeoutMs)) : void 0;
			const gatewayOpts = {
				gatewayUrl,
				gatewayToken,
				timeoutMs
			};
			const resolveGatewayWriteMeta = () => {
				return {
					sessionKey: typeof params.sessionKey === "string" && params.sessionKey.trim() ? params.sessionKey.trim() : opts?.agentSessionKey?.trim() || void 0,
					note: typeof params.note === "string" && params.note.trim() ? params.note.trim() : void 0,
					restartDelayMs: typeof params.restartDelayMs === "number" && Number.isFinite(params.restartDelayMs) ? Math.floor(params.restartDelayMs) : void 0
				};
			};
			const resolveConfigWriteParams = async () => {
				const raw = readStringParam(params, "raw", { required: true });
				let baseHash = readStringParam(params, "baseHash");
				if (!baseHash) baseHash = resolveBaseHashFromSnapshot(await callGatewayTool("config.get", gatewayOpts, {}));
				if (!baseHash) throw new Error("Missing baseHash from config snapshot.");
				return {
					raw,
					baseHash,
					...resolveGatewayWriteMeta()
				};
			};
			if (action === "config.get") return jsonResult({
				ok: true,
				result: await callGatewayTool("config.get", gatewayOpts, {})
			});
			if (action === "config.schema") return jsonResult({
				ok: true,
				result: await callGatewayTool("config.schema", gatewayOpts, {})
			});
			if (action === "config.apply") {
				const { raw, baseHash, sessionKey, note, restartDelayMs } = await resolveConfigWriteParams();
				return jsonResult({
					ok: true,
					result: await callGatewayTool("config.apply", gatewayOpts, {
						raw,
						baseHash,
						sessionKey,
						note,
						restartDelayMs
					})
				});
			}
			if (action === "config.patch") {
				const { raw, baseHash, sessionKey, note, restartDelayMs } = await resolveConfigWriteParams();
				return jsonResult({
					ok: true,
					result: await callGatewayTool("config.patch", gatewayOpts, {
						raw,
						baseHash,
						sessionKey,
						note,
						restartDelayMs
					})
				});
			}
			if (action === "update.run") {
				const { sessionKey, note, restartDelayMs } = resolveGatewayWriteMeta();
				return jsonResult({
					ok: true,
					result: await callGatewayTool("update.run", {
						...gatewayOpts,
						timeoutMs: timeoutMs ?? DEFAULT_UPDATE_TIMEOUT_MS
					}, {
						sessionKey,
						note,
						restartDelayMs,
						timeoutMs: timeoutMs ?? DEFAULT_UPDATE_TIMEOUT_MS
					})
				});
			}
			throw new Error(`Unknown action: ${action}`);
		}
	};
}

//#endregion
export { createGatewayTool };