import "./pi-embedded-helpers-C7GyAcoc.js";
import { T as loadSessionEntry, or as enqueueSystemEvent, yt as requestHeartbeatNow } from "./reply-Bnpxcafr.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-XH65-wH1.js";
import "./koi-scope-je0O-Kk9.js";
import "./model-selection-DHqY0wuU.js";
import "./dist-CFhZJtYo.js";
import "./dist-cjs-DiQp4ztu.js";
import "./boolean-D-3joTkO.js";
import "./env-ChCKTuXK.js";
import "./github-copilot-token-BqhLBQWA.js";
import "./version-BKRSzdyx.js";
import { o as loadConfig } from "./config-ZjEd8561.js";
import "./manifest-registry-DEGu_o5t.js";
import { r as normalizeChannelId } from "./plugins-Ct7Mnq1x.js";
import { l as updateSessionStore } from "./sessions-COz6-MPd.js";
import "./image-DYRH6hYg.js";
import "./dist-nhxaQYGz.js";
import "./lib-pS0Bd7GL.js";
import "./src-ByySp9O0.js";
import "./core-B7QS0Vnt.js";
import "./pi-model-discovery-Cy-rVVvR.js";
import "./sandbox-BeaBvIJZ.js";
import "./chrome-CROsH9kD.js";
import "./skills-D0qJwRRD.js";
import "./routes-DP4mWBwK.js";
import "./server-context-0I52nf-b.js";
import "./image-ops-CQFojSu1.js";
import "./message-channel-CaDAAMe0.js";
import "./logging-ADUQX6n5.js";
import "./accounts-DFSZwaCs.js";
import "./paths-DLKQOevr.js";
import "./tool-images-DlkXfMNL.js";
import "./redact-1AXapBET.js";
import "./tool-display-DYOxwSs6.js";
import "./deliver-CkS1xVhO.js";
import "./dispatcher-CoG7Bmmx.js";
import "./dist-B556KqJe.js";
import "./pi-tool-definition-adapter-CnsO-0rY.js";
import "./manager-6pqEqm7q.js";
import "./sqlite-CYnXobrn.js";
import "./warnings-Ds_WSeah.js";
import "./proxy-from-env-DxUIcU4P.js";
import "./login-qr-ekueLD_2.js";
import "./channel-summary-1rzVva2g.js";
import "./device-identity-CpMBJtRJ.js";
import "./client-BM6xyPUD.js";
import "./call-JFo1_L0m.js";
import "./koi-events-DhwDeG-q.js";
import "./pairing-store-BrlNnaod.js";
import "./links-BupJpVpQ.js";
import "./progress-EICDZThJ.js";
import "./node-pairing-DuliQoRe.js";
import "./pi-tools.policy-XgYp6L9R.js";
import "./onboard-helpers-FO60qqTG.js";
import "./prompt-style-hXUwxLRe.js";
import "./pairing-labels-DLc3GnhN.js";
import "./satisfies-Dp_OBiSc.js";
import "./session-cost-usage-BNV86lI0.js";
import "./control-service-DQtH-td4.js";
import "./restart-sentinel-BqQzvk3k.js";
import "./channel-selection-DhBJOelv.js";
import "./event-log-CL2tmo5v.js";
import "./deps-CX3Skz28.js";
import { t as koiCommand } from "./koi-Dv4SlCoI.js";
import { t as formatForLog } from "./ws-log-D428yCp4.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 };