import "./pi-embedded-helpers-Ny2JybJV.js";
import { St as requestHeartbeatNow, T as loadSessionEntry, lr as enqueueSystemEvent } from "./reply-CL83zh9t.js";
import { s as defaultRuntime } from "./subsystem-hATE68va.js";
import "./paths-VdmjGGyc.js";
import "./theme-C5EwWDWE.js";
import "./ansi-By7x1TI7.js";
import { u as normalizeMainKey } from "./session-key-B2OXLVi_.js";
import "./utils-D019Z2NU.js";
import "./exec-xrC0ejqg.js";
import "./koi-scope-D8R_V4oO.js";
import "./model-selection-Bue40sP3.js";
import "./dist-CUiRTtgg.js";
import "./dist-cjs-DKbiqPag.js";
import "./boolean-CBeSt-pi.js";
import "./env-Dliiu-O6.js";
import "./github-copilot-token-CNBLk7kR.js";
import { o as loadConfig } from "./config-CJCyYQfd.js";
import "./manifest-registry-oBOOUSYE.js";
import { r as normalizeChannelId } from "./plugins-4Dg2aV3Z.js";
import { l as updateSessionStore } from "./sessions-p608GJQF.js";
import "./image-Cm8pagSS.js";
import "./dist-qohLth5U.js";
import "./lib-DySFL26z.js";
import "./src-CuBVmkDD.js";
import "./core-CYIM8X9C.js";
import "./pi-model-discovery-BJB6xKfm.js";
import "./sandbox-CH6Z4NF9.js";
import "./chrome-qnrH3SE9.js";
import "./skills-belB1fF2.js";
import "./routes-B_ID_OU2.js";
import "./server-context-BfQWGTuX.js";
import "./image-ops-D4trOw4b.js";
import "./message-channel-DFpLxeOe.js";
import "./logging-DbUpYaKc.js";
import "./accounts-Grk0tpBF.js";
import "./paths-DeB-Vw2o.js";
import "./tool-images-BotO6WKu.js";
import "./redact-AS2CBwfj.js";
import "./tool-display-DcE_Uu-6.js";
import "./deliver-DaqlX5n9.js";
import "./dispatcher-CvOxCTiO.js";
import "./dist-Cldz93r6.js";
import "./pi-tool-definition-adapter-Bm-MOj6J.js";
import "./manager-M02jv6fr.js";
import "./sqlite-ciTubP4r.js";
import "./warnings-WXNLPyeJ.js";
import "./proxy-from-env-CZI-BeJ4.js";
import "./login-qr-jct4RHB3.js";
import "./channel-summary-CaRm5ceF.js";
import "./device-identity-Bb4mQJBL.js";
import "./net-CgTtDqcj.js";
import "./call-CJHT-9_x.js";
import "./koi-events-mTBifGCl.js";
import "./pairing-store-C3Jk-2f9.js";
import "./links-RRRDj3kH.js";
import "./progress-DpXGZ7eP.js";
import "./node-pairing-C8IUm3Xm.js";
import "./pi-tools.policy-C2-uMacJ.js";
import "./onboard-helpers-BfbPZ2qa.js";
import "./prompt-style-VlLGOsyw.js";
import "./pairing-labels-gxX2Garz.js";
import "./satisfies-Bvl3f_kk.js";
import "./session-cost-usage-C1dZUsv0.js";
import "./control-service-Deb7vSlB.js";
import "./channel-selection-C4X4L8u3.js";
import "./event-log-Bp_kcsW9.js";
import "./deps-C09ak7pX.js";
import { t as koiCommand } from "./koi-C6i0qbe-.js";
import { t as formatForLog } from "./ws-log-BSxE5LhM.js";
import { randomUUID } from "node:crypto";

