/** * Shared helpers for sessions backed by a persistent multiplexer * (tmux / herdr / zellij / zmx / hc). These backends keep the CLI alive across worker * exits BY DESIGN (idle-suspend, lazy restore), so several daemon paths must * resolve / name / probe / kill the backing session WITHOUT a live worker: * the restore-time zombie sweep and terminal wake (session-manager.ts), and * the /close teardown of orphaned sessions (worker-pool.ts killWorker). * * This module owns the backend dispatch so those paths can't drift apart. * It must stay dependency-light (backends + registry + config only) — both * worker-pool and session-manager import it, and those two already form an * import cycle with each other. */ import { getBot } from '../bot-registry.js'; import { isRemoteBackendId, reconcilePairedBackendId } from './remote-cli-ids.js'; import { TmuxBackend } from '../adapters/backend/tmux-backend.js'; import { HerdrBackend } from '../adapters/backend/herdr-backend.js'; import { ZellijBackend } from '../adapters/backend/zellij-backend.js'; import { ZmxBackend } from '../adapters/backend/zmx-backend.js'; import { hcTerminalName, killHcTerminal, probeHcTerminal, probeHcTerminals, type HcTarget, } from '../adapters/backend/hc/cli-ops.js'; import { HC_CORE_SESSION, hcCoreAddress, hcCorePaths, type HcCoreAddress } from '../adapters/backend/hc/core.js'; import { zmxEnv } from '../setup/ensure-zmx.js'; import type { BackendType, PersistentBackendTarget, SessionProbe } from '../adapters/backend/types.js'; import type { DaemonSession } from './types.js'; export type PersistentBackendType = Extract; /** * Decide whether a post-kill probe still blocks a cold replacement. * * ZMX owns sessions by labels + frozen PID and hc by labels, so an * inconclusive confirmation must remain fail-closed. The older mux backends * only have best-effort process/session probes: after a successful kill, * `unknown` is not proof that the target survived (notably zellij reports zero * live sessions with exit 1). */ export function shouldRejectPersistentPostKillProbe( backendType: PersistentBackendType, probe: SessionProbe, ): boolean { return probe === 'exists' || ((backendType === 'zmx' || backendType === 'hc') && probe === 'unknown'); } export function isSuspendableBackendType( backendType: BackendType | undefined, ): backendType is PersistentBackendType { return backendType === 'tmux' || backendType === 'herdr' || backendType === 'zellij' || backendType === 'zmx' || backendType === 'hc'; } /** * Resolve which persistent backend (if any) backs a session. * * Precedence, most authoritative first: * 1. `ds.initConfig?.backendType` — the live worker's resolved backend this run. * 2. `ds.session.backendType` — the backend stamped on the persisted session * at spawn time (survives daemon restart; see Session.backendType). * 3. An explicit per-bot `backendType` — authoritative even for legacy * sessions, since the bot's choice didn't change across the PTY退役 flip. * * If NONE of those resolve, the session predates backendType stamping AND its * bot pins no backend, so it ran on the OLD probe-based daemon default — which * could have been PTY on a tmux-less host. We deliberately do NOT fall back to * the current `config.daemon.backendType` (now always tmux): doing so would * make `restoreActiveSessions` probe for a `bmx-` pane that never existed, * find it 'missing', and zombie-close a perfectly recoverable session. Treating * it as non-persistent keeps the worker-less active record for lazy resume; a * genuinely surviving tmux pane still reattaches lazily on the next message * (and gets stamped then). */ export function getSessionPersistentBackendType(ds: DaemonSession): PersistentBackendType | undefined { let backendType: BackendType | undefined = ds.initConfig?.backendType ?? ds.session.backendType; if (!backendType) { try { backendType = getBot(ds.larkAppId).config.backendType; } catch { /* bot deregistered */ } } return isSuspendableBackendType(backendType) ? backendType : undefined; } /** * Freeze-once backend resolution for a forkWorker spawn. An already-running * session keeps the backend stamped at its FIRST spawn (`sessionStamp`); only a * brand-new session (no stamp) resolves from the bot's live config, then the * daemon default. worker-pool's forkWorker calls this so a live dashboard * backendType edit only affects NEW sessions and never re-derives a running * session onto a different backend (which would strand its persistent pane). */ export function resolveSpawnBackendType( sessionStamp: BackendType | undefined, botType: BackendType | undefined, defaultType: BackendType, ): BackendType { return sessionStamp ?? botType ?? defaultType; } /** * CLIs that are NOT local processes: they have an empty `resolvedBin` and their * backend translates write() into remote API / headless-CLI calls. For each of * these the cliId and the backendType share a name and must stay paired. * * Adding a remote CLI means adding it here — the alternative (another * hardcoded `=== 'riff'` chain in every helper below) is exactly what made this * generalization necessary. */ // The set itself now lives in the dependency-free core/remote-cli-ids leaf so // light consumers (e.g. the Lark card builder) can share it without pulling in // every PTY backend class through this module. /** True for a backend that runs the agent off-box (no local PTY to own). */ export function isRemoteBackendType(type: BackendType): boolean { return isRemoteBackendId(type); } export { isRemoteCliId } from './remote-cli-ids.js'; /** * Enforce the `cliId === ⇔ backendType === ` pairing invariant * at the ONE spawn chokepoint, so every config entry point (dashboard, `/config * set cli|backendType`, `botmux setup`, hand-edited bots.json) converges: * - a remote CLI on a local backend → force its own backend (a pty/tmux spawn * would fail on the empty resolvedBin); * - a non-remote CLI on a remote backend → fall back to the daemon default * (the CLI's PTY chunked writes would otherwise fan out into remote tasks). * Manual pty/tmux/herdr/zellij overrides for local CLIs pass through. * * NOTE: kept under its historical name `reconcileRiffBackendType` on purpose — * it is imported by name in several modules and renaming it would bloat this * behaviour-preserving refactor into a cross-cutting rename. */ export function reconcileRiffBackendType( cliId: string, resolved: BackendType, defaultType: BackendType, ): BackendType { // A remote CLI dictates its own backend (same name by construction); // defaultType 本身被误配成远端后端时兜底到确定可用的本地后端(pty 无外部依赖)。 // 规则本体在无依赖的 remote-cli-ids,Dashboard 判断零注入时复用同一份。 return reconcilePairedBackendId(cliId, resolved, defaultType) as BackendType; } /** Resolve the frozen/live/default backend precedence and then enforce the * Riff CLI/backend pairing. Keep spawn-time callers on this single helper so * worktree push decisions cannot drift from the backend forkWorker will use. */ export function resolvePairedSpawnBackendType( cliId: string, sessionStamp: BackendType | undefined, botType: BackendType | undefined, defaultType: BackendType, ): BackendType { return reconcileRiffBackendType( cliId, resolveSpawnBackendType(sessionStamp, botType, defaultType), defaultType, ); } /** Whether the live/persisted session is frozen onto the remote Riff backend. * Restart guards must use the session stamp rather than the bot's mutable * current config: changing a bot later must not make an existing Riff * generation look locally restartable. */ export function isRiffBackendSession(ds: DaemonSession): boolean { return (ds.initConfig?.backendType ?? ds.session.backendType) === 'riff'; } /** Whether the live/persisted session is frozen onto ANY remote backend. * Same frozen-stamp rule as isRiffBackendSession. Used by the guards that * must reject BEFORE mutating persisted state (e.g. /cd repin): killWorker * refuses unprepared live retirement for every remote backend, so a caller * that mutates first and retires after would report success while the live * generation keeps running against the old state — the split-brain the riff * guard has always prevented, now needed for mojo too. */ export function isRemoteBackendSession(ds: DaemonSession): boolean { const frozen = ds.initConfig?.backendType ?? ds.session.backendType; return frozen !== undefined && isRemoteBackendType(frozen); } /** * How a session's worker is torn down at daemon shutdown, branched on the * session's FROZEN backend (via getSessionPersistentBackendType), NOT live config: * 'detach' — persistent backend (tmux/herdr/zellij): SIGTERM the worker only, * leaving the multiplexer session alive for re-attach. * 'close' — non-persistent (frozen pty, or unresolvable legacy): killWorker. * Freezing here stops a live backendType edit from changing how a running session * tears down — e.g. detach-preserving a "herdr" session whose real pane is tmux. */ export function shutdownBackendDisposition(ds: DaemonSession): 'remote-drain-detach' | 'detach' | 'close' { const frozen = ds.initConfig?.backendType ?? ds.session.backendType; // Every remote backend must publish its exact final lineage before the local // worker exits. Riff may wait for create/follow-up HTTP; Mojo may wait for the // first `system/init`. Their backend-specific implementations stay behind the // common prepare/abort/commit interface, while the daemon owns one atomic // fleet transaction. Detach never cancels the remote session. if (frozen && isRemoteBackendType(frozen)) return 'remote-drain-detach'; return getSessionPersistentBackendType(ds) ? 'detach' : 'close'; } /** Deterministic backing-session name (`bmx-`, same rule across backends). */ export function persistentSessionName(backendType: PersistentBackendType, sessionId: string): string { if (backendType === 'tmux') return TmuxBackend.sessionName(sessionId); if (backendType === 'zellij') return ZellijBackend.sessionName(sessionId); if (backendType === 'zmx') return ZmxBackend.sessionName(sessionId); if (backendType === 'hc') return hcTerminalName(sessionId); return HerdrBackend.sessionName(sessionId); } /** * This process's botmux hc core, for a row or name that recorded none. A host * that cannot name one gets an empty socket, which every hc operation answers * as unknown. */ function defaultHcCore(): HcCoreAddress { try { return hcCoreAddress(hcCorePaths(process.env)); } catch { return { hcSession: HC_CORE_SESSION, socket: '' }; } } function hasRecordedHcCore(target: HcTarget): boolean { return typeof target.socket === 'string' && target.socket.length > 0 && typeof target.hcSession === 'string' && target.hcSession.trim().length > 0; } /** * Resolve the exact backing resource for daemon lifecycle work. The persisted * worker-selected target wins only when it still matches the frozen backend; * legacy rows fall back to the historical deterministic whole-session target * (for hc: on this process's botmux core). */ export function resolvePersistentBackendTarget( backendType: PersistentBackendType, sessionId: string, persisted?: PersistentBackendTarget, ): PersistentBackendTarget { if (persisted?.backendType === backendType && persisted.sessionName.trim()) { if (persisted.backendType === 'hc') { if (hasRecordedHcCore(persisted)) return persisted; } else if (persisted.backendType !== 'herdr' || persisted.agentName === undefined || persisted.agentName.trim()) { // Herdr's old exclusive host carries no agent identity. Keep the complete // owner beside the resolved (ephemeral) target so destructive lifecycle // work can distinguish `bmx-` from shared/custom host sessions. return persisted.backendType === 'herdr' && persisted.agentName === undefined ? { ...persisted, sessionId } : persisted; } } const sessionName = persistentSessionName(backendType, sessionId); if (backendType === 'herdr') return { backendType, sessionName, sessionId }; if (backendType === 'hc') return { backendType, sessionName, ...defaultHcCore() }; return { backendType, sessionName }; } export function persistentBackendTargetForSession(ds: DaemonSession): PersistentBackendTarget | undefined { const backendType = getSessionPersistentBackendType(ds); if (!backendType) return undefined; return resolvePersistentBackendTarget( backendType, ds.session.sessionId, ds.session.persistentBackendTarget, ); } /** * The only agent-less Herdr target that Botmux may own as a whole session is * its deterministic legacy host. Shared `botmux` / custom hosts and malformed * rows stay fail-closed even when their names merely resemble a managed name. */ function isExclusiveAgentlessHerdrTarget( target: Extract, ): boolean { return target.agentName === undefined && typeof target.sessionId === 'string' && target.sessionId.length > 0 && target.sessionId === target.sessionId.trim() && target.sessionName === persistentSessionName('herdr', target.sessionId); } export function probePersistentBackendTarget(target: PersistentBackendTarget): SessionProbe { if (target.backendType === 'tmux' && (target.socketName !== undefined || target.socketRoot !== undefined)) { return target.socketRoot !== undefined ? TmuxBackend.probeSession(target.sessionName, target.socketName, target.socketRoot) : TmuxBackend.probeSession(target.sessionName, target.socketName); } if (target.backendType === 'zmx' && target.socketDir !== undefined) { return ZmxBackend.probeSession(target.sessionName, zmxEnv(process.env, target.socketDir)); } if (target.backendType === 'hc') return probeHcTerminal(target); if (target.backendType === 'herdr') { if (target.agentName?.trim()) { return HerdrBackend.probeAgent(target.sessionName, target.agentName); } // Legacy exclusive hosts are safe to probe as a whole session only with // complete ownership proof. Shared/custom/malformed targets stay unknown. return isExclusiveAgentlessHerdrTarget(target) ? HerdrBackend.probeSession(target.sessionName) : 'unknown'; } return probePersistentSession(target.backendType, target.sessionName); } /** * hc teardown, fail-closed like ZMX: `bmx-` names no owner (every bot * daemon of the uid shares one core), so only the complete session id matching * the terminal's labels allows it, and anything short of a confirmed end or * absence throws. */ function killHcTarget(target: HcTarget, sessionId: string | undefined): void { const outcome = killHcTerminal(target, sessionId ?? ''); if (outcome.result === 'mismatch') { throw new Error(`hc 终端 ${target.sessionName}(${outcome.address})的所有权标签不匹配,已拒绝删除`); } if (outcome.result === 'unknown') throw new Error(outcome.reason); } /** * `sessionId` is REQUIRED for ZMX and hc: their destruction is identity-verified * against the botmux labels stamped on the session, and `killPersistentSession` * refuses a name-only kill rather than risk destroying a same-named session of * another owner. Callers that hold the owning session must always pass it through. */ export function killPersistentBackendTarget( target: PersistentBackendTarget, sessionId?: string, ): void { if (target.backendType === 'zmx' && target.socketDir !== undefined) { if (!sessionId) throw new Error('ZMX teardown requires the complete owning session id'); ZmxBackend.killManagedSession(target.sessionName, sessionId, undefined, zmxEnv(process.env, target.socketDir)); return; } if (target.backendType === 'hc') { killHcTarget(target, sessionId); return; } if (target.backendType === 'herdr') { if (target.agentName?.trim()) { HerdrBackend.killAgent(target.sessionName, target.agentName); return; } if (!isExclusiveAgentlessHerdrTarget(target) || (sessionId !== undefined && sessionId !== target.sessionId)) { throw new Error('Herdr whole-session teardown requires an exact exclusive owner target'); } HerdrBackend.killSession(target.sessionName); return; } if (target.backendType === 'tmux' && (target.socketName !== undefined || target.socketRoot !== undefined)) { if (target.socketRoot !== undefined) TmuxBackend.killSession(target.sessionName, target.socketName, target.socketRoot); else TmuxBackend.killSession(target.sessionName, target.socketName); return; } killPersistentSession(target.backendType, target.sessionName, sessionId); } /** By name on the backend's default namespace (for hc: this process's botmux core). */ export function probePersistentSession(backendType: PersistentBackendType, name: string): SessionProbe { if (backendType === 'tmux') return TmuxBackend.probeSession(name); if (backendType === 'zellij') return ZellijBackend.probeSession(name); if (backendType === 'zmx') return ZmxBackend.probeSession(name); if (backendType === 'hc') return probeHcTerminal({ backendType, sessionName: name, ...defaultHcCore() }); return HerdrBackend.probeSession(name); } /** * Take one liveness snapshot for a set of backing-session names. * * ZMX, Zellij and hc expose all session states in one command, so probing each * row separately would repeatedly scan the same control plane (and makes * `botmux list` quadratic for ZMX). tmux and Herdr keep their established * per-session probes, but duplicate names are still coalesced here. `socketDir` * is ZMX's; hc names are looked up on this process's botmux core. */ export function probePersistentSessions( backendType: PersistentBackendType, names: Iterable, socketDir?: string, ): ReadonlyMap { const uniqueNames = [...new Set(names)]; const result = new Map(); if (backendType === 'hc') return probeHcTerminals(defaultHcCore(), uniqueNames); if (backendType === 'zmx') { const snapshot = socketDir === undefined ? ZmxBackend.probeSessions() : ZmxBackend.probeSessions(zmxEnv(process.env, socketDir)); for (const name of uniqueNames) { result.set( name, !snapshot.ok ? 'unknown' : snapshot.sessions.includes(name) ? 'exists' : snapshot.unhealthySessions.includes(name) ? 'unknown' : 'missing', ); } return result; } if (backendType === 'zellij') { const snapshot = ZellijBackend.probeLiveSessions(); for (const name of uniqueNames) { result.set(name, !snapshot.ok ? 'unknown' : snapshot.sessions.includes(name) ? 'exists' : 'missing'); } return result; } for (const name of uniqueNames) { result.set(name, probePersistentSession(backendType, name)); } return result; } /** Address identity for caches/batches; ownership still requires the session UUID. */ export function persistentBackendTargetKey(target: PersistentBackendTarget): string { return JSON.stringify([ target.backendType, target.sessionName, target.backendType === 'herdr' ? target.agentName ?? '' : '', target.backendType === 'herdr' && target.agentName === undefined ? target.sessionId ?? '' : '', target.backendType === 'zmx' ? target.socketDir ?? '' : '', ...(target.backendType === 'tmux' && target.socketName !== undefined ? [target.socketName] : []), // socketRoot is optional and appended only when present, preserving every // key produced for legacy targets and for targets with only socketName. ...(target.backendType === 'tmux' && target.socketRoot !== undefined ? [target.socketRoot] : []), ...(target.backendType === 'hc' ? [target.hcSession, target.socket] : []), ]); } /** One list per backend namespace, shared by CLI display and daemon restore. */ export function probePersistentBackendTargets( targets: Iterable, ): ReadonlyMap { const result = new Map(); const groups = new Map>(); const hcCores = new Map>(); for (const target of targets) { const key = persistentBackendTargetKey(target); // Both agent-scoped and legacy exclusive Herdr targets require the same // ownership-aware single-target classifier. Never downgrade either kind to // the name-only batch probe used by whole-session backends. if (target.backendType === 'herdr') { if (!result.has(key)) result.set(key, probePersistentBackendTarget(target)); continue; } if (target.backendType === 'tmux' && target.socketName !== undefined) { if (!result.has(key)) result.set(key, probePersistentBackendTarget(target)); continue; } if (target.backendType === 'hc') { const coreKey = JSON.stringify([target.hcSession, target.socket]); const core = hcCores.get(coreKey) ?? new Map(); core.set(target.sessionName, target); hcCores.set(coreKey, core); continue; } const socketDir = target.backendType === 'zmx' ? target.socketDir : undefined; const groupKey = JSON.stringify([target.backendType, socketDir ?? '']); const group = groups.get(groupKey) ?? new Map(); group.set(target.sessionName, target); groups.set(groupKey, group); } for (const group of groups.values()) { const target = group.values().next().value!; const probes = probePersistentSessions( target.backendType, group.keys(), target.backendType === 'zmx' ? target.socketDir : undefined, ); for (const [name, item] of group) { result.set(persistentBackendTargetKey(item), probes.get(name) ?? 'unknown'); } } for (const core of hcCores.values()) { const probes = probeHcTerminals(core.values().next().value!, core.keys()); for (const [name, item] of core) { result.set(persistentBackendTargetKey(item), probes.get(name) ?? 'unknown'); } } return result; } /** * Kill a backing session. ZMX and hc additionally require the complete botmux * UUID: their public name contains only eight UUID characters, so name-only * deletion could destroy a different session after a prefix collision. */ export function killPersistentSession( backendType: PersistentBackendType, name: string, sessionId?: string, ): void { if (backendType === 'tmux') TmuxBackend.killSession(name); else if (backendType === 'zellij') ZellijBackend.killSession(name); else if (backendType === 'zmx') { if (!sessionId) throw new Error(`refusing name-only ZMX kill for ${name}`); ZmxBackend.killManagedSession(name, sessionId); } else if (backendType === 'hc') killHcTarget({ backendType, sessionName: name, ...defaultHcCore() }, sessionId); else HerdrBackend.killSession(name); } /** * {@link probePersistentBackendTarget} for verifying a kill that just went * through. Killing the last session on a tmux server makes that server exit, * and a probe that connects while it is still going down reads "server exited * unexpectedly" — a server-level error, so 'unknown' — although tmux gives its * own answer a moment later. Only 'unknown' is re-probed, with the same short * backoff as {@link TmuxBackend.probeSessionWithRetry} (at most ~0.75s of * sleep over the default three attempts, on top of each probe's own deadline * — 3s for tmux); 'exists' / 'missing' return at once, and a backing that * stays indeterminate is still 'unknown' for the caller to fail closed on. * A target that is unknown by construction is not re-probed at all. */ export function probePersistentBackendTargetAfterKill( target: PersistentBackendTarget, opts: { attempts?: number; baseDelayMs?: number; /** Test seams. */ probe?: (target: PersistentBackendTarget) => SessionProbe; sleep?: (ms: number) => void; } = {}, ): SessionProbe { const attempts = Math.max(1, Math.floor(opts.attempts ?? 3)); const baseDelayMs = Math.max(0, Math.floor(opts.baseDelayMs ?? 150)); // A shared/custom agentless herdr target is never asked (see // probePersistentBackendTarget): waiting cannot change its answer. if (target.backendType === 'herdr' && !target.agentName?.trim() && !isExclusiveAgentlessHerdrTarget(target)) { return 'unknown'; } const probe = opts.probe ?? probePersistentBackendTarget; const sleep = opts.sleep ?? ((ms: number) => { try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } catch { /* SharedArrayBuffer unavailable: retry immediately */ } }); let result = probe(target); for (let completed = 1; result === 'unknown' && completed < attempts; completed += 1) { const backoff = baseDelayMs * (2 ** (completed - 1)); const jitter = baseDelayMs > 0 ? Math.floor(Math.random() * baseDelayMs) : 0; sleep(backoff + jitter); result = probe(target); } return result; }