UNPKG

@essentialai/cogent-bridge

Version:

Cogent Bridge — cross-agent comms for Claude Code, OpenAI Codex and Slack. Codex users: install with `curl -fsSL https://cogent.tools/install.sh | sh`, then start with `cogent-codex` for real-time peer wake.

245 lines • 11.1 kB
/** * COG-97 — several live Claude Code processes on ONE session. * * Measured 2026-10-30 on the Marvin machine: four interactive Claude Code processes, each started by * hand over weeks, all resuming the same session in the same folder. Every one ran its own Cogent * bridge and could take turns on the same worktree. Nothing stops them: Cogent runs inside each * process and never kills its own ancestors, a plugin update does not restart a running session, and * the stale-bridge reaper spares 3.23.4+ bridges. * * Operator decision 2026-10-30: WARN, then OFFER a command the human runs. Never an automatic kill. * * Source of truth: Claude Code's own `<config>/sessions/<pid>.json` ({pid, sessionId, procStart, * kind, version, startedAt}). A record names a live copy only when its pid is alive AND that pid's * start time still equals `procStart` — a reused pid fails the check. `procStart` is computed the way * Claude Code 2.1.316 computes it (read from its binary, 2026-11-02): field 22 of /proc/<pid>/stat on * Linux, `LC_ALL=C TZ=UTC ps -o lstart= -p <pid>` elsewhere. An unreadable start time is "not a * copy" — never a guess. */ import { execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { ancestorsOf, listProcesses } from "./stale-bridge-reaper.js"; /** The session-record directories Claude Code may use: $CLAUDE_CONFIG_DIR first, then ~/.claude. */ export function claudeSessionDirs(env = process.env) { const dirs = [env.CLAUDE_CONFIG_DIR ? path.join(env.CLAUDE_CONFIG_DIR, "sessions") : null, path.join(os.homedir(), ".claude", "sessions")]; return [...new Set(dirs.filter((d) => !!d).map((d) => path.resolve(d)))]; } /** Every `<pid>.json` record in `dirs` that names a pid, a session and a start time. Never throws. */ export function readSessionRecords(dirs) { const out = []; for (const dir of dirs) { let names; try { names = fs.readdirSync(dir); } catch { continue; } for (const name of names) { if (!/^\d+\.json$/.test(name)) continue; try { const r = JSON.parse(fs.readFileSync(path.join(dir, name), "utf-8")); if (!Number.isInteger(r?.pid) || typeof r.sessionId !== "string" || typeof r.procStart !== "string") continue; out.push({ pid: r.pid, sessionId: r.sessionId, procStart: r.procStart, ...(typeof r.kind === "string" ? { kind: r.kind } : {}), ...(typeof r.version === "string" ? { version: r.version } : {}), ...(typeof r.startedAt === "number" ? { startedAt: r.startedAt } : {}), }); } catch { /* torn or foreign file */ } } } return out; } /** A process's start time in Claude Code's own `procStart` form; undefined when it cannot be read. */ export function procStartOf(pid, platform = process.platform) { try { if (platform === "linux") { const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8"); // Fields after the parenthesised command (which may itself contain spaces): field 3 onward. const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" "); const start = rest[22 - 3]; return start && /^\d+$/.test(start) ? start : undefined; } const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf-8", timeout: 2_000, env: { ...process.env, LC_ALL: "C", TZ: "UTC" }, }).trim(); return out || undefined; } catch { return undefined; } } function alive(pid) { try { process.kill(pid, 0); } catch (err) { return err?.code === "EPERM"; } // A zombie (exited, not yet reaped by its parent) still answers signal 0 but is not running. if (process.platform === "linux") { try { const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf-8"); if (stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z") return false; } catch { return false; } } return true; } /** The LIVE interactive Claude Code processes on `sessionId`, verified pid + start time, oldest first. */ export function liveSessionCopies(sessionId, deps = {}) { const records = deps.records ?? readSessionRecords(claudeSessionDirs()); const startOf = deps.procStartOf ?? ((pid) => procStartOf(pid)); const isAlive = deps.isAlive ?? alive; const seen = new Set(); const copies = records.filter((r) => { if (r.sessionId !== sessionId || (r.kind !== undefined && r.kind !== "interactive")) return false; if (seen.has(r.pid)) return false; if (!isAlive(r.pid) || startOf(r.pid) !== r.procStart) return false; // dead, or the pid was reused seen.add(r.pid); return true; }); return copies.sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0)); } /** * The copies to stop: every live copy except the NEWEST one, the current process and its ancestors * (when this runs inside a copy — a bridge, or the command typed with `!` — that copy is kept). */ export function olderSessionCopies(copies, keep) { if (copies.length < 2) return []; const newest = copies[copies.length - 1]; return copies.filter((c) => c !== newest && !keep.has(c.pid)); } /** The current process and its ancestors (from one `ps` listing). */ export function selfAndAncestors() { return new Set([process.pid, ...ancestorsOf(process.pid, listProcesses())]); } /** COG-97: the command shown to the human — runs the bridge CLI's `stop-duplicate-sessions`. */ export function stopDuplicatesCommand(sessionId, version) { return `npx -y @essentialai/cogent-bridge@${version} stop-duplicate-sessions ${sessionId}`; } /** * COG-97: the warning a bridge gives when other live copies of ITS OWN session exist, or null. * `others` excludes this process's own copy (an ancestor of the bridge). */ export function duplicateSessionWarning(sessionId, others, version) { if (others.length === 0) return null; const list = others .map((c) => `pid ${c.pid}${c.startedAt ? ` (started ${new Date(c.startedAt).toISOString().slice(0, 16).replace("T", " ")} UTC` : " ("}${c.version ? `, Claude Code ${c.version}` : ""})`) .join("; "); return (`${others.length} other live Claude Code process${others.length === 1 ? " is" : "es are"} running THIS session ` + `(${sessionId}): ${list}. Each can take turns in the same folder at the same time. Tell your user; to stop the ` + `older copies (the newest copy and the one running this command are kept), they can run: ` + `${stopDuplicatesCommand(sessionId, version)}`); } /** * Stop `targets`: re-verify each (session + start time) right before signalling, SIGTERM, then * SIGKILL for any survivor after `graceMs`. Never signals a pid in `keep`. */ export async function stopSessionCopies(sessionId, targets, keep, deps = {}) { const startOf = deps.procStartOf ?? ((pid) => procStartOf(pid)); const isAlive = deps.isAlive ?? alive; const kill = deps.kill ?? ((pid, sig) => process.kill(pid, sig)); const res = { stopped: [], killed: [], survivors: [], refused: [] }; const sent = []; for (const t of targets) { if (keep.has(t.pid)) { res.refused.push({ pid: t.pid, why: "is this process or one of its ancestors" }); } else if (t.sessionId !== sessionId) { res.refused.push({ pid: t.pid, why: `belongs to session ${t.sessionId}` }); } else if (startOf(t.pid) !== t.procStart) { res.refused.push({ pid: t.pid, why: "start time no longer matches its session record (exited, or the pid was reused)" }); } else { try { kill(t.pid, "SIGTERM"); sent.push(t); } catch (err) { res.refused.push({ pid: t.pid, why: `SIGTERM failed: ${err.message}` }); } } } if (sent.length === 0) return res; await new Promise((r) => setTimeout(r, deps.graceMs ?? 5_000)); const gone = (t) => !isAlive(t.pid) || startOf(t.pid) !== t.procStart; const killedNow = []; for (const t of sent) { if (gone(t)) { res.stopped.push(t.pid); continue; } try { kill(t.pid, "SIGKILL"); killedNow.push(t); } catch { res.survivors.push(t.pid); } } // SIGKILL is delivered asynchronously: report "killed" only once the process is really gone. const deadline = Date.now() + (deps.killWaitMs ?? 2_000); while (killedNow.some((t) => !gone(t)) && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50)); for (const t of killedNow) (gone(t) ? res.killed : res.survivors).push(t.pid); return res; } /** `cogent-bridge stop-duplicate-sessions <sessionId>` — the command the human runs. Returns an exit code. */ export async function runStopDuplicateSessions(args, write = (s) => process.stdout.write(s)) { const sessionId = args.find((a) => !a.startsWith("-")); if (!sessionId || !/^[0-9a-f-]{8,}$/i.test(sessionId)) { write("usage: cogent-bridge stop-duplicate-sessions <claude-session-id>\n"); return 2; } const keep = selfAndAncestors(); const copies = liveSessionCopies(sessionId); const targets = olderSessionCopies(copies, keep); write(`${copies.length} live Claude Code process(es) on session ${sessionId}.\n`); const newest = copies[copies.length - 1]; for (const c of copies) { if (c !== newest && keep.has(c.pid)) { write(` kept pid ${c.pid}: this command runs inside it — close that Claude Code session yourself.\n`); } } if (targets.length === 0) { write("Nothing to stop (the newest copy and the one running this command are always kept).\n"); return 0; } for (const t of targets) write(` stopping pid ${t.pid}${t.version ? ` (Claude Code ${t.version})` : ""}\n`); const r = await stopSessionCopies(sessionId, targets, keep); if (r.stopped.length) write(`stopped (SIGTERM): ${r.stopped.join(", ")}\n`); if (r.killed.length) write(`killed after the grace period (SIGKILL): ${r.killed.join(", ")}\n`); for (const x of r.refused) write(`not stopped: pid ${x.pid} — ${x.why}\n`); if (r.survivors.length) write(`STILL RUNNING: ${r.survivors.join(", ")}\n`); return r.survivors.length || r.refused.some((x) => x.why.startsWith("SIGTERM failed")) ? 1 : 0; } //# sourceMappingURL=duplicate-sessions.js.map