import { execFileSync } from "node:child_process" import { isIPv4 } from "node:net" import { homedir } from "node:os" import { join } from "node:path" const targets = process.env.MMAPP_IX_CHR_HOSTS?.split(",").map(value => value.trim()) ?? [] if (targets.length !== 2 || new Set(targets).size !== 2 || !targets.every(isIPv4)) { throw new Error("MMAPP_IX_CHR_HOSTS must identify two distinct, isolated CHR IPv4 addresses") } export const hosts = [targets[0], targets[1]] as const const key = join(homedir(), ".ssh", "chr_claude") const known = process.env.MMAPP_IX_TEST_KNOWN_HOSTS ?? join(homedir(), ".ssh", "known_hosts") export const quote = (value: string) => '"' + value.replace(/[\\"$]/g, "\\$&").replace(/\n/g, "\\n") + '"' export const sshOptions = ["-F", process.platform === "win32" ? "NUL" : "/dev/null", "-i", key, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes", "-o", "UserKnownHostsFile=" + known, "-o", "ConnectTimeout=12", "-o", "LogLevel=ERROR"] export function cli(side: number, expression: string, stage?: string) { const args = [...sshOptions, "claude@" + hosts[side], `:onerror err in={ ${expression.replace(/\r?\n\s*/g, " ")}; :put "IX_OK" } do={ :put ("IX_ERROR:" . $err) }`] const run = () => execFileSync("ssh", args, { encoding: "utf8", timeout: 35000, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] }).trim() let stdout: string try { for (let attempt = 0;; attempt++) { try { stdout = run(); break } catch (error) { // Retry only when the command could not have reached the router. const failure = error as { status?: number; stderr?: string; stdout?: string } if (attempt >= 2 || failure.status !== 255 || failure.stdout || !/^ssh: connect to host .* port 22: Connection timed out\s*$/i.test(failure.stderr ?? "")) throw error } } } catch (error) { if (stage) throw Error(`CHR ${side + 1}: SSH failed during ${stage}`) throw error } if (!stdout.split(/\r?\n/).includes("IX_OK") || stdout.includes("IX_ERROR") || /syntax error|expected end|expected closing/.test(stdout)) { const diagnostic = stdout.replace(/[a-f0-9]{36,}/gi, "[redacted]").slice(0, 420) throw Error(`CHR ${side + 1} rejected ${stage ?? expression.slice(0, 360)} ยท ${diagnostic}`) } return stdout.replace(/\r?\n?IX_OK$/, "").trim() }