import { isRexBlockId, isRexServerAddress, isRexSessionId, isMuxSocketPath, validateMuxLaunchContext, type MuxName, type MuxTarget, isZellijSessionName, isHerdrCoreTerminalId, } from "./multiplexer-contracts"; import { CMUX_DISCOVERY_TIMEOUT_MS, cmuxCandidate, verifyCmuxTarget, verifyCmuxTargetAsync, type CmuxTarget, } from "./multiplexer-cmux"; import { probeLiveMuxTarget, probeLiveMuxTargetAsync, type LiveMuxProbe, type LiveMuxTarget, } from "./multiplexer-live-probes"; import { closestMuxAncestor, readProcessContext, readProcessContextAsync, type ProcessContext, type ProcessInspectionFailure, } from "./multiplexer-process-context"; export type CurrentMuxContext = | { readonly kind: "absent" } | { readonly kind: "ready"; readonly target: MuxTarget } | { readonly kind: "unavailable"; readonly candidates: readonly MuxName[]; readonly message: string; }; const MUX_LABELS: Record = { tmux: "tmux", zellij: "Zellij", herdr: "Herdr", rex: "Rex", "herdr-core": "Herdr Core", wezterm: "WezTerm", cmux: "cmux", }; function safeSelector(value: string | undefined): value is string { return ( !!value && value.length <= 4096 && !value.startsWith("-") && value.trim() === value && !/[\x00-\x1f\x7f]/.test(value) ); } function contextCandidates(env: NodeJS.ProcessEnv): { names: MuxName[]; targets: LiveMuxTarget[]; cmux: CmuxTarget | undefined; } { const names: MuxName[] = []; const targets: LiveMuxTarget[] = []; if (env.TMUX !== undefined || env.TMUX_PANE !== undefined) { names.push("tmux"); if (/^%\d+$/.test(env.TMUX_PANE ?? "")) { const server = /^(.*),\d+,\d+$/.exec(env.TMUX ?? "")?.[1]; if (isMuxSocketPath(server)) targets.push({ mux: "tmux", paneId: env.TMUX_PANE!, server, }); } } if ( env.ZELLIJ !== undefined || env.ZELLIJ_SESSION_NAME !== undefined || env.ZELLIJ_PANE_ID !== undefined ) { names.push("zellij"); if ( isZellijSessionName(env.ZELLIJ_SESSION_NAME) && /^\d+$/.test(env.ZELLIJ_PANE_ID ?? "") ) { targets.push({ mux: "zellij", paneId: env.ZELLIJ_PANE_ID!, session: env.ZELLIJ_SESSION_NAME, }); } } if (env.HERDR_ENV === "1" || env.HERDR_PANE_ID !== undefined) { names.push("herdr"); if ( env.HERDR_ENV === "1" && isMuxSocketPath(env.HERDR_SOCKET_PATH) && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(env.HERDR_PANE_ID ?? "") ) { targets.push({ mux: "herdr", paneId: env.HERDR_PANE_ID!, session: env.HERDR_SOCKET_PATH, }); } } if ( env.REX_SESSION !== undefined || env.REX_BLOCK !== undefined || env.TERM_PROGRAM?.trim().toLowerCase() === "rex" ) { names.push("rex"); if ( isRexSessionId(env.REX_SESSION) && isRexBlockId(env.REX_BLOCK) && isRexServerAddress(env.REX_SERVER) ) { targets.push({ mux: "rex", paneId: env.REX_BLOCK, session: env.REX_SESSION, server: env.REX_SERVER, }); } } if ( env.HC_TERMINAL_ID !== undefined || env.HC_TERMINAL_SOCKET !== undefined ) { names.push("herdr-core"); if ( isHerdrCoreTerminalId(env.HC_TERMINAL_ID) && isMuxSocketPath(env.HC_TERMINAL_SOCKET) ) { targets.push({ mux: "herdr-core", paneId: env.HC_TERMINAL_ID, server: env.HC_TERMINAL_SOCKET, }); } } if (env.WEZTERM_PANE !== undefined || env.WEZTERM_UNIX_SOCKET !== undefined) { names.push("wezterm"); if ( /^\d+$/.test(env.WEZTERM_PANE ?? "") && isMuxSocketPath(env.WEZTERM_UNIX_SOCKET) ) { targets.push({ mux: "wezterm", paneId: env.WEZTERM_PANE!, server: env.WEZTERM_UNIX_SOCKET, }); } } if ( env.CMUX_SOCKET_PATH !== undefined || env.CMUX_WORKSPACE_ID !== undefined || env.CMUX_SURFACE_ID !== undefined || env.TERM_PROGRAM?.trim().toLowerCase() === "cmux" ) { names.push("cmux"); } return { names, targets, cmux: cmuxCandidate(env) }; } function inspectionScope(targets: LiveMuxTarget[]) { return targets.some((target) => target.mux === "herdr-core") ? "ancestry" : "all"; } function cmuxMatch(target: CmuxTarget): LiveMuxProbe { // Like a direct WezTerm TTY match, this identifies the immediate terminal. return { kind: "match", target, distance: 0 }; } function probeCmux(target: CmuxTarget, context: ProcessContext): LiveMuxProbe { try { verifyCmuxTarget( target, context.processes.get(context.pid)?.tty, CMUX_DISCOVERY_TIMEOUT_MS, ); return cmuxMatch(target); } catch { // Socket errors and invalid replies cannot prove ownership. return { kind: "unknown" }; } } async function probeCmuxAsync( target: CmuxTarget, context: ProcessContext, signal?: AbortSignal, ): Promise { try { await verifyCmuxTargetAsync( target, context.processes.get(context.pid)?.tty, signal, ); return cmuxMatch(target); } catch { // Advisory probes use the same ownership rule without blocking Pi. return { kind: "unknown" }; } } /** Resolve ownership, not focus or an inherited environment-marker priority. */ export function resolveCurrentMuxContext( env: NodeJS.ProcessEnv = process.env, ): CurrentMuxContext { const { names, targets, cmux } = contextCandidates(env); if (names.length === 0) return { kind: "absent" }; let failure: ProcessInspectionFailure | undefined; const recordFailure = (value: ProcessInspectionFailure) => { failure = value; }; const context = readProcessContext( process.pid, inspectionScope(targets), recordFailure, ); if (!context) return unavailableContext(names, "process ancestry unavailable", failure); const probes = targets.map((target) => probeLiveMuxTarget(target, context, env), ); if (cmux) probes.push(probeCmux(cmux, context)); return selectCurrentMuxContext(names, context, probes); } /** Advisory status checks must not block Pi while host commands are pending. */ export async function resolveCurrentMuxContextAsync( env: NodeJS.ProcessEnv = process.env, signal?: AbortSignal, ): Promise { signal?.throwIfAborted(); const observation = { ...env }; const { names, targets, cmux } = contextCandidates(observation); if (names.length === 0) return { kind: "absent" }; let failure: ProcessInspectionFailure | undefined; const recordFailure = (value: ProcessInspectionFailure) => { failure = value; }; const context = await readProcessContextAsync( process.pid, inspectionScope(targets), signal, recordFailure, ); signal?.throwIfAborted(); if (!context) return unavailableContext(names, "process ancestry unavailable", failure); const probes = targets.map((target) => probeLiveMuxTargetAsync(target, context, observation, signal), ); if (cmux) probes.push(probeCmuxAsync(cmux, context, signal)); const results = await Promise.all(probes); signal?.throwIfAborted(); return selectCurrentMuxContext(names, context, results); } function unavailableContext( names: MuxName[], reason: "process ancestry unavailable" | "host ownership not verified", failure?: ProcessInspectionFailure, ): CurrentMuxContext { const detail = failure ? ` (stage=${failure.stage}, reason=${failure.reason}, elapsed=${failure.elapsedMs} ms)` : ""; return { kind: "unavailable", candidates: names, message: `${names.map((name) => MUX_LABELS[name]).join("/")} context is unavailable: ${reason}${detail}; refusing to guess.`, }; } function selectCurrentMuxContext( names: MuxName[], context: ProcessContext, probes: LiveMuxProbe[], ): CurrentMuxContext { const unavailable = unavailableContext(names, "host ownership not verified"); const matches = probes .filter((probe) => probe.kind === "match") .sort((a, b) => a.distance - b.distance); const winner = matches[0]; if (!winner || matches[1]?.distance === winner.distance) return unavailable; // A PID-backed match can be ranked -1 when Pi is the pane root itself. // That cannot break a tie with another direct controlling-TTY claim. if ( winner.distance === -1 && matches.some((match) => match.target.mux === "cmux") ) { return unavailable; } // A verified outer pane is not proof of ownership past a nearer mux whose // API or inherited pane selector could not be verified. const nearest = closestMuxAncestor(context); const nearestDistance = nearest ? context.ancestors.findIndex((ancestor) => ancestor.pid === nearest.pid) : -1; if ( nearest && nearestDistance >= 0 && (nearestDistance < winner.distance || (nearestDistance === winner.distance && (winner.target.mux !== "zellij" || nearest.mux !== "zellij"))) ) { // Zellij proves an ancestor relationship, not a pane PID, allowing only // a same-distance Zellij root; PID-backed matches need strict separation. return unavailable; } const target = winner.target as MuxTarget; try { validateMuxLaunchContext(target.mux, { ...target, kind: "attached" }); } catch { // A malformed probe result cannot grant launch authority. return unavailable; } return { kind: "ready", target: Object.freeze({ ...target }) }; }