Файли
openidea/crates/ide-agent/src/native/codex/mod.rs
T
Deng Liuтаdengliu 19aef36354 feat(agents): add Agent Memory settings and a per-session memory picker (#6826)
Adds Settings › Agents › Memory and a Session Memory picker (/memory, /memories, the composer + menu and the context meter link). They list each agent's own instruction files, path-scoped rules and auto-memory notes: AGENTS.md, CLAUDE.md and .claude/rules, .github/copilot-instructions.md and .github/instructions, .cursor/rules, GEMINI.md, and the Claude Code, Codex and Hermes auto-memory folders.

Per-file modes (Auto / Always / Off) and the auto-memory policy (Inherit / Read & Write / Read Only / Off) are stored in settings.toml at user or workspace scope and never edit tracked files. Workspace entries load only in trusted projects. Each driver receives the policy natively: Claude Code through --settings and --add-dir, Codex through its memories config and /memories, GitHub Copilot through excludedTools and the system message, and Hermes through config.yaml. A file set to Always is staged into other agents' sessions. Auto-memory notes can be promoted into the workspace AGENTS.md, and an idle session restarts when a memory policy changes.

Groups of the same agent are titled by scope, for example Claude Code (User) and Claude Code (Auto Memory).

Closes #6810

Co-authored-by: dengliu <[email protected]>
2026-11-29 22:38:20 +08:00

1668 рядки
75 KiB
Rust

//! Codex over `codex app-server`: JSON-RPC (v2 threads and turns) on the child's stdio,
//! translated to and from ACP. A codex thread is an ACP session; a subagent's thread is
//! a subagent session of the thread that spawned it.
mod commands;
mod translate;
mod trust;
pub(crate) use commands::BUILTIN_COMMANDS;
#[cfg(test)]
mod tests;
use super::Shim;
use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec;
use crate::{AgentCommand, AgentCommandChoice, AgentCommandSource};
use commands::{BuiltinCommand, ParsedCommand};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, OnceLock, Weak};
use std::time::{Duration, Instant};
use tokio::sync::oneshot;
use translate::{Choice, Failure, ModelInfo, Settings};
/// Notifications codex need not send: the client builds diffs from the items.
const OPT_OUT: [&str; 1] = ["turn/diff/updated"];
/// A running command's output is sent at most this often.
const OUTPUT_EVERY: Duration = Duration::from_millis(200);
/// How long a `session/cancel` with no turn running still stops the prompt that follows.
const EARLY_CANCEL: Duration = Duration::from_secs(1);
/// How long the client's connection outlives codex.
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// What a thread's name is asked for with, after its first turn.
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
language the user writes in. Reply with the title only, without quotes or a closing period.";
/// Slash-command metadata for provider discovery and sessions without an advertised list.
pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
BUILTIN_COMMANDS
.iter()
.map(|command| AgentCommand {
name: command.name.to_owned(),
description: command.description.to_owned(),
hint: command.hint.map(str::to_owned),
source: AgentCommandSource::Command,
choices: command
.choices
.iter()
.map(|(name, description)| AgentCommandChoice {
name: (*name).to_owned(),
description: (*description).to_owned(),
})
.collect(),
})
.collect()
}
pub(crate) fn connect(
spec: &ProviderSpec,
cwd: &Path,
client: Arc<dyn Handler>,
on_stderr: Box<dyn Fn(String) + Send + Sync>,
) -> std::io::Result<Peer> {
attach(client, |events| {
let command = super::newest_install(&spec.command);
Peer::spawn_framed(&command, &spec.args, cwd, &spec.env, events, on_stderr, Framing::Lines)
})
}
/// A model lookup uses app-server directly: no thread, task, prompt or project MCP.
pub(crate) async fn discover(
spec: ProviderSpec,
cwd: std::path::PathBuf,
) -> Result<crate::catalogs::Discovered, String> {
let spec = tokio::task::spawn_blocking({
let cwd = cwd.clone();
move || spec.resolve_for_launch(&cwd)
})
.await
.map_err(|e| e.to_string())?;
let peer = Peer::spawn_framed(
&spec.command,
&spec.args,
&cwd,
&spec.env,
Arc::new(ide_jsonrpc::NoopHandler),
Box::new(|_| {}),
Framing::Lines,
)
.map_err(|e| e.to_string())?;
let _stop = crate::catalogs::KillPeer(peer.clone());
tokio::time::timeout(Duration::from_secs(30), async {
let _: Value = peer.request("initialize", initialize_params(), None).await.map_err(|e| e.to_string())?;
peer.notify("initialized", Value::Null).map_err(|e| e.to_string())?;
let mut models = list_models(&peer).await.map_err(|e| e.message)?;
models.retain(|model| !model.hidden);
let mut settings = Settings::of(&json!({}), &models);
if settings.model.is_empty()
&& let Some(model) = models.first()
{
settings.model = model.id.clone();
settings.fit_effort(&models);
}
let options = translate::config_options(&models, &settings);
let config = crate::config::options_of(&json!({ "configOptions": options }));
let levels = models
.iter()
.map(|model| {
let mut settings = settings.clone();
settings.model = model.id.clone();
settings.fit_effort(&models);
let options = translate::config_options(&models, &settings);
let levels = crate::config::options_of(&json!({ "configOptions": options }))
.into_iter()
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
.collect();
(model.id.clone(), levels)
})
.collect();
Ok(crate::catalogs::Discovered { config, commands: None, levels })
})
.await
.map_err(|_| "Codex model discovery timed out".to_owned())?
}
fn initialize_params() -> Value {
json!({
"clientInfo": { "name": "openidea", "title": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
"capabilities": { "experimentalApi": true, "optOutNotificationMethods": OPT_OUT },
})
}
async fn list_models(peer: &Peer) -> Result<Vec<ModelInfo>, ResponseError> {
let mut all = Vec::new();
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page: Value = peer.request("model/list", json!({ "cursor": cursor }), None).await.map_err(from_codex)?;
let Some(data) = page.get("data").and_then(Value::as_array) else {
return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model list"));
};
let models = translate::models_of(&page);
if models.len() != data.len() {
return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model list"));
}
all.extend(models);
match page.get("nextCursor") {
None | Some(Value::Null) => return Ok(all),
Some(Value::String(next)) if next.is_empty() => return Ok(all),
Some(Value::String(next)) if seen.insert(next.clone()) => cursor = json!(next),
_ => return Err(error(codes::INTERNAL_ERROR, "Codex returned an invalid model-list cursor")),
}
}
}
/// Connects `client` to a shim driving the codex connection `connect_codex` opens (it
/// gets the handler for what codex sends). Each side's end closes the other.
fn attach(
client: Arc<dyn Handler>,
connect_codex: impl FnOnce(Arc<dyn Handler>) -> std::io::Result<Peer>,
) -> std::io::Result<Peer> {
let shim = Arc::new(CodexShim {
runtime: tokio::runtime::Handle::current(),
codex: OnceLock::new(),
client: OnceLock::new(),
state: Mutex::new(State::default()),
models: tokio::sync::Mutex::new(None),
skills: tokio::sync::Mutex::new(()),
});
let codex = connect_codex(Arc::new(CodexEvents(Arc::downgrade(&shim))))?;
let _ = shim.codex.set(codex.clone());
let ours = super::serve(shim.clone(), client);
let to_client = shim.client.get().cloned().expect("serve attaches the client");
{
let (shim, codex, to_client) = (shim.clone(), codex.clone(), to_client.clone());
tokio::spawn(async move {
codex.closed().await;
shim.codex_gone();
// Answers already on their way (the turn that just ended) go out first.
tokio::time::sleep(EXIT_GRACE).await;
to_client.kill();
});
}
tokio::spawn(async move {
to_client.closed().await;
codex.kill();
});
Ok(ours)
}
struct CodexShim {
runtime: tokio::runtime::Handle,
codex: OnceLock<Peer>,
client: OnceLock<Peer>,
state: Mutex<State>,
/// `model/list`, fetched once.
models: tokio::sync::Mutex<Option<Arc<Vec<ModelInfo>>>>,
/// Keep skill snapshots in request order, including invalidations during session setup.
skills: tokio::sync::Mutex<()>,
}
#[derive(Default)]
struct State {
initialized: bool,
/// By codex thread id, which is also the ACP session id.
threads: HashMap<String, Thread>,
/// The last `account/rateLimits/updated` snapshot.
rate_limits: Option<Value>,
/// Project trust has been checked (and, when needed, asked about) on this connection.
trust_checked: HashSet<String>,
/// Codex exited.
gone: bool,
}
#[derive(Default)]
struct Thread {
/// The session whose agent spawned this one (a subagent's thread).
parent: Option<String>,
/// What turns run with (sessions of their own only).
settings: Option<Settings>,
cwd: Option<String>,
/// The turn running now.
turn: Option<String>,
/// The last turn that completed.
completed: Option<String>,
/// The `session/prompt` waiting for its turn to end.
prompt: Option<PendingPrompt>,
/// The current turn's tool items, for approval titles.
items: HashMap<String, Value>,
/// Output of running commands, by item id.
outputs: HashMap<String, Output>,
/// Items whose text was streamed (their completion doesn't repeat it).
streamed: HashSet<String>,
/// Kind and item of the text chunk sent last, while nothing else followed it.
last_chunk: Option<(&'static str, String)>,
/// The last error reported for the running turn.
error: Option<Value>,
/// A `session/cancel` that came with no turn running: it can overtake the
/// `session/prompt` sent just before it.
early_cancel: Option<Instant>,
/// The latest agent message (a subagent's answer).
answer: String,
/// The latest `thread/tokenUsage/updated` payload, for the `/status` command.
token_usage: Option<Value>,
/// The thread has a name.
named: bool,
/// A name is being asked for.
naming: bool,
}
struct PendingPrompt {
done: oneshot::Sender<(Value, Option<Value>)>,
/// Known once `turn/start` answers or `turn/started` arrives.
turn: Option<String>,
/// Cancelled before the turn was known: interrupt it as soon as it is.
cancel: bool,
}
struct Output {
text: String,
sent: Instant,
}
/// Receives what codex sends.
struct CodexEvents(Weak<CodexShim>);
impl Handler for CodexEvents {
fn on_notification(&self, method: &str, params: Value) {
if let Some(shim) = self.0.upgrade() {
shim.on_codex_notification(method, &params);
}
}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
let shim = self.0.upgrade().ok_or((codes::INTERNAL_ERROR, "closed".to_owned()))?;
shim.on_codex_request(method, &params)
}
}
impl Shim for CodexShim {
fn attach(&self, client: Peer) {
let _ = self.client.set(client);
}
}
impl Handler for CodexShim {
fn on_notification(&self, method: &str, params: Value) {
if method == "session/cancel"
&& let Some(session) = params.get("sessionId").and_then(Value::as_str)
{
self.cancel(session);
}
}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.on_request_with_data(method, params).map_err(|(code, message, _)| (code, message))
}
fn on_request_with_data(&self, method: &str, params: Value) -> Result<Value, (i64, String, Option<Value>)> {
self.runtime.block_on(self.handle(method, params)).map_err(|e| (e.code, e.message, e.data))
}
}
/// The `error` of an ACP response.
#[derive(Debug)]
struct ResponseError {
code: i64,
message: String,
data: Option<Value>,
}
fn error(code: i64, message: impl Into<String>) -> ResponseError {
ResponseError { code, message: message.into(), data: None }
}
fn invalid(message: impl Into<String>) -> ResponseError {
error(codes::INVALID_PARAMS, message)
}
/// A failed codex request, for the ACP client.
fn from_codex(e: RpcError) -> ResponseError {
match e {
RpcError::Server { code, message, data } => {
// Protocol errors can list method names containing "auth"; they are not sign-in failures.
let protocol = matches!(
code,
codes::PARSE_ERROR | codes::INVALID_REQUEST | codes::METHOD_NOT_FOUND | codes::INVALID_PARAMS
);
let code = if !protocol && crate::acp::auth_required(code, &message) { AUTH_REQUIRED } else { code };
ResponseError { code, message, data }
}
RpcError::Closed => error(codes::INTERNAL_ERROR, "Codex exited"),
e => error(codes::INTERNAL_ERROR, e.to_string()),
}
}
fn str_param<'a>(params: &'a Value, key: &str) -> Result<&'a str, ResponseError> {
params.get(key).and_then(Value::as_str).ok_or_else(|| invalid(format!("missing {key}")))
}
/// Fills a `thread/start`/`thread/resume`/`thread/fork` request's `config` with the session's
/// MCP servers and its staged skills: the off ones, by path (`skills.config` entries with
/// `enabled = false`, which the CLI honors for the copies it discovers natively too).
fn apply_thread_config(params: &Value, request: &mut Value) {
let mut config = translate::mcp_config(params).unwrap_or_else(|| json!({}));
let off: Vec<Value> = params
.pointer("/_meta/openidea/skills/codexOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| {
let path = entry.get(1)?.as_str()?;
Some(json!({ "path": path, "enabled": false }))
})
.collect();
if !off.is_empty()
&& let Some(map) = config.as_object_mut()
{
map.insert("skills".into(), json!({ "config": off }));
}
if let Some(mem) = params.pointer("/_meta/openidea/memory")
&& let Some(map) = config.as_object_mut()
{
let mut mem_cfg = serde_json::Map::new();
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
mem_cfg.insert("use_memories".into(), json!(use_m));
}
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
mem_cfg.insert("generate_memories".into(), json!(gen_m));
}
if !mem_cfg.is_empty() {
map.insert("memories".into(), Value::Object(mem_cfg));
}
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
map.insert("developer_instructions".into(), json!(dev));
}
}
if !config.as_object().is_some_and(|m| m.is_empty()) {
request["config"] = config;
}
// The workspace's other roots join the thread's own: they are where `workspace-write`
// may write and what the model is told the workspace holds.
if let Some(extra) = params.get("additionalDirectories").and_then(Value::as_array).filter(|a| !a.is_empty())
&& let Some(cwd) = params.get("cwd").filter(|c| c.is_string())
{
request["runtimeWorkspaceRoots"] = std::iter::once(cwd).chain(extra).cloned().collect();
}
}
impl CodexShim {
fn codex(&self) -> &Peer {
self.codex.get().expect("attached before any message")
}
async fn call(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
self.codex().request(method, params, None).await.map_err(from_codex)
}
fn warning(&self, message: impl Into<String>) {
if let Some(client) = self.client.get() {
let _ = client.notify(crate::WARNING_NOTIFICATION, json!({ "message": message.into() }));
}
}
async fn handle(&self, method: &str, params: Value) -> Result<Value, ResponseError> {
match method {
"initialize" => self.initialize().await,
"session/new" => self.new_session(&params).await,
"session/load" => self.load_session(&params).await,
"session/fork" => self.fork_session(&params).await,
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params).await,
"_openidea/steer" => self.steer(&params).await,
"_openidea/rollback" => self.rollback(&params).await,
"session/close" => self.close(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
}
}
async fn initialize(&self) -> Result<Value, ResponseError> {
let info = self.call("initialize", initialize_params()).await?;
self.codex().notify("initialized", Value::Null).map_err(from_codex)?;
self.state.lock().initialized = true;
// `<client>/<codex version> (<platform>) …`
let version = info
.get("userAgent")
.and_then(Value::as_str)
.and_then(|ua| ua.split_whitespace().next())
.and_then(|first| first.split_once('/'))
.map(|(_, v)| v.to_owned());
Ok(json!({
"protocolVersion": 1,
"agentCapabilities": {
"loadSession": true,
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
"_meta": { "openidea": { "rollback": true, "steer": true } },
},
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
"authMethods": [],
}))
}
/// Cache only complete, successful listings; a failed page must never become availability.
async fn models(&self) -> Result<Arc<Vec<ModelInfo>>, ResponseError> {
let mut cached = self.models.lock().await;
if let Some(models) = cached.as_ref() {
return Ok(models.clone());
}
let models = Arc::new(list_models(self.codex()).await?);
*cached = Some(models.clone());
Ok(models)
}
async fn publish_skills(&self, session: &str) {
let _listing = self.skills.lock().await;
let cwd = self.state.lock().threads.get(session).and_then(|t| t.cwd.clone());
let Some(cwd) = cwd else { return };
let result =
tokio::time::timeout(Duration::from_secs(5), self.call("skills/list", json!({ "cwds": [cwd] }))).await;
if let Ok(Ok(result)) = result
&& let Some(update) = translate::skill_commands(&result)
&& self.state.lock().threads.contains_key(session)
{
self.emit(session, update);
}
}
/// Hands the session's staged skills to the app-server: the farm's `codex` tree joins
/// its discovery roots. Best-effort: a CLI version without `skills/extraRoots/set`
/// (the method arrived later than some pinned installs) runs without the farm, as
/// before.
async fn apply_skill_roots(&self, session: &str, params: &Value) {
let roots = params
.pointer("/_meta/openidea/skills/codexExtraRoots")
.and_then(Value::as_array)
.map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>())
.unwrap_or_default();
if roots.is_empty() {
return;
}
let set = tokio::time::timeout(
Duration::from_secs(5),
self.call("skills/extraRoots/set", json!({ "extraRoots": roots })),
)
.await;
match set {
Ok(Ok(_)) => {}
Ok(Err(e)) => tracing::info!("codex session {session}: could not set the extra skill roots: {}", e.message),
Err(e) => tracing::info!("codex session {session}: could not set the extra skill roots: {e}"),
}
}
/// Registers a thread codex opened for a session of its own; returns its `configOptions`.
fn open_thread(&self, result: &Value, models: &[ModelInfo], settings: Option<Settings>) -> (String, Value) {
let thread = result.get("thread").unwrap_or(&Value::Null);
let id = thread.get("id").and_then(Value::as_str).unwrap_or_default().to_owned();
let settings = settings.unwrap_or_else(|| Settings::of(result, models));
let options = translate::config_options(models, &settings);
let cwd = result.get("cwd").or(thread.get("cwd")).and_then(Value::as_str).map(str::to_owned);
let mut state = self.state.lock();
let t = state.threads.entry(id.clone()).or_default();
t.parent = None;
t.settings = Some(settings);
t.cwd = cwd;
t.named = thread.get("name").and_then(Value::as_str).is_some_and(|n| !n.trim().is_empty());
(id, options)
}
async fn new_session(&self, params: &Value) -> Result<Value, ResponseError> {
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
request["ephemeral"] = json!(true);
}
let result = self.call("thread/start", request).await?;
let mut settings = Settings::of(&result, &models);
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
let (id, options) = self.open_thread(&result, &models, Some(settings));
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
/// Resumes the thread and replays its history before answering.
async fn load_session(&self, params: &Value) -> Result<Value, ResponseError> {
let id = str_param(params, "sessionId")?;
let models = self.models().await?;
self.prepare_project_trust(params).await;
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
let result = self.call("thread/resume", request).await?;
let mut settings = Settings::of(&result, &models);
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
let (_, options) = self.open_thread(&result, &models, Some(settings));
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
let thread = result.get("thread").unwrap_or(&Value::Null);
for update in translate::history(thread, cwd.as_deref()) {
self.emit(id, update);
}
self.apply_skill_roots(id, params).await;
self.publish_skills(id).await;
Ok(json!({ "configOptions": options }))
}
async fn fork_session(&self, params: &Value) -> Result<Value, ResponseError> {
let source = str_param(params, "sessionId")?;
let models = self.models().await?;
self.prepare_project_trust(params).await;
let settings = self.state.lock().threads.get(source).and_then(|t| t.settings.clone());
let mut request = json!({ "threadId": source, "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
request["sandbox"] = json!(s.mode.sandbox_mode());
}
let result = self.call("thread/fork", request).await?;
let (id, options) = self.open_thread(&result, &models, settings);
self.apply_skill_roots(&id, params).await;
self.publish_skills(&id).await;
Ok(json!({ "sessionId": id, "configOptions": options }))
}
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let option = str_param(params, "configId")?;
let value = str_param(params, "value")?;
let models = self.models().await?;
let mut state = self.state.lock();
let settings = state
.threads
.get_mut(session)
.and_then(|t| t.settings.as_mut())
.ok_or_else(|| invalid(format!("no session {session}")))?;
settings.set(&models, option, value).map_err(invalid)?;
Ok(json!({ "configOptions": translate::config_options(&models, settings) }))
}
async fn prompt(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?.to_owned();
let prompt = params.get("prompt").unwrap_or(&Value::Null);
let command = commands::parse(prompt);
if let Some(command) = command.as_ref()
&& !command.starts_turn()
{
return self.local_command(&session, command).await;
}
let input = translate::user_input(prompt);
if input.is_empty() {
return Err(invalid("empty prompt"));
}
let models = if command.is_none() { Some(self.models().await?) } else { None };
let (done, ended) = oneshot::channel();
let settings = {
let mut state = self.state.lock();
if state.gone {
return Err(error(codes::INTERNAL_ERROR, "Codex exited"));
}
let t = state.threads.get_mut(&session).ok_or_else(|| invalid(format!("no session {session}")))?;
if t.prompt.is_some() {
return Err(invalid("a turn is already running"));
}
let cancel = t.early_cancel.take().is_some_and(|at| at.elapsed() < EARLY_CANCEL);
t.prompt = Some(PendingPrompt { done, turn: None, cancel });
t.error = None;
t.settings.clone()
};
let started = match command.as_ref() {
Some(command) => match command.command {
BuiltinCommand::Compact => {
// Codex reports compaction as its own turn, using the same started/completed
// notifications that finish the pending session/prompt above.
self.call("thread/compact/start", json!({ "threadId": session })).await
}
BuiltinCommand::Review | BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
self.call("review/start", json!({ "threadId": session, "target": review_target(command) })).await
}
_ => unreachable!("local commands return before a pending turn is created"),
},
None => {
let models = models.expect("ordinary prompts load the model catalog");
let mut request = json!({ "threadId": session, "input": input, "summary": "auto" });
if let Some(s) = &settings {
request["model"] = json!(s.model_slug(&models));
request["approvalPolicy"] = json!(s.mode.approval_policy());
request["sandboxPolicy"] = s.mode.sandbox_policy();
// Omit the default so older app-server versions keep accepting normal
// turns; selecting Plan opts into this newer request field.
if s.collaboration_mode == translate::PLAN_COLLABORATION_MODE
|| s.collaboration_mode_override.is_some()
{
request["collaborationMode"] = translate::collaboration_mode(s, &models);
}
if let Some(effort) = &s.effort {
request["effort"] = json!(effort);
}
if let Some(tier) = s.service_tier_override(&models) {
request["serviceTier"] = json!(tier);
}
}
self.call("turn/start", request).await
}
};
if let Ok(started) = &started
&& let Some(turn) = started.pointer("/turn/id").and_then(Value::as_str)
{
self.turn_known(&session, turn, false);
}
if started.is_ok()
&& command.is_none()
&& let Some(thread) = self.state.lock().threads.get_mut(&session)
&& let Some(settings) = thread.settings.as_mut()
{
// A Default override is needed only for the first turn that resets a resumed
// Plan thread; omitting it afterwards preserves compatibility with older Codex.
settings.collaboration_mode_override = None;
}
if let Err(e) = started {
if let Some(t) = self.state.lock().threads.get_mut(&session) {
t.prompt = None;
}
return Err(e);
}
let (turn, last_error) = ended.await.map_err(|_| error(codes::INTERNAL_ERROR, "Codex exited"))?;
let rate_limits = self.state.lock().rate_limits.clone();
stop_reason(&turn, last_error, rate_limits.as_ref())
}
/// Runs commands that codex-acp historically handled locally: configuration, status,
/// inventory, naming and account actions. They complete without starting a model turn.
async fn local_command(&self, session: &str, command: &ParsedCommand) -> Result<Value, ResponseError> {
let (settings, cwd, token_usage, rate_limits) = {
let state = self.state.lock();
if state.gone {
return Err(error(codes::INTERNAL_ERROR, "Codex exited"));
}
let thread = state.threads.get(session).ok_or_else(|| invalid(format!("no session {session}")))?;
if thread.prompt.is_some() || thread.turn.is_some() {
return Err(invalid("a turn is already running"));
}
(thread.settings.clone(), thread.cwd.clone(), thread.token_usage.clone(), state.rate_limits.clone())
};
match command.command {
BuiltinCommand::Plan => {
if !command.rest.is_empty() {
self.say(session, command_usage(BuiltinCommand::Plan));
return Ok(json!({ "stopReason": "end_turn" }));
}
let models = self.models().await?;
let options = {
let mut state = self.state.lock();
let thread =
state.threads.get_mut(session).ok_or_else(|| invalid(format!("no session {session}")))?;
let settings = thread.settings.as_mut().ok_or_else(|| invalid(format!("no session {session}")))?;
settings.collaboration_mode = if settings.collaboration_mode == translate::PLAN_COLLABORATION_MODE {
translate::DEFAULT_COLLABORATION_MODE.to_owned()
} else {
translate::PLAN_COLLABORATION_MODE.to_owned()
};
settings.collaboration_mode_override = Some(settings.collaboration_mode.clone());
translate::config_options(&models, settings)
};
self.emit(session, json!({ "sessionUpdate": "config_option_update", "configOptions": options }));
}
BuiltinCommand::Status => {
let text =
status_text(session, settings.as_ref(), cwd.as_deref(), token_usage.as_ref(), rate_limits.as_ref());
self.say(session, text);
}
BuiltinCommand::Skills => {
let cwd = cwd.ok_or_else(|| invalid(format!("no session {session}")))?;
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
self.say(session, skills_text(&found));
}
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
BuiltinCommand::Mcp => match command.rest.as_str() {
"" => self.say(session, self.mcp_text(session).await?),
rest if rest.eq_ignore_ascii_case("reconnect") => {
self.call("config/mcpServer/reload", json!({})).await?;
self.say(session, self.mcp_text(session).await?);
}
_ => self.say(session, command_usage(BuiltinCommand::Mcp)),
},
BuiltinCommand::Rename => {
if command.rest.is_empty() {
self.say(session, command_usage(BuiltinCommand::Rename));
} else {
self.call("thread/name/set", json!({ "threadId": session, "name": command.rest })).await?;
// User commands are authoritative over the automatic title, so the manager
// must retain this title through later generated-name updates.
self.emit(
session,
json!({ "sessionUpdate": "session_info_update", "title": command.rest, "userNamed": true }),
);
}
}
BuiltinCommand::Logout => {
self.call("account/logout", Value::Null).await?;
self.say(session, "Logged out from Codex account.");
}
BuiltinCommand::Goal => self.goal_command(session, &command.rest).await?,
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit if command.rest.is_empty() => {
self.say(session, command_usage(command.command));
}
BuiltinCommand::ReviewBranch | BuiltinCommand::ReviewCommit => {
return Err(invalid("review command did not start a turn"));
}
BuiltinCommand::Review | BuiltinCommand::Compact => {
return Err(invalid("turn command reached the local command path"));
}
}
Ok(json!({ "stopReason": "end_turn" }))
}
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let arg = rest.trim().to_ascii_lowercase();
match arg.as_str() {
"" | "show" => {
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
let summary = res
.get("summary")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.unwrap_or("No consolidated memories for this thread yet.");
self.say(session, summary);
}
"on" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
self.say(session, "Memory generation enabled for this thread.");
}
"off" => {
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
self.say(session, "Memory generation disabled for this thread.");
}
"reset" => {
self.call("memory/reset", Value::Null).await?;
self.say(session, "Reset local Codex memories.");
}
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
}
Ok(())
}
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
let argument = rest.trim();
if argument.is_empty() {
self.say(session, command_usage(BuiltinCommand::Goal));
return Ok(());
}
match argument.to_ascii_lowercase().as_str() {
"clear" => {
self.call("thread/goal/clear", json!({ "threadId": session })).await?;
self.say(session, "Goal cleared.");
}
"pause" => {
let response = self
.call("thread/goal/set", json!({ "threadId": session, "status": "paused", "origin": "user" }))
.await?;
self.say(
session,
format!(
"Goal is now {}.",
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("paused")
),
);
}
"resume" => {
let response = self
.call("thread/goal/set", json!({ "threadId": session, "status": "active", "origin": "user" }))
.await?;
self.say(
session,
format!(
"Goal is now {}.",
response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active")
),
);
}
_ if argument.chars().count() > 4000 => {
self.say(session, "Command \"/goal\" requires goal text of at most 4000 characters.");
}
_ => {
let response = self
.call(
"thread/goal/set",
json!({ "threadId": session, "objective": argument, "status": "active", "origin": "user" }),
)
.await?;
let status = response.pointer("/goal/status").and_then(Value::as_str).unwrap_or("active");
self.say(session, format!("Goal set and {status}."));
}
}
Ok(())
}
async fn mcp_text(&self, session: &str) -> Result<String, ResponseError> {
let response = self
.call("mcpServerStatus/list", json!({ "threadId": session, "detail": "toolsAndAuthOnly", "limit": 100 }))
.await?;
Ok(mcp_text(&response))
}
fn say(&self, session: &str, text: impl AsRef<str>) {
self.emit(session, translate::chunk("agent_message_chunk", text.as_ref()));
}
async fn steer(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let turn = self.state.lock().threads.get(session).and_then(|t| t.turn.clone());
let turn = turn.ok_or_else(|| invalid("no turn is running"))?;
let input = translate::user_input(params.get("prompt").unwrap_or(&Value::Null));
self.call("turn/steer", json!({ "threadId": session, "expectedTurnId": turn, "input": input })).await?;
Ok(json!({}))
}
async fn rollback(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let turns = params.get("turns").and_then(Value::as_u64).filter(|n| *n > 0).ok_or_else(|| invalid("turns"))?;
match self.call("thread/rollback", json!({ "threadId": session, "numTurns": turns })).await {
Ok(_) => {}
Err(e)
if e.code == codes::METHOD_NOT_FOUND
|| (e.code == codes::INVALID_REQUEST
&& e.message.contains("unknown variant `thread/rollback`")) =>
{
self.revert(session, turns).await?;
}
Err(e) => return Err(e),
}
Ok(json!({}))
}
/// New Codex versions replace rollback counts with an exclusive turn id.
async fn revert(&self, session: &str, mut remaining: u64) -> Result<(), ResponseError> {
let mut cursor = Value::Null;
let mut seen = HashSet::new();
loop {
let page = self
.call(
"thread/turns/list",
json!({ "threadId": session, "sortDirection": "desc", "limit": remaining.min(100), "cursor": cursor }),
)
.await?;
let turns = page.get("data").and_then(Value::as_array).ok_or_else(|| invalid("Codex returned no turns"))?;
if remaining <= turns.len() as u64 {
let before = str_param(&turns[remaining as usize - 1], "id")?;
self.call("thread/revert", json!({ "threadId": session, "beforeTurnId": before })).await?;
return Ok(());
}
remaining -= turns.len() as u64;
let next = page.get("nextCursor").and_then(Value::as_str);
let Some(next) = next.filter(|next| seen.insert((*next).to_owned())) else {
return Err(invalid(
"Codex history has fewer turns than the conversation; reload the task before editing",
));
};
cursor = json!(next);
}
}
/// Stops following the session's thread (codex unloads it once nothing follows it).
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
let session = str_param(params, "sessionId")?;
let known = self.state.lock().threads.remove(session).is_some();
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
}
Ok(json!({}))
}
/// `session/cancel`: interrupts the session's turn, or the one about to start.
fn cancel(&self, session: &str) {
let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(session) else { return };
match t.turn.clone() {
Some(turn) => self.interrupt(session, &turn),
None => match t.prompt.as_mut() {
Some(p) => p.cancel = true,
None => t.early_cancel = Some(Instant::now()),
},
}
}
fn interrupt(&self, session: &str, turn: &str) {
let codex = self.codex().clone();
let params = json!({ "threadId": session, "turnId": turn });
self.runtime.spawn(async move {
if let Err(e) = codex.request::<_, Value>("turn/interrupt", params, None).await {
tracing::warn!("codex: interrupting the turn failed: {e}");
}
});
}
/// Turn `turn` of `session` is known: from `turn/start`'s answer, or `started` with
/// `turn/started`. Codex rejects an interrupt until it has started the turn, so a
/// stop that came earlier waits for that.
fn turn_known(&self, session: &str, turn: &str, started: bool) {
let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(session) else { return };
if t.completed.as_deref() == Some(turn) {
return;
}
if started {
t.turn = Some(turn.to_owned());
}
let Some(p) = t.prompt.as_mut() else { return };
if p.turn.is_none() {
p.turn = Some(turn.to_owned());
}
if started && p.turn.as_deref() == Some(turn) && std::mem::take(&mut p.cancel) {
self.interrupt(session, turn);
}
}
fn codex_gone(&self) {
let mut state = self.state.lock();
state.gone = true;
for t in state.threads.values_mut() {
t.prompt = None;
}
}
fn emit(&self, session: &str, update: Value) {
if let Some(client) = self.client.get() {
let _ = client.notify("session/update", json!({ "sessionId": session, "update": update }));
}
}
fn on_codex_notification(self: &Arc<Self>, method: &str, params: &Value) {
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default();
match method {
"configWarning" => {
let Some(summary) = params.get("summary").and_then(Value::as_str).filter(|s| !s.trim().is_empty())
else {
return;
};
let mut message = summary.trim().to_owned();
for key in ["details", "path"] {
if let Some(value) = params.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
message.push_str("\n\n");
message.push_str(value.trim());
}
}
self.warning(message);
}
"warning" => {
if let Some(message) = params.get("message").and_then(Value::as_str).filter(|s| !s.trim().is_empty()) {
self.warning(message);
}
}
"skills/changed" => {
let shim = self.clone();
let sessions: Vec<String> = self
.state
.lock()
.threads
.iter()
.filter(|(_, t)| t.settings.is_some() && t.parent.is_none())
.map(|(id, _)| id.clone())
.collect();
self.runtime.spawn(async move {
for session in sessions {
shim.publish_skills(&session).await;
}
});
}
"turn/started" => {
if let Some(turn) = params.pointer("/turn/id").and_then(Value::as_str) {
self.turn_known(thread, turn, true);
}
self.subagent_state(thread, json!({ "state": "running" }));
}
"turn/completed" => self.turn_completed(thread, params.get("turn").unwrap_or(&Value::Null)),
"item/started" => self.item(thread, params.get("item").unwrap_or(&Value::Null), false),
"item/completed" => self.item(thread, params.get("item").unwrap_or(&Value::Null), true),
"item/agentMessage/delta" | "item/plan/delta" => self.text(thread, params, "agent_message_chunk", false),
"item/reasoning/summaryTextDelta" => self.text(thread, params, "agent_thought_chunk", false),
"item/reasoning/textDelta" => self.text(thread, params, "agent_thought_chunk", true),
"item/reasoning/summaryPartAdded" => {
if params.get("summaryIndex").and_then(Value::as_u64).unwrap_or(0) > 0 {
let mut p = params.clone();
p["delta"] = json!("\n\n");
self.text(thread, &p, "agent_thought_chunk", false);
}
}
"item/commandExecution/outputDelta" => self.command_output(thread, params),
"item/fileChange/patchUpdated" => {
let id = params.get("itemId").and_then(Value::as_str).unwrap_or_default();
let item = json!({ "id": id, "type": "fileChange", "changes": params.get("changes") });
self.with_thread(thread, |t, cwd| {
let mut update = translate::tool_call(&item, true, cwd, None)?;
update.as_object_mut()?.remove("status");
t.last_chunk = None;
Some(update)
});
}
"turn/plan/updated" => self.with_thread(thread, |t, _| {
t.last_chunk = None;
Some(translate::plan(params))
}),
"thread/tokenUsage/updated" => self.with_thread(thread, |t, _| {
if let Some(usage) = params.get("tokenUsage") {
t.token_usage = Some(usage.clone());
}
translate::usage(params)
}),
"thread/name/updated" => self.with_thread(thread, |t, _| {
let title = params.get("threadName").and_then(Value::as_str)?;
t.named = true;
Some(json!({ "sessionUpdate": "session_info_update", "title": title }))
}),
"thread/started" => self.thread_started(params.get("thread").unwrap_or(&Value::Null)),
"error" => {
if params.get("willRetry").and_then(Value::as_bool) != Some(true)
&& let Some(t) = self.state.lock().threads.get_mut(thread)
{
t.error = params.get("error").cloned();
}
}
"account/rateLimits/updated" => self.state.lock().rate_limits = params.get("rateLimits").cloned(),
_ => {}
}
}
/// Sends what `f` makes of the known thread `thread` (given its cwd), under the lock so
/// updates keep their order.
fn with_thread(&self, thread: &str, f: impl FnOnce(&mut Thread, Option<&str>) -> Option<Value>) {
let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(thread) else { return };
let cwd = t.cwd.clone();
if let Some(update) = f(t, cwd.as_deref()) {
self.emit(thread, update);
}
}
/// A streamed piece of a message or reasoning item. `raw` reasoning text is used only
/// for items without a summary.
fn text(&self, thread: &str, params: &Value, kind: &'static str, raw: bool) {
let item = params.get("itemId").and_then(Value::as_str).unwrap_or_default();
let Some(delta) = params.get("delta").and_then(Value::as_str).filter(|d| !d.is_empty()) else { return };
self.with_thread(thread, |t, _| {
let summarized = t.streamed.contains(&format!("summary:{item}"));
if raw && summarized {
return None;
}
if !raw && kind == "agent_thought_chunk" {
t.streamed.insert(format!("summary:{item}"));
}
t.streamed.insert(item.to_owned());
Some(t.chunk(kind, item, delta))
});
}
fn command_output(&self, thread: &str, params: &Value) {
let item = params.get("itemId").and_then(Value::as_str).unwrap_or_default();
let delta = params.get("delta").and_then(Value::as_str).unwrap_or_default();
self.with_thread(thread, |t, _| {
let out = t
.outputs
.entry(item.to_owned())
.or_insert_with(|| Output { text: String::new(), sent: Instant::now() - OUTPUT_EVERY });
out.text.push_str(delta);
if out.text.len() > 2 * translate::MAX_OUTPUT {
out.text = translate::tail(&out.text);
}
if out.sent.elapsed() < OUTPUT_EVERY {
return None;
}
out.sent = Instant::now();
t.last_chunk = None;
Some(translate::command_output(item, &out.text))
});
}
fn item(&self, thread: &str, item: &Value, done: bool) {
let id = item.get("id").and_then(Value::as_str).unwrap_or_default().to_owned();
match item.get("type").and_then(Value::as_str).unwrap_or_default() {
"userMessage" | "hookPrompt" => {}
ty @ ("agentMessage" | "plan" | "reasoning") => {
if !done {
return;
}
let (kind, text) = if ty == "reasoning" {
("agent_thought_chunk", translate::reasoning_text(item))
} else {
("agent_message_chunk", item.get("text").and_then(Value::as_str).unwrap_or_default().to_owned())
};
self.with_thread(thread, |t, _| {
if ty == "agentMessage" {
t.answer = text.clone();
}
t.streamed.remove(&format!("summary:{id}"));
if t.streamed.remove(&id) || text.is_empty() {
return None;
}
Some(t.chunk(kind, &id, &text))
});
if ty == "agentMessage"
&& let Some(update) = translate::question_update(item)
{
self.emit(thread, update);
}
}
"subAgentActivity" => {
let child = item.get("agentThreadId").and_then(Value::as_str).unwrap_or_default();
let name = item.get("agentPath").and_then(Value::as_str).and_then(|p| p.rsplit('/').next());
if !done && item.get("kind").and_then(Value::as_str) == Some("started") {
self.spawned(thread, child, name, None, &id);
}
}
"collabAgentToolCall" if item.get("tool").and_then(Value::as_str) == Some("spawnAgent") => {
if !done {
return;
}
let prompt = item.get("prompt").and_then(Value::as_str);
for child in item.get("receiverThreadIds").and_then(Value::as_array).into_iter().flatten() {
if let Some(child) = child.as_str() {
self.spawned(thread, child, None, prompt, &id);
}
}
}
_ => self.with_thread(thread, |t, cwd| {
let output = if done { t.outputs.remove(&id).map(|o| o.text) } else { None };
let update = translate::tool_call(item, done, cwd, output.as_deref())?;
if done {
t.items.remove(&id);
} else {
t.items.insert(id.clone(), item.clone());
}
t.last_chunk = None;
Some(update)
}),
}
}
/// A subagent thread `child` started by session `parent`: announced on the parent, with
/// what it was asked.
fn spawned(&self, parent: &str, child: &str, name: Option<&str>, prompt: Option<&str>, call: &str) {
if child.is_empty() {
return;
}
let mut state = self.state.lock();
if !state.threads.contains_key(parent) {
return;
}
let cwd = state.threads.get(parent).and_then(|t| t.cwd.clone());
let known = state.threads.contains_key(child);
let t = state.threads.entry(child.to_owned()).or_default();
t.parent = Some(parent.to_owned());
t.cwd = t.cwd.take().or(cwd);
if !known {
let mut announce = json!({ "sessionUpdate": "subagent_update", "sessionId": child,
"state": { "state": "running" }, "capabilities": { "cancel": {} } });
if let Some(name) = name {
announce["title"] = json!(name);
}
self.emit(parent, announce);
}
if let Some(prompt) = prompt.filter(|p| !p.is_empty()) {
if known {
self.emit(
parent,
json!({ "sessionUpdate": "subagent_update", "sessionId": child, "description": prompt }),
);
}
self.emit(
parent,
json!({ "sessionUpdate": "session_message", "messageId": call, "senderSessionId": parent,
"recipientSessionId": child, "content": [{ "type": "text", "text": prompt }] }),
);
}
}
/// A thread codex started on its own: a subagent when its parent is a session here.
fn thread_started(&self, thread: &Value) {
let (Some(id), Some(parent)) =
(thread.get("id").and_then(Value::as_str), thread.get("parentThreadId").and_then(Value::as_str))
else {
return;
};
let name = thread.get("agentNickname").or(thread.get("agentRole")).and_then(Value::as_str);
let known = self.state.lock().threads.contains_key(id);
self.spawned(parent, id, name, None, "");
if known && let Some(name) = name {
self.emit(parent, json!({ "sessionUpdate": "subagent_update", "sessionId": id, "title": name }));
}
}
/// Reports a subagent thread's state on its parent.
fn subagent_state(&self, thread: &str, state_of: Value) {
let parent = self.state.lock().threads.get(thread).and_then(|t| t.parent.clone());
if let Some(parent) = parent {
self.emit(
parent.as_str(),
json!({ "sessionUpdate": "subagent_update", "sessionId": thread, "state": state_of }),
);
}
}
fn turn_completed(self: &Arc<Self>, thread: &str, turn: &Value) {
let id = turn.get("id").and_then(Value::as_str).unwrap_or_default();
let completed = turn.get("status").and_then(Value::as_str) == Some("completed");
let (parent, answer, name) = {
let mut state = self.state.lock();
let Some(t) = state.threads.get_mut(thread) else { return };
if t.turn.as_deref().is_none_or(|r| r == id) {
t.turn = None;
}
t.completed = Some(id.to_owned());
t.items.clear();
t.last_chunk = None;
let error = t.error.take();
if t.prompt.as_ref().is_some_and(|p| p.turn.as_deref().is_none_or(|p| p == id))
&& let Some(p) = t.prompt.take()
{
let _ = p.done.send((turn.clone(), error.clone()));
}
let answer = std::mem::take(&mut t.answer);
let name =
completed && !id.is_empty() && t.parent.is_none() && t.settings.is_some() && !t.named && !t.naming;
t.naming |= name;
(t.parent.clone(), (answer, error), name)
};
if name {
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
}
let Some(parent) = parent else { return };
let (answer, error) = answer;
let mut state_of = match turn.get("status").and_then(Value::as_str) {
Some("interrupted") => json!({ "state": "idle", "stopReason": "cancelled" }),
Some("failed") => json!({ "state": "idle", "stopReason": "error" }),
_ => json!({ "state": "idle", "stopReason": "end_turn" }),
};
if let Some(e) = turn.get("error").filter(|e| !e.is_null()).or(error.as_ref()) {
state_of["error"] = json!({ "code": codes::INTERNAL_ERROR, "message": translate::error_message(e) });
}
self.emit(&parent, json!({ "sessionUpdate": "subagent_update", "sessionId": thread, "state": state_of }));
if !answer.is_empty() {
self.emit(
&parent,
json!({ "sessionUpdate": "session_message", "messageId": format!("{thread}:{id}"),
"senderSessionId": thread, "recipientSessionId": parent,
"content": [{ "type": "text", "text": answer }] }),
);
}
}
/// Names a thread from what it holds after `turn`, as codex leaves naming to its
/// clients; `thread/name/updated` brings the name back. Unnamed, the next turn tries again.
async fn name_thread(&self, thread: &str, turn: &str) {
let sample = json!({ "threadId": thread, "expectedTurnId": turn, "prompt": NAME_PROMPT, "effort": "low" });
let named = match self.call("thread/sample", sample).await {
Ok(r) => match r.get("text").and_then(Value::as_str).and_then(translate::thread_name) {
Some(name) => {
self.call("thread/name/set", json!({ "threadId": thread, "name": name })).await.map(|_| ())
}
None => Err(error(codes::INTERNAL_ERROR, "codex gave no name")),
},
Err(e) => Err(e),
};
if let Err(e) = &named {
tracing::debug!("naming codex thread {thread}: {}", e.message);
}
if let Some(t) = self.state.lock().threads.get_mut(thread) {
t.naming = false;
t.named |= named.is_ok();
}
}
/// Requests from codex: approvals and questions, asked as ACP permission requests.
fn on_codex_request(&self, method: &str, params: &Value) -> Result<Value, (i64, String)> {
let thread = params.get("threadId").and_then(Value::as_str).unwrap_or_default().to_owned();
let item_id = params.get("itemId").and_then(Value::as_str).unwrap_or_default().to_owned();
let (item, cwd) = {
let state = self.state.lock();
let t = state.threads.get(&thread);
(t.and_then(|t| t.items.get(&item_id).cloned()), t.and_then(|t| t.cwd.clone()))
};
let cwd = cwd.as_deref();
let reason = params.get("reason").and_then(Value::as_str).filter(|r| !r.is_empty());
let decline = json!({ "decision": "decline" });
match method {
"item/commandExecution/requestApproval" => {
let choices = translate::decisions(params, true);
let title = translate::command_approval_title(params, item.as_ref());
let mut input = json!({
"command": translate::approval_command(params, item.as_ref()),
"cwd": params.get("cwd"),
});
if let Some(network) = params.get("networkApprovalContext").filter(|c| !c.is_null()) {
input["networkApprovalContext"] = network.clone();
}
let call = tool_call_of(&item_id, &title, "execute", reason, Some(input));
Ok(self.ask(&thread, call, &choices, decline))
}
"item/fileChange/requestApproval" => {
let choices = translate::decisions(params, false);
let title = translate::file_approval_title(item.as_ref(), cwd);
let mut call = tool_call_of(&item_id, &title, "edit", reason, None);
if let Some(content) = item
.as_ref()
.and_then(|i| translate::tool_call(i, false, cwd, None))
.and_then(|c| c.get("content").cloned())
{
call["content"] = content;
}
Ok(self.ask(&thread, call, &choices, decline))
}
"item/permissions/requestApproval" => {
let requested = params.get("permissions").cloned().unwrap_or(json!({}));
let choice = |id: &str, name: &str, kind: &str, answer: Value| Choice {
option: json!({ "optionId": id, "name": name, "kind": kind }),
answer,
};
let choices = [
choice(
"turn",
"Allow for this turn",
"allow_once",
json!({ "permissions": requested, "scope": "turn" }),
),
choice(
"session",
"Allow for this session",
"allow_always",
json!({ "permissions": requested, "scope": "session" }),
),
choice("decline", "Decline", "reject_once", json!({ "permissions": {}, "scope": "turn" })),
];
let title = reason.map_or_else(|| "Allow more access".to_owned(), str::to_owned);
let call = tool_call_of(&item_id, &title, "other", None, Some(requested.clone()));
Ok(self.ask(&thread, call, &choices, json!({ "permissions": {}, "scope": "turn" })))
}
"item/tool/requestUserInput" => {
let questions = params.get("questions").and_then(Value::as_array).cloned().unwrap_or_default();
// One permission request carrying all the questions, so the client shows
// them as a card (as it does for Claude's `AskUserQuestion`).
let asked: Vec<Value> = questions
.iter()
.filter_map(|q| {
let id = q.get("id").and_then(Value::as_str)?;
let question = q.get("question").and_then(Value::as_str)?;
let options: Vec<Value> = q
.get("options")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|o| {
let label = o.get("label").and_then(Value::as_str)?;
Some(json!({
"label": label,
"description": o.get("description").and_then(Value::as_str).unwrap_or_default(),
}))
})
.collect();
Some(json!({
"answerKey": id,
"header": q.get("header").and_then(Value::as_str).unwrap_or_default(),
"question": question,
"multiSelect": q.get("multiSelect").and_then(Value::as_bool).unwrap_or(false),
"options": options,
}))
})
.collect();
if asked.is_empty() {
return Ok(json!({ "answers": {} }));
}
let title = asked[0].get("question").and_then(Value::as_str).unwrap_or("Codex has a question");
let mut call = tool_call_of(&item_id, title, "other", None, None);
call["_meta"] = json!({ "questions": asked });
let options = [json!({ "optionId": "submit", "name": "Submit", "kind": "allow_once" })];
let picked: serde_json::Map<String, Value> = self
.ask_option(&thread, call, &options)
.and_then(|reply| serde_json::from_str(&reply).ok())
.unwrap_or_default();
let mut answers = serde_json::Map::new();
for q in &questions {
let Some(qid) = q.get("id").and_then(Value::as_str) else { continue };
if let Some(labels) = picked
.get(qid)
.filter(|labels| labels.as_array().is_some_and(|labels| labels.iter().all(Value::is_string)))
{
answers.insert(qid.to_owned(), json!({ "answers": labels }));
}
}
Ok(json!({ "answers": answers }))
}
"mcpServer/elicitation/request" => {
let server = params.get("serverName").and_then(Value::as_str).unwrap_or("An MCP server");
let message = params.get("message").and_then(Value::as_str).unwrap_or_default();
let accept = match params.get("mode").and_then(Value::as_str) {
Some("url") => json!({ "action": "accept" }),
_ => json!({ "action": "accept", "content": {} }),
};
let choices = [
Choice {
option: json!({ "optionId": "accept", "name": "Accept", "kind": "allow_once" }),
answer: accept,
},
Choice {
option: json!({ "optionId": "decline", "name": "Decline", "kind": "reject_once" }),
answer: json!({ "action": "decline" }),
},
];
let mut title = format!("{server}: {message}");
if let Some(url) = params.get("url").and_then(Value::as_str) {
title.push_str(&format!(" ({url})"));
}
let call = tool_call_of(&format!("elicitation:{server}"), &title, "other", None, None);
Ok(self.ask(&thread, call, &choices, json!({ "action": "decline" })))
}
_ => Err((codes::METHOD_NOT_FOUND, format!("unsupported request {method}"))),
}
}
/// Asks the client; returns the selected option id (`None` when cancelled).
fn ask_option(&self, session: &str, tool_call: Value, options: &[Value]) -> Option<String> {
let client = self.client.get().cloned()?;
let params = json!({ "sessionId": session, "toolCall": tool_call, "options": options });
let outcome: Result<Value, RpcError> =
self.runtime.block_on(client.request("session/request_permission", params, None));
match outcome {
Ok(outcome) => outcome
.pointer("/outcome/outcome")
.and_then(Value::as_str)
.filter(|outcome| *outcome == "selected")
.and_then(|_| outcome.pointer("/outcome/optionId").and_then(Value::as_str).map(str::to_owned)),
Err(e) => {
tracing::debug!("codex: question request failed: {e}");
None
}
}
}
/// Asks the client; returns the answer for codex (`otherwise` when cancelled).
fn ask(&self, session: &str, tool_call: Value, choices: &[Choice], otherwise: Value) -> Value {
let Some(client) = self.client.get().cloned() else { return otherwise };
let options: Vec<Value> = choices.iter().map(|c| c.option.clone()).collect();
let params = json!({ "sessionId": session, "toolCall": tool_call, "options": options });
let outcome: Result<Value, RpcError> =
self.runtime.block_on(client.request("session/request_permission", params, None));
match outcome {
Ok(outcome) => translate::answer_of(choices, &outcome, otherwise),
Err(e) => {
tracing::debug!("codex: permission request failed: {e}");
otherwise
}
}
}
}
impl Thread {
/// A text chunk of `item`; a new item of the same kind right after another starts a
/// new paragraph.
fn chunk(&mut self, kind: &'static str, item: &str, text: &str) -> Value {
let text = match &self.last_chunk {
Some((k, i)) if *k == kind && i != item => format!("\n\n{text}"),
_ => text.to_owned(),
};
self.last_chunk = Some((kind, item.to_owned()));
translate::chunk(kind, &text)
}
}
/// The ACP `toolCall` of a permission request.
fn tool_call_of(id: &str, title: &str, kind: &str, reason: Option<&str>, raw: Option<Value>) -> Value {
let mut call = json!({ "toolCallId": id, "title": title, "kind": kind, "status": "pending" });
if let Some(reason) = reason {
call["content"] = json!([{ "type": "content", "content": { "type": "text", "text": reason } }]);
}
if let Some(raw) = raw {
call["rawInput"] = raw;
}
call
}
/// The `session/prompt` answer for a turn that ended.
fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Value>) -> Result<Value, ResponseError> {
let stop = match turn.get("status").and_then(Value::as_str) {
Some("interrupted") => "cancelled",
Some("failed") => {
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
let message = translate::error_message(&e);
return match translate::classify(&e, rate_limits) {
Failure::UsageLimit(resets) => Err(ResponseError {
code: codes::INTERNAL_ERROR,
message,
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
}),
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
};
}
_ => "end_turn",
};
Ok(json!({ "stopReason": stop }))
}
/// The `review/start` target of a parsed review command.
fn review_target(command: &ParsedCommand) -> Value {
match command.command {
BuiltinCommand::Review if command.rest.is_empty() => json!({ "type": "uncommittedChanges" }),
BuiltinCommand::Review => json!({ "type": "custom", "instructions": command.rest }),
BuiltinCommand::ReviewBranch => json!({ "type": "baseBranch", "branch": command.rest }),
BuiltinCommand::ReviewCommit => json!({ "type": "commit", "sha": command.rest, "title": null }),
_ => unreachable!("only review commands have review targets"),
}
}
fn command_usage(command: BuiltinCommand) -> String {
match command {
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
BuiltinCommand::Rename => "Command \"/rename\" requires new name.".to_owned(),
_ => "This command does not accept arguments.".to_owned(),
}
}
fn status_text(
session: &str,
settings: Option<&Settings>,
cwd: Option<&str>,
token_usage: Option<&Value>,
rate_limits: Option<&Value>,
) -> String {
let mut lines = Vec::new();
if let Some(settings) = settings {
lines.push(format!("**Model:** {}", settings.model));
lines.push(format!("**Collaboration:** {}", settings.collaboration_mode));
lines.push(format!("**Approval:** {}", settings.mode.approval_policy()));
lines.push(format!("**Sandbox:** {}", settings.mode.sandbox_mode()));
}
if let Some(cwd) = cwd {
lines.push(format!("**Directory:** {cwd}"));
}
lines.push(format!("**Session:** `{session}`"));
if let Some(usage) = token_usage {
let total = usage.pointer("/total/totalTokens").and_then(Value::as_u64);
let used = usage.pointer("/last/totalTokens").and_then(Value::as_u64);
let window = usage.get("modelContextWindow").and_then(Value::as_u64).filter(|window| *window > 0);
if let (Some(total), Some(used), Some(window)) = (total, used, window) {
let percent = (used.saturating_mul(100) + window / 2) / window;
lines.push(format!("**Token usage:** {total} total"));
lines.push(format!("**Context window:** {used} / {window} ({percent}%)"));
}
}
if let Some(primary) = rate_limits.and_then(|r| r.get("primary"))
&& let Some(used) = primary.get("usedPercent").and_then(Value::as_f64)
{
lines.push(format!("**Rate limit:** {used:.0}% used"));
}
lines.join(" \n")
}
fn skills_text(response: &Value) -> String {
let mut seen = HashSet::new();
let names: Vec<String> = response
.get("data")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|entry| entry.get("skills").and_then(Value::as_array))
.flatten()
.filter(|skill| skill.get("enabled") != Some(&Value::Bool(false)))
.filter_map(|skill| {
let name = skill.get("name").and_then(Value::as_str)?.trim();
if name.is_empty() || !seen.insert(name.to_owned()) {
return None;
}
let description = skill
.pointer("/interface/shortDescription")
.or_else(|| skill.get("shortDescription"))
.or_else(|| skill.get("description"))
.and_then(Value::as_str)
.unwrap_or_default();
Some(if description.is_empty() { name.to_owned() } else { format!("{name}: {description}") })
})
.collect();
if names.is_empty() {
"No skills configured.".to_owned()
} else {
format!("Available skills:\n{}", names.iter().map(|name| format!("- {name}")).collect::<Vec<_>>().join("\n"))
}
}
fn mcp_text(response: &Value) -> String {
let servers = response.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
if servers.is_empty() {
return "No MCP servers configured.".to_owned();
}
let lines = servers
.iter()
.filter_map(|server| {
let name = server.get("name").and_then(Value::as_str)?;
let status = server
.get("runtimeStatus")
.and_then(Value::as_str)
.or_else(|| server.get("authStatus").and_then(Value::as_str))
.unwrap_or("unknown");
let tools = server.get("tools").and_then(Value::as_object).map_or(0, serde_json::Map::len);
Some(format!("- {name}: {status}, {tools} tools"))
})
.collect::<Vec<_>>();
format!("MCP servers:\n{}", lines.join("\n"))
}
#[cfg(test)]
mod reconnect_tests;