//#region src/gateway/server-node-events.ts
const handleNodeEvent = async (ctx, nodeId, evt) => {
	switch (evt.event) {
		case "voice.transcript": {
			if (!evt.payloadJSON) return;
			let payload;
			try {
				payload = JSON.parse(evt.payloadJSON);
			} catch {
				return;
			}
			const obj = typeof payload === "object" && payload !== null ? payload : {};
			const text = typeof obj.text === "string" ? obj.text.trim() : "";
			if (!text) return;
			if (text.length > 2e4) return;
			const sessionKeyRaw = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : "";
			const rawMainKey = normalizeMainKey(loadConfig().session?.mainKey);
			const sessionKey = sessionKeyRaw.length > 0 ? sessionKeyRaw : rawMainKey;
			const { storePath, entry, canonicalKey } = loadSessionEntry(sessionKey);
			const now = Date.now();
			const sessionId = entry?.sessionId ?? randomUUID();
			if (storePath) await updateSessionStore(storePath, (store) => {
				store[canonicalKey] = {
					sessionId,
					updatedAt: now,
					thinkingLevel: entry?.thinkingLevel,
					verboseLevel: entry?.verboseLevel,
					reasoningLevel: entry?.reasoningLevel,
					systemSent: entry?.systemSent,
					sendPolicy: entry?.sendPolicy,
					lastChannel: entry?.lastChannel,
					lastTo: entry?.lastTo
				};
			});
			ctx.addChatRun(sessionId, {
				sessionKey,
				clientRunId: `voice-${randomUUID()}`
			});
			koiCommand({
				message: text,
				sessionId,
				sessionKey,
				thinking: "low",
				deliver: false,
				messageChannel: "node"
			}, defaultRuntime, ctx.deps).catch((err) => {
				ctx.logGateway.warn(`koi failed node=${nodeId}: ${formatForLog(err)}`);
			});
			return;
		}
		case "koi.request": {
			if (!evt.payloadJSON) return;
			let link = null;
			try {
				link = JSON.parse(evt.payloadJSON);
			} catch {
				return;
			}
			const message = (link?.message ?? "").trim();
			if (!message) return;
			if (message.length > 2e4) return;
			const channel = normalizeChannelId(typeof link?.channel === "string" ? link.channel.trim() : "") ?? void 0;
			const to = typeof link?.to === "string" && link.to.trim() ? link.to.trim() : void 0;
			const deliver = Boolean(link?.deliver) && Boolean(channel);
			const sessionKeyRaw = (link?.sessionKey ?? "").trim();
			const sessionKey = sessionKeyRaw.length > 0 ? sessionKeyRaw : `node-${nodeId}`;
			const { storePath, entry, canonicalKey } = loadSessionEntry(sessionKey);
			const now = Date.now();
			const sessionId = entry?.sessionId ?? randomUUID();
			if (storePath) await updateSessionStore(storePath, (store) => {
				store[canonicalKey] = {
					sessionId,
					updatedAt: now,
					thinkingLevel: entry?.thinkingLevel,
					verboseLevel: entry?.verboseLevel,
					reasoningLevel: entry?.reasoningLevel,
					systemSent: entry?.systemSent,
					sendPolicy: entry?.sendPolicy,
					lastChannel: entry?.lastChannel,
					lastTo: entry?.lastTo
				};
			});
			koiCommand({
				message,
				sessionId,
				sessionKey,
				thinking: link?.thinking ?? void 0,
				deliver,
				to,
				channel,
				timeout: typeof link?.timeoutSeconds === "number" ? link.timeoutSeconds.toString() : void 0,
				messageChannel: "node"
			}, defaultRuntime, ctx.deps).catch((err) => {
				ctx.logGateway.warn(`koi failed node=${nodeId}: ${formatForLog(err)}`);
			});
			return;
		}
		case "chat.subscribe": {
			if (!evt.payloadJSON) return;
			let payload;
			try {
				payload = JSON.parse(evt.payloadJSON);
			} catch {
				return;
			}
			const obj = typeof payload === "object" && payload !== null ? payload : {};
			const sessionKey = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : "";
			if (!sessionKey) return;
			ctx.nodeSubscribe(nodeId, sessionKey);
			return;
		}
		case "chat.unsubscribe": {
			if (!evt.payloadJSON) return;
			let payload;
			try {
				payload = JSON.parse(evt.payloadJSON);
			} catch {
				return;
			}
			const obj = typeof payload === "object" && payload !== null ? payload : {};
			const sessionKey = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : "";
			if (!sessionKey) return;
			ctx.nodeUnsubscribe(nodeId, sessionKey);
			return;
		}
		case "exec.started":
		case "exec.finished":
		case "exec.denied": {
			if (!evt.payloadJSON) return;
			let payload;
			try {
				payload = JSON.parse(evt.payloadJSON);
			} catch {
				return;
			}
			const obj = typeof payload === "object" && payload !== null ? payload : {};
			const sessionKey = typeof obj.sessionKey === "string" ? obj.sessionKey.trim() : `node-${nodeId}`;
			if (!sessionKey) return;
			const runId = typeof obj.runId === "string" ? obj.runId.trim() : "";
			const command = typeof obj.command === "string" ? obj.command.trim() : "";
			const exitCode = typeof obj.exitCode === "number" && Number.isFinite(obj.exitCode) ? obj.exitCode : void 0;
			const timedOut = obj.timedOut === true;
			const output = typeof obj.output === "string" ? obj.output.trim() : "";
			const reason = typeof obj.reason === "string" ? obj.reason.trim() : "";
			let text = "";
			if (evt.event === "exec.started") {
				text = `Exec started (node=${nodeId}${runId ? ` id=${runId}` : ""})`;
				if (command) text += `: ${command}`;
			} else if (evt.event === "exec.finished") {
				const exitLabel = timedOut ? "timeout" : `code ${exitCode ?? "?"}`;
				text = `Exec finished (node=${nodeId}${runId ? ` id=${runId}` : ""}, ${exitLabel})`;
				if (output) text += `\n${output}`;
			} else {
				text = `Exec denied (node=${nodeId}${runId ? ` id=${runId}` : ""}${reason ? `, ${reason}` : ""})`;
				if (command) text += `: ${command}`;
			}
			enqueueSystemEvent(text, {
				sessionKey,
				contextKey: runId ? `exec:${runId}` : "exec"
			});
			requestHeartbeatNow({ reason: "exec-event" });
			return;
		}
		default: return;
	}
};

//#endregion
export { handleNodeEvent };