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.

1,076 lines • 49.1 kB
import path from "node:path"; import { readFileSync, readlinkSync, statSync } from "node:fs"; import fs from "node:fs/promises"; import { spawn, spawnSync } from "node:child_process"; import WebSocket from "ws"; import { getConfig } from "../config.js"; import { logger } from "../logger.js"; import { codexHomeDir } from "./agent-config.js"; import { effectiveSandbox } from "./codex-cli.js"; const defaultWsFactory = (url, opts) => new WebSocket(url, opts); /** Control socket for the codex app-server daemon under a given codex home. */ export function appServerSocketPath(codexHome = codexHomeDir()) { return path.join(codexHome, "app-server-control", "app-server-control.sock"); } /** * Is an app-server daemon ALREADY listening on this codex home's control socket? * * 🔴 WHY ANCESTRY WAS NOT ENOUGH. {@link runningUnderAppServerDaemon} answers "was I spawned * under a daemon?" — but the daemon is a SHARED, MACHINE-WIDE SINGLETON (see ensureDaemon), so a * process that is not its descendant can still use it. A codex agent whose bridge runs outside a * `cogent-codex`-launched codex — a standalone monitor script, a systemd unit, an MCP server under * a plain codex — always answered "no", fell back to `exec-resume`, and `codex exec resume * <thread>` then took the EXCLUSIVE WRITER on that thread. On 2026-09-02 that locked the operator * out of their own live session (`already has an active writer (code -32600)`) while a perfectly * good daemon was running on the same machine. * * Deliberately narrow: this reports only whether a daemon is ALREADY up. It never starts one, so a * machine without a daemon keeps its previous behaviour exactly. A stale socket file costs one * failed attempt and falls through to `exec-resume`, which is the pre-existing path anyway. * * `isSocket()` rather than `existsSync` on purpose: a leftover REGULAR FILE at the socket path * must not be mistaken for a live daemon. */ export function appServerDaemonRunning(codexHome = codexHomeDir()) { try { return statSync(appServerSocketPath(codexHome)).isSocket(); } catch { return false; } } /** The `ws+unix://<sock>:/rpc` URL the daemon speaks JSON-RPC over. */ export function rpcUrl(sock) { return `ws+unix://${sock}:/rpc`; } // --------------------------------------------------------------------------- // Am I running under the app-server daemon? (rail auto-detection) // --------------------------------------------------------------------------- /** * When codex runs `--remote` (attached to the daemon, e.g. launched via * cogent-codex), codex's app-server DAEMON — not the codex TUI — is the process * that spawns the plugin's MCP server. So the wake decision cannot rely on an env * flag reaching the bridge (the daemon doesn't carry it). Instead we detect the * situation structurally: the bridge is a descendant of `codex … app-server` * exactly when codex is `--remote`. Then the app-server rail is the RIGHT one and * we use it automatically — no `COGENT_CODEX_WAKE` needed anywhere. * * Pure + unit-testable: walk an ancestry via the injected `getProc`, return true * if any ancestor's command line is the codex app-server. `codex-cli` (Homebrew/npm) * and other names never match; only `codex … app-server`. */ export function ancestryHasAppServer(startPid, getProc, maxDepth = 8) { let pid = startPid; for (let i = 0; i < maxDepth && pid > 1; i++) { const p = getProc(pid); if (!p) return false; if (APP_SERVER_CMD.test(p.cmd)) return true; pid = p.ppid; } return false; } /** A `codex … app-server` command line (the daemon, its updater); `codex-cli` and others never match. */ const APP_SERVER_CMD = /(?:^|\/)codex\S*\s+app-server(?:\s|$)/; /** `ps`-backed process lookup (cross-platform: macOS + Linux). null if unknown. */ function psProc(pid) { try { const out = spawnSync("ps", ["-o", "ppid=,args=", "-p", String(pid)], { encoding: "utf8", timeout: 3000, }).stdout?.trim(); const m = out?.match(/^(\d+)\s+(.*)$/s); if (!m) return null; return { ppid: parseInt(m[1], 10), cmd: m[2] }; } catch { return null; } } let _underDaemon; /** * Memoized: is THIS bridge process running under a `codex … app-server` daemon * (i.e. codex is `--remote`)? Cached for the process lifetime — ancestry is fixed. */ export function runningUnderAppServerDaemon() { if (_underDaemon === undefined) { _underDaemon = ancestryHasAppServer(process.ppid, psProc); } return _underDaemon; } function readDaemonRecord(codexHome) { const file = path.join(codexHome, "app-server-daemon", "daemon.pid"); try { const rec = JSON.parse(readFileSync(file, "utf8")); const pid = rec?.pid; if (!Number.isInteger(pid) || pid <= 1) return null; const id = rec.processIdentity ?? {}; return { pid, ...(typeof id.bootId === "string" ? { bootId: id.bootId } : {}), ...(Number.isInteger(id.startTicks) ? { startTicks: id.startTicks } : {}), writtenMs: statSync(file).mtimeMs, }; } catch { return null; } } /** The daemon itself (`codex app-server --listen …`), not its updater or a `daemon start` command. */ const APP_SERVER_DAEMON_CMD = /(?:^|\/)codex\S*\s+app-server\s+--listen(?:\s|=|$)/; /** codex writes the record ~0.55 s before the socket (measured, 0.169.0): until then it is starting, not broken. */ const DAEMON_STARTING_MS = 10_000; /** * Is the recorded pid still the process the record was written for? Linux: the record's boot id * and start ticks against /proc, so a pid from an earlier boot or reused since does not count. * Where /proc or the record lacks a field (macOS), the command-line check alone decides. */ export function daemonIdentityMatches(rec, procRoot = "/proc") { try { if (rec.bootId !== undefined) { const boot = readFileSync(path.join(procRoot, "sys", "kernel", "random", "boot_id"), "utf8").trim(); if (boot !== rec.bootId) return false; } } catch { /* no /proc */ } try { if (rec.startTicks !== undefined) { const stat = readFileSync(path.join(procRoot, String(rec.pid), "stat"), "utf8"); // after "<pid> (<comm>) ": field 3 is index 0, so field 22 is index 19 const ticks = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]); if (ticks !== rec.startTicks) return false; } } catch { /* no /proc */ } return true; } /** * Does this bridge see the same /tmp as the daemon? A bridge in another mount namespace (a systemd * unit with PrivateTmp=yes) cannot see the daemon's socket even while it is fine, so it must not * judge it, and a restart would not help it. Linux: unreadable = cannot tell = false. No /proc * (macOS): one namespace. */ export function sameMountNamespace(pid, procRoot = "/proc") { try { return readlinkSync(path.join(procRoot, "self", "ns", "mnt")) === readlinkSync(path.join(procRoot, String(pid), "ns", "mnt")); } catch { return process.platform !== "linux"; } } /** * 🔴 COG-105: is the codex app-server daemon RUNNING while its control socket is GONE? * * The daemon's socket lives in /tmp (`/tmp/codex-daemon-<uid>/…` on Linux and macOS), reached * through the link {@link appServerSocketPath}. On 2026-11-16 a manual /tmp clean-up deleted it. * The daemon kept listening on the deleted file: the windows already connected kept working, but * every new connect failed ENOENT, codex never re-created the socket, and every wake fell back to * exec-resume without a word about why. Only a daemon restart brings the socket back. * * Narrow on purpose, because the answer tells a person to restart every Codex agent's MCP servers: * the socket must be missing outright (anything else at the path is a different fault); the * daemon's record must be older than a start takes; it must name a live `codex app-server --listen` * process that is the one the record was written for; and that process must share this bridge's * /tmp. Anything unsure is not claimed. */ export function appServerSocketGone(codexHome = codexHomeDir(), deps = {}) { const link = appServerSocketPath(codexHome); try { statSync(link); // follows the link return null; } catch (err) { if (err.code !== "ENOENT") return null; } const rec = readDaemonRecord(codexHome); if (rec === null) return null; if ((deps.now ?? Date.now)() - rec.writtenMs < DAEMON_STARTING_MS) return null; const p = (deps.proc ?? psProc)(rec.pid); if (!p || !APP_SERVER_DAEMON_CMD.test(p.cmd)) return null; const same = deps.sameDaemon ?? ((r) => daemonIdentityMatches(r) && sameMountNamespace(r.pid)); if (!same(rec)) return null; let socket = link; try { socket = path.resolve(path.dirname(link), readlinkSync(link)); } catch { /* the link itself is gone: name the link */ } return { pid: rec.pid, socket }; } /** * COG-105: what a wake records and tells the asker when the socket is gone — the cause and the one * fix. The asker is usually another AGENT with a shell, and an agent acting on the hint would be the * automatic restart this rail never does: the restart restarts every Codex agent's MCP servers on * the machine. So the fix is addressed to a person, and an agent is told not to run it. */ export function socketGoneReason(gone) { return (`APP_SERVER_SOCKET_GONE: the codex app-server daemon (pid ${gone.pid}) is running, but its socket ` + `${gone.socket} no longer exists, so no new connection can reach it. Only a restart re-creates it: ` + "`codex app-server daemon restart`, run by a person on that machine when no Codex turn is running. " + "Agents: do not run it yourselves — it restarts the MCP servers of every Codex agent on that " + "machine; tell your human instead."); } export function resetAppServerAncestryCache() { _underDaemon = undefined; } /** * Whether the app-server daemon has been ensured in THIS bridge process. The * daemon is a long-lived background process, so we start/confirm it once and * cache the socket; if it later dies, the ws connect fails → appServerUnavailable * → graceful fallback (and the cache is left for the next process). Reset for * test isolation. Mirrors the `sandboxOverride` module-cache pattern. */ let ensuredSock = null; export function resetDaemonCache() { ensuredSock = null; } const defaultRun = (cmd, args, env) => new Promise((resolve) => { const child = spawn(cmd, args, { env, stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; let stderr = ""; child.stdout.on("data", (c) => (stdout += c.toString())); child.stderr.on("data", (c) => (stderr += c.toString())); child.on("error", (err) => resolve({ stdout, stderr: stderr + String(err), code: 127 })); child.on("close", (code) => resolve({ stdout, stderr, code })); }); const defaultSocketExists = async (p) => { try { await fs.stat(p); return true; } catch { return false; } }; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** * Ensure the codex app-server daemon is running for `codexHome` and return its * control socket. Idempotent (`codex app-server daemon start` is a no-op when the * daemon is already up). Throws if the socket never appears — the caller * (`execRemote`) catches this and falls back to the `exec-resume` rail. */ export async function ensureDaemon(codexHome = codexHomeDir(), deps = {}) { if (ensuredSock) return ensuredSock; const run = deps.run ?? defaultRun; const socketExists = deps.socketExists ?? defaultSocketExists; const waitMs = deps.waitMs ?? 8000; const pollMs = deps.pollMs ?? 150; const codexPath = getConfig().COGENT_CODEX_PATH; const env = { ...process.env, CODEX_HOME: codexHome }; const res = await run(codexPath, ["app-server", "daemon", "start"], env); // The app-server daemon spawns/updates from a MANAGED-STANDALONE codex install // at a fixed path; the npm/Homebrew `@openai/codex` package does NOT create it, // so the daemon refuses to start. Surface codex's official remediation clearly // (the caller falls back to exec-resume → the honest "queued" message). if (/managed standalone Codex install not found/i.test(`${res.stdout}\n${res.stderr}`)) { throw new Error("MANAGED_CODEX_REQUIRED: the codex app-server daemon needs the managed-standalone " + "codex install, which the npm/Homebrew @openai/codex package does not provide. " + "Install it with: curl -fsSL https://chatgpt.com/codex/install.sh | sh " + "then relaunch via cogent-codex. (Until then, codex answers at its next turn, not in real time.)"); } // `daemon start` prints JSON with the socketPath; fall back to the derived path. let sock = appServerSocketPath(codexHome); try { const parsed = JSON.parse(res.stdout.trim()); if (parsed && typeof parsed.socketPath === "string") sock = parsed.socketPath; } catch { /* non-JSON stdout (e.g. "already running") → derived path */ } const deadline = Date.now() + waitMs; while (!(await socketExists(sock))) { if (Date.now() >= deadline) { throw new Error(`app-server daemon socket did not appear at ${sock} within ${waitMs}ms (stderr: ${res.stderr.trim() || "none"})`); } await sleep(pollMs); } ensuredSock = sock; return sock; } /** True if an item looks like the agent's final message ("agentMessage"/"agent_message"). */ function isAgentMessage(item) { return typeof item?.type === "string" && /^agent[_-]?message$/i.test(item.type); } /** Pull the text out of an agent-message item (plain `.text` or a content[] of text parts). */ function itemText(item) { if (typeof item?.text === "string") return item.text; if (Array.isArray(item?.content)) { return item.content .filter((c) => typeof c?.text === "string") .map((c) => c.text) .join(""); } return ""; } /** * Extract the agent's reply text from the collected turn notifications. Prefers * the final `turn/completed` items; falls back to streamed `item/completed` * agent messages when the completed turn carries none. Tolerant of the exact * shape (experimental API) — the live test pins the real wire format. */ export function extractAgentMessageText(notes) { const fromCompleted = []; const fromStream = []; for (const n of notes) { if (n.method === "turn/completed") { const items = n.params?.items ?? n.params?.turn?.items ?? []; for (const it of items) if (isAgentMessage(it)) fromCompleted.push(itemText(it)); } else if (n.method === "item/completed") { const it = n.params?.item; if (isAgentMessage(it)) fromStream.push(itemText(it)); } } const chosen = fromCompleted.length > 0 ? fromCompleted : fromStream; return chosen.join("").trim(); } /** * A thin JSON-RPC-over-WebSocket client for the codex app-server daemon. * `connect()` resolves once the socket is open + `initialize` succeeds. */ export class AppServerClient { ws; nextId = 1; pending = new Map(); notifyListeners = new Set(); closeListeners = new Set(); opened; openResolved = false; /** * COG-87: the socket is gone. `ws` drops a send on a closed socket without an error, so a * request on it would wait for an answer that cannot come — request() rejects at once instead. */ closed = false; constructor(ws) { this.ws = ws; this.opened = new Promise((resolve, reject) => { ws.on("open", () => { this.openResolved = true; resolve(); }); ws.on("unexpected-response", (_req, res) => { if (!this.openResolved) reject(new Error(`app-server ws upgrade rejected: HTTP ${res?.statusCode}`)); }); ws.on("error", (err) => { if (!this.openResolved) reject(err); else this._failAll(err); }); ws.on("close", () => { this.closed = true; if (this.openResolved) this._failAll(new Error("app-server ws closed")); for (const cb of this.closeListeners) cb(); }); }); ws.on("message", (data) => this._onMessage(data)); } /** Await the open handshake. Rejects (before open) on connect/upgrade errors. */ waitOpen() { return this.opened; } _failAll(err) { for (const [, p] of this.pending) p.reject(err); this.pending.clear(); } _onMessage(data) { let msg; try { msg = JSON.parse(data.toString()); } catch { return; // ignore non-JSON frames } if (typeof msg.id === "number" && this.pending.has(msg.id)) { const p = this.pending.get(msg.id); this.pending.delete(msg.id); if (msg.error) p.reject(Object.assign(new Error(msg.error.message ?? "rpc error"), { rpcError: msg.error })); else p.resolve(msg.result); return; } if (typeof msg.method === "string") { for (const cb of this.notifyListeners) cb(msg); } } /** Issue a JSON-RPC request and resolve with its result (rejects on rpc error). */ request(method, params) { if (this.closed) return Promise.reject(new Error("app-server ws closed")); const id = this.nextId++; const p = new Promise((resolve, reject) => { this.pending.set(id, { resolve, reject }); }); this.ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params })); return p; } /** Subscribe to server notifications; returns an unsubscribe fn. */ onNotification(cb) { this.notifyListeners.add(cb); return () => this.notifyListeners.delete(cb); } /** * COG-95: be told when the socket closes. A request in flight learns it by rejection, but the * late-answer wait has no request in flight — without this it would sit out its whole window * on a connection that can no longer deliver anything. */ onClose(cb) { this.closeListeners.add(cb); return () => this.closeListeners.delete(cb); } close() { try { this.ws.close(); } catch { /* ignore */ } } } /** * Map COGENT_CODEX_SANDBOX to an explicit turn/start `sandboxPolicy`, so a PEER's * injected turn is bounded by the CONFIGURED sandbox — not by whatever privilege * the human happened to launch codex with (a live thread may be * danger-full-access). Keeps the app-server rail's sandbox consistent with the * exec-resume rail. The default mode is `bypass` (dangerFullAccess) since COG-87. */ export function sandboxPolicyFor(mode, cwd) { switch (mode) { case "read-only": return { type: "readOnly", networkAccess: false }; case "danger-full-access": case "bypass": return { type: "dangerFullAccess" }; case "workspace-write": case "full-auto": default: return { type: "workspaceWrite", writableRoots: [cwd], networkAccess: false, excludeTmpdirEnvVar: false, excludeSlashTmp: false, }; } } /** Read the owner's setting from a ThreadResumeResponse (`sandbox`, `activePermissionProfile`, `cwd`). */ export function ownerSandboxFrom(resume) { const sandbox = resume?.sandbox && typeof resume.sandbox === "object" ? resume.sandbox : null; const id = resume?.activePermissionProfile?.id; const cwd = typeof resume?.cwd === "string" && resume.cwd ? resume.cwd : null; return { sandbox, permissionProfileId: typeof id === "string" && id ? id : null, cwd }; } /** Key-order-independent JSON, so `{a,b}` and `{b,a}` compare equal. */ function canonical(v) { if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`; if (v && typeof v === "object") { return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`; } return JSON.stringify(v); } /** * 🔴 COG-87 (round-3 review HIGH): a policy in the shape thread/resume REPORTS it. Measured on * codex 0.163.0 and 0.164.0-alpha.12 (via turn/start and thread/settings/update): workspaceWrite * `writableRoots` loses every root equal to the thread cwd (also written "cwd/") and exact * duplicates; the other roots keep their order, a subdirectory of cwd is kept, and every other * field — and readOnly / dangerFullAccess as a whole — comes back as sent. So the wake's own * workspaceWrite [cwd] reads back as [], and compared raw it looked like a setting no wake sent. * Normalises exactly that, nothing more. Without the thread cwd (not in the resume), unchanged. */ function asReported(policy, threadCwd) { const p = policy; if (!threadCwd || p?.type !== "workspaceWrite" || !Array.isArray(p.writableRoots)) return policy; const cwd = threadCwd.replace(/\/+$/, ""); const roots = []; for (const r of p.writableRoots) { if ((typeof r === "string" && r.replace(/\/+$/, "") === cwd) || roots.includes(r)) continue; roots.push(r); } return { ...p, writableRoots: roots }; } /** A policy we SENT vs one codex REPORTED, both in codex's reported shape (COG-87). */ function samePolicy(sent, reported, threadCwd) { return canonical(asReported(sent, threadCwd)) === canonical(asReported(reported, threadCwd)); } /** * The thread/settings/update params that put the owner's setting back, or null when the wake * changed nothing. A named profile is restored by id: `permissions` brings back both the sandbox * and the profile (measured), while `sandboxPolicy` would leave the profile null. The two fields * are mutually exclusive (codex answers -32600 "`permissions` cannot be combined with * `sandboxPolicy`" — measured). Throws when the owner's setting is unknown, so the caller reports * it instead of silently leaving the wake's policy on the thread. */ export function restoreParamsFor(threadId, sent, owner) { // Any sandboxPolicy clears an active profile, even an identical sandbox — always restore it. if (owner.permissionProfileId) return { threadId, permissions: owner.permissionProfileId }; if (!owner.sandbox) throw new Error("thread/resume returned no sandbox — the owner's setting is unknown"); if (samePolicy(sent, owner.sandbox, owner.cwd)) return null; return { threadId, sandboxPolicy: owner.sandbox }; } /** Bound on the restore call, so a dead daemon cannot hang the wake. */ export const RESTORE_TIMEOUT_MS = 10_000; const threadWakes = new Map(); function joinThreadWake(threadId) { let wakes = threadWakes.get(threadId); if (!wakes) { wakes = { inFlight: 0, owner: null, captured: false, policySent: false, sent: [], retained: false }; threadWakes.set(threadId, wakes); } wakes.inFlight++; return wakes; } /** `work`, or a rejection once RESTORE_TIMEOUT_MS has passed without it settling. */ async function boundedRestore(work) { let timer; try { return await Promise.race([ work, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`no answer within ${RESTORE_TIMEOUT_MS}ms`)), RESTORE_TIMEOUT_MS); }), ]); } finally { if (timer) clearTimeout(timer); } } /** * Put the owner's setting back on the thread (COG-87). Never throws: returns null on success or * when nothing needed restoring, else the reason it failed — the caller makes that LOUD. * * When the wake's connection is gone (closed mid-wake, or it dies during the restore), the * restore is retried ONCE over a fresh connection (`dial` + the wake's own `handshake`), bounded * by RESTORE_TIMEOUT_MS too — the dead client would only drop the request and wait out the bound * for nothing (COG-87 round-2 review). */ async function restoreOwnerSandbox(client, threadId, sent, owner, dial, handshake) { if (sent.length === 0) return null; // turn/start was never sent → nothing of ours is on the thread let params = null; try { if (!owner) throw new Error("thread/resume did not answer — the owner's setting is unknown"); // Overlapping wakes may have sent different policies; restore if ANY differs from the owner's. for (const s of sent) params ??= restoreParamsFor(threadId, s, owner); if (!params) return null; await boundedRestore(client.request("thread/settings/update", params)); return null; } catch (err) { if (!params || !client.closed) return err.message; const first = err.message; let fresh; try { await boundedRestore((async () => { fresh = dial(); await handshake(fresh); await fresh.request("thread/settings/update", params); })()); return null; } catch (retryErr) { return `${first}; the retry over a fresh connection failed: ${retryErr.message}`; } finally { fresh?.close(); } } } /** Bound on each best-effort instrumentation call (COG-95): it may cost a wake nothing. */ export const PROBE_TIMEOUT_MS = 2_000; /** `work`, or undefined once `ms` has passed or it failed — instrumentation never throws. */ async function bestEffort(work, ms) { let timer; try { return await Promise.race([ work, new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), ms); timer.unref?.(); }), ]); } catch { return undefined; } finally { if (timer) clearTimeout(timer); } } /** * The daemon's version from its InitializeResponse (COG-95). The 0.164 schema has no version field — * only `userAgent` (`codexHome`, `platformFamily`, `platformOs`, `userAgent`); the userAgent's value * was NOT measured, so this takes an explicit version field if one ever appears, else the first * `/x.y.z` in the userAgent, else the userAgent itself (bounded). */ export function codexVersionFrom(init) { if (!init || typeof init !== "object") return undefined; const o = init; for (const v of [o.version, o.codexVersion, o.serverVersion, o.serverInfo?.version]) { if (typeof v === "string" && v) return v; } if (typeof o.userAgent === "string" && o.userAgent) { return /\/(\d+\.\d+\.\d+[0-9A-Za-z.+-]*)/.exec(o.userAgent)?.[1] ?? o.userAgent.slice(0, 120); } return undefined; } /** The key codex gives the Cogent plugin's Stop hook in `hooks/list` (operator-measured, 2026-10-27). */ export const COGENT_STOP_HOOK_KEY = "cogent@cogent:hooks.json:stop:0:0"; /** * Cogent's codex Stop hook (rail C) as `hooks/list` reports it, or null when it is not listed. * Measured shape (codex 0.164.0): `{data:[{cwd, hooks:[{key, eventName:"stop", pluginId, enabled, * trustStatus}]}]}`. Rail C was off for six days on this machine by an accidental untick * (PLAN.md) — recording its state per wake is what tells the experiment whether it was a backup. */ export function stopHookFrom(list) { const groups = Array.isArray(list?.data) ? list.data : []; for (const g of groups) { for (const h of Array.isArray(g?.hooks) ? g.hooks : []) { const cogentStop = h?.key === COGENT_STOP_HOOK_KEY || (String(h?.eventName ?? "").toLowerCase() === "stop" && typeof h?.pluginId === "string" && h.pluginId.startsWith("cogent@")); if (cogentStop) { return { enabled: h.enabled === true, trust: typeof h.trustStatus === "string" ? h.trustStatus : "unknown" }; } } } return null; } /** * COG-96: ask the running app-server daemon how it lists Cogent's Stop hook for `cwd`. Never starts * a daemon. `undefined` = could not ask (no daemon, no answer in time, an error); `null` = asked and * the hook is not listed (e.g. a custom MCP config without the plugin). */ export async function probeCogentStopHook(cwd, deps = {}) { if (!deps.socketPath && !appServerDaemonRunning()) return undefined; const sock = deps.socketPath ?? appServerSocketPath(); let client; try { client = new AppServerClient((deps.wsFactory ?? defaultWsFactory)(rpcUrl(sock), { perMessageDeflate: false, headers: { Host: "localhost" } })); const c = client; const list = await bestEffort((async () => { await c.waitOpen(); await c.request("initialize", { clientInfo: { name: "cogent-bridge", version: "1" }, capabilities: { experimentalApi: true } }); return c.request("hooks/list", { cwds: [cwd] }); })(), deps.timeoutMs ?? 3_000); return list === undefined ? undefined : stopHookFrom(list); } catch { return undefined; } finally { try { client?.close(); } catch { /* already closed */ } } } /** * COG-96: the sentence to show a codex user when Cogent's Stop hook (rail C) will not run, or null. * Codex (0.166.0, hooks/src/engine/plugin_fingerprint.rs) fingerprints EVERY file of the installed * plugin, so each Cogent release — the bundled bridge changes every time — turns the approval into * "modified" and codex skips the hook until the user approves it again. Cogent must not approve it * on the user's behalf (that is codex's consent step), so it says so instead. */ export function codexStopHookWarning(state) { if (!state) return null; // not listed / could not ask: nothing to say for sure const effect = "Until then Codex does not run it, so messages that arrive while you are busy are not caught at the end of " + "your turn (Cogent's check-on-stop)."; if (!state.enabled) { return `Cogent's Codex Stop hook is turned OFF in /hooks. Turn it back on in Codex's /hooks screen. ${effect}`; } if (state.trust === "trusted" || state.trust === "managed") return null; return (`Cogent's Codex Stop hook is "${state.trust}": Codex asks you to approve a plugin's hooks again after every ` + `Cogent update. Open /hooks in Codex and trust the two cogent hooks (or restart Codex and choose to review ` + `hooks). ${effect}`); } let loggedInitKeys = false; const idempotencyCache = new Map(); /** How long a completed injection is remembered to suppress a duplicate delivery. */ const IDEMPOTENCY_TTL_MS = 300_000; /** Clear the injection idempotency cache and the per-thread wake records (test isolation). */ export function resetAppServerIdempotency() { idempotencyCache.clear(); threadWakes.clear(); } /** * Inject `message` as a turn into the codex thread `threadId` via the app-server * daemon, and return the agent's reply as a {@link CliExecResult} (parallel to * `execCodex`). When `deps.idempotencyKey` is set, a duplicate injection of the * same message into the same thread is coalesced/short-circuited (never a second * daemon turn). Closing our client afterward only detaches THIS client — the * daemon + thread (and the human's TUI) persist. */ export function execCodexViaAppServer(threadId, message, cwd, timeoutMs, deps = {}) { const key = deps.idempotencyKey ? `${threadId}::${deps.idempotencyKey}` : null; if (!key) return _injectTurn(threadId, message, cwd, timeoutMs, deps); const existing = idempotencyCache.get(key); if (existing) { // Completed within TTL → same result (no second turn). Still in-flight → // coalesce onto the same promise (e.g. a redelivery while the daemon runs). return existing.done ? Promise.resolve(existing.done.result) : existing.promise; } const promise = _injectTurn(threadId, message, cwd, timeoutMs, deps); const entry = { promise }; idempotencyCache.set(key, entry); // `_injectTurn` always RESOLVES a CliExecResult (never throws); cache success // AND failure for the TTL so a redelivery is suppressed either way, then evict. void promise.then((result) => { entry.done = { result, at: Date.now() }; const t = setTimeout(() => idempotencyCache.delete(key), IDEMPOTENCY_TTL_MS); if (typeof t.unref === "function") t.unref(); }); return promise; } async function _injectTurn(threadId, message, cwd, timeoutMs, deps = {}) { const config = getConfig(); const effectiveTimeout = timeoutMs ?? config.COGENT_TIMEOUT_MS; const truncated = config.COGENT_CHAR_LIMIT > 0 && message.length > config.COGENT_CHAR_LIMIT ? message.slice(0, config.COGENT_CHAR_LIMIT) + "\n...[truncated]" : message; const sock = deps.socketPath ?? appServerSocketPath(); const wsFactory = deps.wsFactory ?? defaultWsFactory; // COG-95 instrumentation: the wake's own initialize answer (the restore retry's is not kept). let initAnswer; // Shared by the wake and by the restore's one retry over a fresh connection (COG-87). const handshake = async (c) => { await c.waitOpen(); const init = await c.request("initialize", { clientInfo: { name: "cogent-bridge", version: "1" }, // Also required by thread/resume `excludeTurns` below: codex 0.145–0.150.1 reject it // without this ("requires experimentalApi capability"); 0.151.0+ accept it either way. capabilities: { experimentalApi: true }, }); if (initAnswer === undefined) initAnswer = init; return c; }; const dial = () => new AppServerClient(wsFactory(rpcUrl(sock), { perMessageDeflate: false, headers: { Host: "localhost" } })); let client; try { client = dial(); await handshake(client); } catch (err) { // Could not reach/handshake the daemon → let the caller fall back to exec-resume. return { stdout: "", stderr: `APP_SERVER_UNAVAILABLE: ${err.message}`, exitCode: 1, appServerUnavailable: true, }; } // COG-95 instrumentation, best effort: never awaited by the wake. A daemon that does not know // `hooks/list` answers an RPC error, which only leaves `stopHook` unknown (absent). if (!loggedInitKeys && initAnswer && typeof initAnswer === "object") { loggedInitKeys = true; logger.debug(`codex app-server initialize answered with keys: ${Object.keys(initAnswer).join(", ")}`); } const codexVersion = codexVersionFrom(initAnswer); let stopHook; void bestEffort(client.request("hooks/list", { cwds: [cwd] }), PROBE_TIMEOUT_MS).then((list) => { if (list !== undefined) stopHook = stopHookFrom(list); }); // COG-95: the mode turn/start carried — set only once a turn was asked for. let sandboxMode; const instrumented = (r) => ({ ...r, ...(codexVersion ? { codexVersion } : {}), ...(stopHook !== undefined ? { stopHook } : {}), ...(sandboxMode ? { sandbox: sandboxMode } : {}), }); // COG-87: what this wake put on the thread; the owner's setting lives on the shared per-thread // record, so an overlapping wake never captures another wake's policy — the finally restores. const wakes = joinThreadWake(threadId); let sent = null; let result; // COG-95: set once a late wait owns the client; `releaseClient` lets it close after the restore. let lateOwnsClient = false; let releaseClient = () => { }; const clientReleased = new Promise((resolve) => (releaseClient = resolve)); try { // Attach to the human's existing live thread (does NOT create a new one), // then inject the peer message as a turn on THAT thread. // // 🔴 excludeTurns: without it the daemon answers with the WHOLE conversation // (thread.turns, every item and tool output). We never read it, and it grows with the // agent's session: measured 46 MiB for a 142 MiB rollout and 115 MiB for a 480 MiB one, // which exceeds the `ws` client's default 100 MiB maxPayload → the wake failed with // "Max payload size exceeded" on every message to a long-running agent. It changes only // what WE receive — the model still sees its full history (measured: a code word planted // before an excludeTurns resume was recalled after it). const resumed = await client.request("thread/resume", { threadId, cwd, excludeTurns: true }); // COG-87: capture only while no wake on this thread has sent turn/start — after that the // thread may carry a wake's policy, and the first capture is reused instead. if (!wakes.captured && !wakes.policySent) { wakes.owner = ownerSandboxFrom(resumed); wakes.captured = true; } else if (wakes.retained && !wakes.policySent) { // First resume after a failed restore, before this group sent anything: the thread holds // either a policy a wake sent (the restore failure left it) or one the human set since. // Only the latter replaces the kept owner. An unknown setting is no evidence of a change. wakes.retained = false; const fresh = ownerSandboxFrom(resumed); const known = fresh.permissionProfileId !== null || fresh.sandbox !== null; const ours = fresh.permissionProfileId === null && wakes.sent.some((p) => samePolicy(p, fresh.sandbox, fresh.cwd)); if (known && !ours) { wakes.owner = fresh; wakes.sent = []; } } // Subscribe BEFORE turn/start so no completion is missed; buffer until we know // OUR turn id. Verified against codex 0.147: turn/completed carries // `params.turn.id` (the same id turn/start returns). We match on it so a // CONCURRENT turn on the same thread — e.g. the human's own turn — can never be // captured as this peer's reply. If the daemon omits the id (older codex), // fall back to a threadId match. const buffered = []; let myTurnId; const isMine = (msg) => msg.method === "turn/completed" && (myTurnId !== undefined ? msg.params?.turn?.id === myTurnId : msg.params?.threadId === threadId); let deliver = null; const off = client.onNotification((msg) => { if (msg.method !== "turn/completed") return; if (myTurnId === undefined) { buffered.push(msg); // hold until we learn our turn id return; } if (isMine(msg) && deliver) { const d = deliver; deliver = null; d(msg); } }); // Bound the injected peer turn by the CONFIGURED sandbox (not the human session's // privilege). effectiveSandbox, like the exec-resume rail: the COGENT_CODEX_SANDBOX_FALLBACK // override must reach both rails (COG-87). Recorded BEFORE the request, so a turn/start that // fails after the daemon applied it is still restored. sandboxMode = deps.sandbox ?? effectiveSandbox(config); sent = sandboxPolicyFor(sandboxMode, cwd); wakes.policySent = true; const startResult = await client.request("turn/start", { threadId, input: [{ type: "text", text: truncated }], sandboxPolicy: sent, // Native correlation id (daemon does NOT auto-dedupe on it — our own // idempotency guard does; this is for daemon-side correlation/telemetry). ...(deps.idempotencyKey ? { clientUserMessageId: deps.idempotencyKey } : {}), }); myTurnId = startResult?.turn?.id; let waitTimer; const turnCompleted = await new Promise((resolve) => { deliver = resolve; const early = buffered.find(isMine); // did our completion arrive before we knew the id? if (early) { deliver = null; resolve(early); return; } waitTimer = setTimeout(() => { if (deliver) { deliver = null; resolve(null); } }, effectiveTimeout); }); // COG-95: a turn that ended in time used to leave this timer running out the whole timeout. if (waitTimer) clearTimeout(waitTimer); if (!turnCompleted) { result = instrumented({ stdout: "", stderr: `CLI_TIMEOUT: app-server turn did not complete within ${effectiveTimeout}ms`, exitCode: null, gaveUpAt: new Date().toISOString(), }); if (deps.lateAnswerMaxMs !== undefined) { // 🔴 COG-95: by turn id ONLY. Without one, isMine falls back to the thread id, and over a // late window of up to hours that would deliver the HUMAN's next turn as this peer's answer. if (myTurnId === undefined) result.lateSkipped = "no-turn-id"; else { result.late = armLateWait(client, deps.lateAnswerMaxMs, (d) => (deliver = d), off, clientReleased); lateOwnsClient = true; } } } else { result = instrumented({ stdout: extractAgentMessageText([turnCompleted]), stderr: "", exitCode: 0, captureContract: "event_stream", stable: true, }); } if (!lateOwnsClient) off(); } catch (err) { // A turn/thread RPC errored on the daemon. This is NOT a reachability // problem, so do not flag appServerUnavailable (falling back to exec-resume // would hit the same live thread and also fail). result = instrumented({ stdout: "", stderr: `CLI_EXEC_FAILED: app-server turn failed: ${err.message}`, exitCode: 1, }); } finally { // 🔴 COG-87: put the owner's setting back on success, failure AND timeout — otherwise the // human's next turns run under the wake's sandbox. On a timeout the wake turn may still be // running; the update applies to SUBSEQUENT turns, so it does not cut that turn short. // A failed restore is loud and rides on the result, but never replaces the wake's reply. // Only the LAST overlapping wake restores: an earlier one would put the owner's setting back // under a wake still running, and that wake's policy would then stay on the thread. // Still `retained` here = no resume in this group answered, so nothing was sent and it is // unknown whether the human changed the setting since: putting the kept snapshot back could // undo their change, so the record waits for a wake that can see the thread (COG-87). if (sent) wakes.sent.push(sent); const last = --wakes.inFlight === 0; const restoreError = last && !wakes.retained ? await restoreOwnerSandbox(client, threadId, wakes.sent, wakes.owner, dial, handshake) : null; if (restoreError) { const note = `COG-87: could not restore the owner's sandbox on codex thread ${threadId} after the wake: ` + `${restoreError}. The human's next turns on this thread may run under the wake's sandbox ` + `(${wakes.sent[wakes.sent.length - 1]?.type ?? "unknown"}) until they change it.`; logger.warn(note); if (result) result.sandboxRestoreError = note; } // Drop the record once nothing is in flight — unless the restore failed with the owner known: // then the wake's policy is still on the thread and the next wake must not capture it. Kept // too while still `retained`: no wake in this group saw the thread. A wake that joined // during the restore keeps the record (it restores when it finishes). const ownerKnown = !!(wakes.owner?.permissionProfileId || wakes.owner?.sandbox); if (last && wakes.inFlight === 0 && threadWakes.get(threadId) === wakes) { if ((restoreError && ownerKnown) || wakes.retained) { // The next group starts fresh: nothing of it is on the thread yet. wakes.retained = true; wakes.policySent = false; } else { threadWakes.delete(threadId); } } // COG-95: an armed late wait owns the client and closes it itself — after this restore, which // it must never cut short. Otherwise the wake is over and the client goes now. if (lateOwnsClient) releaseClient(); else client.close(); } return result; // both the try and the catch assign it } /** * COG-95 option A: keep waiting, after the wake's timeout, for the turn identified by the caller's * turn-id matcher (`setDeliver` installs the resolver the notification listener already calls). * * Owns `client` from here on: every exit — completion, the late window, the socket closing, an * exception — closes it exactly once, and only after `released` (the COG-87 restore in the wake's * `finally` may still be using it). The restore and the per-thread wake count are NOT moved here: * the restore stays at the timeout, or the wake's sandbox would sit on the human's thread for the * whole late window. Never rejects. */ function armLateWait(client, windowMs, setDeliver, offNotifications, released) { return new Promise((resolveLate) => { let settled = false; let windowTimer; let offClose = () => { }; const now = () => new Date().toISOString(); const finish = (r) => { if (settled) return; settled = true; setDeliver(null); if (windowTimer) clearTimeout(windowTimer); offNotifications(); offClose(); void released.then(() => client.close()); resolveLate(r); }; try { setDeliver((msg) => { try { finish(msg ? { stdout: extractAgentMessageText([msg]), turnEndedAt: now() } : { stdout: null, reason: "error", at: now(), error: "no turn/completed frame" }); } catch (err) { finish({ stdout: null, reason: "error", at: now(), error: err.message }); } }); // The wait before the timeout never listened for this: a dead socket would have held the // late wait for its whole window. offClose = client.onClose(() => finish({ stdout: null, reason: "closed", at: now() })); if (client.closed) finish({ stdout: null, reason: "closed", at: now() }); // Already settled (the socket closed before the timeout): finish() found no timer to clear, // so arming one now would leave it, and the client it holds, alive for the whole window. if (settled) return; windowTimer = setTimeout(() => finish({ stdout: null, reason: "window", at: now() }), windowMs); // A bridge that is shutting down must not be held open by an hours-long timer alone. windowTimer.unref?.(); } catch (err) { finish({ stdout: null, reason: "error", at: now(), error: err.message }); } }); } //# sourceMappingURL=codex-app-server.js.map