import "./pi-embedded-helpers-Df7l-4vq.js";
import { Et as requestHeartbeatNow, T as loadSessionEntry, pr as enqueueSystemEvent } from "./reply-CZUaueaY.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 "./logger-BKidfKRU.js";
import "./exec-BBWSxSu-.js";
import "./koi-scope-BeICsBhH.js";
import "./model-selection-DvQd6xjM.js";
import "./dist-Czg7dzzf.js";
import "./dist-cjs-CtVce_lP.js";
import "./boolean-D-3joTkO.js";
import "./env-ChCKTuXK.js";
import "./github-copilot-token-BqhLBQWA.js";
import { o as loadConfig } from "./config-BOTdzMIB.js";
import "./manifest-registry-D7MfBQxU.js";
import { r as normalizeChannelId } from "./plugins-dW6cc0qG.js";
import { l as updateSessionStore } from "./sessions-DyqGkYWU.js";
import "./image-CUVl1Hhm.js";
import "./dist-iFsGHQA2.js";
import "./lib-C-WEldjv.js";
import "./src-CiVOi-Ma.js";
import "./core-DrwlWTgS.js";
import "./pi-model-discovery-E8vIYAbb.js";
import "./sandbox-CDOYKOkn.js";
import "./chrome-CTicuLaA.js";
import "./skills-DHpPesfZ.js";
import "./routes-C952rvWJ.js";
import "./server-context-Cs8Yx5qf.js";
import "./image-ops-B6MN1Uli.js";
import "./message-channel-B-LM-U45.js";
import "./logging-Dn5qdhsZ.js";
import "./accounts-B8F2xBS8.js";
import "./paths-DSzdyYR5.js";
import "./tool-images-DOYdkgEG.js";
import "./redact-Db6nXe_o.js";
import "./tool-display-CGLMse-l.js";
import "./deliver-BU-ss2iZ.js";
import "./dispatcher-Da_eDTB8.js";
import "./dist-JRNJAZWM.js";
import "./pi-tool-definition-adapter-DZBstpDD.js";
import "./manager-CvGvPIqL.js";
import "./sqlite-CbC9FUO2.js";
import "./warnings-D1qUihoO.js";
import "./proxy-from-env-BBdtl5-Y.js";
import "./login-qr-BDJgj3j2.js";
import "./channel-summary-DZinsO88.js";
import "./device-identity-CBC9Fa-4.js";
import "./client-CnWPlz1L.js";
import "./call-By5olg7I.js";
import "./koi-events-CVGX2xkt.js";
import "./pairing-store-DnxZNJ-U.js";
import "./links-DlFnXfJ_.js";
import "./progress-X-YSIEVf.js";
import "./node-pairing-ClP_ps1x.js";
import "./pi-tools.policy-CA2hGIde.js";
import "./onboard-helpers-DXmuVr9a.js";
import "./prompt-style-ko1k1LE0.js";
import "./pairing-labels-CNooTiAc.js";
import "./satisfies-D4f4jwpc.js";
import "./session-cost-usage-BiwFgQ3E.js";
import "./control-service-CamrxDfq.js";
import "./channel-selection-BTYECKhQ.js";
import "./event-log-DMRSRkMD.js";
import "./deps-BkqEahC_.js";
import { t as koiCommand } from "./koi-B9sw4JKe.js";
import { t as formatForLog } from "./ws-log-BHfGSne1.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 };