import "./paths-WcYpcMAY.js";
import { o as createSubsystemLogger } from "./entry.js";
import "./auth-profiles-CaNK0cUT.js";
import "./exec-CmvuUufz.js";
import "./agent-scope-E2aR3Ci_.js";
import "./github-copilot-token-CKOQDjEZ.js";
import "./emitter-BKo8D7Oj.js";
import "./sqlite-CVrhPija.js";
import "./reliability-BnL75OlZ.js";
import "./manifest-registry-AgGLF4V7.js";
import "./validation-B00oOkJ3.js";
import { u as resolveConfigSnapshotHash } from "./config-CoCeK5B2.js";
import "./client-DtQEs2_8.js";
import "./call-CkgY6Bq7.js";
import "./message-channel-DKXbq8GH.js";
import { t as extractDeliveryInfo } from "./sessions-CFJLtXRH.js";
import "./accounts-CNwod9BY.js";
import "./accounts-C3i8BBiA.js";
import "./normalize-CRf-uoB2.js";
import "./bindings-B1hNZin3.js";
import "./logging-BiuZwq5D.js";
import "./plugins-DMpYx7kb.js";
import "./image-ops-D0pBQqKh.js";
import "./dock-BvRrtCWj.js";
import "./accounts-CdYdWklO.js";
import "./paths-CDTtU20P.js";
import "./tool-images-B4eVOjD0.js";
import { a as jsonResult, u as readStringParam } from "./common-CxpUJZLb.js";
import { t as callGatewayTool } from "./gateway-CWnGRD4E.js";
import { o as scheduleGatewaySigusr1Restart } from "./restart-Nxw1Kl9F.js";
import { i as stringEnum } from "./typebox-C14oleuH.js";
import { n as formatDoctorNonInteractiveHint, s as writeRestartSentinel } from "./restart-sentinel-DlT1-lDY.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 };