@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.
347 lines • 18.1 kB
TypeScript
import { CliExecResult } from "../types.js";
import { type Config } from "../config.js";
/**
* The `app-server` codex real-time-wake rail.
*
* codex >=0.145 has a SINGLE-WRITER thread-store: a codex agent open in an
* interactive TUI holds an exclusive writer on its thread, so the `exec-resume`
* rail (`codex exec resume <same id>`) fast-fails `-32600 already has an active
* writer`. Here we inject the peer's message as a TURN through codex's
* app-server daemon instead — the daemon is the single writer; the human's
* `codex --remote` TUI and this bridge client are both just RPC clients, so
* there is no conflict (proven end-to-end in scratchpad/appserver-ws-proof.mjs).
*
* Transport (all verified against codex 0.147): a WebSocket on the daemon's
* unix socket at path `/rpc`, permessage-deflate DISABLED and `Host: localhost`
* (the real client sends no extensions; otherwise the upgrade hangs up). No auth
* token for the LOCAL unix socket. JSON-RPC messages are one WS text frame each
* (no LSP/newline framing).
*/
/** Minimal surface of a `ws` WebSocket we use — injectable for tests. */
export interface WsLike {
on(event: string, cb: (...args: any[]) => void): void;
send(data: string): void;
close(): void;
}
export type WsFactory = (url: string, opts: Record<string, unknown>) => WsLike;
/** Control socket for the codex app-server daemon under a given codex home. */
export declare function appServerSocketPath(codexHome?: string): string;
/**
* 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 declare function appServerDaemonRunning(codexHome?: string): boolean;
/** The `ws+unix://<sock>:/rpc` URL the daemon speaks JSON-RPC over. */
export declare function rpcUrl(sock: string): string;
/**
* 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 declare function ancestryHasAppServer(startPid: number, getProc: (pid: number) => {
cmd: string;
ppid: number;
} | null, maxDepth?: number): boolean;
/**
* 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 declare function runningUnderAppServerDaemon(): boolean;
/** A running app-server daemon whose control socket no longer exists (COG-105). */
export interface SocketGone {
/** The daemon's pid, from its own record. */
pid: number;
/** What is gone: the file the link points to (in /tmp), or the link itself. */
socket: string;
}
/** The daemon's own record, `<codex home>/app-server-daemon/daemon.pid` (codex 0.169.0, measured). */
export interface DaemonRecord {
pid: number;
/** Linux: /proc/sys/kernel/random/boot_id when the daemon started. */
bootId?: string;
/** Linux: field 22 of /proc/<pid>/stat, the daemon's start time in clock ticks. */
startTicks?: number;
/** When the record was written (the file's mtime). */
writtenMs: number;
}
/**
* 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 declare function daemonIdentityMatches(rec: DaemonRecord, procRoot?: string): boolean;
/**
* 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 declare function sameMountNamespace(pid: number, procRoot?: string): boolean;
/** Injectable for tests. */
export interface SocketGoneDeps {
/** Process lookup (default `ps`). */
proc?: (pid: number) => {
cmd: string;
ppid: number;
} | null;
/** Is the recorded pid that daemon, seeing our /tmp? (default: daemonIdentityMatches && sameMountNamespace) */
sameDaemon?: (rec: DaemonRecord) => boolean;
now?: () => number;
}
/**
* 🔴 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 declare function appServerSocketGone(codexHome?: string, deps?: SocketGoneDeps): SocketGone | null;
/**
* 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 declare function socketGoneReason(gone: SocketGone): string;
export declare function resetAppServerAncestryCache(): void;
export interface EnsureDaemonDeps {
/** Run a command; injectable for tests. Returns collected stdout/stderr/code. */
run?: (cmd: string, args: string[], env: NodeJS.ProcessEnv) => Promise<{
stdout: string;
stderr: string;
code: number | null;
}>;
/** Does the control socket exist yet? Injectable for tests. */
socketExists?: (p: string) => Promise<boolean>;
/** Total budget to wait for the socket to appear (ms). */
waitMs?: number;
/** Poll interval while waiting (ms). */
pollMs?: number;
}
export declare function resetDaemonCache(): void;
/**
* 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 declare function ensureDaemon(codexHome?: string, deps?: EnsureDaemonDeps): Promise<string>;
interface JsonRpcMessage {
jsonrpc?: string;
id?: number;
method?: string;
params?: any;
result?: any;
error?: {
code?: number;
message?: string;
};
}
/**
* 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 declare function extractAgentMessageText(notes: JsonRpcMessage[]): string;
/**
* A thin JSON-RPC-over-WebSocket client for the codex app-server daemon.
* `connect()` resolves once the socket is open + `initialize` succeeds.
*/
export declare class AppServerClient {
private ws;
private nextId;
private pending;
private notifyListeners;
private closeListeners;
private opened;
private openResolved;
/**
* 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: boolean;
constructor(ws: WsLike);
/** Await the open handshake. Rejects (before open) on connect/upgrade errors. */
waitOpen(): Promise<void>;
private _failAll;
private _onMessage;
/** Issue a JSON-RPC request and resolve with its result (rejects on rpc error). */
request(method: string, params?: unknown): Promise<any>;
/** Subscribe to server notifications; returns an unsubscribe fn. */
onNotification(cb: (msg: JsonRpcMessage) => void): () => void;
/**
* 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: () => void): () => void;
close(): void;
}
export interface AppServerDeps {
/** Injectable WebSocket factory (tests supply a fake). */
wsFactory?: WsFactory;
/** Override the daemon socket path (default derives from codex home). */
socketPath?: string;
/**
* Stable id of the inbound message (relay MessageRecord.id). When set, a
* duplicate injection of the SAME message into the SAME thread is coalesced
* (still in-flight) or short-circuited (recently completed) so the daemon
* never runs the peer's turn twice — the async-daemon-turn duplicate risk
* (the daemon keeps running a turn after our client times out/disconnects).
* Also sent as turn/start `clientUserMessageId` for daemon-side correlation.
*/
idempotencyKey?: string;
/**
* COG-95 option A (experiment switch on): when the turn outlives `timeoutMs`, keep listening for
* its completion this much longer and hand it back as `CliExecResult.late`. Unset = today.
*/
lateAnswerMaxMs?: number;
/** COG-95: the sandbox mode the caller resolved for this wake; unset → effectiveSandbox() now. */
sandbox?: Config["COGENT_CODEX_SANDBOX"];
}
/**
* codex 0.147 SandboxPolicy (shape from `codex app-server generate-ts`).
* `workspaceWrite` carries the exclude flags; `readOnly` carries networkAccess.
*/
type SandboxPolicy = {
type: "dangerFullAccess";
} | {
type: "readOnly";
networkAccess: boolean;
} | {
type: "workspaceWrite";
writableRoots: string[];
networkAccess: boolean;
excludeTmpdirEnvVar: boolean;
excludeSlashTmp: boolean;
};
/**
* 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 declare function sandboxPolicyFor(mode: Config["COGENT_CODEX_SANDBOX"], cwd: string): SandboxPolicy;
/**
* 🔴 COG-87: the thread owner's OWN permission setting, read from the thread/resume response.
*
* turn/start's `sandboxPolicy` is "Override the sandbox policy for this turn and subsequent turns"
* (codex 0.163.0 and 0.164.0-alpha.12): the wake's policy STAYS on the human's thread. The TUI
* sends no policy on its own turns, so the human's next turns ran under the wake's sandbox.
* Measured live on both versions: after a wake turn with `dangerFullAccess`, thread/resume
* reports `sandbox: dangerFullAccess` and `activePermissionProfile: null` — and the profile is
* cleared even when the wake sends the SAME sandbox the owner already had.
*
* `sandbox` is passed back to codex verbatim (never re-derived), so any variant codex emits
* (incl. externalSandbox) restores exactly.
*/
export interface OwnerSandbox {
sandbox: Record<string, unknown> | null;
permissionProfileId: string | null;
/** The thread's cwd as thread/resume reports it: codex keeps it implicit in writableRoots. */
cwd: string | null;
}
/** Read the owner's setting from a ThreadResumeResponse (`sandbox`, `activePermissionProfile`, `cwd`). */
export declare function ownerSandboxFrom(resume: any): OwnerSandbox;
/**
* 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 declare function restoreParamsFor(threadId: string, sent: SandboxPolicy, owner: OwnerSandbox): Record<string, unknown> | null;
/** Bound on the restore call, so a dead daemon cannot hang the wake. */
export declare const RESTORE_TIMEOUT_MS = 10000;
/** Bound on each best-effort instrumentation call (COG-95): it may cost a wake nothing. */
export declare const PROBE_TIMEOUT_MS = 2000;
/**
* 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 declare function codexVersionFrom(init: unknown): string | undefined;
/** The key codex gives the Cogent plugin's Stop hook in `hooks/list` (operator-measured, 2026-10-27). */
export declare 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 declare function stopHookFrom(list: unknown): {
enabled: boolean;
trust: string;
} | 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 declare function probeCogentStopHook(cwd: string, deps?: {
wsFactory?: WsFactory;
socketPath?: string;
timeoutMs?: number;
}): Promise<{
enabled: boolean;
trust: string;
} | null | undefined>;
/**
* 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 declare function codexStopHookWarning(state: {
enabled: boolean;
trust: string;
} | null | undefined): string | null;
/** Clear the injection idempotency cache and the per-thread wake records (test isolation). */
export declare function resetAppServerIdempotency(): void;
/**
* 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 declare function execCodexViaAppServer(threadId: string, message: string, cwd: string, timeoutMs?: number, deps?: AppServerDeps): Promise<CliExecResult>;
export {};
//# sourceMappingURL=codex-app-server.d.ts.map