Official
codex
Codex agent provider: runs the Codex CLI's app-server for each account.
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/codex@0.2.5
Permissions in 0.2.5
Files
agent.ts102.8 KB
// The Codex provider: one `codex app-server` process per account, one
// Codex thread per Divergence session (a session id is a thread id).
// See NOTES.md for the protocol facts behind every choice here.
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Queue from "effect/Queue";
import * as Result from "effect/Result";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as z from "zod";
import { Host, Process, parse } from "divergence/effect";
import type { PluginServices, EffectAgent } from "divergence/effect";
import { RpcTransport, TransportFailed, request, shutdown, runProcess, callHostToolEffect } from "../sdk/effect.ts";
import type { TransportError } from "../sdk/effect.ts";
import type { RpcProcess, ProcessExit } from "../sdk/process.ts";
import { splitArgs } from "../sdk/process.ts";
import type { JsonRpcConnection, RpcRequest, Responder, RequestOptions } from "../sdk/jsonrpc.ts";
import { ProviderError, errorMessage } from "../sdk/errors.ts";
import { taskOutput } from "../sdk/tasks.ts";
import { SessionWatch } from "../sdk/sessions.ts";
import * as wire from "./wire.ts";
import * as requests from "./requests.ts";
import { itemNotice } from "./items.ts";
import { mergeLimits } from "./quota.ts";
import type { Instance } from "./instances.ts";
import type {
Child,
Task,
Session,
Facts,
Event,
History,
ToolCall,
ToolContent,
Usage,
QuestionField,
QuestionAnswer,
SessionOptions,
PromptInput,
UsageLimits,
AgentInfo,
} from "./types.ts";
import { sessionSchema, answerSchema, promptSchema } from "./types.ts";
export { ProviderError };
interface Pending<A> {
session: string;
request: string;
answer: (value: A | null) => void;
}
type Maintenance = NonNullable<AgentInfo["maintenance"]>;
import { methodNotFound, RpcError } from "../sdk/jsonrpc.ts";
import { agentEvent, consumedInput, newId, compact, outcome, rejectedInput, QUEUED_INPUT_HELD } from "../sdk/agent.ts";
import type { ProcessReport } from "../sdk/agent.ts";
import { installerOf, npmPrefix, isNewer, latestNpmEffect, latestBrewEffect } from "../sdk/maintenance.ts";
import * as map from "./map.ts";
import { setStatus, parentOf, factsOfThread, applyFacts } from "./children.ts";
import { nativeRejection, threadGone, threadUnmaterialized, resumeFailure } from "./errors.ts";
import {
OPTION_MODEL,
OPTION_REASONING,
startParams,
resumeParams,
forkParams,
turnParams,
userInput,
} from "./params.ts";
import { agentId, displayName, homeOf } from "./instances.ts";
import { loadModels, optionsFor, providerMethods, selectProvider } from "./catalog.ts";
import { authenticate, gatewayChanged } from "./auth.ts";
import { ICON } from "./icon.ts";
import { contextText, echoSchema, storageValues } from "../sdk/context.ts";
import { readResource, callTool } from "./mcp.ts";
export const FAMILY = "codex";
/// Reported to the app-server as the client's version.
export const CLIENT_VERSION = "0.2.0";
/// Raised when a thread's turns map differently, so a thread read before is
/// read again once (images were left out before 2, and images sent as a
/// file path before 3, newer display items before 4, MCP Apps before 5,
/// and viewed images before 6).
const HISTORY_FORMAT = 6;
/// The npm package that publishes the CLI.
const NPM_PACKAGE = "@openai/codex";
/// Turns read per `thread/turns/list` call, and the point at which a very
/// long thread stops being loaded.
const TURN_PAGE = 100;
const MAX_TURNS = 2000;
/// Subagent threads read for one `read_session`, at every depth together.
const MAX_SUBAGENT_THREADS = 64;
/// How long a Stop waits on each subagent's interrupt, and on all of them.
const CHILD_INTERRUPT = 3000;
const CHILDREN_INTERRUPT = 10_000;
/// The Codex version out of the app-server's user agent, which reads
/// `<client>/<codex version> (<platform>) …`.
export function versionOf(userAgent: unknown) {
if (typeof userAgent !== "string") return null;
const slash = userAgent.indexOf("/");
if (slash < 0) return null;
const version =
userAgent
.slice(slash + 1)
.trim()
.split(/\s+/)[0] ?? "";
return version || null;
}
/// How long Codex keeps a thread loaded after the last client let go.
const THREAD_UNLOAD_DELAY_SECS = 5;
function now() {
return new Date().toISOString();
}
export function newSession(workspace = "", options: Record<string, unknown> = {}): Session {
return {
workspace,
options: { ...options },
run: null,
turn: null,
inputs: new Map(),
endedTurns: new Set(),
// The host's id of each user message, with the turn it started. A
// rollback names the host's id; Codex only knows its turns.
turns: new Map(),
// Items that received a delta, so the completed item does not repeat
// the streamed text.
streamed: new Set(),
startedTools: new Set(),
// Reasoning held back while it could still be only the stdin notice.
held: new Map(),
};
}
/// Whether reasoning text could still turn out to be the stdin notice.
function couldBeStdinNotice(text: string) {
return map.STDIN_NOTICE.startsWith(text.trimStart()) || map.isStdinNotice(text);
}
function historyKey(kind: "client" | "native", agent: string, session: string, id: string) {
return `history:${JSON.stringify([kind, agent, session, id])}`;
}
export class CodexAgent {
terminals = new Map<string, { thread: string; published: boolean; task: import("divergence/protocol").TaskInfo }>();
instance: Instance;
transport: RpcTransport["Service"];
scope: Scope.Scope;
env: Record<string, string>;
emit: (event: Event) => void;
/// Sends a process report (`agent/process`) to the host's process pool.
report: (report: ProcessReport) => void;
id: string;
name: string;
proc: RpcProcess | null;
/// The pool's id for `proc`, and the threads loaded in it: those it
/// started, resumed or forked, until they are closed or it exits.
processId: string | null = null;
loaded = new Set<string>();
hostFeatures = new Set<string>();
connecting: Fiber.Fiber<RpcProcess, ProviderError | TransportError> | null;
userAgent: string | null;
models = new Map<string, wire.Model[]>();
gatewayLogins = new Map<string, { done: Deferred.Deferred<void, ProviderError>; loginId?: string | null }>();
sessions: Map<string, Session>;
approvals: Map<string, Pending<string>>;
/// Each file change item's diffs while it runs: Codex's approval names
/// the item only, and the card shows what it changes.
fileChanges: Map<string, ToolContent[]>;
questions: Map<string, Pending<QuestionAnswer>>;
skills: Map<string, string>;
subagents: Map<string, Child>;
accountDirty: boolean;
/// Each sign-in the browser has yet to finish, by Codex's login id;
/// `account/login/completed` settles it.
logins = new Map<string, Deferred.Deferred<void, ProviderError>>();
quotaDisplay: z.infer<typeof wire.limits> | null = null;
quotaFacts: import("divergence/protocol").UsageRecovery | null = null;
accountGeneration = 0;
/// The last `config/read` failure the app was told about, so the options
/// a chat lists over and over report it once, and again after a success.
configFailure: string | null = null;
/// The out-of-band diagnostics already shown (`configWarning` and the
/// like), which each app-server repeats.
diagnostics = new Set<string>();
/// The last configuration `config/read` gave for each workspace: a turn
/// carries its sandbox settings (`turnParams`).
configs = new Map<string, wire.Config>();
/// Reports a thread started in the Codex app or CLI (`sessions_changed`).
sessionWatch: SessionWatch;
jobs: Queue.Queue<Effect.Effect<unknown, unknown, PluginServices>>;
imageNotifications = new Map<string, { method: wire.Routed; params: wire.Notification }[]>();
enqueue(job: Effect.Effect<unknown, unknown, PluginServices>) {
Queue.offerUnsafe(this.jobs, job);
}
background = Effect.fn("Codex.background")(function* (this: CodexAgent) {
yield* Stream.runForEach(Stream.fromQueue(this.jobs), (job) => job.pipe(Effect.forkIn(this.scope))).pipe(
Effect.forkIn(this.scope),
);
});
request = Effect.fn("Codex.request")(
<M extends keyof typeof wire.responses>(
connection: JsonRpcConnection,
method: M,
params?: unknown,
options: Omit<RequestOptions, "signal"> = {},
) => request<z.infer<(typeof wire.responses)[M]>>(connection, method, wire.responses[method], params, options),
);
latest = Effect.fn("Codex.latest")(function* (
this: CodexAgent,
manager: string,
name: string,
prefix: string | null,
) {
return yield* manager === "brew" ? latestBrewEffect(name) : latestNpmEffect(name, prefix);
});
/// `api`: the plugin API. `instance`: the account. `env`: the login
/// environment's `HOME`, `CODEX_HOME` and `CODEX_ARGS`. `emit`: sends an
/// agent event and `report` a process report (both set once the agent is
/// registered).
constructor({
instance,
scope,
transport,
jobs,
env = {},
emit = () => {},
report = () => {},
}: {
instance: Instance;
scope: Scope.Scope;
transport: RpcTransport["Service"];
jobs: CodexAgent["jobs"];
env?: Record<string, string>;
emit?: (event: Event) => void;
report?: (report: ProcessReport) => void;
}) {
this.scope = scope;
this.transport = transport;
this.jobs = jobs;
this.instance = instance;
this.env = env;
this.emit = emit;
this.report = report;
this.id = agentId(instance);
this.name = displayName(instance);
this.proc = null;
this.connecting = null;
this.userAgent = null;
this.models.clear();
this.sessions = new Map();
this.approvals = new Map();
this.fileChanges = new Map();
this.questions = new Map();
// Skill name to the path Codex knows it by, filled by `list_skills`.
this.skills = new Map();
// Subagent thread id to its chat and task, at any depth.
this.subagents = new Map();
// The account changed, so a cached status must be read again.
this.accountDirty = false;
this.sessionWatch = new SessionWatch({
session: map.rolloutThread,
own: (thread) => this.sessions.has(thread) || this.subagents.has(thread) || this.loaded.has(thread),
report: (workspace) => this.emit({ sessionId: "", event: "sessions_changed", workspace }),
run: (work) => this.enqueue(work),
});
}
/// The handlers the host calls, by `agent/<method>` name.
definition(
before: Effect.Effect<Record<string, string>, never, PluginServices> = Effect.succeed(this.env),
): EffectAgent {
const call = <S extends z.ZodType, A, E>(
schema: S,
handler: (params: z.infer<S>) => Effect.Effect<A, E, PluginServices>,
) =>
Effect.fn("Codex.handler")(
function* (this: CodexAgent, params: unknown) {
this.env = yield* before;
return yield* handler(yield* parse("codex handler", schema, params));
}.bind(this),
);
const session = z.object({ sessionId: z.string() });
const handlers: EffectAgent = {
id: this.id,
name: this.name,
icon: ICON,
initialize: call(z.object({ hostFeatures: z.array(z.string()).optional() }).optional(), (params) =>
this.initialize(params),
),
list_options: call(z.object({ workspace: z.string() }), (params) => this.listOptions(params)),
list_commands: call(z.unknown(), () => this.listCommands()),
list_sessions: call(z.object({ workspace: z.string() }), (params) => this.listSessions(params)),
read_session: call(session, (params) => this.readSession(params)),
list_skills: call(z.object({ workspace: z.string() }), (params) => this.listSkills(params)),
create_session: call(sessionSchema, (params) => this.createSession(params)),
resume_session: call(
sessionSchema.extend({ sessionId: z.string(), requireResume: z.boolean().optional() }),
(params) => this.resumeSession(params),
),
close_session: call(session, (params) => this.closeSession(params)),
fork_session: call(sessionSchema.extend({ sessionId: z.string(), itemId: z.string().optional() }), (params) =>
this.forkSession(params),
),
prompt: call(session.extend({ input: promptSchema }), (params) => this.prompt(params)),
cancel: call(session, (params) => this.cancel(params)),
cancel_task: call(session.extend({ taskId: z.string() }), (params) => this.cancelTask(params)),
set_option: call(session.extend({ optionId: z.string(), value: z.unknown() }), (params) =>
this.setOption(params),
),
respond_to_approval: call(z.object({ approvalId: z.string(), optionId: z.string() }), (params) =>
this.respondToApproval(params),
),
respond_to_question: call(z.object({ questionId: z.string(), answer: answerSchema }), (params) =>
this.respondToQuestion(params),
),
rollback: call(session.extend({ itemId: z.string() }), (params) => this.rollback(params)),
compact: call(session, (params) => this.compact(params)),
usage_limits: call(z.unknown(), () => this.usageLimits()),
update: call(z.unknown(), () => this.update()),
authenticate: call(z.object({ method: z.string() }), (params) => this.authenticate(params)),
logout: call(z.unknown(), () => this.logout()),
};
// The API's agent types do not list the pool and MCP App calls yet.
// Threads share one app-server, so there is no `suspend_session`.
return Object.assign(handlers, {
stop_process: call(z.object({ processId: z.string() }), (params) => this.stopProcess(params)),
mcp_read_resource: call(
session.extend({ server: z.string(), uri: z.string(), toolCallId: z.string().optional() }),
(params) => readResource(this, params),
),
mcp_call_tool: call(
session.extend({ server: z.string(), name: z.string(), arguments: z.record(z.string(), z.unknown()), toolCallId: z.string().optional() }),
(params) => callTool(this, params),
),
});
}
// --- connection -------------------------------------------------------------
home() {
return homeOf(this.instance, this.env);
}
/// The live app-server, started on first use and again when it died.
client = Effect.fn("Codex.client")(function* (
this: CodexAgent,
): Effect.fn.Return<RpcProcess, ProviderError | TransportError, PluginServices> {
if (this.proc?.alive) return this.proc;
let connecting = this.connecting;
if (!connecting) {
connecting = yield* this.connect().pipe(
Effect.ensuring(
Effect.sync(() => {
this.connecting = null;
}),
),
Effect.forkIn(this.scope),
);
this.connecting = connecting;
}
return yield* Fiber.join(connecting);
});
connect = Effect.fn("Codex.connect")(function* (this: CodexAgent) {
const transport = this.transport;
const launch = splitArgs(this.env.CODEX_ARGS ?? "");
// A thread this app let go of (`releaseIdle`) is unloaded soon after,
// so another Codex program can take it over.
const args = ["app-server", "-c", `thread_unload_delay_secs=${THREAD_UNLOAD_DELAY_SECS}`, ...launch, ...this.instance.args];
const home = this.home();
let proc: RpcProcess | undefined;
proc = yield* transport
.spawn("codex", args, {
name: "codex",
env: home ? { CODEX_HOME: home } : undefined,
onNotification: ({ method, params }) => this.onNotification(method, params),
onRequest: (request) => this.onRequest(request),
onExit: (status, tail) => this.onExit(proc, status, tail),
})
.pipe(
Effect.provideService(Scope.Scope, this.scope),
Effect.mapError(
(error) =>
new ProviderError({
message: `the codex CLI could not be started (it must be on the login PATH): ${errorMessage(error)}`,
}),
),
);
const initialized = yield* Effect.result(
this.request(proc.connection, "initialize", {
clientInfo: { name: "divergence", title: "Divergence", version: CLIENT_VERSION },
capabilities: { experimentalApi: true, requestAttestation: false, requiredHumanApproval: true, explicitGatewayOauth: true },
}),
);
if (Result.isFailure(initialized)) {
const tail = proc.stderrTail().join("\n");
yield* shutdown(proc, 500).pipe(Effect.catchTag("TransportFailed", () => Effect.void));
return yield* new ProviderError({
message: `codex app-server rejected initialize: ${errorMessage(initialized.failure)}${tail ? `\n${tail}` : ""}`,
});
}
proc.connection.notify("initialized", null);
this.userAgent = initialized.success.userAgent ?? "";
this.proc = proc;
this.processId = newId("codex-app-server");
this.loaded.clear();
this.reportProcess("started");
return proc;
});
/// The app-server ended: every subagent still at work and every run
/// still going fails, so nothing waits on a process that is gone.
onExit(proc: RpcProcess | undefined, status: ProcessExit | null, tail: string[]) {
if (proc && this.proc !== proc && this.proc !== null) return;
const detail = tail?.length ? `: ${tail.slice(-5).join(" | ")}` : "";
console.info(`codex app-server exited (${JSON.stringify(status)})${detail}`);
if (this.proc === proc && this.processId) this.reportProcess("stopped");
this.proc = null;
this.processId = null;
this.loaded.clear();
this.invalidateQuota();
for (const terminal of this.terminals.values()) {
terminal.task.status = "failed";
terminal.task.endedAt = new Date().toISOString();
this.emitTerminal(terminal);
}
this.terminals.clear();
for (const login of this.logins.values())
Deferred.doneUnsafe(login, Effect.fail(new ProviderError({ message: "the codex app-server exited before the sign-in finished" })));
this.logins.clear();
for (const login of this.gatewayLogins.values()) Deferred.doneUnsafe(login.done, Effect.fail(new ProviderError({ message: "The Codex app-server exited before gateway sign-in finished." })));
this.gatewayLogins.clear();
for (const [thread, child] of this.subagents) {
if (!map.isLive(child.task.status)) continue;
this.updateChild(thread, (c) => {
c.turn = null;
c.task.summary ??= "The codex app-server exited";
return setStatus(c, "failed");
});
}
for (const [session, state] of this.sessions) {
// A thread is loaded in the app-server that started or resumed it;
// the next one knows none of them until they are resumed again.
state.unloaded = true;
state.stopping = undefined;
this.finishRun(session, outcome.failed("the codex app-server exited"));
}
}
/// The connection with `sessionId`'s thread loaded in it: a thread that
/// was open in an app-server that exited (an update, a crash) is resumed
/// in the new one first, or `turn/start` fails with "thread not found".
loadedConnection = Effect.fn("Codex.loadedConnection")(function* (this: CodexAgent, sessionId: string) {
const { connection } = yield* this.client();
const state = this.sessions.get(sessionId);
if (state?.releasing) yield* Deferred.await(state.releasing);
if (state?.unloaded) {
yield* this.request(connection, "thread/resume", resumeParams(sessionId, state)).pipe(
Effect.mapError((error) => resumeFailure(sessionId, error)),
);
state.unloaded = false;
this.loadedThread(sessionId);
}
return connection;
});
/// Stops the app-server. The next call starts a fresh one.
shutdownProcess = Effect.fn("Codex.shutdownProcess")(function* (this: CodexAgent) {
if (this.proc) yield* shutdown(this.proc);
});
/// The pool stops the app-server: its threads become unloaded
/// (`onExit`), and each is resumed in the next one on its next prompt
/// (`loadedConnection`). An id of an app-server that already exited
/// has nothing left to stop.
stopProcess = Effect.fn("Codex.stopProcess")(function* (this: CodexAgent, { processId }: { processId: string }) {
if (processId === this.processId) yield* this.shutdownProcess();
return {};
});
// --- process reports ------------------------------------------------------------
/// One shared pool slot: the app-server, with the threads loaded in it.
reportProcess(state: ProcessReport["state"]) {
if (!this.processId) return;
this.report({
processId: this.processId,
state,
sessions: state === "stopped" ? [] : [...this.loaded],
shared: true,
external: false,
});
}
loadedThread(thread: string) {
if (this.loaded.has(thread)) return;
this.loaded.add(thread);
this.reportProcess("sessions");
}
// --- events ---------------------------------------------------------------------
send(event: Event) {
this.emit(event);
}
runOf(session: string) {
return this.sessions.get(session)?.run ?? null;
}
/// Emits an event for a Codex thread. A subagent runs in its own thread;
/// its events belong to the chat that spawned it, tagged with the task,
/// so the transcript nests them instead of dropping them.
emitFor(thread: string, kind: import("divergence/protocol").AgentEventKind) {
const child = this.subagents.get(thread);
const session = child ? child.root : thread;
this.emit(agentEvent(session, kind, { runId: this.runOf(session), taskId: child ? thread : null }));
}
/// The host session a thread belongs to: itself, or the chat of the
/// subagent it is.
rootOf(thread: string) {
return this.subagents.get(thread)?.root ?? thread;
}
/// Sends a subagent's snapshot to its chat. The host places it inside
/// `parentTaskId`, so the event itself is untagged.
emitTask(thread: string) {
const child = this.subagents.get(thread);
if (!child) return;
const event: { sessionId: string; runId?: string } = { sessionId: child.root };
const runId = this.runOf(child.root);
if (runId) event.runId = runId;
this.send(Object.assign(event, { event: "task" as const }, compact(child.task)));
}
/// Changes a known subagent and sends its snapshot when that changed
/// anything. `false` for a thread that is not a subagent.
updateChild(thread: string, change: (child: Child) => boolean) {
const child = this.subagents.get(thread);
if (!child) return false;
if (change(child)) this.emitTask(thread);
return true;
}
/// Registers a subagent `parent` started, or adds what is now known
/// about one already registered, and sends its snapshot. A grandchild
/// reports into the same chat, inside its parent's task.
registerChild(thread: string, parent: string, facts: Facts) {
let child = this.subagents.get(thread);
if (child) {
applyFacts(facts, child);
} else {
// `thread/started` reports every thread of the app-server; one whose
// parent is neither a chat here nor a known subagent is not ours.
const parentChild = this.subagents.get(parent);
let root;
let parentTask = null;
if (parentChild) {
root = parentChild.root;
parentTask = parent;
} else if (this.sessions.has(parent)) {
root = parent;
} else {
return;
}
const task: Task = { id: thread, title: "", status: "running", startedAt: now() };
if (parentTask) task.parentTaskId = parentTask;
child = {
root,
turn: null,
endedTurns: new Set(),
task,
taskName: null,
tools: new Set(),
streamed: new Set(),
held: new Map(),
};
applyFacts(facts, child);
this.subagents.set(thread, child);
}
this.emitTask(thread);
}
/// Registers a subagent a collab call addresses but this process never
/// saw start (it was spawned before a restart), so its events reach the
/// chat. Its names come from its own thread record.
adoptChild(thread: string, parent: string) {
// A chat is never a subagent, even when a child addresses it.
if (this.subagents.has(thread) || this.sessions.has(thread)) return;
this.registerChild(thread, parent, {});
this.readFacts(thread);
}
/// Fills a registered subagent's prompt and names from its own thread
/// record, in the background, on the running connection.
readFacts(thread: string) {
const proc = this.proc;
if (!proc?.alive) return;
this.enqueue(
this.request(proc.connection, "thread/read", { threadId: thread, includeTurns: false }).pipe(
Effect.tap((response) =>
Effect.sync(() => {
if (response.thread) this.registerChild(thread, "", factsOfThread(response.thread));
}),
),
Effect.catchTag(["TransportFailed", "ParseFailed"], (error) =>
Effect.sync(() => console.debug(`could not read the subagent thread ${thread}: ${errorMessage(error)}`)),
),
),
);
}
notice(thread: string, level: import("divergence/protocol").NoticeLevel, message: unknown) {
this.emitFor(thread, { event: "notice", level, message: String(message) });
}
/// Shows a diagnostic Codex sent out of band, once per run.
diagnose(thread: string | null, message: string) {
if (!this.diagnostics.has(message)) this.notice(thread ?? "", "warning", message);
this.diagnostics.add(message);
}
/// Ends the active run of `session`. A second call does nothing, so a
/// run always ends with exactly one `run_finished`.
finishRun(session: string, result: import("../sdk/agent.ts").RunOutcome) {
const state = this.sessions.get(session);
if (!state) return;
if (state.turn) state.endedTurns.add(state.turn);
if (state.starting) Deferred.doneUnsafe(state.starting, Effect.succeed(null));
state.starting = undefined;
state.turn = null;
const runId = state.run;
state.run = null;
if (runId) this.send({ sessionId: session, runId, event: "run_finished", outcome: result });
this.releaseIdle(session);
}
/// Codex lets one program at a time write a thread, and it keeps that
/// lock while the thread is loaded. A chat lets go of its thread once
/// nothing of it runs here (no turn, background terminal or subagent),
/// so the Codex CLI or app can continue it; Codex unloads it after
/// `thread_unload_delay_secs` (see `connect`), and the next prompt here
/// resumes it first (`loadedConnection`).
releaseIdle(session: string) {
const state = this.sessions.get(session);
const proc = this.proc;
if (!state || state.unloaded || state.run || state.turn || state.stopping || !proc?.alive) return;
const owned = (thread: string) => thread === session || this.subagents.get(thread)?.root === session;
for (const terminal of this.terminals.values()) if (owned(terminal.thread)) return;
for (const [thread, child] of this.subagents) if (owned(thread) && map.isLive(child.task.status)) return;
state.unloaded = true;
const released = Deferred.makeUnsafe<void>();
state.releasing = released;
this.enqueue(
this.request(proc.connection, "thread/unsubscribe", { threadId: session }).pipe(
Effect.catchTag(["TransportFailed", "ParseFailed"], (error) =>
Effect.sync(() => console.warn(`could not release the codex thread ${session}: ${errorMessage(error)}`)),
),
Effect.ensuring(
Effect.sync(() => {
if (state.releasing === released) state.releasing = undefined;
Deferred.doneUnsafe(released, Effect.void);
}),
),
),
);
}
/// The streaming state of a thread: its session's, or its subagent's.
streamState(thread: string) {
return this.subagents.get(thread) ?? this.sessions.get(thread) ?? null;
}
markStreamed(thread: string, item: string) {
this.streamState(thread)?.streamed.add(item);
}
wasStreamed(thread: string, item: string) {
return this.streamState(thread)?.streamed.has(item) ?? false;
}
/// A tool item already reported as started.
toolStarted(thread: string, item: string) {
const child = this.subagents.get(thread);
if (child) return child.tools.has(item);
return this.sessions.get(thread)?.startedTools.has(item) ?? false;
}
/// A reasoning delta. The first text of an item is held while it could
/// still be only `codex exec`'s stdin notice, which is not reasoning.
reasoningDelta(thread: string, item: string, delta: string) {
const state = this.streamState(thread);
const first = state ? !state.streamed.has(item) : false;
if (state) state.streamed.add(item);
const held = state?.held.get(item);
if (held !== undefined) {
const text = held + delta;
if (couldBeStdinNotice(text)) {
state?.held.set(item, text);
return;
}
state?.held.delete(item);
this.emitFor(thread, { event: "reasoning_delta", itemId: item, text, mode: "append" });
return;
}
if (first && delta && couldBeStdinNotice(delta)) {
state?.held.set(item, delta);
return;
}
this.emitFor(thread, { event: "reasoning_delta", itemId: item, text: delta, mode: "append" });
}
/// A completed reasoning item's held text: dropped when it is the stdin
/// notice, sent otherwise.
releaseHeld(thread: string, item: string) {
const state = this.streamState(thread);
const held = state?.held.get(item);
if (held === undefined) return;
state?.held.delete(item);
if (!map.isStdinNotice(held))
this.emitFor(thread, { event: "reasoning_delta", itemId: item, text: held, mode: "append" });
}
// --- notifications -----------------------------------------------------------------
/// A notification that does not fit the wire schema is Codex's protocol
/// drifting from this plugin, and one this plugin fails to handle is its
/// own bug. Either may lose part of a turn, so the chat it belongs to is
/// told (the whole app when no thread is named), not only the log.
onNotification(method: string, params: unknown) {
// Its `error` is a string, not a turn's error, so it has its own schema.
if (method === "account/login/completed") {
const completed = wire.loginCompleted.safeParse(params);
if (completed.success) return this.loginCompleted(completed.data);
}
if (method === "account/gatewayOAuth/changed") {
this.enqueue(gatewayChanged(this, params));
return;
}
if (!wire.isRouted(method)) return;
const thread = wire.threadOf(params);
const failed = (message: string) => {
console.warn(`codex: ${message}`);
if (thread) this.notice(thread, "warning", message);
else this.send({ sessionId: "", event: "notice", level: "warning", message });
};
const parsed = wire.notification.safeParse(params ?? {});
if (!parsed.success) {
const issues = parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
failed(`Codex sent a ${method} this plugin cannot read (${issues})`);
return;
}
try {
const root = thread && this.rootOf(thread);
const pending = root && this.imageNotifications.get(root);
if (pending) {
pending.push({ method, params: parsed.data });
} else if (root && (method === "item/started" || method === "item/completed") && parsed.data.item?.type === "imageView" && this.proc?.alive) {
this.imageNotifications.set(root, []);
this.enqueue(this.deliverImage(root, method, parsed.data, this.proc.connection));
} else this.routeNotification(method, parsed.data);
} catch (error) {
failed(`Divergence failed to handle Codex's ${method}: ${errorMessage(error)}`);
}
}
/// Resolve the file through the app-server that viewed it before forwarding
/// later events in the chat, so the host stores the picture with its row.
deliverImage = Effect.fn("Codex.deliverImage")(function* (this: CodexAgent, root: string, method: wire.Routed, params: wire.Notification, connection: JsonRpcConnection) {
try {
const call = map.toolCallFromItem(params.item, this.hostFeatures.has("mcpApps"));
if (call) yield* this.inlineToolImage(connection, call);
this.routeNotification(method, params, call ?? undefined);
} catch (error) {
this.notice(root, "warning", `Divergence failed to handle Codex's ${method}: ${errorMessage(error)}`);
} finally {
const pending = this.imageNotifications.get(root) ?? [];
this.imageNotifications.delete(root);
for (const event of pending) this.onNotification(event.method, event.params);
}
});
inlineToolImage = Effect.fn("Codex.inlineToolImage")(function* (this: CodexAgent, connection: JsonRpcConnection, call: ToolCall) {
for (const image of call.content ?? []) {
if (image.type !== "image" || !image.path) continue;
const result = yield* Effect.result(this.request(connection, "fs/readFile", { path: image.path }));
if (Result.isSuccess(result)) {
image.data = result.success.dataBase64;
delete image.path;
} else console.debug(`could not read the image ${image.path}: ${result.failure.message}`);
}
});
routeNotification(method: wire.Routed, p: wire.Notification, imageCall?: ToolCall) {
const thread = typeof p.threadId === "string" ? p.threadId : null;
const stream = thread ? this.streamState(thread) : null;
// Correlated late input evidence belongs to its original run even after
// retirement. Fence known retired turns, not every differing ID: child
// activity and native turn/started are independent lifecycle evidence.
const nativeTurn = p.turnId ?? p.turn?.id;
const item = method === "item/started" || method === "item/completed" ? p.item : null;
// Command processes keep producing output after their native turn retired.
// Their lifetime is the command item, rather than that turn's lifetime.
if (thread && item?.type === "commandExecution") this.terminalItem(thread, item);
if (thread && method === "item/commandExecution/outputDelta" && typeof p.itemId === "string") {
const terminal = this.terminals.get(JSON.stringify([thread, p.itemId]));
if (terminal && typeof p.delta === "string") {
terminal.task.output = taskOutput((terminal.task.output ?? "") + p.delta);
this.emitTerminal(terminal, p.delta);
}
}
if (thread && item) this.consumeInput(thread, item);
if (nativeTurn && stream?.endedTurns.has(nativeTurn)) {
// Child snapshots outlive the turn that spawned/addressed them; these
// bookkeeping items cannot finish the parent or revive its run.
if (thread && item?.type === "collabAgentToolCall") this.onCollabItem(thread, item);
if (thread && item?.type === "subAgentActivity") this.onActivity(thread, item);
// A command can outlive its turn: its completion still ends the row
// the turn started (an unknown row stays unknown to the host).
if (thread && method === "item/completed" && item) this.lateCompletion(thread, item, imageCall);
return;
}
switch (method) {
case "item/agentMessage/delta":
if (thread === null || typeof p.itemId !== "string") return;
this.markStreamed(thread, p.itemId);
this.emitFor(thread, {
event: "text_delta",
itemId: p.itemId,
text: typeof p.delta === "string" ? p.delta : "",
mode: "append",
});
return;
case "item/reasoning/textDelta":
case "item/reasoning/summaryTextDelta":
if (thread === null || typeof p.itemId !== "string") return;
this.reasoningDelta(thread, p.itemId, typeof p.delta === "string" ? p.delta : "");
return;
case "item/started":
if (thread === null || !p.item) return;
this.onItemStarted(thread, p.item, imageCall);
return;
case "item/completed":
if (thread === null || !p.item) return;
this.onItemCompleted(thread, p.item, imageCall);
return;
case "item/commandExecution/outputDelta":
case "item/fileChange/outputDelta":
if (thread === null || typeof p.itemId !== "string") return;
this.emitFor(thread, {
event: "tool_call_updated",
id: p.itemId,
outputDelta: typeof p.delta === "string" ? p.delta : "",
});
return;
case "item/fileChange/patchUpdated": {
if (thread === null || typeof p.itemId !== "string") return;
const content = map.diffContent(Array.isArray(p.changes) ? p.changes : []);
this.fileChanges.set(p.itemId, content);
this.emitFor(thread, { event: "tool_call_updated", id: p.itemId, content });
return;
}
case "turn/started": {
if (thread === null || typeof p.turn?.id !== "string") return;
const turn = p.turn.id;
if (stream?.turn && stream.turn !== turn) stream.endedTurns.add(stream.turn);
const isChild = this.updateChild(thread, (child) => {
child.turn = turn;
child.streamed.clear();
child.held.clear();
return setStatus(child, "running");
});
if (!isChild) {
const state = this.sessions.get(thread);
// Codex starts turns in the order it was asked, so while a Stop
// waits for its turn's name, the next turn announced is that one.
if (state?.stopping && !state.stopping.turn) this.nameStopped(thread, state.stopping, turn);
else if (state) {
if (!state.run) {
state.run = newId("codex-run");
this.emitFor(thread, { event: "run_started" });
}
state.turn = turn;
state.streamed.clear();
state.startedTools.clear();
state.held.clear();
if (state.starting) Deferred.doneUnsafe(state.starting, Effect.succeed(turn));
}
}
return;
}
case "turn/completed": {
if (thread === null || typeof p.turn?.id !== "string") return;
if (!["completed", "interrupted", "failed"].includes(p.turn.status ?? "")) return;
stream?.endedTurns.add(p.turn.id);
// A terminal event cannot settle a different live native turn.
if (stream?.turn && stream.turn !== p.turn.id) return;
for (const terminal of this.terminals.values()) {
if (terminal.thread !== thread || terminal.published) continue;
terminal.published = true;
this.emitTerminal(terminal);
}
// A subagent's turn is not the chat's run.
const status = map.turnTaskStatus(p.turn.status);
const message = typeof p.turn.error?.message === "string" && p.turn.error.message ? p.turn.error.message : null;
const isChild = this.updateChild(thread, (child) => {
child.turn = null;
let changed = false;
if (status === "failed" && message) {
child.task.summary = message;
changed = true;
}
// The parent may already have been told it is done for good; a
// finished turn does not reopen it.
if (status === "idle" && child.task.status === "completed") return changed;
return setStatus(child, status) || changed;
});
if (isChild) {
const root = this.subagents.get(thread)?.root;
if (root) this.releaseIdle(root);
return;
}
switch (p.turn.status) {
case "completed":
this.finishRun(thread, outcome.completed());
return;
case "interrupted":
this.finishRun(thread, outcome.cancelled());
return;
case "failed":
this.quotaFailure(thread, p.turn.error);
this.finishRun(
thread,
outcome.failed(p.turn.error ? (p.turn.error.message ?? "") : "the codex turn failed"),
);
return;
default:
return;
}
}
case "turn/plan/updated":
if (thread === null) return;
this.emitFor(thread, { event: "plan", ...map.planFromSteps(p.plan) });
return;
case "thread/tokenUsage/updated": {
if (thread === null || !p.tokenUsage) return;
const tokens = (value: unknown) =>
typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : 0;
// A subagent's usage is what it spent in total; the chat's is the
// size of its context window.
const total: Usage = { usedTokens: tokens(p.tokenUsage.total?.totalTokens) };
const isChild = this.updateChild(thread, (child) => {
child.task.usage = total;
return false;
});
let usage: Usage = total;
if (!isChild) {
usage = { usedTokens: tokens(p.tokenUsage.last?.totalTokens) };
if (Number.isInteger(p.tokenUsage.modelContextWindow))
usage.contextWindow = p.tokenUsage.modelContextWindow ?? undefined;
}
this.emitFor(thread, { event: "usage", ...usage });
return;
}
case "thread/started": {
const spawn = map.threadSpawn(p.thread);
// Only spawned subagents; review, compaction and guardian threads
// are Codex's own business.
if (spawn && typeof p.thread?.id === "string")
this.registerChild(p.thread.id, spawn.parentThreadId, factsOfThread(p.thread));
return;
}
case "thread/status/changed": {
if (thread === null || p.status?.type !== "active") return;
const status = map.threadWaiting(p.status) ? "waiting" : "running";
this.updateChild(thread, (child) => map.isLive(child.task.status) && setStatus(child, status));
return;
}
case "thread/name/updated":
if (thread === null) return;
this.emitFor(
thread,
compact({ event: "session_info", title: typeof p.threadName === "string" ? p.threadName : null }),
);
return;
case "error": {
if (thread === null) return;
const message = p.error
? typeof p.error.message === "string"
? p.error.message
: ""
: "codex reported an error";
// Codex recovers from an error it retries; it is not the turn's
// failure, so it does not stay in the chat as one.
this.notice(thread, p.willRetry ? "warning" : "error", message);
this.quotaFailure(thread, p.error);
// Even a non-retry error is not the terminal turn notification.
// Native retries/grace/tool settlement retain ownership until completed.
return;
}
case "warning":
this.notice(thread ?? "", "warning", p.message ?? "");
return;
case "guardianWarning":
// Codex reports successful auto-reviews as warnings too.
if (p.message?.startsWith("Automatic approval review approved (")) return;
this.notice(thread ?? "", "warning", p.message ?? "Codex automatic approval review failed.");
return;
// Diagnostics Codex sends out of band. Dropping them leaves the user
// with no explanation when the agent misbehaves. Every app-server
// sends them again as it starts (at launch, after an update or an
// idle stop), so each is shown once.
case "deprecationNotice":
case "configWarning":
case "windows/worldWritableWarning":
this.diagnose(thread, map.diagnostic(method, p));
return;
case "model/rerouted": {
const message =
typeof p.fromModel === "string" && typeof p.toModel === "string"
? `Codex switched from ${p.fromModel} to ${p.toModel}.`
: "Codex switched to a different model.";
this.notice(thread ?? "", "info", message);
return;
}
// A summary part is a section break in the reasoning; without it the
// parts run together as one paragraph.
case "item/reasoning/summaryPartAdded":
if (thread === null || typeof p.itemId !== "string") return;
if (this.wasStreamed(thread, p.itemId)) this.reasoningDelta(thread, p.itemId, "\n\n");
return;
case "item/mcpToolCall/progress":
if (thread === null || typeof p.itemId !== "string") return;
if (typeof p.message === "string" && p.message) {
this.emitFor(thread, { event: "tool_call_updated", id: p.itemId, outputDelta: `${p.message}\n` });
}
return;
case "account/rateLimits/updated": {
const first = this.sessions.keys().next();
const recovery = map.usageRecovery(p, "codex/account/rateLimits/updated", now(), this.quotaFacts?.identity);
this.quotaFacts = recovery;
this.quotaDisplay = mergeLimits(this.quotaDisplay, p);
const limits = map.usageLimits(this.quotaDisplay, recovery);
this.emitFor(first.done ? "" : first.value, { event: "usage_limits", ...limits });
return;
}
case "account/updated":
this.accountDirty = true;
this.invalidateQuota();
return;
// Codex watches its skill folders: one was added, changed or removed.
case "skills/changed":
this.send({ sessionId: "", event: "skills_changed" });
return;
// Another Codex client answered a request we are also showing.
// Without this the card waits for an answer that has been given.
case "serverRequest/resolved":
if (p.requestId === undefined || p.requestId === null) return;
this.withdrawRequest(JSON.stringify(p.requestId));
return;
default:
// Every method in `wire.routed` has a case above.
method satisfies never;
}
}
/// Closes the approval or question `request` asked, telling the UI to
/// drop the card, and leaves the app-server unanswered by us.
withdrawRequest(request: string) {
for (const [id, entry] of this.approvals) {
if (entry.request !== request) continue;
this.approvals.delete(id);
entry.answer(null);
this.emitFor(entry.session, { event: "approval_resolved", id });
return;
}
for (const [id, entry] of this.questions) {
if (entry.request !== request) continue;
this.questions.delete(id);
entry.answer(null);
this.emitFor(entry.session, { event: "question_resolved", id });
return;
}
}
/// A collab tool call (multi-agent v1) becomes subagent tasks.
/// Registering the child thread lets `emitFor` route the child's own
/// events into the chat instead of dropping them.
onCollabItem(thread: string, item: wire.Item) {
const sender = typeof item.senderThreadId === "string" && item.senderThreadId ? item.senderThreadId : thread;
const receivers = (Array.isArray(item.receiverThreadIds) ? item.receiverThreadIds : []).filter(
(id) => typeof id === "string",
);
const states = item.agentsStates && typeof item.agentsStates === "object" ? item.agentsStates : {};
if (item.tool === "spawnAgent") {
for (const child of receivers) {
this.registerChild(child, sender, {
toolCallId: typeof item.id === "string" ? item.id : null,
prompt: typeof item.prompt === "string" ? item.prompt : null,
model: typeof item.model === "string" ? item.model : null,
effort: typeof item.reasoningEffort === "string" ? item.reasoningEffort : null,
});
}
} else if (item.tool !== "listAgents") {
// A call to a subagent this process never saw start: one from
// before a restart that the agent talks to again.
for (const child of [...receivers, ...Object.keys(states)]) this.adoptChild(child, sender);
}
for (const [child, state] of Object.entries(states)) {
const status = map.collabStatus(state?.status);
const message = typeof state?.message === "string" && state.message.trim() ? state.message : null;
this.updateChild(child, (c) => {
let changed = false;
// The child's answer is its result, never its title.
if (message !== null && c.task.summary !== message) {
c.task.summary = message;
changed = true;
}
// `pendingInit` and `running` are what the child's own turns
// report better.
return status ? setStatus(c, status) || changed : changed;
});
}
}
/// A multi-agent v2 subagent event. A v2 spawn appears only as a
/// `started` activity.
onActivity(thread: string, item: wire.Item) {
const target = typeof item.agentThreadId === "string" ? item.agentThreadId : "";
if (!target) return;
const path = typeof item.agentPath === "string" ? item.agentPath : "";
if (item.kind === "started") {
// The path's last segment is the task name its parent gave it; v2
// sends the instruction itself encrypted. Since 0.169 the activity
// names the child's model and effort.
this.registerChild(target, thread, {
taskName: map.pathTaskName(path),
model: typeof item.model === "string" ? item.model : null,
effort: typeof item.reasoningEffort === "string" ? item.reasoningEffort : null,
});
const child = this.subagents.get(target);
const described = !child || child.task.prompt || child.task.name;
if (!described) this.readFacts(target);
return;
}
// A child the chat started before a restart and addresses again. Only
// the chat's own activities adopt one: inside a child, an activity may
// name an ancestor (`/root` is the chat itself).
if (path !== "/root" && this.sessions.has(thread)) this.adoptChild(target, thread);
const status = map.activityStatus(item.kind);
if (!status) return;
// Only the thread that started the child speaks for it.
this.updateChild(target, (child) => parentOf(child) === thread && setStatus(child, status));
}
/// Notes a tool a subagent ran: its count and its live activity line.
childTool(thread: string, call: ToolCall, running: boolean) {
this.updateChild(thread, (child) => {
const added = !child.tools.has(call.id);
child.tools.add(call.id);
child.task.toolUses = child.tools.size;
const activity = running && call.title ? call.title : null;
const active = running && (child.task.activity ?? null) !== activity;
if (active) {
if (activity === null) delete child.task.activity;
else child.task.activity = activity;
}
return added || active;
});
}
consumeInput(thread: string, item: wire.Item) {
if (item.type !== "userMessage" || !item.clientId) return;
if (item.id) {
const client = item.clientId;
const native = item.id;
this.enqueue(
Effect.gen({ self: this }, function* () {
const host = yield* Host;
const { value } = yield* host.call("host/storage.get", {
key: historyKey("client", this.id, thread, client),
});
if (value != null)
yield* host.call("host/storage.set", { key: historyKey("native", this.id, thread, native), value });
}).pipe(
Effect.catch((error) =>
Effect.sync(() =>
this.notice(thread, "error", `Could not retain history identity: ${errorMessage(error)}`),
),
),
),
);
}
const state = this.sessions.get(thread);
const input = state?.inputs.get(item.clientId);
if (!input) return;
state?.inputs.delete(item.clientId);
for (const event of consumedInput(input, input.contextId, item.id ?? item.clientId))
this.emit(agentEvent(thread, event, { runId: input.runId }));
}
quotaFailure(thread: string, error: z.infer<typeof wire.turnError> | null | undefined) {
if (error?.codexErrorInfo !== "usageLimitExceeded" || !this.sessions.get(thread)?.run) return;
const facts = this.quotaFacts;
this.emitFor(thread, {
event: "usage_blocked",
recovery: {
...facts,
availability: "blocked",
observedAt: now(),
source: "codex/usageLimitExceeded",
reason: error.message ?? "Codex reported usage quota exhaustion",
},
});
}
invalidateQuota() {
this.accountGeneration += 1;
this.quotaFacts = null;
this.quotaDisplay = null;
}
onItemStarted(thread: string, item: wire.Item, imageCall?: ToolCall) {
switch (map.itemType(item)) {
case "collabAgentToolCall":
this.onCollabItem(thread, item);
return;
case "subAgentActivity":
this.onActivity(thread, item);
return;
case "contextCompaction":
this.emitFor(thread, { event: "compacting" });
return;
case null:
case "userMessage":
case "agentMessage":
case "reasoning":
case "plan":
case "hookPrompt":
case "enteredReviewMode":
case "exitedReviewMode":
return;
default: {
const call = imageCall ?? map.toolCallFromItem(item, this.hostFeatures.has("mcpApps"));
if (!call) return;
if (map.itemType(item) === "fileChange") this.fileChanges.set(call.id, call.content ?? []);
if (item.type === "sleep") call.status = "running";
this.emitFor(thread, { event: "tool_call_started", ...call });
this.childTool(thread, call, true);
this.sessions.get(thread)?.startedTools.add(call.id);
}
}
}
onItemCompleted(thread: string, item: wire.Item, imageCall?: ToolCall) {
const notice = itemNotice(item);
if (notice !== null) {
this.notice(thread, "info", notice);
return;
}
const question = map.backgroundQuestion(item);
if (question) this.emitFor(thread, { event: "question", ...question });
switch (map.itemType(item)) {
case "collabAgentToolCall":
this.onCollabItem(thread, item);
return;
case "subAgentActivity":
this.onActivity(thread, item);
return;
case null:
case "userMessage":
case "plan":
return;
case "agentMessage": {
const text = typeof item.text === "string" ? item.text : "";
// A subagent's latest message is its progress, and its last one is
// its result.
if (text.trim()) {
this.updateChild(thread, (child) => {
const changed = child.task.summary !== text;
child.task.summary = text;
return changed;
});
}
if (!this.wasStreamed(thread, item.id ?? "") && text) {
this.emitFor(thread, { event: "text_delta", itemId: item.id ?? "", text, mode: "replace" });
}
return;
}
case "reasoning": {
this.releaseHeld(thread, item.id ?? "");
const text = map.reasoningText(item.summary, item.content);
if (!this.wasStreamed(thread, item.id ?? "") && text.trim() && !map.isStdinNotice(text)) {
this.emitFor(thread, { event: "reasoning_delta", itemId: item.id ?? "", text, mode: "replace" });
}
return;
}
case "contextCompaction":
this.emitFor(thread, { event: "compacted" });
return;
default: {
const call = imageCall ?? map.toolCallFromItem(item, this.hostFeatures.has("mcpApps"));
if (!call) return;
this.fileChanges.delete(call.id);
const started = this.toolStarted(thread, call.id);
this.childTool(thread, call, false);
if (started) {
this.emitFor(thread, {
event: "tool_call_updated",
id: call.id,
status: call.status,
title: call.title,
kind: call.kind,
input: call.input ?? null,
content: call.content ?? [],
locations: call.locations ?? [],
});
} else {
this.emitFor(thread, { event: "tool_call_started", ...call });
}
}
}
}
/// The completion of a tool item whose turn has ended: an update of its
/// row, never a new row.
lateCompletion(thread: string, item: wire.Item, imageCall?: ToolCall) {
const call = imageCall ?? map.toolCallFromItem(item, this.hostFeatures.has("mcpApps"));
if (!call) return;
this.fileChanges.delete(call.id);
this.childTool(thread, call, false);
this.emitFor(thread, {
event: "tool_call_updated",
id: call.id,
status: call.status,
title: call.title,
kind: call.kind,
input: call.input ?? null,
content: call.content ?? [],
locations: call.locations ?? [],
});
}
// --- server requests ------------------------------------------------------------------
terminalItem(thread: string, item: wire.Item) {
if (!item.id) return;
const key = JSON.stringify([thread, item.id]);
let terminal = this.terminals.get(key);
if (!terminal) {
if (!item.processId || item.status !== "inProgress") return;
const child = this.subagents.get(thread);
terminal = {
thread,
published: false,
task: {
id: `terminal/${thread}/${item.id}`,
kind: "terminal",
title: item.command || "Terminal",
command: item.command ?? undefined,
toolCallId: item.id,
parentTaskId: child ? thread : undefined,
status: "running",
background: true,
startedAt: new Date().toISOString(),
output: "",
},
};
this.terminals.set(key, terminal);
}
if (typeof item.aggregatedOutput === "string") terminal.task.output = taskOutput(item.aggregatedOutput);
if (item.status !== "inProgress") {
terminal.task.status =
item.status === "completed" ? "completed" : item.status === "declined" ? "cancelled" : "failed";
terminal.task.endedAt = new Date().toISOString();
}
this.emitTerminal(terminal);
if (terminal.task.status !== "running") {
this.terminals.delete(key);
this.releaseIdle(this.subagents.get(thread)?.root ?? thread);
}
}
emitTerminal(
terminal: { thread: string; published: boolean; task: import("divergence/protocol").TaskInfo },
delta?: string,
) {
if (!terminal.published) return;
// The task already names its parent; it is not an event inside that parent.
this.send({
sessionId: this.rootOf(terminal.thread),
event: "task",
...terminal.task,
...(delta === undefined ? {} : { output: undefined, outputDelta: taskOutput(delta) }),
});
}
/// Answers a request the app-server sent. One this plugin cannot read
/// or handle is refused, and the chat says so: Codex goes on without
/// the approval or answer it asked for.
onRequest(request: RpcRequest) {
try {
return this.handleRequest(request);
} catch (error) {
const message = `Divergence could not handle Codex's ${request.method}: ${errorMessage(error)}`;
console.warn(`codex: ${message}`);
this.notice(wire.threadOf(request.params) ?? "", "warning", message);
request.reply.err(error);
return undefined;
}
}
handleRequest({ id, method, params, reply }: RpcRequest) {
// Canonical JSON, so the id matches the one `serverRequest/resolved`
// reports for the same request.
const request = JSON.stringify(id);
const p = wire.notification.parse(params ?? {});
switch (method) {
case "item/commandExecution/requestApproval":
return this.commandApproval(p, reply, request);
case "item/fileChange/requestApproval":
return this.fileChangeApproval(p, reply, request);
case "item/tool/requestUserInput":
return this.userInputRequest(p, reply, request);
case "mcpServer/elicitation/request":
return this.elicitation(p, reply, request);
case "item/tool/call":
return this.toolCall(p, reply);
default:
// `item/permissions/requestApproval`,
// `account/chatgptAuthTokens/refresh`, …: answered at once so the
// app-server never waits on us.
reply.err(methodNotFound(method));
return undefined;
}
}
/// Runs one of the plugin tools given at thread start. The host runs
/// it; a tool can take minutes, and code mode's `execute` calls other
/// tools while it runs, so nothing here waits for it.
toolCall(p: wire.Notification, reply: Responder) {
if (typeof p.threadId !== "string" || typeof p.tool !== "string")
throw new Error("item/tool/call without a thread or a tool");
const session = this.rootOf(p.threadId);
this.enqueue(
callHostToolEffect({
agentId: this.id,
sessionId: session,
name: p.tool,
input: p.arguments ?? null,
callId: typeof p.callId === "string" ? p.callId : null,
}).pipe(Effect.tap((result) => Effect.sync(() => reply.ok(map.dynamicToolResponse(result))))),
);
}
commandApproval(p: wire.Notification, reply: Responder, request: string) {
if (typeof p.threadId !== "string" || typeof p.itemId !== "string")
throw new Error("an approval without a thread or an item");
const { title, call } = requests.commandApproval({ ...p, itemId: p.itemId });
this.askApproval(p.threadId, title, call, reply, request, requests.commandDecisions(p));
}
fileChangeApproval(p: wire.Notification, reply: Responder, request: string) {
if (typeof p.threadId !== "string" || typeof p.itemId !== "string")
throw new Error("an approval without a thread or an item");
const { title, call } = requests.fileChangeApproval({ ...p, itemId: p.itemId }, this.fileChanges.get(p.itemId) ?? []);
this.askApproval(p.threadId, title, call, reply, request);
}
/// Emits the approval and answers the app-server once the user decides.
askApproval(session: string, title: string, call: ToolCall, reply: Responder, request: string, choices = requests.commandDecisions({})) {
const id = newId("codex-approval");
const entry = {
session,
request,
// `null` withdraws the request without answering it.
answer: (decision: string | null) => {
if (this.approvals.get(id) === entry) this.approvals.delete(id);
if (decision === null) reply.discard();
else reply.ok({ decision: choices.decisions.get(decision) ?? "decline" });
},
};
this.approvals.set(id, entry);
this.emitFor(session, { event: "approval", id, title, toolCall: call, options: choices.options });
}
/// An MCP server asks through Codex: an MCP tool approval (Computer Use
/// and other MCP tools), an external page to open, or a form.
elicitation(p: wire.Notification, reply: Responder, request: string) {
if (typeof p.threadId !== "string") throw new Error("an elicitation without a thread");
const session = p.threadId;
const message = typeof p.message === "string" ? p.message : "";
const meta = p._meta && typeof p._meta === "object" && !Array.isArray(p._meta) ? p._meta : null;
if (meta?.codex_approval_kind === "mcp_tool_call") {
const id = newId("codex-elicitation");
const entry = {
session,
request,
// `null` withdraws the request without answering it.
answer: (decision: string | null) => {
if (this.approvals.get(id) === entry) this.approvals.delete(id);
if (decision === null) reply.discard();
else reply.ok(requests.mcpApprovalReply(decision));
},
};
this.approvals.set(id, entry);
this.emitFor(session, { event: "approval", id, title: message, options: requests.mcpApprovalOptions(meta.persist) });
return;
}
const mode = typeof p.mode === "string" ? p.mode : "";
if (mode === "url") {
const url = typeof p.url === "string" && /^https?:\/\//.test(p.url) ? p.url : null;
if (url === null) {
this.notice(session, "error", "Codex requested an invalid external URL");
reply.ok(requests.REFUSE);
return;
}
this.askElicitation(session, request, reply, { message, url, fields: [] }, (answer) => ({
action: answer.cancelled ? "cancel" : "accept",
content: null,
_meta: null,
}));
return;
}
if (!["form", "openai/form", "openaiForm"].includes(mode)) {
reply.err(methodNotFound("mcpServer/elicitation/request"));
return;
}
const schema = p.requestedSchema ?? {};
this.askElicitation(session, request, reply, { message, fields: map.elicitationFields(schema) }, (answer) =>
answer.cancelled
? requests.REFUSE
: { action: "accept", content: map.elicitationContent(schema, answer.values ?? {}), _meta: null },
);
}
/// Emits an elicitation as a question and replies with `respond(answer)`.
askElicitation(
session: string,
request: string,
reply: Responder,
question: { message: string; url?: string; fields: QuestionField[] },
respond: (answer: QuestionAnswer) => unknown,
) {
const id = newId("codex-elicitation");
const entry = {
session,
request,
// `null` withdraws the question without answering it.
answer: (answer: QuestionAnswer | null) => {
if (this.questions.get(id) === entry) this.questions.delete(id);
if (answer === null) reply.discard();
else reply.ok(respond(answer));
},
};
this.questions.set(id, entry);
this.emitFor(session, { event: "question", responseMode: "tool", id, ...question });
}
userInputRequest(p: wire.Notification, reply: Responder, request: string) {
if (typeof p.threadId !== "string") throw new Error("a question without a thread");
const questions = Array.isArray(p.questions) ? p.questions : [];
const id = newId("codex-question");
const fields = requests.userInputFields(questions);
const entry = {
session: p.threadId,
request,
// `null` withdraws the question without answering it.
answer: (answer: QuestionAnswer | null) => {
if (this.questions.get(id) === entry) this.questions.delete(id);
if (answer === null) {
reply.discard();
return;
}
reply.ok(requests.userInputReply(questions, answer));
},
};
this.questions.set(id, entry);
this.emitFor(p.threadId, { event: "question", responseMode: "tool", id, fields });
}
// --- reading threads -------------------------------------------------------------------
/// The turns of a thread, oldest first, following `nextCursor`. The
/// pages are read newest first, so a thread longer than `MAX_TURNS`
/// loses its oldest turns (`cut`), never its latest.
/// `itemsView: "full"`: the default summary view drops the items the
/// transcript is built from.
allTurns = Effect.fn("Codex.allTurns")(function* (
this: CodexAgent,
connection: JsonRpcConnection,
thread: string,
): Effect.fn.Return<{ turns: wire.Turn[]; cut: boolean }, TransportError> {
const turns: wire.Turn[] = [];
let cursor: string | null = null;
let cut = false;
for (;;) {
const response: z.infer<(typeof wire.responses)["thread/turns/list"]> = yield* this.request(
connection,
"thread/turns/list",
{ threadId: thread, cursor, limit: TURN_PAGE, sortDirection: "desc", itemsView: "full" },
);
turns.push(...(response.data ?? []));
const next: string | null | undefined = response.nextCursor;
if (!next) break;
cursor = next;
if (turns.length >= MAX_TURNS) {
cut = true;
break;
}
}
return { turns: turns.reverse(), cut };
});
/// A thread's record and every turn of it. `thread/read` with
/// `includeTurns` returns one page and is deprecated for `paginated`
/// threads, so the turns are paged separately; only a legacy thread on
/// an app-server without `thread/turns/list` falls back to it.
readThread = Effect.fn("Codex.readThread")(function* (
this: CodexAgent,
connection: JsonRpcConnection,
thread: string,
head?: { thread?: wire.Thread | null },
): Effect.fn.Return<History, TransportError> {
const response =
head ?? (yield* this.request(connection, "thread/read", { threadId: thread, includeTurns: false }));
const record = response.thread ?? { id: thread };
const paginated = record.historyMode === "paginated";
let turns: wire.Turn[] | null = null;
let cut = false;
const listed = yield* Effect.result(this.allTurns(connection, thread));
if (Result.isSuccess(listed)) {
if (listed.success.turns.length || paginated) ({ turns, cut } = listed.success);
} else if (threadUnmaterialized(thread, listed.failure)) turns = [];
else
console.debug(`thread/turns/list is unavailable for ${thread}; using thread/read: ${listed.failure.message}`);
if (turns === null) {
const full = yield* this.request(connection, "thread/read", { threadId: thread, includeTurns: true });
turns = full.thread?.turns ?? [];
}
return { thread: record, turns, cut };
});
/// Every subagent thread the turns start, and theirs in turn, read one
/// generation at a time. A child that cannot be read is left out; its
/// row is still rebuilt from what the parent's items say about it.
readChildren = Effect.fn("Codex.readChildren")(function* (
this: CodexAgent,
connection: JsonRpcConnection,
turns: wire.Turn[],
) {
const children = new Map<string, History>();
let generation = map.childIds(turns);
while (generation.length) {
const room = Math.max(0, MAX_SUBAGENT_THREADS - children.size);
if (generation.length > room) {
console.warn(`reading only ${MAX_SUBAGENT_THREADS} subagent threads`);
generation = generation.slice(0, room);
}
const read = yield* Effect.forEach(generation, (id) => Effect.result(this.readThread(connection, id)), {
concurrency: "unbounded",
});
const next: string[] = [];
generation.forEach((id, index) => {
// forEach preserves the generation's length and order.
const result = read[index]!;
if (Result.isSuccess(result)) {
next.push(...map.childIds(result.success.turns));
children.set(id, result.success);
} else console.debug(`could not read the subagent thread ${id}: ${result.failure.message}`);
});
const seen = new Set<string>();
generation = next.filter((id) => !children.has(id) && !seen.has(id) && Boolean(seen.add(id)));
}
return children;
});
/// Puts the bytes of each image a user message names by path in place of
/// the path, so the message shows the picture. Codex reads the files: this
/// plugin has no grant to. A file that is gone keeps showing its path.
inlineLocalImages = Effect.fn("Codex.inlineLocalImages")(function* (
this: CodexAgent,
connection: JsonRpcConnection,
histories: readonly (readonly wire.Turn[])[],
) {
const found = histories.flatMap((turns) => map.localImages(turns));
const paths = [...new Set(found.map((image) => image.path))];
const read = yield* Effect.forEach(
paths,
(path) => Effect.result(this.request(connection, "fs/readFile", { path })),
{
concurrency: 8,
},
);
const bytes = new Map<string, string>();
paths.forEach((path, index) => {
// forEach preserves the paths' length and order.
const result = read[index]!;
if (Result.isSuccess(result)) bytes.set(path, result.success.dataBase64);
else console.debug(`could not read the image ${path}: ${result.failure.message}`);
});
for (const { content, index, path, mimeType } of found) {
const data = bytes.get(path);
if (data) content[index] = { type: "image", url: `data:${mimeType};base64,${data}` };
}
});
/// The subagents below `thread` at every depth, `thread` included when
/// it is one itself.
subtree(thread: string) {
const found = new Set<string>();
if (this.subagents.has(thread)) found.add(thread);
const parents = [thread];
while (parents.length) {
const parent = parents.pop();
for (const [id, child] of this.subagents) {
if (parentOf(child) === parent && !found.has(id)) {
found.add(id);
parents.push(id);
}
}
}
return found;
}
/// Interrupts the live turn of each of `threads`, in parallel, giving
/// each a few seconds and all of them a bound, so a Stop never hangs on
/// a subagent that does not answer.
interruptChildren = Effect.fn("Codex.interruptChildren")(function* (
this: CodexAgent,
connection: JsonRpcConnection,
threads: Set<string>,
) {
const turns: [string, string][] = [];
for (const id of threads) {
const turn = this.subagents.get(id)?.turn;
if (turn) turns.push([id, turn]);
}
const interrupts = Effect.forEach(
turns,
([thread, turn]) =>
this.request(
connection,
"turn/interrupt",
{ threadId: thread, turnId: turn },
{ timeout: CHILD_INTERRUPT },
).pipe(
// Stop is best effort: the original provider also continued when a child refused or timed out.
Effect.catchTag(["TransportFailed", "ParseFailed"], () =>
Effect.sync(() => console.debug(`the subagent ${thread} did not stop in time`)),
),
),
{ concurrency: "unbounded" },
);
yield* Effect.raceFirst(interrupts, Effect.sleep(CHILDREN_INTERRUPT));
});
/// Cancels every approval `threads` wait on, so the app-server stops
/// waiting for the user.
releaseApprovals(threads: Set<string>) {
for (const [id, entry] of [...this.approvals]) {
if (!threads.has(entry.session)) continue;
this.approvals.delete(id);
entry.answer("cancel");
}
}
/// Interrupts the named turn a Stop ended, then lets the thread go.
interruptStopped(session: string, stopping: { run: string; turn: string | null }) {
const proc = this.proc;
const done = Effect.sync(() => this.stopped(session, stopping));
if (!proc?.alive) return done;
return this.request(proc.connection, "turn/interrupt", { threadId: session, turnId: stopping.turn }).pipe(
Effect.catchTag(["TransportFailed", "ParseFailed"], (error) =>
Effect.sync(() => console.warn(`could not interrupt the codex turn ${stopping.turn}: ${errorMessage(error)}`)),
),
Effect.ensuring(done),
);
}
/// A Stop is over: Codex answered its interrupt or never started the turn.
stopped(session: string, stopping: { run: string; turn: string | null }) {
const state = this.sessions.get(session);
if (state?.stopping !== stopping) return;
state.stopping = undefined;
this.releaseIdle(session);
}
/// Codex named the turn of a run Stop ended before it knew the turn: the
/// turn is fenced and interrupted now.
nameStopped(session: string, stopping: { run: string; turn: string | null }, turn: string) {
this.sessions.get(session)?.endedTurns.add(turn);
stopping.turn = turn;
this.enqueue(this.interruptStopped(session, stopping));
}
loadModels = loadModels;
config = Effect.fn("Codex.config")(function* (this: CodexAgent, workspace: string) {
const result = yield* Effect.result(
Effect.gen(
function* (this: CodexAgent) {
const { connection } = yield* this.client();
const response = yield* this.request(connection, "config/read", { cwd: workspace });
return response.config ?? {};
}.bind(this),
),
);
if (Result.isSuccess(result)) {
this.configFailure = null;
this.configs.set(workspace, result.success);
return result.success;
}
// The built-in defaults start every chat Supervised, the strictest mode,
// so the chat keeps working; the user is told their own configuration
// (their approval mode, model and effort) is not in effect.
const message = `Codex could not read its configuration, so its defaults apply instead of yours: ${result.failure.message}`;
if (this.configFailure !== message) {
this.configFailure = message;
console.warn(`codex: ${message}`);
this.send({ sessionId: "", event: "notice", level: "warning", message });
}
return {};
});
optionsFor = optionsFor;
/// The account's subscription limits, read when the host asks for them.
/// Later changes arrive as `account/rateLimits/updated`.
limits = Effect.fn("Codex.limits")(function* (this: CodexAgent) {
const result = yield* Effect.result(
Effect.gen(
function* (this: CodexAgent) {
const { connection } = yield* this.client();
const generation = this.accountGeneration;
// `account/read` exposes the active routing account, not just an
// email or CODEX_HOME. Older servers may omit it; the usage read's
// own native accountId remains valid evidence when present.
const account = yield* Effect.result(this.request(connection, "account/read", {}));
const response = yield* this.request(connection, "account/rateLimits/read", {
excludeResetCreditDetails: true,
});
if (generation !== this.accountGeneration) return null;
const identity = Result.isSuccess(account) ? account.success.workspaceRouting?.chatgptAccountId : null;
this.quotaFacts = map.usageRecovery(response, "codex/account/rateLimits/read", now(), identity);
this.quotaDisplay = mergeLimits(null, response);
return map.usageLimits(this.quotaDisplay, this.quotaFacts);
}.bind(this),
),
);
return Result.isSuccess(result) ? result.success : null;
});
/// Who owns the installed `codex`, and so whether Divergence may
/// upgrade it. Proven from the resolved real path; anything unproven
/// reports the version but stays manual.
maintenance = Effect.fn("Codex.maintenance")(function* (this: CodexAgent, installedVersion: string | null) {
const process = yield* Process;
const found = yield* process
.which("codex")
.pipe(
Effect.catchTag(["HostCallFailed", "NeedsReview", "PermissionNotGranted"], () =>
Effect.succeed({ path: null, realPath: null }),
),
);
const realPath = found.realPath;
const manager = installerOf(realPath, ["/.codex/"]);
let latest: string | null = null;
if (manager === "npm") latest = yield* this.latest("npm", NPM_PACKAGE, npmPrefix(realPath));
else if (manager === "homebrew") latest = yield* this.latest("brew", "codex", null);
else if (manager === "native") latest = yield* this.latest("npm", NPM_PACKAGE, null);
const out: Maintenance = { canUpdate: manager !== "" };
if (installedVersion) out.installedVersion = installedVersion;
if (installedVersion && latest && isNewer(installedVersion, latest)) out.latestVersion = latest;
if (manager) out.manager = manager;
return { out, realPath, manager };
});
// --- agent methods ------------------------------------------------------------------------
initialize = Effect.fn("Codex.initialize")(function* (this: CodexAgent, params: { hostFeatures?: string[] } = {}) {
this.hostFeatures = new Set(params.hostFeatures);
const { connection } = yield* this.client();
const version = versionOf(this.userAgent);
const account = yield* Effect.result(this.request(connection, "account/read", {}));
const status: AgentInfo["status"] = Result.isSuccess(account)
? (account.success.account !== null && account.success.account !== undefined) ||
!account.success.requiresOpenaiAuth
? { state: "ready" }
: { state: "auth_required", message: "Sign in with `codex login`" }
: { state: "unavailable", message: account.failure.message };
// The account's limits are not read here: the host re-initializes
// every agent on a timer and reads limits on its own shared one.
const { out: maintenance } = yield* this.maintenance(version);
const gateway = yield* providerMethods(this);
const info: AgentInfo = {
id: this.id,
name: this.name,
description: "OpenAI Codex, over the app-server protocol",
icon: ICON,
capabilities: {
reasoning: true,
images: true,
approvals: true,
questions: true,
sessionList: true,
sessionHistory: true,
resume: true,
slashCommands: false,
steer: true,
cancel: true,
skills: true,
rollback: true,
fork: true,
forkAt: true,
compact: true,
usageLimits: true,
subagents: true,
cancelTask: true,
context: { labelled: true, ordinaryFiles: true, commands: true },
...(this.hostFeatures.has("mcpApps") ? { mcpApps: true } : {}),
},
authMethods: [
...gateway.methods,
{
id: "chatgpt",
name: "Sign in with ChatGPT",
description: "Opens the browser, the same flow as `codex login`",
},
],
status: gateway.status ?? status,
maintenance,
family: FAMILY,
continuationKey: this.home() ?? "",
};
if (version) info.version = version;
return info;
});
listOptions = Effect.fn("Codex.listOptions")(function* (this: CodexAgent, { workspace }: { workspace?: string }) {
return { options: yield* this.optionsFor(String(workspace ?? ""), {}) };
});
listCommands = Effect.fn("Codex.listCommands")(function* (this: CodexAgent) {
return { commands: [] };
});
listSessions = Effect.fn("Codex.listSessions")(function* (this: CodexAgent, { workspace }: { workspace?: string }) {
const { connection } = yield* this.client();
const threads: wire.Thread[] = [];
let cursor: string | null = null;
do {
const response: z.infer<(typeof wire.responses)["thread/list"]> = yield* this.request(connection, "thread/list", {
cwd: String(workspace ?? ""),
limit: 100,
...(cursor ? { cursor } : {}),
});
threads.push(...(response.data ?? []));
cursor = response.nextCursor ?? null;
} while (cursor);
this.sessionWatch.know(threads.flatMap((thread) => (thread.id ? [thread.id] : [])));
const home = this.home();
if (home) yield* this.sessionWatch.watch(`${home.replace(/\/+$/, "")}/sessions`, this.scope);
return {
sessions: threads
.filter((thread) => typeof thread.id === "string" && map.threadParent(thread) === null)
.map((thread) =>
compact({
id: thread.id,
title: map.threadTitle(thread.name, thread.preview, thread.turns),
createdAt: map.timestamp(thread.createdAt),
updatedAt: map.timestamp(thread.updatedAt),
}),
),
};
});
listSkills = Effect.fn("Codex.listSkills")(function* (this: CodexAgent, { workspace }: { workspace?: string }) {
const { connection } = yield* this.client();
// Codex watches skill folders only while a thread is loaded, so its
// cache can predate a skill installed since: the host asks for what is
// on disk now.
const response = yield* this.request(connection, "skills/list", { cwds: [String(workspace ?? "")], forceReload: true });
const skills: { name: string; description: string; source: string; manualOnly: boolean }[] = [];
const paths = new Map<string, string>();
for (const entry of response.data ?? []) {
for (const skill of entry.skills ?? []) {
if (typeof skill.name !== "string" || typeof skill.path !== "string" || skill.enabled === false) continue;
paths.set(skill.name, skill.path);
skills.push({
name: skill.name,
description: skill.interface?.shortDescription ?? skill.shortDescription ?? skill.description ?? "",
source: typeof skill.scope === "string" ? skill.scope : "",
manualOnly: false,
});
}
}
this.skills = paths;
return { skills };
});
readSession = Effect.fn("Codex.readSession")(function* (
this: CodexAgent,
{ sessionId, version }: { sessionId: string; workspace?: string; version?: string },
) {
const { connection } = yield* this.client();
// The thread's update time, taken before its turns are read, is the
// read's version: an unchanged thread is not read again.
const read = yield* Effect.result(
this.request(connection, "thread/read", { threadId: sessionId, includeTurns: false }),
);
if (Result.isFailure(read)) {
// Codex no longer has the thread (its record was deleted): it has
// nothing to add to the chat, which keeps its stored copy. The next
// prompt finds it unavailable and continues in a new thread.
if (threadGone(sessionId, read.failure)) return { items: [], aliases: [], echoes: [] };
return yield* Effect.fail(read.failure);
}
const head = read.success;
const stamp =
typeof head.thread?.updatedAt === "number"
? `${HISTORY_FORMAT}:${this.hostFeatures.has("mcpApps")}:updated:${head.thread.updatedAt}`
: undefined;
if (stamp && stamp === version) return { items: [], aliases: [], echoes: [], version: stamp };
const { thread, turns, cut } = yield* this.readThread(connection, sessionId, head);
const title = map.threadTitle(thread.name, thread.preview, turns);
if (title) this.send({ sessionId, event: "session_info", title });
const children = yield* this.readChildren(connection, turns);
const histories = [turns, ...[...children.values()].map((child) => child.turns)];
yield* this.inlineLocalImages(connection, histories);
const items = map.transcriptWithSubagents(turns, children, null, this.hostFeatures.has("mcpApps"));
const calls = (items: import("divergence/protocol").TranscriptItem[]): ToolCall[] => items.flatMap((item) => item.role === "tool" ? [item.call] : item.role === "task" ? calls(item.items ?? []) : []);
const viewed = new Set(histories.flatMap((turns) => turns.flatMap((turn) => (turn.items ?? []).flatMap((item) => item.type === "imageView" && item.id ? [item.id] : []))));
yield* Effect.forEach(calls(items).filter((call) => viewed.has(call.id)), (call) => this.inlineToolImage(connection, call), { concurrency: 8 });
if (cut)
items.unshift({
id: `${sessionId}/cut`,
role: "notice",
text: `Only the latest ${MAX_TURNS} turns of this Codex conversation are shown.`,
});
const aliases: { itemId: string; nativeItemId: string }[] = [];
const echoes: import("divergence/protocol").NativeEcho[] = [];
// Every user message's stored identity in one host call, not one each.
const users = turns.flatMap((turn) => (turn.items ?? []).filter((item) => item.type === "userMessage" && item.id));
const keys = users.flatMap((item) => [
historyKey("native", this.id, sessionId, item.id!),
...(item.clientId ? [historyKey("client", this.id, sessionId, item.clientId)] : []),
]);
const values = yield* storageValues(keys);
let at = 0;
for (const item of users) {
let value = values[at++];
if (item.clientId) {
const client = values[at++];
value ??= client;
}
if (typeof value === "string") aliases.push({ itemId: value, nativeItemId: item.id! });
else if (value != null)
echoes.push({ ...(yield* parse("stored Codex ingress", echoSchema, value)), nativeItemId: item.id! });
}
return { items, aliases, echoes, ...(stamp ? { version: stamp } : {}) };
});
createSession = Effect.fn("Codex.createSession")(function* (this: CodexAgent, params: SessionOptions) {
const { connection } = yield* this.client();
const response = yield* this.request(connection, "thread/start", startParams(params)).pipe(
Effect.mapError((error) => new ProviderError({ message: `thread/start failed: ${errorMessage(error)}` })),
);
const id = response.thread?.id;
if (typeof id !== "string") return yield* new ProviderError({ message: "thread/start answered without a thread" });
this.sessions.set(id, newSession(params.workspace ?? "", { ...params.options, ...(response.modelProvider ? { model_provider: response.modelProvider } : {}) }));
this.loadedThread(id);
return { sessionId: id };
});
resumeSession = Effect.fn("Codex.resumeSession")(function* (
this: CodexAgent,
params: SessionOptions & { sessionId: string; requireResume?: boolean },
) {
const { connection } = yield* this.client();
const resumed = yield* Effect.result(
this.request(connection, "thread/resume", resumeParams(params.sessionId, params)),
);
if (Result.isFailure(resumed)) {
const error = resumed.failure;
if (
params.requireResume &&
error instanceof TransportFailed &&
error.cause instanceof RpcError &&
error.cause.code === -32600 &&
error.cause.message === `thread/resume failed: no rollout found for thread id ${params.sessionId}`
)
return { unavailable: `Codex has no persisted history for thread ${params.sessionId}` };
return yield* resumeFailure(params.sessionId, error);
}
const state = this.sessions.get(params.sessionId) ?? newSession();
state.workspace = params.workspace ?? "";
state.options = { ...params.options, ...(resumed.success.modelProvider ? { model_provider: resumed.success.modelProvider } : {}) };
state.unloaded = false;
this.sessions.set(params.sessionId, state);
this.loadedThread(params.sessionId);
return {};
});
closeSession = Effect.fn("Codex.closeSession")(function* (this: CodexAgent, { sessionId }: { sessionId: string }) {
if (this.proc?.alive)
yield* Effect.result(this.request(this.proc.connection, "thread/unsubscribe", { threadId: sessionId }));
this.sessions.delete(sessionId);
if (this.loaded.delete(sessionId)) this.reportProcess("sessions");
return {};
});
/// With `itemId` the copy stops before the turn that message started:
/// Codex forks through a turn, so the turn before it is the last one kept.
forkSession = Effect.fn("Codex.forkSession")(function* (
this: CodexAgent,
params: SessionOptions & { sessionId: string; itemId?: string },
) {
const { connection } = yield* this.client();
const fork: Record<string, unknown> = forkParams(params.sessionId, params);
if (params.itemId !== undefined) {
const { turns } = yield* this.allTurns(connection, params.sessionId);
const known = this.sessions.get(params.sessionId)?.turns.get(params.itemId);
const at = turns.findIndex(
(turn) => turn.id === known || (turn.items ?? []).some((item) => map.itemId(item) === params.itemId),
);
if (at < 0) return yield* new ProviderError({ message: `codex does not know message ${params.itemId}` });
if (at === 0) return yield* new ProviderError({ message: "nothing comes before the first message to fork" });
fork.lastTurnId = turns[at - 1]!.id;
}
const response = yield* this.request(connection, "thread/fork", fork).pipe(
Effect.mapError((error) => new ProviderError({ message: `thread/fork failed: ${errorMessage(error)}` })),
);
const id = response.thread?.id;
if (typeof id !== "string") return yield* new ProviderError({ message: "thread/fork answered without a thread" });
this.sessions.set(id, newSession(params.workspace ?? "", { ...params.options, ...(response.modelProvider ? { model_provider: response.modelProvider } : {}) }));
this.loadedThread(id);
return { sessionId: id };
});
prompt = Effect.fn("Codex.prompt")(function* (
this: CodexAgent,
{ sessionId, input }: { sessionId: string; input?: PromptInput },
) {
const delivery = input?.delivery;
const rejected = (reason: string) => {
for (const event of rejectedInput(input ?? {}, reason)) this.send({ sessionId, ...event });
return new ProviderError({ message: reason });
};
if (delivery?.intent === "queue") return yield* rejected(QUEUED_INPUT_HELD);
const connection = yield* this.loadedConnection(sessionId);
const known = this.sessions.get(sessionId);
const workspace = known?.workspace ?? "";
const options = { ...(known?.options ?? {}) };
const blocks = userInput(input?.blocks, this.skills);
if (input?.context) blocks.unshift({ type: "text", text: contextText(input.context), text_elements: [] });
const clientId = delivery?.attemptId ?? input?.itemId;
if (input?.itemId && clientId) {
const result = yield* Effect.result(
(yield* Host).call("host/storage.set", {
key: historyKey("client", this.id, sessionId, clientId),
value:
input.context && delivery
? {
nativeItemId: clientId,
attemptId: delivery.attemptId,
origin: { kind: "combined", inputId: delivery.inputId, contextId: input.context.id },
}
: input.itemId,
}),
);
if (Result.isFailure(result))
return yield* rejected(`Could not retain input identity: ${errorMessage(result.failure)}`);
}
if (known?.run) {
const runId = known.run;
const turn = known.turn ?? (known.starting ? yield* Deferred.await(known.starting) : null);
if (!turn || known.run !== runId)
return yield* rejected("The original Codex turn ended before steering could be submitted");
if (delivery)
known.inputs.set(delivery.attemptId, {
...delivery,
runId,
...(input?.context ? { contextId: input.context.id } : {}),
});
const result = yield* Effect.result(
this.request(
connection,
"turn/steer",
{
threadId: sessionId,
input: blocks,
expectedTurnId: turn,
...(clientId ? { clientUserMessageId: clientId } : {}),
},
{ timeout: null },
),
);
if (Result.isFailure(result)) {
const reason = `turn/steer failed: ${errorMessage(result.failure)}`;
if (nativeRejection(result.failure)) {
if (delivery) known.inputs.delete(delivery.attemptId);
return yield* rejected(reason);
}
return yield* new ProviderError({ message: reason });
}
return {
runId,
receipt: { evidence: "native_admission" as const, ...(delivery ? { nativeInputId: delivery.attemptId } : {}) },
};
}
const config = this.configs.get(workspace) ?? (yield* this.config(workspace));
const runId = newId("codex-run");
const hostItem = typeof input?.itemId === "string" ? input.itemId : null;
const state = known ?? newSession(workspace, options);
this.sessions.set(sessionId, state);
if (!state.workspace) state.workspace = workspace;
state.run = runId;
state.turn = null;
state.streamed.clear();
state.startedTools.clear();
state.held.clear();
const starting = Deferred.makeUnsafe<string | null>();
state.starting = starting;
if (delivery)
state.inputs.set(delivery.attemptId, {
...delivery,
runId,
...(input?.context ? { contextId: input.context.id } : {}),
});
const fiber = yield* this.request(
connection,
"turn/start",
{
...turnParams(sessionId, blocks, workspace, options, config),
...(clientId ? { clientUserMessageId: clientId } : {}),
},
{
timeout: null,
},
).pipe(
Effect.tap((response) =>
Effect.sync(() => {
const current = this.sessions.get(sessionId);
const turn = response.turn?.id;
if (!current || typeof turn !== "string") {
if (current?.stopping?.run === runId) this.stopped(sessionId, current.stopping);
Deferred.doneUnsafe(starting, Effect.succeed(null));
return;
}
if (hostItem) current.turns.set(hostItem, turn);
if (current.run === runId) current.turn ??= turn;
else if (current.stopping?.run === runId && !current.stopping.turn)
this.nameStopped(sessionId, current.stopping, turn);
else if (current.turn !== turn) current.endedTurns.add(turn);
Deferred.doneUnsafe(starting, Effect.succeed(turn));
}),
),
Effect.tapError((error) =>
Effect.sync(() => {
Deferred.doneUnsafe(starting, Effect.succeed(null));
if (state.stopping?.run === runId) this.stopped(sessionId, state.stopping);
if (nativeRejection(error)) {
if (delivery) state.inputs.delete(delivery.attemptId);
rejected(errorMessage(error));
}
if (state.run === runId) {
this.notice(sessionId, "error", errorMessage(error));
this.finishRun(sessionId, outcome.failed(errorMessage(error)));
}
}),
),
Effect.result,
Effect.forkIn(this.scope),
);
if (delivery) {
const result = yield* Fiber.join(fiber);
if (Result.isFailure(result)) return yield* new ProviderError({ message: errorMessage(result.failure) });
if (!result.success.turn?.id)
return yield* new ProviderError({
message: "turn/start answered without a turn identity; delivery is uncertain",
});
return {
runId,
receipt: {
evidence: "native_admission" as const,
nativeInputId: delivery.attemptId,
...(input?.context
? {
context: {
contextId: input.context.id,
evidence: "native_admission" as const,
nativeInputId: delivery.attemptId,
},
}
: {}),
},
};
}
return { runId };
});
cancel = Effect.fn("Codex.cancel")(function* (this: CodexAgent, { sessionId }: { sessionId: string }) {
const threads = this.subtree(sessionId);
const state = this.sessions.get(sessionId);
const proc = this.proc;
// The run ends at once and the interrupts go out behind it, so a Stop
// never waits on a slow app-server. The chat's turn is interrupted
// after its subagents', or as soon as Codex names it when Stop came
// before that.
if (proc?.alive) {
const stopping = state?.run ? { run: state.run, turn: state.turn } : null;
if (state && stopping) state.stopping = stopping;
this.enqueue(
this.interruptChildren(proc.connection, new Set(threads)).pipe(
Effect.andThen(stopping?.turn ? this.interruptStopped(sessionId, stopping) : Effect.void),
),
);
}
threads.add(sessionId);
this.releaseApprovals(threads);
this.finishRun(sessionId, outcome.cancelled());
return {};
});
cancelTask = Effect.fn("Codex.cancelTask")(function* (
this: CodexAgent,
{ sessionId, taskId }: { sessionId: string; taskId: string },
) {
const child = this.subagents.get(taskId);
if (!child || child.root !== sessionId)
return yield* new ProviderError({ message: `no codex subagent ${taskId} in this chat` });
if (!child.turn) return yield* new ProviderError({ message: "the subagent is not running" });
const threads = this.subtree(taskId);
const { connection } = yield* this.client();
yield* this.interruptChildren(connection, threads);
this.releaseApprovals(threads);
return {};
});
setOption = Effect.fn("Codex.setOption")(function* (
this: CodexAgent,
{ sessionId, optionId, value }: { sessionId: string; optionId: string; value: unknown },
) {
const state = this.sessions.get(sessionId) ?? newSession();
this.sessions.set(sessionId, state);
if (optionId === "model_provider") return yield* selectProvider(this, sessionId, state, value);
state.options[optionId] = value;
if (optionId === OPTION_MODEL) delete state.options[OPTION_REASONING];
return { options: yield* this.optionsFor(state.workspace, state.options) };
});
respondToApproval = Effect.fn("Codex.respondToApproval")(function* (
this: CodexAgent,
{ approvalId, optionId }: { approvalId: string; optionId: string },
) {
const entry = this.approvals.get(approvalId);
// Settled before the answer came (withdrawn or the turn ended): nothing
// waits for it, which the host shows as answered.
if (!entry) return { notPending: true };
this.approvals.delete(approvalId);
entry.answer(optionId);
return {};
});
respondToQuestion = Effect.fn("Codex.respondToQuestion")(function* (
this: CodexAgent,
{ questionId, answer }: { questionId: string; answer?: QuestionAnswer },
) {
const entry = this.questions.get(questionId);
if (!entry) return yield* new ProviderError({ message: `no codex question is waiting for ${questionId}` });
this.questions.delete(questionId);
entry.answer(answer ?? { values: {}, cancelled: false });
return {};
});
/// Rewinds the thread so `itemId` and everything after it is gone. Codex
/// reverts by turn, so the turn holding that item is found first;
/// `thread/revert` rewrites the history only, which is why the host
/// pairs it with its own checkpoint.
rollback = Effect.fn("Codex.rollback")(function* (
this: CodexAgent,
{ sessionId, itemId }: { sessionId: string; itemId: string },
) {
const connection = yield* this.loadedConnection(sessionId);
let turnId = this.sessions.get(sessionId)?.turns.get(itemId) ?? null;
if (!turnId) {
const { turns } = yield* this.allTurns(connection, sessionId);
turnId = turns.find((turn) => (turn.items ?? []).some((item) => map.itemId(item) === itemId))?.id ?? null;
if (!turnId) return yield* new ProviderError({ message: `codex does not know message ${itemId}` });
}
yield* this.request(connection, "thread/revert", { threadId: sessionId, beforeTurnId: turnId }).pipe(
Effect.mapError((error) => new ProviderError({ message: `thread/revert failed: ${errorMessage(error)}` })),
);
this.releaseIdle(sessionId);
return {};
});
compact = Effect.fn("Codex.compact")(function* (this: CodexAgent, { sessionId }: { sessionId: string }) {
const connection = yield* this.loadedConnection(sessionId);
yield* this.request(connection, "thread/compact/start", { threadId: sessionId }, { timeout: null }).pipe(
Effect.mapError((error) => new ProviderError({ message: `thread/compact/start failed: ${errorMessage(error)}` })),
);
return {};
});
usageLimits = Effect.fn("Codex.usageLimits")(function* (this: CodexAgent) {
return { limits: yield* this.limits() };
});
/// A sign-in the browser finished, failed or the app-server gave up on
/// (after ten minutes).
loginCompleted({ loginId, success, error }: wire.LoginCompleted) {
const login = loginId ? this.logins.get(loginId) : undefined;
if (!login) return;
Deferred.doneUnsafe(
login,
success ? Effect.void : Effect.fail(new ProviderError({ message: error || "the sign-in did not finish" })),
);
}
/// Starts the ChatGPT sign-in: the app-server answers with the page to
/// open and finishes the login itself when the browser comes back. The
/// call answers once it has, so "signed in" means signed in.
authenticate = authenticate;
logout = Effect.fn("Codex.logout")(function* (this: CodexAgent) {
const { connection } = yield* this.client();
yield* this.request(connection, "account/logout", {}).pipe(
Effect.mapError((error) => new ProviderError({ message: `account/logout failed: ${errorMessage(error)}` })),
);
this.accountDirty = true;
this.invalidateQuota();
return {};
});
/// Upgrades the installed Codex through whichever installer owns it.
update = Effect.fn("Codex.update")(function* (this: CodexAgent) {
const { manager, realPath } = yield* this.maintenance(null);
let result;
if (manager === "npm") {
const prefix = npmPrefix(realPath);
if (!prefix) return yield* new ProviderError({ message: "could not find the npm prefix that owns codex" });
result = yield* runProcess("npm", ["install", "-g", "--prefix", prefix, `${NPM_PACKAGE}@latest`]).pipe(
Effect.scoped,
);
} else if (manager === "homebrew") result = yield* runProcess("brew", ["upgrade", "codex"]).pipe(Effect.scoped);
else if (manager === "native") result = yield* runProcess("codex", ["update"]).pipe(Effect.scoped);
else
return yield* new ProviderError({
message: "Divergence cannot prove which installer owns this codex, so it must be updated by hand",
});
if (result.code !== 0)
return yield* new ProviderError({
message: result.stderr.trim() || `the update ended with ${result.code ?? result.signal}`,
});
yield* this.shutdownProcess();
this.models.clear();
return {};
});
}
No comments yet.