import { c as resolveAgentWorkspaceDir, r as listAgentIds } from "../../run-with-concurrency-KRm2JLiI.js";
import "../../paths-BANciGCS.js";
import { i as defaultRuntime, t as createSubsystemLogger } from "../../subsystem-CgTeEziN.js";
import { B as resolveAgentIdFromSessionKey } from "../../workspace-Cf_FbQuR.js";
import "../../logger-n2Gpq0AH.js";
import "../../model-selection-BkYBmupV.js";
import "../../github-copilot-token-DG2sYnVk.js";
import { o as isGatewayStartupEvent } from "../../legacy-names-DEoEk9jn.js";
import "../../thinking-BSAfU9e5.js";
import { n as SILENT_REPLY_TOKEN } from "../../tokens-DDwNxggx.js";
import { o as agentCommand, s as createDefaultDeps } from "../../pi-embedded-C-fQc1WY.js";
import "../../accounts-yr7rL--h.js";
import "../../plugins-DE02D3EJ.js";
import "../../send-BMLdAiDH.js";
import "../../send-DVafQkY6.js";
import "../../deliver-3KBqsj7a.js";
import "../../diagnostic-D5XKhC_g.js";
import "../../accounts-kYYknnjO.js";
import "../../image-ops-CH-bKC6L.js";
import "../../send-C7CON8yb.js";
import "../../pi-model-discovery-B1S8d5YJ.js";
import { Dt as resolveMainSessionKey, J as updateSessionStore, Tt as resolveAgentMainSessionKey, W as loadSessionStore } from "../../pi-embedded-helpers-CIxZUqQl.js";
import "../../chrome-ANFAbsTM.js";
import "../../frontmatter-BqvyjOGD.js";
import "../../skills-GUmCCgYD.js";
import "../../path-alias-guards-Bj2dz01O.js";
import "../../redact-Asry9UBT.js";
import "../../errors-DtMXuwMd.js";
import "../../fs-safe-DLFU_2Jt.js";
import "../../proxy-env-yOHn3u7d.js";
import "../../store-Dm9ec8nX.js";
import "../../accounts-D_3bkTzM.js";
import { s as resolveStorePath } from "../../paths-DiVFtCJv.js";
import "../../tool-images-DiQlk_40.js";
import "../../image-BE5qITiS.js";
import "../../audio-transcription-runner-XipAmvqa.js";
import "../../fetch-DCzFGsuQ.js";
import "../../fetch-guard-DZlxlct6.js";
import "../../api-key-rotation-BAaWeojM.js";
import "../../proxy-fetch-D8ON61si.js";
import "../../ir-BYKelQNp.js";
import "../../render-95l30zcf.js";
import "../../target-errors-Cjz4vggK.js";
import "../../commands-registry-CuTRGuZ3.js";
import "../../skill-commands-B4zt0wTA.js";
import "../../fetch-BAzGA01Q.js";
import "../../channel-activity-O-d_7wHA.js";
import "../../tables-oq7iWlSA.js";
import "../../send-BtZ4CakX.js";
import "../../outbound-attachment-wFQ0sOG6.js";
import "../../send-6vy4Ubai.js";
import "../../proxy-DULbDMaI.js";
import "../../manager-Bn0_zYXb.js";
import "../../query-expansion-DSXtYSpj.js";
import fs from "node:fs/promises";
import path from "node:path";
import crypto from "node:crypto";

//#region src/gateway/boot.ts
function generateBootSessionId() {
	return `boot-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").replace("T", "_").replace("Z", "")}-${crypto.randomUUID().slice(0, 8)}`;
}
const log$1 = createSubsystemLogger("gateway/boot");
const BOOT_FILENAME = "BOOT.md";
function buildBootPrompt(content) {
	return [
		"You are running a boot check. Follow BOOT.md instructions exactly.",
		"",
		"BOOT.md:",
		content,
		"",
		"If BOOT.md asks you to send a message, use the message tool (action=send with channel + target).",
		"Use the `target` field (not `to`) for message tool destinations.",
		`After sending with the message tool, reply with ONLY: ${SILENT_REPLY_TOKEN}.`,
		`If nothing needs attention, reply with ONLY: ${SILENT_REPLY_TOKEN}.`
	].join("\n");
}
async function loadBootFile(workspaceDir) {
	const bootPath = path.join(workspaceDir, BOOT_FILENAME);
	try {
		const trimmed = (await fs.readFile(bootPath, "utf-8")).trim();
		if (!trimmed) return { status: "empty" };
		return {
			status: "ok",
			content: trimmed
		};
	} catch (err) {
		if (err.code === "ENOENT") return { status: "missing" };
		throw err;
	}
}
function snapshotMainSessionMapping(params) {
	const agentId = resolveAgentIdFromSessionKey(params.sessionKey);
	const storePath = resolveStorePath(params.cfg.session?.store, { agentId });
	try {
		const entry = loadSessionStore(storePath, { skipCache: true })[params.sessionKey];
		if (!entry) return {
			storePath,
			sessionKey: params.sessionKey,
			canRestore: true,
			hadEntry: false
		};
		return {
			storePath,
			sessionKey: params.sessionKey,
			canRestore: true,
			hadEntry: true,
			entry: structuredClone(entry)
		};
	} catch (err) {
		log$1.debug("boot: could not snapshot main session mapping", {
			sessionKey: params.sessionKey,
			error: String(err)
		});
		return {
			storePath,
			sessionKey: params.sessionKey,
			canRestore: false,
			hadEntry: false
		};
	}
}
async function restoreMainSessionMapping(snapshot) {
	if (!snapshot.canRestore) return;
	try {
		await updateSessionStore(snapshot.storePath, (store) => {
			if (snapshot.hadEntry && snapshot.entry) {
				store[snapshot.sessionKey] = snapshot.entry;
				return;
			}
			delete store[snapshot.sessionKey];
		}, { activeSessionKey: snapshot.sessionKey });
		return;
	} catch (err) {
		return err instanceof Error ? err.message : String(err);
	}
}
async function runBootOnce(params) {
	const bootRuntime = {
		log: () => {},
		error: (message) => log$1.error(String(message)),
		exit: defaultRuntime.exit
	};
	let result;
	try {
		result = await loadBootFile(params.workspaceDir);
	} catch (err) {
		const message = err instanceof Error ? err.message : String(err);
		log$1.error(`boot: failed to read ${BOOT_FILENAME}: ${message}`);
		return {
			status: "failed",
			reason: message
		};
	}
	if (result.status === "missing" || result.status === "empty") return {
		status: "skipped",
		reason: result.status
	};
	const sessionKey = params.agentId ? resolveAgentMainSessionKey({
		cfg: params.cfg,
		agentId: params.agentId
	}) : resolveMainSessionKey(params.cfg);
	const message = buildBootPrompt(result.content ?? "");
	const sessionId = generateBootSessionId();
	const mappingSnapshot = snapshotMainSessionMapping({
		cfg: params.cfg,
		sessionKey
	});
	let agentFailure;
	try {
		await agentCommand({
			message,
			sessionKey,
			sessionId,
			deliver: false,
			senderIsOwner: true
		}, bootRuntime, params.deps);
	} catch (err) {
		agentFailure = err instanceof Error ? err.message : String(err);
		log$1.error(`boot: agent run failed: ${agentFailure}`);
	}
	const mappingRestoreFailure = await restoreMainSessionMapping(mappingSnapshot);
	if (mappingRestoreFailure) log$1.error(`boot: failed to restore main session mapping: ${mappingRestoreFailure}`);
	if (!agentFailure && !mappingRestoreFailure) return { status: "ran" };
	return {
		status: "failed",
		reason: [agentFailure ? `agent run failed: ${agentFailure}` : void 0, mappingRestoreFailure ? `mapping restore failed: ${mappingRestoreFailure}` : void 0].filter((part) => Boolean(part)).join("; ")
	};
}

//#endregion
//#region src/hooks/bundled/boot-md/handler.ts
const log = createSubsystemLogger("hooks/boot-md");
const runBootChecklist = async (event) => {
	if (!isGatewayStartupEvent(event)) return;
	if (!event.context.cfg) return;
	const cfg = event.context.cfg;
	const deps = event.context.deps ?? createDefaultDeps();
	const agentIds = listAgentIds(cfg);
	for (const agentId of agentIds) {
		const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
		const result = await runBootOnce({
			cfg,
			deps,
			workspaceDir,
			agentId
		});
		if (result.status === "failed") {
			log.warn("boot-md failed for agent startup run", {
				agentId,
				workspaceDir,
				reason: result.reason
			});
			continue;
		}
		if (result.status === "skipped") log.debug("boot-md skipped for agent startup run", {
			agentId,
			workspaceDir,
			reason: result.reason
		});
	}
};

//#endregion
export { runBootChecklist as default };