Base: codex-main originale (prima del fork aKode)
This commit is contained in:
347
codex-rs/exec/src/cli.rs
Normal file
347
codex-rs/exec/src/cli.rs
Normal file
@@ -0,0 +1,347 @@
|
||||
use clap::Args;
|
||||
use clap::FromArgMatches;
|
||||
use clap::Parser;
|
||||
use clap::ValueEnum;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_utils_cli::SharedCliOptions;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
version,
|
||||
override_usage = "codex exec [OPTIONS] [PROMPT]\n codex exec [OPTIONS] <COMMAND> [ARGS]"
|
||||
)]
|
||||
pub struct Cli {
|
||||
/// Action to perform. If omitted, runs a new non-interactive session.
|
||||
#[command(subcommand)]
|
||||
pub command: Option<Command>,
|
||||
|
||||
/// Error out when config.toml contains fields that are not recognized by this version of Codex.
|
||||
#[arg(long = "strict-config", global = true, default_value_t = false)]
|
||||
pub strict_config: bool,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub shared: ExecSharedCliOptions,
|
||||
|
||||
/// Source classification for newly created or forked threads.
|
||||
#[arg(long = "thread-source", value_name = "SOURCE", global = true)]
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
|
||||
/// Request an experimental Cyber access program for this turn (OpenAI provider only).
|
||||
/// Omit to use server defaults. Not supported with review; fork requires a prompt.
|
||||
#[arg(long, value_enum, value_name = "PROGRAM", global = true)]
|
||||
pub cyber_access_program: Option<CyberAccessProgramCliArg>,
|
||||
|
||||
/// Allow running Codex outside a Git repository.
|
||||
#[arg(long = "skip-git-repo-check", global = true, default_value_t = false)]
|
||||
pub skip_git_repo_check: bool,
|
||||
|
||||
/// Save trust for this project and future chats, including MCP commands outside the sandbox.
|
||||
/// Persists even with --ephemeral. Does not override an explicitly untrusted project.
|
||||
#[arg(long, global = true)]
|
||||
pub trust: bool,
|
||||
|
||||
/// Run without persisting session files to disk.
|
||||
#[arg(long = "ephemeral", global = true, default_value_t = false)]
|
||||
pub ephemeral: bool,
|
||||
|
||||
/// Do not load `$CODEX_HOME/config.toml`; auth still uses `CODEX_HOME`.
|
||||
#[arg(long = "ignore-user-config", global = true, default_value_t = false)]
|
||||
pub ignore_user_config: bool,
|
||||
|
||||
/// Do not load user or project execpolicy `.rules` files.
|
||||
#[arg(long = "ignore-rules", global = true, default_value_t = false)]
|
||||
pub ignore_rules: bool,
|
||||
|
||||
/// Path to a JSON Schema file describing the model's final response shape.
|
||||
#[arg(long = "output-schema", value_name = "FILE", global = true)]
|
||||
pub output_schema: Option<PathBuf>,
|
||||
|
||||
#[clap(skip)]
|
||||
pub config_overrides: CliConfigOverrides,
|
||||
|
||||
/// Specifies color settings for use in the output.
|
||||
#[arg(long = "color", value_enum, default_value_t = Color::Auto)]
|
||||
pub color: Color,
|
||||
|
||||
/// Print events to stdout as JSONL.
|
||||
#[arg(
|
||||
long = "json",
|
||||
alias = "experimental-json",
|
||||
default_value_t = false,
|
||||
global = true
|
||||
)]
|
||||
pub json: bool,
|
||||
|
||||
/// Specifies file where the last message from the agent should be written.
|
||||
#[arg(
|
||||
long = "output-last-message",
|
||||
short = 'o',
|
||||
value_name = "FILE",
|
||||
global = true
|
||||
)]
|
||||
pub last_message_file: Option<PathBuf>,
|
||||
|
||||
/// Initial instructions for the agent. If not provided as an argument (or
|
||||
/// if `-` is used), instructions are read from stdin. If stdin is piped and
|
||||
/// a prompt is also provided, stdin is appended as a `<stdin>` block.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
#[value(rename_all = "snake_case")]
|
||||
pub enum CyberAccessProgramCliArg {
|
||||
Standard,
|
||||
DaybreakBlue,
|
||||
DaybreakRed,
|
||||
}
|
||||
|
||||
impl From<CyberAccessProgramCliArg> for codex_app_server_protocol::CyberAccessProgram {
|
||||
fn from(value: CyberAccessProgramCliArg) -> Self {
|
||||
match value {
|
||||
CyberAccessProgramCliArg::Standard => Self::Standard,
|
||||
CyberAccessProgramCliArg::DaybreakBlue => Self::DaybreakBlue,
|
||||
CyberAccessProgramCliArg::DaybreakRed => Self::DaybreakRed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for Cli {
|
||||
type Target = SharedCliOptions;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.shared.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for Cli {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.shared.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ExecSharedCliOptions(SharedCliOptions);
|
||||
|
||||
impl ExecSharedCliOptions {
|
||||
pub fn into_inner(self) -> SharedCliOptions {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for ExecSharedCliOptions {
|
||||
type Target = SharedCliOptions;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::DerefMut for ExecSharedCliOptions {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Args for ExecSharedCliOptions {
|
||||
fn augment_args(cmd: clap::Command) -> clap::Command {
|
||||
mark_exec_global_args(SharedCliOptions::augment_args(cmd))
|
||||
}
|
||||
|
||||
fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
|
||||
mark_exec_global_args(SharedCliOptions::augment_args_for_update(cmd))
|
||||
}
|
||||
}
|
||||
|
||||
impl FromArgMatches for ExecSharedCliOptions {
|
||||
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
|
||||
SharedCliOptions::from_arg_matches(matches).map(Self)
|
||||
}
|
||||
|
||||
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
|
||||
self.0.update_from_arg_matches(matches)
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_exec_global_args(cmd: clap::Command) -> clap::Command {
|
||||
cmd.mut_arg("model", |arg| arg.global(true))
|
||||
.mut_arg("dangerously_bypass_approvals_and_sandbox", |arg| {
|
||||
arg.global(true)
|
||||
})
|
||||
.mut_arg("bypass_hook_trust", |arg| arg.global(true))
|
||||
.mut_arg("worktree", |arg| arg.global(true))
|
||||
}
|
||||
|
||||
#[derive(Debug, clap::Subcommand)]
|
||||
pub enum Command {
|
||||
/// Resume a previous session by id or pick the most recent with --last.
|
||||
Resume(ResumeArgs),
|
||||
|
||||
/// Fork a previous session by id into a new session.
|
||||
Fork(ForkArgs),
|
||||
|
||||
/// Run a code review against the current repository.
|
||||
Review(ReviewArgs),
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct ForkArgs {
|
||||
/// Conversation/session id (UUID) or thread name to fork.
|
||||
#[arg(value_name = "SESSION_ID")]
|
||||
pub session_id: String,
|
||||
|
||||
/// Optional image(s) to attach to the prompt sent after forking.
|
||||
#[arg(
|
||||
long = "image",
|
||||
short = 'i',
|
||||
value_name = "FILE",
|
||||
value_delimiter = ',',
|
||||
num_args = 1
|
||||
)]
|
||||
pub images: Vec<PathBuf>,
|
||||
|
||||
/// Optional prompt to send after forking. If `-` is used, read from stdin.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
struct ResumeArgsRaw {
|
||||
// Note: This is the direct clap shape. We reinterpret the positional when --last is set
|
||||
// so "codex resume --last <prompt>" treats the positional as a prompt, not a session id.
|
||||
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
|
||||
/// If omitted, use --last to pick the most recent recorded session.
|
||||
#[arg(value_name = "SESSION_ID")]
|
||||
session_id: Option<String>,
|
||||
|
||||
/// Resume the most recent recorded session (newest) without specifying an id.
|
||||
#[arg(long = "last", default_value_t = false)]
|
||||
last: bool,
|
||||
|
||||
/// Show all sessions (disables cwd filtering).
|
||||
#[arg(long = "all", default_value_t = false)]
|
||||
all: bool,
|
||||
|
||||
/// Optional image(s) to attach to the prompt sent after resuming.
|
||||
#[arg(
|
||||
long = "image",
|
||||
short = 'i',
|
||||
value_name = "FILE",
|
||||
value_delimiter = ',',
|
||||
num_args = 1
|
||||
)]
|
||||
images: Vec<PathBuf>,
|
||||
|
||||
/// Prompt to send after resuming the session. If `-` is used, read from stdin.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
prompt: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResumeArgs {
|
||||
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
|
||||
/// If omitted, use --last to pick the most recent recorded session.
|
||||
pub session_id: Option<String>,
|
||||
|
||||
/// Resume the most recent recorded session (newest) without specifying an id.
|
||||
pub last: bool,
|
||||
|
||||
/// Show all sessions (disables cwd filtering).
|
||||
pub all: bool,
|
||||
|
||||
/// Optional image(s) to attach to the prompt sent after resuming.
|
||||
pub images: Vec<PathBuf>,
|
||||
|
||||
/// Prompt to send after resuming the session. If `-` is used, read from stdin.
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ResumeArgsRaw> for ResumeArgs {
|
||||
fn from(raw: ResumeArgsRaw) -> Self {
|
||||
// When --last is used without an explicit prompt, treat the positional as the prompt
|
||||
// (clap can’t express this conditional positional meaning cleanly).
|
||||
let (session_id, prompt) = if raw.last && raw.prompt.is_none() {
|
||||
(None, raw.session_id)
|
||||
} else {
|
||||
(raw.session_id, raw.prompt)
|
||||
};
|
||||
Self {
|
||||
session_id,
|
||||
last: raw.last,
|
||||
all: raw.all,
|
||||
images: raw.images,
|
||||
prompt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Args for ResumeArgs {
|
||||
fn augment_args(cmd: clap::Command) -> clap::Command {
|
||||
ResumeArgsRaw::augment_args(cmd)
|
||||
}
|
||||
|
||||
fn augment_args_for_update(cmd: clap::Command) -> clap::Command {
|
||||
ResumeArgsRaw::augment_args_for_update(cmd)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromArgMatches for ResumeArgs {
|
||||
fn from_arg_matches(matches: &clap::ArgMatches) -> Result<Self, clap::Error> {
|
||||
ResumeArgsRaw::from_arg_matches(matches).map(Self::from)
|
||||
}
|
||||
|
||||
fn update_from_arg_matches(&mut self, matches: &clap::ArgMatches) -> Result<(), clap::Error> {
|
||||
*self = ResumeArgsRaw::from_arg_matches(matches).map(Self::from)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct ReviewArgs {
|
||||
/// Review staged, unstaged, and untracked changes.
|
||||
#[arg(
|
||||
long = "uncommitted",
|
||||
default_value_t = false,
|
||||
conflicts_with_all = ["base", "commit", "prompt"]
|
||||
)]
|
||||
pub uncommitted: bool,
|
||||
|
||||
/// Review changes against the given base branch.
|
||||
#[arg(
|
||||
long = "base",
|
||||
value_name = "BRANCH",
|
||||
conflicts_with_all = ["uncommitted", "commit", "prompt"]
|
||||
)]
|
||||
pub base: Option<String>,
|
||||
|
||||
/// Review the changes introduced by a commit.
|
||||
#[arg(
|
||||
long = "commit",
|
||||
value_name = "SHA",
|
||||
conflicts_with_all = ["uncommitted", "base", "prompt"]
|
||||
)]
|
||||
pub commit: Option<String>,
|
||||
|
||||
/// Optional commit title to display in the review summary.
|
||||
#[arg(long = "title", value_name = "TITLE", requires = "commit")]
|
||||
pub commit_title: Option<String>,
|
||||
|
||||
/// Custom review instructions. If `-` is used, read from stdin.
|
||||
#[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
|
||||
pub prompt: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
|
||||
#[value(rename_all = "kebab-case")]
|
||||
pub enum Color {
|
||||
Always,
|
||||
Never,
|
||||
#[default]
|
||||
Auto,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cli_tests.rs"]
|
||||
mod tests;
|
||||
153
codex-rs/exec/src/cli_tests.rs
Normal file
153
codex-rs/exec/src/cli_tests.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn resume_parses_prompt_after_global_flags() {
|
||||
const PROMPT: &str = "echo resume-with-global-flags-after-subcommand";
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"resume",
|
||||
"--last",
|
||||
"--json",
|
||||
"--model",
|
||||
"gpt-5.2-codex",
|
||||
"--cyber-access-program",
|
||||
"daybreak_blue",
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"--skip-git-repo-check",
|
||||
"--ephemeral",
|
||||
"--ignore-user-config",
|
||||
"--ignore-rules",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
assert!(cli.ephemeral);
|
||||
assert!(cli.ignore_user_config);
|
||||
assert!(cli.ignore_rules);
|
||||
assert_eq!(
|
||||
cli.cyber_access_program,
|
||||
Some(CyberAccessProgramCliArg::DaybreakBlue)
|
||||
);
|
||||
let Some(Command::Resume(args)) = cli.command else {
|
||||
panic!("expected resume command");
|
||||
};
|
||||
let effective_prompt = args.prompt.clone().or_else(|| {
|
||||
if args.last {
|
||||
args.session_id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
assert_eq!(effective_prompt.as_deref(), Some(PROMPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_accepts_output_flags_after_subcommand() {
|
||||
const PROMPT: &str = "echo resume-with-output-file";
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"resume",
|
||||
"session-123",
|
||||
"-o",
|
||||
"/tmp/resume-output.md",
|
||||
"--output-schema",
|
||||
"/tmp/schema.json",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
cli.last_message_file,
|
||||
Some(PathBuf::from("/tmp/resume-output.md"))
|
||||
);
|
||||
assert_eq!(cli.output_schema, Some(PathBuf::from("/tmp/schema.json")));
|
||||
let Some(Command::Resume(args)) = cli.command else {
|
||||
panic!("expected resume command");
|
||||
};
|
||||
assert_eq!(args.session_id.as_deref(), Some("session-123"));
|
||||
assert_eq!(args.prompt.as_deref(), Some(PROMPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fork_parses_prompt_after_global_flags() {
|
||||
const PROMPT: &str = "continue on the fork";
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"fork",
|
||||
"session-123",
|
||||
"--json",
|
||||
"--model",
|
||||
"gpt-5.2-codex",
|
||||
"--thread-source",
|
||||
"automated_review",
|
||||
"--skip-git-repo-check",
|
||||
"--ephemeral",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
assert!(cli.json);
|
||||
assert!(cli.ephemeral);
|
||||
assert_eq!(
|
||||
cli.thread_source,
|
||||
Some(ThreadSource::Feature("automated_review".to_string()))
|
||||
);
|
||||
let Some(Command::Fork(args)) = cli.command else {
|
||||
panic!("expected fork command");
|
||||
};
|
||||
assert_eq!(args.session_id, "session-123");
|
||||
assert_eq!(args.prompt.as_deref(), Some(PROMPT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_config_isolation_flags() {
|
||||
let cli = Cli::parse_from([
|
||||
"codex-exec",
|
||||
"--ignore-user-config",
|
||||
"--ignore-rules",
|
||||
"summarize",
|
||||
]);
|
||||
|
||||
assert!(cli.ignore_user_config);
|
||||
assert!(cli.ignore_rules);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approve_for_me_flag_applies_to_resume_when_passed_at_exec_root() {
|
||||
for flag in ["--approve-for-me", "--not-so-yolo"] {
|
||||
let cli = Cli::parse_from(["codex-exec", flag, "resume", "--last"]);
|
||||
|
||||
assert!(cli.auto_review);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approve_for_me_flag_conflicts_with_other_sandbox_modes() {
|
||||
for conflicting_args in [
|
||||
vec!["--sandbox", "read-only"],
|
||||
vec!["--dangerously-bypass-approvals-and-sandbox"],
|
||||
] {
|
||||
let mut args = vec!["codex-exec", "--approve-for-me"];
|
||||
args.extend(conflicting_args);
|
||||
args.push("summarize");
|
||||
|
||||
let error = Cli::try_parse_from(args).expect_err("flags should conflict");
|
||||
assert_eq!(error.kind(), clap::error::ErrorKind::ArgumentConflict);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_flag_is_accepted_after_fork_subcommand() {
|
||||
let cli = Cli::try_parse_from(["codex-exec", "fork", "session-id", "--worktree"])
|
||||
.expect("worktree should be a global exec argument");
|
||||
|
||||
assert!(cli.worktree);
|
||||
assert!(matches!(cli.command, Some(Command::Fork(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_flag_is_accepted_before_fork_subcommand() {
|
||||
let cli = Cli::try_parse_from(["codex-exec", "--worktree", "fork", "session-id"])
|
||||
.expect("worktree should be accepted before the fork subcommand");
|
||||
|
||||
assert!(cli.worktree);
|
||||
assert!(matches!(cli.command, Some(Command::Fork(_))));
|
||||
}
|
||||
112
codex-rs/exec/src/daybreak.rs
Normal file
112
codex-rs/exec/src/daybreak.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
//! Resolve the cyber treatment for an exec turn from the connected server's catalog.
|
||||
|
||||
use crate::RequestIdSequencer;
|
||||
use codex_app_server_client::InProcessAppServerClient;
|
||||
use codex_app_server_protocol::Account;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::CyberAccessProgram;
|
||||
use codex_app_server_protocol::GetAccountParams;
|
||||
use codex_app_server_protocol::GetAccountResponse;
|
||||
use codex_app_server_protocol::ModelListParams;
|
||||
use codex_app_server_protocol::ModelListResponse;
|
||||
use codex_features::Feature;
|
||||
use codex_features::Features;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::openai_models::ModelAccessPrograms;
|
||||
|
||||
pub(crate) async fn program_for_turn(
|
||||
features: &Features,
|
||||
client: &InProcessAppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
model: &str,
|
||||
provider_id: &str,
|
||||
provider: Option<&ModelProviderInfo>,
|
||||
enabled: bool,
|
||||
) -> anyhow::Result<Option<CyberAccessProgram>> {
|
||||
if !provider.is_some_and(|provider| provider.supports_cyber_access_programs(provider_id)) {
|
||||
anyhow::ensure!(
|
||||
!enabled,
|
||||
"Daybreak requires a model provider with Cyber access program support"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
if enabled {
|
||||
anyhow::ensure!(
|
||||
matches!(
|
||||
read_account(client, request_ids).await?,
|
||||
Some(Account::Chatgpt { .. } | Account::ApiKey { .. })
|
||||
),
|
||||
"Daybreak requires a signed-in ChatGPT account or an OpenAI API key"
|
||||
);
|
||||
}
|
||||
|
||||
let mut cursor = None;
|
||||
loop {
|
||||
let result = client
|
||||
.request_typed::<ModelListResponse>(ClientRequest::ModelList {
|
||||
request_id: request_ids.next(),
|
||||
params: ModelListParams {
|
||||
cursor,
|
||||
limit: None,
|
||||
include_hidden: Some(true),
|
||||
model_provider: None,
|
||||
},
|
||||
})
|
||||
.await;
|
||||
let Ok(result) = result else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(selected) = result.data.into_iter().find(|entry| entry.model == model) {
|
||||
let programs = selected
|
||||
.available_access_programs
|
||||
.map(ModelAccessPrograms::from)
|
||||
.filter(|programs| !programs.cyber.is_empty());
|
||||
let Some(programs) = programs else {
|
||||
return Ok(None);
|
||||
};
|
||||
if enabled {
|
||||
return programs
|
||||
.daybreak()
|
||||
.map(|program| Some(program.into()))
|
||||
.ok_or_else(|| anyhow::anyhow!("Daybreak is unavailable for model {model}; turn it off or choose a compatible model"));
|
||||
}
|
||||
let Some(standard) = programs.standard() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let eligible = match read_account(client, request_ids).await.unwrap_or(None) {
|
||||
Some(Account::Chatgpt { .. }) => true,
|
||||
Some(Account::ApiKey { .. }) => {
|
||||
features.enabled(Feature::ApiKeyCyberAccessPrograms)
|
||||
}
|
||||
Some(Account::AmazonBedrock { .. } | Account::Gcp {}) | None => false,
|
||||
};
|
||||
return Ok(eligible.then_some(standard.into()));
|
||||
}
|
||||
match result.next_cursor {
|
||||
Some(next) => cursor = Some(next),
|
||||
None => {
|
||||
// Preserve automatic treatment for explicit model IDs absent from the catalog.
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_account(
|
||||
client: &InProcessAppServerClient,
|
||||
request_ids: &mut RequestIdSequencer,
|
||||
) -> anyhow::Result<Option<Account>> {
|
||||
let account = client
|
||||
.request_typed::<GetAccountResponse>(ClientRequest::GetAccount {
|
||||
request_id: request_ids.next(),
|
||||
params: GetAccountParams {
|
||||
refresh_token: false,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map_err(|error| {
|
||||
anyhow::anyhow!("Daybreak account availability could not be determined: {error}")
|
||||
})?;
|
||||
Ok(account.account)
|
||||
}
|
||||
47
codex-rs/exec/src/event_processor.rs
Normal file
47
codex-rs/exec/src/event_processor.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use anyhow::Context;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::BoundOutput;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexStatus {
|
||||
Running,
|
||||
InitiateShutdown,
|
||||
}
|
||||
|
||||
pub(crate) trait EventProcessor {
|
||||
/// Print summary of effective configuration and user prompt.
|
||||
fn print_config_summary(
|
||||
&mut self,
|
||||
config: &Config,
|
||||
prompt: &str,
|
||||
session_configured: &SessionConfiguredEvent,
|
||||
);
|
||||
|
||||
/// Handle a single typed app-server notification emitted by the agent.
|
||||
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus;
|
||||
|
||||
/// Handle a local exec warning that is not represented as an app-server notification.
|
||||
fn process_warning(&mut self, message: String) -> CodexStatus;
|
||||
|
||||
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
pub(crate) fn handle_last_message(
|
||||
last_agent_message: Option<&str>,
|
||||
path: &Path,
|
||||
file: BoundOutput,
|
||||
) -> anyhow::Result<()> {
|
||||
file.write(last_agent_message.unwrap_or_default().as_bytes())
|
||||
.with_context(|| format!("Failed to write last message file {path:?}"))?;
|
||||
if last_agent_message.is_none() {
|
||||
eprintln!(
|
||||
"Warning: no last agent message; wrote empty content to {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
550
codex-rs/exec/src/event_processor_with_human_output.rs
Normal file
550
codex-rs/exec/src/event_processor_with_human_output.rs
Normal file
@@ -0,0 +1,550 @@
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use codex_app_server_protocol::CommandExecutionStatus;
|
||||
use codex_app_server_protocol::McpToolCallStatus;
|
||||
use codex_app_server_protocol::PatchApplyStatus;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::ThreadTokenUsage;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::BoundOutput;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_protocol::num_format::format_with_separators;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_sandbox_summary::summarize_permission_profile;
|
||||
use owo_colors::OwoColorize;
|
||||
use owo_colors::Style;
|
||||
|
||||
use crate::event_processor::CodexStatus;
|
||||
use crate::event_processor::EventProcessor;
|
||||
use crate::event_processor::handle_last_message;
|
||||
|
||||
pub(crate) struct EventProcessorWithHumanOutput {
|
||||
bold: Style,
|
||||
cyan: Style,
|
||||
dimmed: Style,
|
||||
green: Style,
|
||||
italic: Style,
|
||||
magenta: Style,
|
||||
red: Style,
|
||||
yellow: Style,
|
||||
show_agent_reasoning: bool,
|
||||
show_raw_agent_reasoning: bool,
|
||||
last_message_path: Option<PathBuf>,
|
||||
final_message: Option<String>,
|
||||
final_message_rendered: bool,
|
||||
emit_final_message_on_shutdown: bool,
|
||||
last_total_token_usage: Option<ThreadTokenUsage>,
|
||||
last_turn_diff: String,
|
||||
}
|
||||
|
||||
impl EventProcessorWithHumanOutput {
|
||||
pub(crate) fn create_with_ansi(
|
||||
with_ansi: bool,
|
||||
config: &Config,
|
||||
last_message_path: Option<PathBuf>,
|
||||
) -> Self {
|
||||
let style = |styled: Style, plain: Style| if with_ansi { styled } else { plain };
|
||||
Self {
|
||||
bold: style(Style::new().bold(), Style::new()),
|
||||
cyan: style(Style::new().cyan(), Style::new()),
|
||||
dimmed: style(Style::new().dimmed(), Style::new()),
|
||||
green: style(Style::new().green(), Style::new()),
|
||||
italic: style(Style::new().italic(), Style::new()),
|
||||
magenta: style(Style::new().magenta(), Style::new()),
|
||||
red: style(Style::new().red(), Style::new()),
|
||||
yellow: style(Style::new().yellow(), Style::new()),
|
||||
show_agent_reasoning: !config.hide_agent_reasoning,
|
||||
show_raw_agent_reasoning: config.show_raw_agent_reasoning,
|
||||
last_message_path,
|
||||
final_message: None,
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_item_started(&self, item: &ThreadItemPayload) {
|
||||
match item {
|
||||
ThreadItemPayload::CommandExecution { command, cwd, .. } => {
|
||||
eprintln!(
|
||||
"{}\n{} in {cwd}",
|
||||
"exec".style(self.italic).style(self.magenta),
|
||||
command.style(self.bold),
|
||||
);
|
||||
}
|
||||
ThreadItemPayload::McpToolCall { server, tool, .. } => {
|
||||
eprintln!(
|
||||
"{} {} {}",
|
||||
"mcp:".style(self.bold),
|
||||
format!("{server}/{tool}").style(self.cyan),
|
||||
"started".style(self.dimmed)
|
||||
);
|
||||
}
|
||||
ThreadItemPayload::WebSearch(item) => {
|
||||
eprintln!("{} {}", "web search:".style(self.bold), item.query);
|
||||
}
|
||||
ThreadItemPayload::FileChange { .. } => {
|
||||
eprintln!("{}", "apply patch".style(self.bold));
|
||||
}
|
||||
ThreadItemPayload::CollabAgentToolCall { tool, .. } => {
|
||||
eprintln!("{} {:?}", "collab:".style(self.bold), tool);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_item_completed(&mut self, item: ThreadItemPayload) {
|
||||
match item {
|
||||
ThreadItemPayload::AgentMessage { text, .. } => {
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"codex".style(self.italic).style(self.magenta),
|
||||
text
|
||||
);
|
||||
self.final_message = Some(text);
|
||||
self.final_message_rendered = true;
|
||||
}
|
||||
ThreadItemPayload::Reasoning {
|
||||
summary, content, ..
|
||||
} => {
|
||||
if self.show_agent_reasoning
|
||||
&& let Some(text) =
|
||||
reasoning_text(&summary, &content, self.show_raw_agent_reasoning)
|
||||
&& !text.trim().is_empty()
|
||||
{
|
||||
eprintln!("{}", text.style(self.dimmed));
|
||||
}
|
||||
}
|
||||
ThreadItemPayload::CommandExecution {
|
||||
command: _,
|
||||
aggregated_output,
|
||||
exit_code,
|
||||
status,
|
||||
duration_ms,
|
||||
..
|
||||
} => {
|
||||
let duration_suffix = duration_ms
|
||||
.map(|duration_ms| format!(" in {duration_ms}ms"))
|
||||
.unwrap_or_default();
|
||||
match status {
|
||||
CommandExecutionStatus::Completed => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" succeeded{duration_suffix}:").style(self.green)
|
||||
);
|
||||
}
|
||||
CommandExecutionStatus::Failed => {
|
||||
let exit_code = exit_code.unwrap_or(1);
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" exited {exit_code}{duration_suffix}:").style(self.red)
|
||||
);
|
||||
}
|
||||
CommandExecutionStatus::Declined => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" declined{duration_suffix}:").style(self.yellow)
|
||||
);
|
||||
}
|
||||
CommandExecutionStatus::InProgress => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
format!(" in progress{duration_suffix}:").style(self.dimmed)
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(output) = aggregated_output
|
||||
&& !output.trim().is_empty()
|
||||
{
|
||||
eprintln!("{output}");
|
||||
}
|
||||
}
|
||||
ThreadItemPayload::FileChange {
|
||||
changes, status, ..
|
||||
} => {
|
||||
let status_text = match status {
|
||||
PatchApplyStatus::Completed => "completed",
|
||||
PatchApplyStatus::Failed => "failed",
|
||||
PatchApplyStatus::Declined => "declined",
|
||||
PatchApplyStatus::InProgress => "in_progress",
|
||||
};
|
||||
eprintln!("{} {}", "patch:".style(self.bold), status_text);
|
||||
for change in changes {
|
||||
eprintln!("{}", change.path.style(self.dimmed));
|
||||
}
|
||||
}
|
||||
ThreadItemPayload::McpToolCall {
|
||||
server,
|
||||
tool,
|
||||
status,
|
||||
error,
|
||||
..
|
||||
} => {
|
||||
let status_text = match status {
|
||||
McpToolCallStatus::Completed => "completed".style(self.green),
|
||||
McpToolCallStatus::Failed => "failed".style(self.red),
|
||||
McpToolCallStatus::InProgress => "in_progress".style(self.dimmed),
|
||||
};
|
||||
eprintln!(
|
||||
"{} {} {}",
|
||||
"mcp:".style(self.bold),
|
||||
format!("{server}/{tool}").style(self.cyan),
|
||||
format!("({status_text})").style(self.dimmed)
|
||||
);
|
||||
if let Some(error) = error {
|
||||
eprintln!("{}", error.message.style(self.red));
|
||||
}
|
||||
}
|
||||
ThreadItemPayload::WebSearch(item) => {
|
||||
eprintln!("{} {}", "web search:".style(self.bold), item.query);
|
||||
}
|
||||
ThreadItemPayload::ContextCompaction { .. } => {
|
||||
eprintln!("{}", "context compacted".style(self.dimmed));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EventProcessor for EventProcessorWithHumanOutput {
|
||||
fn print_config_summary(
|
||||
&mut self,
|
||||
config: &Config,
|
||||
prompt: &str,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
) {
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
eprintln!("OpenAI Codex v{VERSION}\n--------");
|
||||
for (key, value) in config_summary_entries(config, session_configured_event) {
|
||||
eprintln!("{} {}", format!("{key}:").style(self.bold), value);
|
||||
}
|
||||
eprintln!("--------");
|
||||
eprintln!("{}\n{}", "user".style(self.cyan), prompt);
|
||||
}
|
||||
|
||||
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
|
||||
match notification {
|
||||
ServerNotification::ConfigWarning(notification) => {
|
||||
let details = notification
|
||||
.details
|
||||
.map(|details| format!(" ({details})"))
|
||||
.unwrap_or_default();
|
||||
eprintln!(
|
||||
"{} {}{}",
|
||||
"warning:".style(self.yellow).style(self.bold),
|
||||
notification.summary,
|
||||
details
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::Warning(notification) => self.process_warning(notification.message),
|
||||
ServerNotification::AuthRecoveryStarted(notification) => {
|
||||
eprintln!("{}", notification.message);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::AuthRecoveryCompleted(notification) => {
|
||||
eprintln!("{}", notification.message.style(self.green));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::Error(notification) => {
|
||||
eprintln!(
|
||||
"{} {}",
|
||||
"ERROR:".style(self.red).style(self.bold),
|
||||
notification.error
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::DeprecationNotice(notification) => {
|
||||
eprintln!(
|
||||
"{} {}",
|
||||
"deprecated:".style(self.yellow).style(self.bold),
|
||||
notification.summary
|
||||
);
|
||||
if let Some(details) = notification.details {
|
||||
eprintln!("{}", details.style(self.dimmed));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::HookStarted(notification) => {
|
||||
eprintln!(
|
||||
"{} {}",
|
||||
"hook:".style(self.bold),
|
||||
format!("{:?}", notification.run.event_name).style(self.dimmed)
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::HookCompleted(notification) => {
|
||||
eprintln!(
|
||||
"{} {} {:?}",
|
||||
"hook:".style(self.bold),
|
||||
format!("{:?}", notification.run.event_name).style(self.dimmed),
|
||||
notification.run.status
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemStarted(notification) => {
|
||||
self.render_item_started(¬ification.item.payload);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => {
|
||||
self.render_item_completed(notification.item.payload);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelRerouted(notification) => {
|
||||
eprintln!(
|
||||
"{} {} -> {}",
|
||||
"model rerouted:".style(self.yellow).style(self.bold),
|
||||
notification.from_model,
|
||||
notification.to_model
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelVerification(_) => CodexStatus::Running,
|
||||
ServerNotification::ThreadTokenUsageUpdated(notification) => {
|
||||
self.last_total_token_usage = Some(notification.token_usage);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnCompleted(notification) => match notification.turn.status {
|
||||
TurnStatus::Completed => {
|
||||
let rendered_message = self
|
||||
.final_message_rendered
|
||||
.then(|| self.final_message.clone())
|
||||
.flatten();
|
||||
if let Some(final_message) =
|
||||
final_message_from_turn_items(notification.turn.items.as_slice())
|
||||
{
|
||||
self.final_message_rendered =
|
||||
rendered_message.as_deref() == Some(final_message.as_str());
|
||||
self.final_message = Some(final_message);
|
||||
}
|
||||
self.emit_final_message_on_shutdown = true;
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Failed => {
|
||||
self.final_message = None;
|
||||
self.final_message_rendered = false;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
if let Some(error) = notification.turn.error {
|
||||
eprintln!("{} {}", "ERROR:".style(self.red).style(self.bold), error);
|
||||
}
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Interrupted => {
|
||||
self.final_message = None;
|
||||
self.final_message_rendered = false;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
eprintln!("{}", "turn interrupted".style(self.dimmed));
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::InProgress => CodexStatus::Running,
|
||||
},
|
||||
ServerNotification::TurnDiffUpdated(notification) => {
|
||||
if notification.diff != self.last_turn_diff && !notification.diff.trim().is_empty()
|
||||
{
|
||||
eprintln!("{}", notification.diff);
|
||||
}
|
||||
// Remember empty updates too, so a restored diff is rendered again.
|
||||
self.last_turn_diff = notification.diff;
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnPlanUpdated(notification) => {
|
||||
if let Some(explanation) = notification.explanation {
|
||||
eprintln!("{}", explanation.style(self.italic));
|
||||
}
|
||||
for step in notification.plan {
|
||||
match step.status {
|
||||
codex_app_server_protocol::TurnPlanStepStatus::Completed => {
|
||||
eprintln!(" {} {}", "✓".style(self.green), step.step);
|
||||
}
|
||||
codex_app_server_protocol::TurnPlanStepStatus::InProgress => {
|
||||
eprintln!(" {} {}", "→".style(self.cyan), step.step);
|
||||
}
|
||||
codex_app_server_protocol::TurnPlanStepStatus::Pending => {
|
||||
eprintln!(
|
||||
" {} {}",
|
||||
"•".style(self.dimmed),
|
||||
step.step.style(self.dimmed)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnStarted(_) => {
|
||||
self.last_turn_diff.clear();
|
||||
CodexStatus::Running
|
||||
}
|
||||
_ => CodexStatus::Running,
|
||||
}
|
||||
}
|
||||
|
||||
fn process_warning(&mut self, message: String) -> CodexStatus {
|
||||
eprintln!(
|
||||
"{} {message}",
|
||||
"warning:".style(self.yellow).style(self.bold)
|
||||
);
|
||||
CodexStatus::Running
|
||||
}
|
||||
|
||||
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()> {
|
||||
let print_to_stdout = should_print_final_message_to_stdout(
|
||||
self.emit_final_message_on_shutdown
|
||||
.then_some(self.final_message.as_deref())
|
||||
.flatten(),
|
||||
std::io::stdout().is_terminal(),
|
||||
std::io::stderr().is_terminal(),
|
||||
);
|
||||
let output_result = if self.emit_final_message_on_shutdown
|
||||
&& let (Some(path), Some(file)) = (self.last_message_path.as_deref(), output)
|
||||
&& !(print_to_stdout && file.is_stdout())
|
||||
{
|
||||
handle_last_message(self.final_message.as_deref(), path, file)
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
|
||||
if let Some(usage) = &self.last_total_token_usage {
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"tokens used".style(self.dimmed),
|
||||
format_with_separators(blended_total(usage))
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(clippy::print_stdout)]
|
||||
if print_to_stdout && let Some(message) = self.final_message.as_deref() {
|
||||
println!("{message}");
|
||||
} else if should_print_final_message_to_tty(
|
||||
self.emit_final_message_on_shutdown
|
||||
.then_some(self.final_message.as_deref())
|
||||
.flatten(),
|
||||
self.final_message_rendered,
|
||||
std::io::stdout().is_terminal(),
|
||||
std::io::stderr().is_terminal(),
|
||||
) && let Some(message) = self.final_message.as_deref()
|
||||
{
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"codex".style(self.italic).style(self.magenta),
|
||||
message
|
||||
);
|
||||
}
|
||||
output_result
|
||||
}
|
||||
}
|
||||
|
||||
fn config_summary_entries(
|
||||
config: &Config,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
let permission_profile = config.permissions.effective_permission_profile();
|
||||
let mut entries = vec![
|
||||
("workdir", config.cwd.display().to_string()),
|
||||
("model", session_configured_event.model.clone()),
|
||||
(
|
||||
"provider",
|
||||
session_configured_event.model_provider_id.clone(),
|
||||
),
|
||||
(
|
||||
"approval",
|
||||
config.permissions.approval_policy.value().to_string(),
|
||||
),
|
||||
(
|
||||
"sandbox",
|
||||
summarize_permission_profile(
|
||||
&permission_profile,
|
||||
&PathUri::from_abs_path(&config.cwd),
|
||||
&config.effective_workspace_roots(),
|
||||
),
|
||||
),
|
||||
];
|
||||
if config.model_provider.wire_api == WireApi::Responses {
|
||||
entries.push((
|
||||
"reasoning effort",
|
||||
config
|
||||
.model_reasoning_effort
|
||||
.as_ref()
|
||||
.map(std::string::ToString::to_string)
|
||||
.unwrap_or_else(|| "none".to_string()),
|
||||
));
|
||||
entries.push((
|
||||
"reasoning summaries",
|
||||
config
|
||||
.model_reasoning_summary
|
||||
.map(|summary| summary.to_string())
|
||||
.unwrap_or_else(|| "none".to_string()),
|
||||
));
|
||||
}
|
||||
entries.push((
|
||||
"session id",
|
||||
session_configured_event.session_id.to_string(),
|
||||
));
|
||||
entries
|
||||
}
|
||||
|
||||
fn reasoning_text(
|
||||
summary: &[String],
|
||||
content: &[String],
|
||||
show_raw_agent_reasoning: bool,
|
||||
) -> Option<String> {
|
||||
let entries = if show_raw_agent_reasoning && !content.is_empty() {
|
||||
content
|
||||
} else {
|
||||
summary
|
||||
};
|
||||
if entries.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(entries.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn final_message_from_turn_items(
|
||||
items: &[impl std::borrow::Borrow<ThreadItemPayload>],
|
||||
) -> Option<String> {
|
||||
items
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| match item.borrow() {
|
||||
ThreadItemPayload::AgentMessage { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().rev().find_map(|item| match item.borrow() {
|
||||
ThreadItemPayload::Plan { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn blended_total(usage: &ThreadTokenUsage) -> i64 {
|
||||
let cached_input = usage.total.cached_input_tokens.max(0);
|
||||
let non_cached_input = (usage.total.input_tokens - cached_input).max(0);
|
||||
(non_cached_input + usage.total.output_tokens.max(0)).max(0)
|
||||
}
|
||||
|
||||
fn should_print_final_message_to_stdout(
|
||||
final_message: Option<&str>,
|
||||
stdout_is_terminal: bool,
|
||||
stderr_is_terminal: bool,
|
||||
) -> bool {
|
||||
final_message.is_some() && !(stdout_is_terminal && stderr_is_terminal)
|
||||
}
|
||||
|
||||
fn should_print_final_message_to_tty(
|
||||
final_message: Option<&str>,
|
||||
final_message_rendered: bool,
|
||||
stdout_is_terminal: bool,
|
||||
stderr_is_terminal: bool,
|
||||
) -> bool {
|
||||
final_message.is_some() && !final_message_rendered && stdout_is_terminal && stderr_is_terminal
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "event_processor_with_human_output_tests.rs"]
|
||||
mod tests;
|
||||
649
codex-rs/exec/src/event_processor_with_human_output_tests.rs
Normal file
649
codex-rs/exec/src/event_processor_with_human_output_tests.rs
Normal file
@@ -0,0 +1,649 @@
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_utils_sandbox_summary::summarize_permission_profile;
|
||||
use owo_colors::Style;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::EventProcessorWithHumanOutput;
|
||||
use super::config_summary_entries;
|
||||
use super::final_message_from_turn_items;
|
||||
use super::reasoning_text;
|
||||
use super::should_print_final_message_to_stdout;
|
||||
use super::should_print_final_message_to_tty;
|
||||
use crate::event_processor::EventProcessor;
|
||||
|
||||
#[test]
|
||||
fn turn_diff_notifications_render_only_changes() -> anyhow::Result<()> {
|
||||
const CHILD: &str = "CODEX_EXEC_TURN_DIFF_TEST_CHILD";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
// Capture stderr in a child so other tests cannot interfere with rendering.
|
||||
let output = std::process::Command::new(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"event_processor_with_human_output::tests::turn_diff_notifications_render_only_changes",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD, "1")
|
||||
.output()?;
|
||||
assert!(output.status.success(), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"));
|
||||
insta::assert_snapshot!(String::from_utf8(output.stderr)?, @r"
|
||||
turn-1
|
||||
@@ -1 +1 @@
|
||||
-value=1
|
||||
+value=2
|
||||
@@ -1 +1 @@
|
||||
-value=1
|
||||
+value=3
|
||||
@@ -1 +1 @@
|
||||
-value=1
|
||||
+value=2
|
||||
@@ -1 +1 @@
|
||||
-value=1
|
||||
+value=2
|
||||
@@ -1 +1 @@
|
||||
-value=1
|
||||
+value=2
|
||||
turn-2
|
||||
@@ -1 +1 @@
|
||||
-value=1
|
||||
+value=2
|
||||
");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: None,
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
};
|
||||
let first = "@@ -1 +1 @@\n-value=1\n+value=2";
|
||||
let changed = "@@ -1 +1 @@\n-value=1\n+value=3";
|
||||
for (turn_id, diffs) in [
|
||||
// Repeated updates are quiet, but changed and restored diffs still print.
|
||||
(
|
||||
"turn-1",
|
||||
vec![
|
||||
"", " \n", first, first, changed, changed, first, "", first, " \n", first,
|
||||
],
|
||||
),
|
||||
("turn-2", vec![first, first]),
|
||||
] {
|
||||
processor.process_server_notification(ServerNotification::TurnStarted(
|
||||
codex_app_server_protocol::TurnStartedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: turn_id.to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::InProgress,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
eprintln!("{turn_id}");
|
||||
for diff in diffs {
|
||||
assert_eq!(
|
||||
processor.process_server_notification(ServerNotification::TurnDiffUpdated(
|
||||
codex_app_server_protocol::TurnDiffUpdatedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: turn_id.to_string(),
|
||||
diff: diff.to_string(),
|
||||
},
|
||||
)),
|
||||
crate::event_processor::CodexStatus::Running
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppresses_final_stdout_message_when_both_streams_are_terminals() {
|
||||
assert!(!should_print_final_message_to_stdout(
|
||||
Some("hello"),
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_final_stdout_message_when_stdout_is_not_terminal() {
|
||||
assert!(should_print_final_message_to_stdout(
|
||||
Some("hello"),
|
||||
/*stdout_is_terminal*/ false,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_final_stdout_message_when_stderr_is_not_terminal() {
|
||||
assert!(should_print_final_message_to_stdout(
|
||||
Some("hello"),
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppresses_final_stdout_message_when_missing() {
|
||||
assert!(!should_print_final_message_to_stdout(
|
||||
/*final_message*/ None, /*stdout_is_terminal*/ false,
|
||||
/*stderr_is_terminal*/ false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prints_final_tty_message_when_not_yet_rendered() {
|
||||
assert!(should_print_final_message_to_tty(
|
||||
Some("hello"),
|
||||
/*final_message_rendered*/ false,
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppresses_final_tty_message_when_already_rendered() {
|
||||
assert!(!should_print_final_message_to_tty(
|
||||
Some("hello"),
|
||||
/*final_message_rendered*/ true,
|
||||
/*stdout_is_terminal*/ true,
|
||||
/*stderr_is_terminal*/ true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_text_prefers_summary_when_raw_reasoning_is_hidden() {
|
||||
let text = reasoning_text(
|
||||
&["summary".to_string()],
|
||||
&["raw".to_string()],
|
||||
/*show_raw_agent_reasoning*/ false,
|
||||
);
|
||||
|
||||
assert_eq!(text.as_deref(), Some("summary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_text_uses_raw_content_when_enabled() {
|
||||
let text = reasoning_text(
|
||||
&["summary".to_string()],
|
||||
&["raw".to_string()],
|
||||
/*show_raw_agent_reasoning*/ true,
|
||||
);
|
||||
|
||||
assert_eq!(text.as_deref(), Some("raw"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_disabled_permission_profile_as_danger_full_access() {
|
||||
let cwd = PathUri::from_abs_path(&test_path_buf("/tmp").abs());
|
||||
|
||||
assert_eq!(
|
||||
summarize_permission_profile(
|
||||
&PermissionProfile::Disabled,
|
||||
&cwd,
|
||||
std::slice::from_ref(&cwd),
|
||||
),
|
||||
"danger-full-access"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_external_permission_profile() {
|
||||
let cwd = PathUri::from_abs_path(&test_path_buf("/tmp").abs());
|
||||
|
||||
assert_eq!(
|
||||
summarize_permission_profile(
|
||||
&PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
},
|
||||
&cwd,
|
||||
std::slice::from_ref(&cwd),
|
||||
),
|
||||
"external-sandbox (network access enabled)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_managed_workspace_write_permission_profile() {
|
||||
let cwd = test_path_buf("/tmp/project").abs();
|
||||
let cache_root = test_path_buf("/tmp/cache").abs();
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: cwd.clone().into(),
|
||||
access: FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Path {
|
||||
path: cache_root.clone().into(),
|
||||
},
|
||||
access: FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
]),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
summarize_permission_profile(
|
||||
&profile,
|
||||
&PathUri::from_abs_path(&cwd),
|
||||
&[cwd.clone().into(), cache_root.clone().into()],
|
||||
),
|
||||
format!("workspace-write [workdir, {}]", cache_root.display())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarizes_managed_read_only_permission_profile() {
|
||||
let cwd = PathUri::from_abs_path(&test_path_buf("/tmp/project").abs());
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(Vec::new()),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
summarize_permission_profile(&profile, &cwd, std::slice::from_ref(&cwd)),
|
||||
"read-only"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn config_summary_entries_include_runtime_workspace_roots() {
|
||||
let codex_home = tempfile::tempdir().expect("create codex home");
|
||||
let cwd = tempfile::tempdir().expect("create cwd");
|
||||
let extra_root = tempfile::tempdir().expect("create extra root");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build default config");
|
||||
let cwd = cwd.path().to_path_buf().abs();
|
||||
let extra_root = extra_root.path().to_path_buf().abs();
|
||||
let expected_extra_root_name = extra_root
|
||||
.file_name()
|
||||
.expect("extra root should have file name")
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
config.cwd = cwd.clone();
|
||||
config.workspace_roots = vec![cwd.clone(), extra_root];
|
||||
config
|
||||
.permissions
|
||||
.set_workspace_roots(config.workspace_roots.clone());
|
||||
config
|
||||
.permissions
|
||||
.set_permission_profile(PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
))
|
||||
.expect("set permission profile");
|
||||
|
||||
let session_configured_event = SessionConfiguredEvent {
|
||||
session_id: SessionId::new(),
|
||||
thread_id: ThreadId::new(),
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
thread_source: None,
|
||||
thread_name: None,
|
||||
model: "gpt-5.4".to_string(),
|
||||
model_provider_id: config.model_provider_id.clone(),
|
||||
service_tier: None,
|
||||
approval_policy: AskForApproval::Never,
|
||||
approvals_reviewer: config.approvals_reviewer,
|
||||
permission_profile: config.permissions.effective_permission_profile(),
|
||||
active_permission_profile: None,
|
||||
cwd,
|
||||
reasoning_effort: None,
|
||||
network_proxy: None,
|
||||
rollout_path: None,
|
||||
};
|
||||
|
||||
let summary_entries = config_summary_entries(&config, &session_configured_event);
|
||||
let sandbox_summary = summary_entries
|
||||
.iter()
|
||||
.find_map(|(key, value)| (*key == "sandbox").then_some(value))
|
||||
.expect("sandbox summary entry");
|
||||
assert!(
|
||||
sandbox_summary.starts_with("workspace-write [workdir, ")
|
||||
&& sandbox_summary.contains(&expected_extra_root_name),
|
||||
"expected runtime workspace root in sandbox summary: {summary_entries:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_message_from_turn_items_uses_latest_agent_message() {
|
||||
let message = final_message_from_turn_items(&[
|
||||
ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-1".to_string(),
|
||||
text: "first".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
},
|
||||
ThreadItemPayload::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "plan".to_string(),
|
||||
},
|
||||
ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-2".to_string(),
|
||||
text: "second".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
},
|
||||
]);
|
||||
|
||||
assert_eq!(message.as_deref(), Some("second"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn final_message_from_turn_items_falls_back_to_latest_plan() {
|
||||
let message = final_message_from_turn_items(&[
|
||||
ThreadItemPayload::Reasoning {
|
||||
id: "reasoning-1".to_string(),
|
||||
summary: vec!["inspect".to_string()],
|
||||
content: Vec::new(),
|
||||
},
|
||||
ThreadItemPayload::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "first plan".to_string(),
|
||||
},
|
||||
ThreadItemPayload::Plan {
|
||||
id: "plan-2".to_string(),
|
||||
text: "final plan".to_string(),
|
||||
},
|
||||
]);
|
||||
|
||||
assert_eq!(message.as_deref(), Some("final plan"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_completed_recovers_final_message_from_turn_items() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: None,
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: vec![ThreadItem::untimed(ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-1".to_string(),
|
||||
text: "final answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
})],
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message.as_deref(), Some("final answer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_completed_overwrites_stale_final_message_from_turn_items() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("stale answer".to_string()),
|
||||
final_message_rendered: true,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: vec![ThreadItem::untimed(ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-1".to_string(),
|
||||
text: "final answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
})],
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message.as_deref(), Some("final answer"));
|
||||
assert!(!processor.final_message_rendered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_completed_preserves_streamed_final_message_when_turn_items_are_empty() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("streamed answer".to_string()),
|
||||
final_message_rendered: false,
|
||||
emit_final_message_on_shutdown: false,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message.as_deref(), Some("streamed answer"));
|
||||
assert!(processor.emit_final_message_on_shutdown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_failed_clears_stale_final_message() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("partial answer".to_string()),
|
||||
final_message_rendered: true,
|
||||
emit_final_message_on_shutdown: true,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Failed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message, None);
|
||||
assert!(!processor.final_message_rendered);
|
||||
assert!(!processor.emit_final_message_on_shutdown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_interrupted_clears_stale_final_message() {
|
||||
let mut processor = EventProcessorWithHumanOutput {
|
||||
bold: Style::new(),
|
||||
cyan: Style::new(),
|
||||
dimmed: Style::new(),
|
||||
green: Style::new(),
|
||||
italic: Style::new(),
|
||||
magenta: Style::new(),
|
||||
red: Style::new(),
|
||||
yellow: Style::new(),
|
||||
show_agent_reasoning: true,
|
||||
show_raw_agent_reasoning: false,
|
||||
last_message_path: None,
|
||||
final_message: Some("partial answer".to_string()),
|
||||
final_message_rendered: true,
|
||||
emit_final_message_on_shutdown: true,
|
||||
last_total_token_usage: None,
|
||||
last_turn_diff: String::new(),
|
||||
};
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Interrupted,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
status,
|
||||
crate::event_processor::CodexStatus::InitiateShutdown
|
||||
);
|
||||
assert_eq!(processor.final_message, None);
|
||||
assert!(!processor.final_message_rendered);
|
||||
assert!(!processor.emit_final_message_on_shutdown);
|
||||
}
|
||||
646
codex-rs/exec/src/event_processor_with_jsonl_output.rs
Normal file
646
codex-rs/exec/src/event_processor_with_jsonl_output.rs
Normal file
@@ -0,0 +1,646 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use codex_app_server_protocol::CollabAgentTool;
|
||||
use codex_app_server_protocol::CollabAgentToolCallStatus;
|
||||
use codex_app_server_protocol::CommandExecutionStatus;
|
||||
use codex_app_server_protocol::McpToolCallStatus;
|
||||
use codex_app_server_protocol::PatchApplyStatus;
|
||||
use codex_app_server_protocol::PatchChangeKind;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItemPayload;
|
||||
use codex_app_server_protocol::ThreadTokenUsage;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_app_server_protocol::WebSearchAction as ApiWebSearchAction;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::BoundOutput;
|
||||
use codex_protocol::models::WebSearchAction;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
use serde_json::json;
|
||||
|
||||
pub use crate::event_processor::CodexStatus;
|
||||
use crate::event_processor::EventProcessor;
|
||||
use crate::event_processor::handle_last_message;
|
||||
use crate::exec_events::AgentMessageItem;
|
||||
use crate::exec_events::CollabAgentState;
|
||||
use crate::exec_events::CollabAgentStatus;
|
||||
use crate::exec_events::CollabTool;
|
||||
use crate::exec_events::CollabToolCallItem;
|
||||
use crate::exec_events::CollabToolCallStatus;
|
||||
use crate::exec_events::CommandExecutionItem;
|
||||
use crate::exec_events::CommandExecutionStatus as ExecCommandExecutionStatus;
|
||||
use crate::exec_events::ErrorItem;
|
||||
use crate::exec_events::FileChangeItem;
|
||||
use crate::exec_events::FileUpdateChange;
|
||||
use crate::exec_events::ItemCompletedEvent;
|
||||
use crate::exec_events::ItemStartedEvent;
|
||||
use crate::exec_events::ItemUpdatedEvent;
|
||||
use crate::exec_events::McpToolCallItem;
|
||||
use crate::exec_events::McpToolCallItemError;
|
||||
use crate::exec_events::McpToolCallItemResult;
|
||||
use crate::exec_events::McpToolCallStatus as ExecMcpToolCallStatus;
|
||||
use crate::exec_events::PatchApplyStatus as ExecPatchApplyStatus;
|
||||
use crate::exec_events::PatchChangeKind as ExecPatchChangeKind;
|
||||
use crate::exec_events::ReasoningItem;
|
||||
use crate::exec_events::ThreadErrorEvent;
|
||||
use crate::exec_events::ThreadEvent;
|
||||
use crate::exec_events::ThreadItem as ExecThreadItem;
|
||||
use crate::exec_events::ThreadItemDetails;
|
||||
use crate::exec_events::ThreadStartedEvent;
|
||||
use crate::exec_events::TodoItem;
|
||||
use crate::exec_events::TodoListItem;
|
||||
use crate::exec_events::TurnCompletedEvent;
|
||||
use crate::exec_events::TurnFailedEvent;
|
||||
use crate::exec_events::TurnStartedEvent;
|
||||
use crate::exec_events::Usage;
|
||||
use crate::exec_events::WebSearchItem;
|
||||
|
||||
pub struct EventProcessorWithJsonOutput {
|
||||
last_message_path: Option<PathBuf>,
|
||||
next_item_id: AtomicU64,
|
||||
raw_to_exec_item_id: HashMap<String, String>,
|
||||
running_todo_list: Option<RunningTodoList>,
|
||||
last_total_token_usage: Option<ThreadTokenUsage>,
|
||||
last_critical_error: Option<ThreadErrorEvent>,
|
||||
final_message: Option<String>,
|
||||
emit_final_message_on_shutdown: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct RunningTodoList {
|
||||
item_id: String,
|
||||
items: Vec<TodoItem>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct CollectedThreadEvents {
|
||||
pub events: Vec<ThreadEvent>,
|
||||
pub status: CodexStatus,
|
||||
}
|
||||
|
||||
impl EventProcessorWithJsonOutput {
|
||||
pub fn new(last_message_path: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
last_message_path,
|
||||
next_item_id: AtomicU64::new(0),
|
||||
raw_to_exec_item_id: HashMap::new(),
|
||||
running_todo_list: None,
|
||||
last_total_token_usage: None,
|
||||
last_critical_error: None,
|
||||
final_message: None,
|
||||
emit_final_message_on_shutdown: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn final_message(&self) -> Option<&str> {
|
||||
self.final_message.as_deref()
|
||||
}
|
||||
|
||||
fn next_item_id(&self) -> String {
|
||||
format!("item_{}", self.next_item_id.fetch_add(1, Ordering::SeqCst))
|
||||
}
|
||||
|
||||
#[allow(clippy::print_stdout)]
|
||||
fn emit(&self, event: ThreadEvent) {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&event).unwrap_or_else(|err| {
|
||||
json!({
|
||||
"type": "error",
|
||||
"message": format!("failed to serialize exec json event: {err}"),
|
||||
})
|
||||
.to_string()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn usage_from_last_total(&self) -> Usage {
|
||||
let Some(usage) = self.last_total_token_usage.as_ref() else {
|
||||
return Usage::default();
|
||||
};
|
||||
Usage {
|
||||
input_tokens: usage.total.input_tokens,
|
||||
cached_input_tokens: usage.total.cached_input_tokens,
|
||||
cache_write_input_tokens: usage.total.cache_write_input_tokens,
|
||||
output_tokens: usage.total.output_tokens,
|
||||
reasoning_output_tokens: usage.total.reasoning_output_tokens,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_todo_items(plan: &[codex_app_server_protocol::TurnPlanStep]) -> Vec<TodoItem> {
|
||||
plan.iter()
|
||||
.map(|step| TodoItem {
|
||||
text: step.step.clone(),
|
||||
completed: matches!(
|
||||
step.status,
|
||||
codex_app_server_protocol::TurnPlanStepStatus::Completed
|
||||
),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn map_item_with_id(
|
||||
item: ThreadItemPayload,
|
||||
make_id: impl FnOnce() -> String,
|
||||
) -> Option<ExecThreadItem> {
|
||||
match item {
|
||||
ThreadItemPayload::AgentMessage { text, .. } => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::AgentMessage(AgentMessageItem { text }),
|
||||
}),
|
||||
ThreadItemPayload::Reasoning { summary, .. } => {
|
||||
let text = summary.join("\n");
|
||||
if text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::Reasoning(ReasoningItem { text }),
|
||||
})
|
||||
}
|
||||
ThreadItemPayload::CommandExecution {
|
||||
command,
|
||||
aggregated_output,
|
||||
exit_code,
|
||||
status,
|
||||
..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::CommandExecution(CommandExecutionItem {
|
||||
command,
|
||||
aggregated_output: aggregated_output.unwrap_or_default(),
|
||||
exit_code,
|
||||
status: match status {
|
||||
CommandExecutionStatus::InProgress => ExecCommandExecutionStatus::InProgress,
|
||||
CommandExecutionStatus::Completed => ExecCommandExecutionStatus::Completed,
|
||||
CommandExecutionStatus::Failed => ExecCommandExecutionStatus::Failed,
|
||||
CommandExecutionStatus::Declined => ExecCommandExecutionStatus::Declined,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItemPayload::FileChange {
|
||||
changes, status, ..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::FileChange(FileChangeItem {
|
||||
changes: changes
|
||||
.into_iter()
|
||||
.map(|change| FileUpdateChange {
|
||||
path: change.path,
|
||||
kind: match change.kind {
|
||||
PatchChangeKind::Add => ExecPatchChangeKind::Add,
|
||||
PatchChangeKind::Delete => ExecPatchChangeKind::Delete,
|
||||
PatchChangeKind::Update { .. } => ExecPatchChangeKind::Update,
|
||||
},
|
||||
})
|
||||
.collect(),
|
||||
status: match status {
|
||||
PatchApplyStatus::InProgress => ExecPatchApplyStatus::InProgress,
|
||||
PatchApplyStatus::Completed => ExecPatchApplyStatus::Completed,
|
||||
PatchApplyStatus::Failed | PatchApplyStatus::Declined => {
|
||||
ExecPatchApplyStatus::Failed
|
||||
}
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItemPayload::McpToolCall {
|
||||
server,
|
||||
tool,
|
||||
status,
|
||||
arguments,
|
||||
result,
|
||||
error,
|
||||
..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::McpToolCall(McpToolCallItem {
|
||||
server,
|
||||
tool,
|
||||
status: match status {
|
||||
McpToolCallStatus::InProgress => ExecMcpToolCallStatus::InProgress,
|
||||
McpToolCallStatus::Completed => ExecMcpToolCallStatus::Completed,
|
||||
McpToolCallStatus::Failed => ExecMcpToolCallStatus::Failed,
|
||||
},
|
||||
arguments,
|
||||
result: result.map(|result| McpToolCallItemResult {
|
||||
content: result.content,
|
||||
meta: result.meta,
|
||||
structured_content: result.structured_content,
|
||||
}),
|
||||
error: error.map(|error| McpToolCallItemError {
|
||||
message: error.message,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
ThreadItemPayload::CollabAgentToolCall {
|
||||
tool,
|
||||
sender_thread_id,
|
||||
receiver_thread_ids,
|
||||
prompt,
|
||||
agents_states,
|
||||
status,
|
||||
..
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::CollabToolCall(CollabToolCallItem {
|
||||
tool: match tool {
|
||||
CollabAgentTool::SendMessage
|
||||
| CollabAgentTool::FollowupTask
|
||||
| CollabAgentTool::InterruptAgent
|
||||
| CollabAgentTool::ListAgents => return None,
|
||||
CollabAgentTool::SpawnAgent => CollabTool::SpawnAgent,
|
||||
CollabAgentTool::SendInput => CollabTool::SendInput,
|
||||
CollabAgentTool::ResumeAgent => CollabTool::Wait,
|
||||
CollabAgentTool::Wait => CollabTool::Wait,
|
||||
CollabAgentTool::CloseAgent => CollabTool::CloseAgent,
|
||||
},
|
||||
sender_thread_id,
|
||||
receiver_thread_ids,
|
||||
prompt,
|
||||
agents_states: agents_states
|
||||
.into_iter()
|
||||
.map(|(thread_id, state)| {
|
||||
(
|
||||
thread_id,
|
||||
CollabAgentState {
|
||||
status: match state.status {
|
||||
codex_app_server_protocol::CollabAgentStatus::PendingInit => {
|
||||
CollabAgentStatus::PendingInit
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Running => {
|
||||
CollabAgentStatus::Running
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Interrupted => {
|
||||
CollabAgentStatus::Interrupted
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Completed => {
|
||||
CollabAgentStatus::Completed
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Errored => {
|
||||
CollabAgentStatus::Errored
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::Shutdown => {
|
||||
CollabAgentStatus::Shutdown
|
||||
}
|
||||
codex_app_server_protocol::CollabAgentStatus::NotFound => {
|
||||
CollabAgentStatus::NotFound
|
||||
}
|
||||
},
|
||||
message: state.message,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
status: match status {
|
||||
CollabAgentToolCallStatus::InProgress => CollabToolCallStatus::InProgress,
|
||||
CollabAgentToolCallStatus::Completed => CollabToolCallStatus::Completed,
|
||||
CollabAgentToolCallStatus::Failed => CollabToolCallStatus::Failed,
|
||||
CollabAgentToolCallStatus::Interrupted => return None,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItemPayload::WebSearch(item) => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::WebSearch(WebSearchItem {
|
||||
id: item.id,
|
||||
query: item.query,
|
||||
action: match item.action {
|
||||
Some(ApiWebSearchAction::Search { query, queries }) => {
|
||||
WebSearchAction::Search { query, queries }
|
||||
}
|
||||
Some(ApiWebSearchAction::OpenPage { url }) => {
|
||||
WebSearchAction::OpenPage { url }
|
||||
}
|
||||
Some(ApiWebSearchAction::FindInPage { url, pattern }) => {
|
||||
WebSearchAction::FindInPage { url, pattern }
|
||||
}
|
||||
Some(ApiWebSearchAction::Other) | None => WebSearchAction::Other,
|
||||
},
|
||||
results: item.results,
|
||||
}),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn started_item_id(&mut self, raw_id: &str) -> String {
|
||||
if let Some(existing) = self.raw_to_exec_item_id.get(raw_id) {
|
||||
return existing.clone();
|
||||
}
|
||||
let exec_id = self.next_item_id();
|
||||
self.raw_to_exec_item_id
|
||||
.insert(raw_id.to_string(), exec_id.clone());
|
||||
exec_id
|
||||
}
|
||||
|
||||
fn completed_item_id(&mut self, raw_id: &str) -> String {
|
||||
self.raw_to_exec_item_id
|
||||
.remove(raw_id)
|
||||
.unwrap_or_else(|| self.next_item_id())
|
||||
}
|
||||
|
||||
fn map_started_item(&mut self, item: ThreadItemPayload) -> Option<ExecThreadItem> {
|
||||
match item {
|
||||
ThreadItemPayload::AgentMessage { .. } | ThreadItemPayload::Reasoning { .. } => None,
|
||||
other => {
|
||||
let raw_id = other.id().to_string();
|
||||
Self::map_item_with_id(other, || self.started_item_id(&raw_id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_completed_item_mut(&mut self, item: ThreadItemPayload) -> Option<ExecThreadItem> {
|
||||
if let ThreadItemPayload::Reasoning { summary, .. } = &item
|
||||
&& summary.join("\n").trim().is_empty()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
match &item {
|
||||
ThreadItemPayload::AgentMessage { .. } | ThreadItemPayload::Reasoning { .. } => {
|
||||
Self::map_item_with_id(item, || self.next_item_id())
|
||||
}
|
||||
other => {
|
||||
let raw_id = other.id().to_string();
|
||||
Self::map_item_with_id(item, || self.completed_item_id(&raw_id))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reconcile_unfinished_started_items(
|
||||
&mut self,
|
||||
turn_items: &[codex_app_server_protocol::ThreadItem],
|
||||
) -> Vec<ThreadEvent> {
|
||||
turn_items
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
let raw_id = item.id().to_string();
|
||||
if !self.raw_to_exec_item_id.contains_key(&raw_id) {
|
||||
return None;
|
||||
}
|
||||
self.map_completed_item_mut(item.payload.clone())
|
||||
.map(|item| ThreadEvent::ItemCompleted(ItemCompletedEvent { item }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn final_message_from_turn_items(
|
||||
items: &[impl std::borrow::Borrow<ThreadItemPayload>],
|
||||
) -> Option<String> {
|
||||
items
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| match item.borrow() {
|
||||
ThreadItemPayload::AgentMessage { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().rev().find_map(|item| match item.borrow() {
|
||||
ThreadItemPayload::Plan { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn thread_started_event(session_configured: &SessionConfiguredEvent) -> ThreadEvent {
|
||||
ThreadEvent::ThreadStarted(ThreadStartedEvent {
|
||||
thread_id: session_configured.thread_id.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn collect_warning(&mut self, message: String) -> CollectedThreadEvents {
|
||||
CollectedThreadEvents {
|
||||
events: vec![ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem { message }),
|
||||
},
|
||||
})],
|
||||
status: CodexStatus::Running,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn collect_thread_events(
|
||||
&mut self,
|
||||
notification: ServerNotification,
|
||||
) -> CollectedThreadEvents {
|
||||
let mut events = Vec::new();
|
||||
let status = match notification {
|
||||
ServerNotification::ConfigWarning(notification) => {
|
||||
let message = match notification.details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", notification.summary)
|
||||
}
|
||||
_ => notification.summary,
|
||||
};
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem { message }),
|
||||
},
|
||||
}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::Warning(notification) => {
|
||||
let warning = self.collect_warning(notification.message);
|
||||
events.extend(warning.events);
|
||||
warning.status
|
||||
}
|
||||
ServerNotification::Error(notification) => {
|
||||
let message = match notification.error.additional_details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", notification.error.message)
|
||||
}
|
||||
_ => notification.error.message,
|
||||
};
|
||||
let error = ThreadErrorEvent { message };
|
||||
self.last_critical_error = Some(error.clone());
|
||||
events.push(ThreadEvent::Error(error));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::DeprecationNotice(notification) => {
|
||||
let message = match notification.details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", notification.summary)
|
||||
}
|
||||
_ => notification.summary,
|
||||
};
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem { message }),
|
||||
},
|
||||
}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::HookStarted(_) | ServerNotification::HookCompleted(_) => {
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemStarted(notification) => {
|
||||
if let Some(item) = self.map_started_item(notification.item.payload) {
|
||||
events.push(ThreadEvent::ItemStarted(ItemStartedEvent { item }));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => {
|
||||
if let Some(item) = self.map_completed_item_mut(notification.item.payload) {
|
||||
if let ThreadItemDetails::AgentMessage(AgentMessageItem { text }) =
|
||||
&item.details
|
||||
{
|
||||
self.final_message = Some(text.clone());
|
||||
}
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent { item }));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelRerouted(notification) => {
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: self.next_item_id(),
|
||||
details: ThreadItemDetails::Error(ErrorItem {
|
||||
message: format!(
|
||||
"model rerouted: {} -> {} ({:?})",
|
||||
notification.from_model, notification.to_model, notification.reason
|
||||
),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelVerification(_) => CodexStatus::Running,
|
||||
ServerNotification::ThreadTokenUsageUpdated(notification) => {
|
||||
self.last_total_token_usage = Some(notification.token_usage);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnCompleted(notification) => {
|
||||
if let Some(running) = self.running_todo_list.take() {
|
||||
events.push(ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: running.item_id,
|
||||
details: ThreadItemDetails::TodoList(TodoListItem {
|
||||
items: running.items,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
}
|
||||
events.extend(self.reconcile_unfinished_started_items(¬ification.turn.items));
|
||||
match notification.turn.status {
|
||||
TurnStatus::Completed => {
|
||||
if let Some(final_message) =
|
||||
Self::final_message_from_turn_items(notification.turn.items.as_slice())
|
||||
{
|
||||
self.final_message = Some(final_message);
|
||||
}
|
||||
self.emit_final_message_on_shutdown = true;
|
||||
events.push(ThreadEvent::TurnCompleted(TurnCompletedEvent {
|
||||
usage: self.usage_from_last_total(),
|
||||
}));
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Failed => {
|
||||
self.final_message = None;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
let error = notification
|
||||
.turn
|
||||
.error
|
||||
.map(|error| ThreadErrorEvent {
|
||||
message: match error.additional_details {
|
||||
Some(details) if !details.is_empty() => {
|
||||
format!("{} ({details})", error.message)
|
||||
}
|
||||
_ => error.message,
|
||||
},
|
||||
})
|
||||
.or_else(|| self.last_critical_error.clone())
|
||||
.unwrap_or_else(|| ThreadErrorEvent {
|
||||
message: "turn failed".to_string(),
|
||||
});
|
||||
events.push(ThreadEvent::TurnFailed(TurnFailedEvent { error }));
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::Interrupted => {
|
||||
self.final_message = None;
|
||||
self.emit_final_message_on_shutdown = false;
|
||||
CodexStatus::InitiateShutdown
|
||||
}
|
||||
TurnStatus::InProgress => CodexStatus::Running,
|
||||
}
|
||||
}
|
||||
ServerNotification::TurnDiffUpdated(_) => CodexStatus::Running,
|
||||
ServerNotification::TurnPlanUpdated(notification) => {
|
||||
let items = Self::map_todo_items(¬ification.plan);
|
||||
if let Some(running) = self.running_todo_list.as_mut() {
|
||||
running.items = items.clone();
|
||||
let item_id = running.item_id.clone();
|
||||
events.push(ThreadEvent::ItemUpdated(ItemUpdatedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: item_id,
|
||||
details: ThreadItemDetails::TodoList(TodoListItem { items }),
|
||||
},
|
||||
}));
|
||||
} else {
|
||||
let item_id = self.next_item_id();
|
||||
self.running_todo_list = Some(RunningTodoList {
|
||||
item_id: item_id.clone(),
|
||||
items: items.clone(),
|
||||
});
|
||||
events.push(ThreadEvent::ItemStarted(ItemStartedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: item_id,
|
||||
details: ThreadItemDetails::TodoList(TodoListItem { items }),
|
||||
},
|
||||
}));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::TurnStarted(_) => {
|
||||
events.push(ThreadEvent::TurnStarted(TurnStartedEvent {}));
|
||||
CodexStatus::Running
|
||||
}
|
||||
_ => CodexStatus::Running,
|
||||
};
|
||||
|
||||
CollectedThreadEvents { events, status }
|
||||
}
|
||||
}
|
||||
|
||||
impl EventProcessor for EventProcessorWithJsonOutput {
|
||||
fn print_config_summary(
|
||||
&mut self,
|
||||
_: &Config,
|
||||
_: &str,
|
||||
session_configured: &SessionConfiguredEvent,
|
||||
) {
|
||||
self.emit(Self::thread_started_event(session_configured));
|
||||
}
|
||||
|
||||
fn process_server_notification(&mut self, notification: ServerNotification) -> CodexStatus {
|
||||
let collected = self.collect_thread_events(notification);
|
||||
for event in collected.events {
|
||||
self.emit(event);
|
||||
}
|
||||
collected.status
|
||||
}
|
||||
|
||||
fn process_warning(&mut self, message: String) -> CodexStatus {
|
||||
let collected = self.collect_warning(message);
|
||||
for event in collected.events {
|
||||
self.emit(event);
|
||||
}
|
||||
collected.status
|
||||
}
|
||||
|
||||
fn print_final_output(&mut self, output: Option<BoundOutput>) -> anyhow::Result<()> {
|
||||
if self.emit_final_message_on_shutdown
|
||||
&& let (Some(path), Some(file)) = (self.last_message_path.as_deref(), output)
|
||||
{
|
||||
handle_last_message(self.final_message.as_deref(), path, file)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "event_processor_with_jsonl_output_tests.rs"]
|
||||
mod tests;
|
||||
149
codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs
Normal file
149
codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn failed_turn_does_not_overwrite_output_last_message_file() {
|
||||
let tempdir = tempdir().expect("create tempdir");
|
||||
let output_path = tempdir.path().join("last-message.txt");
|
||||
std::fs::write(&output_path, "keep existing contents").expect("seed output file");
|
||||
|
||||
let mut processor = EventProcessorWithJsonOutput::new(Some(output_path.clone()));
|
||||
|
||||
let collected = processor.collect_thread_events(ServerNotification::ItemCompleted(
|
||||
codex_app_server_protocol::ItemCompletedNotification::new(
|
||||
"thread-1".to_string(),
|
||||
"turn-1".to_string(),
|
||||
ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-1".to_string(),
|
||||
text: "partial answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 0,
|
||||
),
|
||||
));
|
||||
|
||||
assert_eq!(collected.status, CodexStatus::Running);
|
||||
assert_eq!(processor.final_message(), Some("partial answer"));
|
||||
|
||||
let status = processor.process_server_notification(ServerNotification::TurnCompleted(
|
||||
codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Failed,
|
||||
error: Some(codex_app_server_protocol::TurnError {
|
||||
misalignment: None,
|
||||
message: "turn failed".to_string(),
|
||||
additional_details: None,
|
||||
codex_error_info: None,
|
||||
}),
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(status, CodexStatus::InitiateShutdown);
|
||||
assert_eq!(processor.final_message(), None);
|
||||
|
||||
let output = BoundOutput::open(&output_path).expect("bind output");
|
||||
EventProcessor::print_final_output(&mut processor, Some(output)).expect("print final output");
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&output_path).expect("read output file"),
|
||||
"keep existing contents"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_warning_emits_a_non_fatal_error_item() {
|
||||
let mut processor = EventProcessorWithJsonOutput::new(/*last_message_path*/ None);
|
||||
|
||||
let collected = processor.collect_thread_events(ServerNotification::Warning(
|
||||
codex_app_server_protocol::WarningNotification {
|
||||
thread_id: Some("thread-1".to_string()),
|
||||
message: "invalid global instructions".to_string(),
|
||||
},
|
||||
));
|
||||
|
||||
assert_eq!(
|
||||
collected,
|
||||
CollectedThreadEvents {
|
||||
events: vec![ThreadEvent::ItemCompleted(ItemCompletedEvent {
|
||||
item: ExecThreadItem {
|
||||
id: "item_0".to_string(),
|
||||
details: ThreadItemDetails::Error(ErrorItem {
|
||||
message: "invalid global instructions".to_string(),
|
||||
}),
|
||||
},
|
||||
})],
|
||||
status: CodexStatus::Running,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_tool_call_result_preserves_meta_in_jsonl_event() {
|
||||
let mut processor = EventProcessorWithJsonOutput::new(/*last_message_path*/ None);
|
||||
|
||||
let collected = processor.collect_thread_events(ServerNotification::ItemCompleted(
|
||||
codex_app_server_protocol::ItemCompletedNotification::new(
|
||||
"thread-1".to_string(),
|
||||
"turn-1".to_string(),
|
||||
ThreadItemPayload::McpToolCall {
|
||||
id: "mcp-1".to_string(),
|
||||
server: "search service".to_string(),
|
||||
tool: "web_run".to_string(),
|
||||
status: McpToolCallStatus::Completed,
|
||||
arguments: json!({"search_query": [{"q": "OpenAI Codex CLI documentation"}]}),
|
||||
app_context: None,
|
||||
mcp_app_resource_uri: None,
|
||||
mcp_app_ui: None,
|
||||
plugin_id: None,
|
||||
read_only_hint: None,
|
||||
result: Some(Box::new(codex_app_server_protocol::McpToolCallResult {
|
||||
content: vec![json!({"type": "text", "text": "search result"})],
|
||||
structured_content: None,
|
||||
meta: Some(json!({"raw_messages": [{"ref_id": "turn0search0"}]})),
|
||||
})),
|
||||
error: None,
|
||||
duration_ms: Some(42),
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 0,
|
||||
),
|
||||
));
|
||||
|
||||
assert_eq!(collected.status, CodexStatus::Running);
|
||||
assert_eq!(collected.events.len(), 1);
|
||||
|
||||
let ThreadEvent::ItemCompleted(ItemCompletedEvent { item }) = &collected.events[0] else {
|
||||
panic!("expected item.completed event");
|
||||
};
|
||||
let ThreadItemDetails::McpToolCall(item) = &item.details else {
|
||||
panic!("expected MCP tool call item");
|
||||
};
|
||||
let result = item.result.as_ref().expect("expected MCP tool result");
|
||||
assert_eq!(
|
||||
result.meta,
|
||||
Some(json!({"raw_messages": [{"ref_id": "turn0search0"}]}))
|
||||
);
|
||||
|
||||
let serialized = serde_json::to_value(&collected.events[0]).expect("serialize event");
|
||||
assert_eq!(
|
||||
serialized["item"]["result"]["_meta"],
|
||||
json!({"raw_messages": [{"ref_id": "turn0search0"}]})
|
||||
);
|
||||
assert!(serialized["item"]["result"].get("meta").is_none());
|
||||
}
|
||||
324
codex-rs/exec/src/exec_events.rs
Normal file
324
codex-rs/exec/src/exec_events.rs
Normal file
@@ -0,0 +1,324 @@
|
||||
use codex_protocol::models::WebSearchAction;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::HashMap;
|
||||
use ts_rs::TS;
|
||||
|
||||
/// Top-level JSONL events emitted by codex exec
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ThreadEvent {
|
||||
/// Emitted when a new thread is started as the first event.
|
||||
#[serde(rename = "thread.started")]
|
||||
ThreadStarted(ThreadStartedEvent),
|
||||
/// Emitted when a turn is started by sending a new prompt to the model.
|
||||
/// A turn encompasses all events that happen while agent is processing the prompt.
|
||||
#[serde(rename = "turn.started")]
|
||||
TurnStarted(TurnStartedEvent),
|
||||
/// Emitted when a turn is completed. Typically right after the assistant's response.
|
||||
#[serde(rename = "turn.completed")]
|
||||
TurnCompleted(TurnCompletedEvent),
|
||||
/// Indicates that a turn failed with an error.
|
||||
#[serde(rename = "turn.failed")]
|
||||
TurnFailed(TurnFailedEvent),
|
||||
/// Emitted when a new item is added to the thread. Typically the item will be in an "in progress" state.
|
||||
#[serde(rename = "item.started")]
|
||||
ItemStarted(ItemStartedEvent),
|
||||
/// Emitted when an item is updated.
|
||||
#[serde(rename = "item.updated")]
|
||||
ItemUpdated(ItemUpdatedEvent),
|
||||
/// Signals that an item has reached a terminal state—either success or failure.
|
||||
#[serde(rename = "item.completed")]
|
||||
ItemCompleted(ItemCompletedEvent),
|
||||
/// Represents an unrecoverable error emitted directly by the event stream.
|
||||
#[serde(rename = "error")]
|
||||
Error(ThreadErrorEvent),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ThreadStartedEvent {
|
||||
/// The identified of the new thread. Can be used to resume the thread later.
|
||||
pub thread_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS, Default)]
|
||||
|
||||
pub struct TurnStartedEvent {}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TurnCompletedEvent {
|
||||
pub usage: Usage,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TurnFailedEvent {
|
||||
pub error: ThreadErrorEvent,
|
||||
}
|
||||
|
||||
/// Describes the usage of tokens during a turn.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS, Default)]
|
||||
pub struct Usage {
|
||||
/// The number of input tokens used during the turn.
|
||||
pub input_tokens: i64,
|
||||
/// The number of cached input tokens used during the turn.
|
||||
pub cached_input_tokens: i64,
|
||||
/// The number of input tokens written to the prompt cache during the turn.
|
||||
#[serde(default)]
|
||||
pub cache_write_input_tokens: i64,
|
||||
/// The number of output tokens used during the turn.
|
||||
pub output_tokens: i64,
|
||||
/// The number of reasoning output tokens used during the turn.
|
||||
pub reasoning_output_tokens: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ItemStartedEvent {
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ItemCompletedEvent {
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ItemUpdatedEvent {
|
||||
pub item: ThreadItem,
|
||||
}
|
||||
|
||||
/// Fatal error emitted by the stream.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ThreadErrorEvent {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Canonical representation of a thread item and its domain-specific payload.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ThreadItem {
|
||||
pub id: String,
|
||||
#[serde(flatten)]
|
||||
pub details: ThreadItemDetails,
|
||||
}
|
||||
|
||||
/// Typed payloads for each supported thread item type.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ThreadItemDetails {
|
||||
/// Response from the agent.
|
||||
/// Either a natural-language response or a JSON string when structured output is requested.
|
||||
AgentMessage(AgentMessageItem),
|
||||
/// Agent's reasoning summary.
|
||||
Reasoning(ReasoningItem),
|
||||
/// Tracks a command executed by the agent. The item starts when the command is
|
||||
/// spawned, and completes when the process exits with an exit code.
|
||||
CommandExecution(CommandExecutionItem),
|
||||
/// Represents a set of file changes by the agent. The item is emitted only as a
|
||||
/// completed event once the patch succeeds or fails.
|
||||
FileChange(FileChangeItem),
|
||||
/// Represents a call to an MCP tool. The item starts when the invocation is
|
||||
/// dispatched and completes when the MCP server reports success or failure.
|
||||
McpToolCall(McpToolCallItem),
|
||||
/// Represents a call to a collab tool. The item starts when the collab tool is
|
||||
/// invoked and completes when the collab tool reports success or failure.
|
||||
CollabToolCall(CollabToolCallItem),
|
||||
/// Captures a web search request. It starts when the search is kicked off
|
||||
/// and completes when results are returned to the agent.
|
||||
WebSearch(WebSearchItem),
|
||||
/// Tracks the agent's running to-do list. It starts when the plan is first
|
||||
/// issued, updates as steps change state, and completes when the turn ends.
|
||||
TodoList(TodoListItem),
|
||||
/// Describes a non-fatal error surfaced as an item.
|
||||
Error(ErrorItem),
|
||||
}
|
||||
|
||||
/// Response from the agent.
|
||||
/// Either a natural-language response or a JSON string when structured output is requested.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct AgentMessageItem {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// Agent's reasoning summary.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ReasoningItem {
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The status of a command execution.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CommandExecutionStatus {
|
||||
#[default]
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
Declined,
|
||||
}
|
||||
|
||||
/// A command executed by the agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct CommandExecutionItem {
|
||||
pub command: String,
|
||||
pub aggregated_output: String,
|
||||
pub exit_code: Option<i32>,
|
||||
pub status: CommandExecutionStatus,
|
||||
}
|
||||
|
||||
/// A set of file changes by the agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct FileUpdateChange {
|
||||
pub path: String,
|
||||
pub kind: PatchChangeKind,
|
||||
}
|
||||
|
||||
/// The status of a file change.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PatchApplyStatus {
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A set of file changes by the agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct FileChangeItem {
|
||||
pub changes: Vec<FileUpdateChange>,
|
||||
pub status: PatchApplyStatus,
|
||||
}
|
||||
|
||||
/// Indicates the type of the file change.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PatchChangeKind {
|
||||
Add,
|
||||
Delete,
|
||||
Update,
|
||||
}
|
||||
|
||||
/// The status of an MCP tool call.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpToolCallStatus {
|
||||
#[default]
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// The status of a collab tool call.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CollabToolCallStatus {
|
||||
#[default]
|
||||
InProgress,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Supported collab tools.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CollabTool {
|
||||
SpawnAgent,
|
||||
SendInput,
|
||||
Wait,
|
||||
CloseAgent,
|
||||
}
|
||||
|
||||
/// The status of a collab agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum CollabAgentStatus {
|
||||
PendingInit,
|
||||
Running,
|
||||
Interrupted,
|
||||
Completed,
|
||||
Errored,
|
||||
Shutdown,
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// Last known state of a collab agent.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]
|
||||
pub struct CollabAgentState {
|
||||
pub status: CollabAgentStatus,
|
||||
pub message: Option<String>,
|
||||
}
|
||||
|
||||
/// A call to a collab tool.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct CollabToolCallItem {
|
||||
pub tool: CollabTool,
|
||||
pub sender_thread_id: String,
|
||||
pub receiver_thread_ids: Vec<String>,
|
||||
pub prompt: Option<String>,
|
||||
pub agents_states: HashMap<String, CollabAgentState>,
|
||||
pub status: CollabToolCallStatus,
|
||||
}
|
||||
|
||||
/// Result payload produced by an MCP tool invocation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct McpToolCallItemResult {
|
||||
// NOTE: `rmcp::model::Content` (and its `RawContent` variants) would be a
|
||||
// more precise Rust representation of MCP content blocks. We intentionally
|
||||
// use `serde_json::Value` here because this crate exports JSON schema + TS
|
||||
// types (`schemars`/`ts-rs`), and the rmcp model types aren't set up to be
|
||||
// schema/TS friendly (and would introduce heavier coupling to rmcp's Rust
|
||||
// representations). Using `JsonValue` keeps the payload wire-shaped and
|
||||
// easy to export.
|
||||
pub content: Vec<JsonValue>,
|
||||
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub meta: Option<JsonValue>,
|
||||
pub structured_content: Option<JsonValue>,
|
||||
}
|
||||
|
||||
/// Error details reported by a failed MCP tool invocation.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct McpToolCallItemError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// A call to an MCP tool.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct McpToolCallItem {
|
||||
pub server: String,
|
||||
pub tool: String,
|
||||
#[serde(default)]
|
||||
pub arguments: JsonValue,
|
||||
pub result: Option<McpToolCallItemResult>,
|
||||
pub error: Option<McpToolCallItemError>,
|
||||
pub status: McpToolCallStatus,
|
||||
}
|
||||
|
||||
/// A web search request.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct WebSearchItem {
|
||||
pub id: String,
|
||||
pub query: String,
|
||||
pub action: WebSearchAction,
|
||||
/// Structured results returned by web search, when available.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub results: Option<Vec<JsonValue>>,
|
||||
}
|
||||
|
||||
/// An error notification.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct ErrorItem {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// An item in agent's to-do list.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TodoItem {
|
||||
pub text: String,
|
||||
pub completed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, TS)]
|
||||
pub struct TodoListItem {
|
||||
pub items: Vec<TodoItem>,
|
||||
}
|
||||
2586
codex-rs/exec/src/lib.rs
Normal file
2586
codex-rs/exec/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
919
codex-rs/exec/src/lib_tests.rs
Normal file
919
codex-rs/exec/src/lib_tests.rs
Normal file
@@ -0,0 +1,919 @@
|
||||
use super::*;
|
||||
use codex_app_server_protocol::AuthRecoveryNotification;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadItemPayload as AppServerThreadItemPayload;
|
||||
use codex_otel::set_parent_from_w3c_trace_context;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::models::ActivePermissionProfile;
|
||||
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use opentelemetry::trace::TraceContextExt;
|
||||
use opentelemetry::trace::TraceId;
|
||||
use opentelemetry::trace::TracerProvider as _;
|
||||
use opentelemetry_sdk::trace::SdkTracerProvider;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use tempfile::tempdir;
|
||||
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
||||
|
||||
fn test_tracing_subscriber() -> impl tracing::Subscriber + Send + Sync {
|
||||
let provider = SdkTracerProvider::builder().build();
|
||||
let tracer = provider.tracer("codex-exec-tests");
|
||||
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestLogWriter {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
struct TestLogSink {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for TestLogWriter {
|
||||
type Writer = TestLogSink;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
TestLogSink {
|
||||
buffer: Arc::clone(&self.buffer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for TestLogSink {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.buffer.lock().expect("log buffer lock").extend(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_default_stderr_filter_suppresses_otel_self_diagnostics() {
|
||||
let buffer = Arc::new(Mutex::new(Vec::new()));
|
||||
let writer = TestLogWriter {
|
||||
buffer: Arc::clone(&buffer),
|
||||
};
|
||||
let subscriber = tracing_subscriber::registry().with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_ansi(false)
|
||||
.with_writer(writer)
|
||||
.with_filter(EnvFilter::try_new(EXEC_DEFAULT_LOG_FILTER).expect("default filter")),
|
||||
);
|
||||
|
||||
tracing::subscriber::with_default(subscriber, || {
|
||||
tracing::error!(target: "opentelemetry_sdk", "telemetry export failed");
|
||||
tracing::error!(target: "opentelemetry_otlp", "telemetry request failed");
|
||||
tracing::error!(target: "codex_exec_test", "real exec error");
|
||||
});
|
||||
|
||||
let logs = String::from_utf8(buffer.lock().expect("log buffer lock").clone()).expect("utf8");
|
||||
assert!(!logs.contains("telemetry export failed"));
|
||||
assert!(!logs.contains("telemetry request failed"));
|
||||
assert!(logs.contains("real exec error"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_root_span_can_be_parented_from_trace_context() {
|
||||
let subscriber = test_tracing_subscriber();
|
||||
let _guard = tracing::subscriber::set_default(subscriber);
|
||||
|
||||
let parent = codex_protocol::protocol::W3cTraceContext {
|
||||
traceparent: Some("00-00000000000000000000000000000077-0000000000000088-01".into()),
|
||||
tracestate: Some("vendor=value".into()),
|
||||
};
|
||||
let exec_span = exec_root_span();
|
||||
assert!(set_parent_from_w3c_trace_context(&exec_span, &parent));
|
||||
|
||||
let trace_id = exec_span.context().span().span_context().trace_id();
|
||||
assert_eq!(
|
||||
trace_id,
|
||||
TraceId::from_hex("00000000000000000000000000000077").expect("trace id")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_uncommitted_review_request() {
|
||||
let args = ReviewArgs {
|
||||
uncommitted: true,
|
||||
base: None,
|
||||
commit: None,
|
||||
commit_title: None,
|
||||
prompt: None,
|
||||
};
|
||||
let request = build_review_request(&args).expect("builds uncommitted review request");
|
||||
|
||||
let expected = ReviewRequest {
|
||||
target: ReviewTarget::UncommittedChanges,
|
||||
user_facing_hint: None,
|
||||
};
|
||||
|
||||
assert_eq!(request, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_commit_review_request_with_title() {
|
||||
let args = ReviewArgs {
|
||||
uncommitted: false,
|
||||
base: None,
|
||||
commit: Some("123456789".to_string()),
|
||||
commit_title: Some("Add review command".to_string()),
|
||||
prompt: None,
|
||||
};
|
||||
let request = build_review_request(&args).expect("builds commit review request");
|
||||
|
||||
let expected = ReviewRequest {
|
||||
target: ReviewTarget::Commit {
|
||||
sha: "123456789".to_string(),
|
||||
title: Some("Add review command".to_string()),
|
||||
},
|
||||
user_facing_hint: None,
|
||||
};
|
||||
|
||||
assert_eq!(request, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_custom_review_request_trims_prompt() {
|
||||
let args = ReviewArgs {
|
||||
uncommitted: false,
|
||||
base: None,
|
||||
commit: None,
|
||||
commit_title: None,
|
||||
prompt: Some(" custom review instructions ".to_string()),
|
||||
};
|
||||
let request = build_review_request(&args).expect("builds custom review request");
|
||||
|
||||
let expected = ReviewRequest {
|
||||
target: ReviewTarget::Custom {
|
||||
instructions: "custom review instructions".to_string(),
|
||||
},
|
||||
user_facing_hint: None,
|
||||
};
|
||||
|
||||
assert_eq!(request, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_strips_utf8_bom() {
|
||||
let input = [0xEF, 0xBB, 0xBF, b'h', b'i', b'\n'];
|
||||
|
||||
let out = decode_prompt_bytes(&input).expect("decode utf-8 with BOM");
|
||||
|
||||
assert_eq!(out, "hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_decodes_utf16le_bom() {
|
||||
// UTF-16LE BOM + "hi\n"
|
||||
let input = [0xFF, 0xFE, b'h', 0x00, b'i', 0x00, b'\n', 0x00];
|
||||
|
||||
let out = decode_prompt_bytes(&input).expect("decode utf-16le with BOM");
|
||||
|
||||
assert_eq!(out, "hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_decodes_utf16be_bom() {
|
||||
// UTF-16BE BOM + "hi\n"
|
||||
let input = [0xFE, 0xFF, 0x00, b'h', 0x00, b'i', 0x00, b'\n'];
|
||||
|
||||
let out = decode_prompt_bytes(&input).expect("decode utf-16be with BOM");
|
||||
|
||||
assert_eq!(out, "hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_rejects_utf32le_bom() {
|
||||
// UTF-32LE BOM + "hi\n"
|
||||
let input = [
|
||||
0xFF, 0xFE, 0x00, 0x00, b'h', 0x00, 0x00, 0x00, b'i', 0x00, 0x00, 0x00, b'\n', 0x00, 0x00,
|
||||
0x00,
|
||||
];
|
||||
|
||||
let err = decode_prompt_bytes(&input).expect_err("utf-32le should be rejected");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
PromptDecodeError::UnsupportedBom {
|
||||
encoding: "UTF-32LE"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_rejects_utf32be_bom() {
|
||||
// UTF-32BE BOM + "hi\n"
|
||||
let input = [
|
||||
0x00, 0x00, 0xFE, 0xFF, 0x00, 0x00, 0x00, b'h', 0x00, 0x00, 0x00, b'i', 0x00, 0x00, 0x00,
|
||||
b'\n',
|
||||
];
|
||||
|
||||
let err = decode_prompt_bytes(&input).expect_err("utf-32be should be rejected");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
PromptDecodeError::UnsupportedBom {
|
||||
encoding: "UTF-32BE"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_prompt_bytes_rejects_invalid_utf8() {
|
||||
// Invalid UTF-8 sequence: 0xC3 0x28
|
||||
let input = [0xC3, 0x28];
|
||||
|
||||
let err = decode_prompt_bytes(&input).expect_err("invalid utf-8 should fail");
|
||||
|
||||
assert_eq!(err, PromptDecodeError::InvalidUtf8 { valid_up_to: 0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_with_stdin_context_wraps_stdin_block() {
|
||||
let combined = prompt_with_stdin_context("Summarize this concisely", "my output");
|
||||
|
||||
assert_eq!(
|
||||
combined,
|
||||
"Summarize this concisely\n\n<stdin>\nmy output\n</stdin>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_with_stdin_context_preserves_trailing_newline() {
|
||||
let combined = prompt_with_stdin_context("Summarize this concisely", "my output\n");
|
||||
|
||||
assert_eq!(
|
||||
combined,
|
||||
"Summarize this concisely\n\n<stdin>\nmy output\n</stdin>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lagged_event_warning_message_is_explicit() {
|
||||
assert_eq!(
|
||||
lagged_event_warning_message(/*skipped*/ 7),
|
||||
"in-process app-server event stream lagged; dropped 7 events".to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_warnings_are_filtered_to_the_primary_thread() {
|
||||
let primary_thread_id = "thread-1";
|
||||
let turn_id = "turn-1";
|
||||
let outcomes = [
|
||||
codex_app_server_protocol::WarningNotification {
|
||||
thread_id: None,
|
||||
message: "global warning".to_string(),
|
||||
},
|
||||
codex_app_server_protocol::WarningNotification {
|
||||
thread_id: Some(primary_thread_id.to_string()),
|
||||
message: "primary warning".to_string(),
|
||||
},
|
||||
codex_app_server_protocol::WarningNotification {
|
||||
thread_id: Some("thread-2".to_string()),
|
||||
message: "other warning".to_string(),
|
||||
},
|
||||
]
|
||||
.map(|warning| {
|
||||
should_process_notification(
|
||||
&ServerNotification::Warning(warning),
|
||||
primary_thread_id,
|
||||
turn_id,
|
||||
)
|
||||
});
|
||||
|
||||
assert_eq!(outcomes, [true, true, false]);
|
||||
|
||||
let recovery = AuthRecoveryNotification {
|
||||
thread_id: primary_thread_id.to_string(),
|
||||
turn_id: turn_id.to_string(),
|
||||
provider: "example".to_string(),
|
||||
message: "Refresh authentication".to_string(),
|
||||
};
|
||||
let outcomes = [
|
||||
ServerNotification::AuthRecoveryStarted(recovery.clone()),
|
||||
ServerNotification::AuthRecoveryCompleted(recovery.clone()),
|
||||
ServerNotification::AuthRecoveryStarted(AuthRecoveryNotification {
|
||||
thread_id: "thread-2".to_string(),
|
||||
..recovery.clone()
|
||||
}),
|
||||
ServerNotification::AuthRecoveryCompleted(AuthRecoveryNotification {
|
||||
turn_id: "turn-2".to_string(),
|
||||
..recovery
|
||||
}),
|
||||
]
|
||||
.map(|notification| should_process_notification(¬ification, primary_thread_id, turn_id));
|
||||
|
||||
assert_eq!(outcomes, [true, true, false, false]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_lookup_model_providers_filters_only_last_lookup() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build default config");
|
||||
config.model_provider_id = "test-provider".to_string();
|
||||
|
||||
let last_args = crate::cli::ResumeArgs {
|
||||
session_id: None,
|
||||
last: true,
|
||||
all: false,
|
||||
images: vec![],
|
||||
prompt: None,
|
||||
};
|
||||
let named_args = crate::cli::ResumeArgs {
|
||||
session_id: Some("named-session".to_string()),
|
||||
last: false,
|
||||
all: false,
|
||||
images: vec![],
|
||||
prompt: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
resume_lookup_model_providers(&config, &last_args),
|
||||
Some(vec!["test-provider".to_string()])
|
||||
);
|
||||
assert_eq!(resume_lookup_model_providers(&config, &named_args), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_items_for_thread_returns_matching_turn_items() {
|
||||
let thread = AppServerThread {
|
||||
environments: None,
|
||||
id: "thread-1".to_string(),
|
||||
extra: None,
|
||||
session_id: "thread-1".to_string(),
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
section: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
history_mode: Default::default(),
|
||||
model_provider: "openai".to_string(),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
recency_at: Some(0),
|
||||
status: codex_app_server_protocol::ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp/project").abs(),
|
||||
cli_version: "0.0.0-test".to_string(),
|
||||
originator: None,
|
||||
source: codex_app_server_protocol::SessionSource::Exec,
|
||||
can_accept_direct_input: None,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: None,
|
||||
turns: vec![
|
||||
codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: vec![ThreadItem::untimed(
|
||||
AppServerThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-1".to_string(),
|
||||
text: "hello".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
},
|
||||
)],
|
||||
status: codex_app_server_protocol::TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
codex_app_server_protocol::Turn {
|
||||
id: "turn-2".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Full,
|
||||
items: vec![ThreadItem::untimed(AppServerThreadItemPayload::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "ship it".to_string(),
|
||||
})],
|
||||
status: codex_app_server_protocol::TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
turn_items_for_thread(&thread, "turn-1"),
|
||||
Some(vec![ThreadItem::untimed(
|
||||
AppServerThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "msg-1".to_string(),
|
||||
text: "hello".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
}
|
||||
)])
|
||||
);
|
||||
assert_eq!(turn_items_for_thread(&thread, "missing-turn"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_backfill_turn_completed_items_backfills_persisted_summaries_only() {
|
||||
let notification =
|
||||
ServerNotification::TurnCompleted(codex_app_server_protocol::TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: codex_app_server_protocol::TurnItemsView::Summary,
|
||||
items: Vec::new(),
|
||||
status: codex_app_server_protocol::TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
});
|
||||
|
||||
assert!(!should_backfill_turn_completed_items(
|
||||
/*thread_ephemeral*/ true,
|
||||
¬ification
|
||||
));
|
||||
assert!(should_backfill_turn_completed_items(
|
||||
/*thread_ephemeral*/ false,
|
||||
¬ification
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceled_mcp_server_elicitation_response_uses_cancel_action() {
|
||||
let request = serde_json::from_value(serde_json::json!({
|
||||
"mode": "form",
|
||||
"message": "Allow the tool call?",
|
||||
"requestedSchema": { "type": "object", "properties": {} },
|
||||
"_meta": { APPROVAL_KIND_KEY: APPROVAL_KIND_MCP_TOOL_CALL },
|
||||
}))
|
||||
.expect("valid MCP tool approval request");
|
||||
let value = canceled_mcp_server_elicitation_response(&request)
|
||||
.expect("mcp elicitation cancel response should serialize");
|
||||
let response: McpServerElicitationRequestResponse =
|
||||
serde_json::from_value(value).expect("cancel response should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
McpServerElicitationRequestResponse {
|
||||
action: McpServerElicitationAction::Cancel,
|
||||
content: None,
|
||||
meta: Some(serde_json::json!({
|
||||
CANCELLATION_REASON_KEY: McpApprovalCancellationReason::NonInteractive,
|
||||
})),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_params_include_review_policy_when_review_policy_is_manual_only() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
approvals_reviewer: Some(ApprovalsReviewer::User),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with manual-only review policy");
|
||||
|
||||
let params = thread_start_params_from_config(&config, &ThreadSource::User);
|
||||
|
||||
assert_eq!(
|
||||
params.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::User)
|
||||
);
|
||||
assert_eq!(params.sandbox, None);
|
||||
assert_eq!(
|
||||
params.permissions,
|
||||
permissions_selection_from_config(&config)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_params_include_review_policy_when_auto_review_is_enabled() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with guardian review policy");
|
||||
|
||||
let params = thread_start_params_from_config(&config, &ThreadSource::User);
|
||||
|
||||
assert_eq!(
|
||||
params.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_resume_params_only_include_explicit_review_policy_override() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with guardian review policy");
|
||||
|
||||
let params_without_override = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
let params_with_override = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview),
|
||||
);
|
||||
|
||||
assert_eq!(params_without_override.approvals_reviewer, None);
|
||||
assert_eq!(
|
||||
params_with_override.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_exec_config_retries_without_invalid_headless_policy_for_auto_review() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
std::fs::write(
|
||||
codex_home.path().join("config.toml"),
|
||||
r#"
|
||||
approval_policy = "on-request"
|
||||
approvals_reviewer = "auto_review"
|
||||
"#,
|
||||
)
|
||||
.expect("write config");
|
||||
let requirements_path = codex_home.path().join("requirements.toml");
|
||||
std::fs::write(
|
||||
&requirements_path,
|
||||
r#"
|
||||
allowed_approval_policies = ["never", "on-request"]
|
||||
allowed_sandbox_modes = ["read-only", "workspace-write"]
|
||||
"#,
|
||||
)
|
||||
.expect("write requirements");
|
||||
let mut loader_overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
loader_overrides.system_requirements_path = Some(requirements_path);
|
||||
let overrides = ConfigOverrides {
|
||||
cwd: Some(cwd.path().to_path_buf()),
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
sandbox_mode: Some(SandboxMode::DangerFullAccess),
|
||||
..Default::default()
|
||||
};
|
||||
let build_config = |overrides| {
|
||||
ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.loader_overrides(loader_overrides.clone())
|
||||
.harness_overrides(overrides)
|
||||
.build()
|
||||
};
|
||||
|
||||
let error = build_config(overrides.clone())
|
||||
.await
|
||||
.expect_err("synthetic headless approval policy should fail");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("`approval_policy = \"never\"` cannot be used")
|
||||
);
|
||||
|
||||
let config = build_exec_config(
|
||||
overrides,
|
||||
/*preserve_headless_approval_policy*/ false,
|
||||
build_config,
|
||||
)
|
||||
.await
|
||||
.expect("auto-review config should retry without the synthetic approval policy");
|
||||
|
||||
assert_eq!(
|
||||
config.permissions.approval_policy.value(),
|
||||
AskForApproval::OnRequest
|
||||
);
|
||||
assert_eq!(config.approvals_reviewer, ApprovalsReviewer::AutoReview);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_exec_config_preserves_headless_error_when_retry_fails() {
|
||||
let overrides = ConfigOverrides {
|
||||
approval_policy: Some(AskForApproval::Never),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let error = build_exec_config(
|
||||
overrides,
|
||||
/*preserve_headless_approval_policy*/ false,
|
||||
|overrides| async move {
|
||||
let message = if overrides.approval_policy == Some(AskForApproval::Never) {
|
||||
"headless error"
|
||||
} else {
|
||||
"retry error"
|
||||
};
|
||||
Err(std::io::Error::other(message))
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("failed speculative retry should preserve the original error");
|
||||
|
||||
assert_eq!(error.to_string(), "headless error");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_start_params_match_history_to_persistence() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config");
|
||||
|
||||
let params = thread_start_params_from_config(&config, &ThreadSource::User);
|
||||
|
||||
assert_eq!(
|
||||
params.thread_source,
|
||||
Some(codex_app_server_protocol::ThreadSource::User)
|
||||
);
|
||||
assert_eq!(params.history_mode, Some(ThreadHistoryMode::Paginated));
|
||||
|
||||
let thread_source = ThreadSource::Feature("automated_review".to_string());
|
||||
let params = thread_start_params_from_config(&config, &thread_source);
|
||||
assert_eq!(params.thread_source, Some(thread_source));
|
||||
|
||||
config.ephemeral = true;
|
||||
let params = thread_start_params_from_config(&config, &ThreadSource::User);
|
||||
|
||||
assert_eq!(params.ephemeral, Some(true));
|
||||
assert_eq!(params.history_mode, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_lifecycle_params_preserve_hook_trust_bypass() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
bypass_hook_trust: Some(true),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with hook trust bypass");
|
||||
let expected_config = Some(HashMap::from([(
|
||||
"bypass_hook_trust".to_string(),
|
||||
serde_json::Value::Bool(true),
|
||||
)]));
|
||||
|
||||
let start_params = thread_start_params_from_config(&config, &ThreadSource::User);
|
||||
let resume_params = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(start_params.config, expected_config);
|
||||
assert_eq!(resume_params.config, expected_config);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_profile_selection_uses_profile_id_only() {
|
||||
let selection = permission_profile_id_from_active_profile(ActivePermissionProfile::new(
|
||||
BUILT_IN_PERMISSION_PROFILE_WORKSPACE,
|
||||
));
|
||||
|
||||
assert_eq!(selection, BUILT_IN_PERMISSION_PROFILE_WORKSPACE.to_string());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_lifecycle_params_include_legacy_sandbox_when_no_active_profile() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.harness_overrides(ConfigOverrides {
|
||||
sandbox_mode: Some(SandboxMode::DangerFullAccess),
|
||||
..Default::default()
|
||||
})
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config with legacy sandbox override");
|
||||
|
||||
let start_params = thread_start_params_from_config(&config, &ThreadSource::User);
|
||||
let resume_params = thread_resume_params_from_config(
|
||||
&config,
|
||||
"thread-id".to_string(),
|
||||
/*approvals_reviewer_override*/ None,
|
||||
);
|
||||
|
||||
assert_eq!(config.permissions.active_permission_profile(), None);
|
||||
assert_eq!(
|
||||
start_params.sandbox,
|
||||
Some(codex_app_server_protocol::SandboxMode::DangerFullAccess)
|
||||
);
|
||||
assert_eq!(start_params.permissions, None);
|
||||
assert_eq!(
|
||||
resume_params.sandbox,
|
||||
Some(codex_app_server_protocol::SandboxMode::DangerFullAccess)
|
||||
);
|
||||
assert_eq!(resume_params.permissions, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_configured_from_thread_response_uses_review_policy_from_response() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config");
|
||||
let response = sample_thread_start_response();
|
||||
|
||||
let event = session_configured_from_thread_start_response(&response, &config)
|
||||
.expect("build bootstrap session configured event");
|
||||
|
||||
assert_eq!(
|
||||
event.session_id.to_string(),
|
||||
"67e55044-10b1-426f-9247-bb680e5fe0c7"
|
||||
);
|
||||
assert_eq!(
|
||||
event.thread_id.to_string(),
|
||||
"67e55044-10b1-426f-9247-bb680e5fe0c8"
|
||||
);
|
||||
assert_eq!(event.approvals_reviewer, ApprovalsReviewer::AutoReview);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_configured_from_thread_response_uses_permission_profile_from_config() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config");
|
||||
let response = sample_thread_start_response();
|
||||
|
||||
let event = session_configured_from_thread_start_response(&response, &config)
|
||||
.expect("build bootstrap session configured event");
|
||||
|
||||
assert_eq!(
|
||||
event.permission_profile,
|
||||
config.permissions.effective_permission_profile()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_configured_from_thread_response_preserves_thread_source() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config");
|
||||
let response = sample_thread_start_response();
|
||||
|
||||
let event = session_configured_from_thread_start_response(&response, &config)
|
||||
.expect("build bootstrap session configured event");
|
||||
|
||||
assert_eq!(
|
||||
event.thread_source,
|
||||
Some(codex_protocol::protocol::ThreadSource::User)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn session_configured_from_thread_response_preserves_parent_thread_id() {
|
||||
let codex_home = tempdir().expect("create temp codex home");
|
||||
let cwd = tempdir().expect("create temp cwd");
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(cwd.path().to_path_buf()))
|
||||
.build()
|
||||
.await
|
||||
.expect("build config");
|
||||
let parent_thread_id = ThreadId::new();
|
||||
let forked_from_id = ThreadId::new();
|
||||
let mut response = sample_thread_start_response();
|
||||
response.thread.parent_thread_id = Some(parent_thread_id.to_string());
|
||||
response.thread.forked_from_id = Some(forked_from_id.to_string());
|
||||
|
||||
let event = session_configured_from_thread_start_response(&response, &config)
|
||||
.expect("build bootstrap session configured event");
|
||||
|
||||
assert_eq!(event.parent_thread_id, Some(parent_thread_id));
|
||||
assert_eq!(event.forked_from_id, Some(forked_from_id));
|
||||
}
|
||||
|
||||
fn sample_thread_start_response() -> ThreadStartResponse {
|
||||
ThreadStartResponse {
|
||||
disabled_plugin_ids: Vec::new(),
|
||||
thread: codex_app_server_protocol::Thread {
|
||||
originator: None,
|
||||
environments: None,
|
||||
id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
|
||||
extra: None,
|
||||
session_id: "67e55044-10b1-426f-9247-bb680e5fe0c7".to_string(),
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
section: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
history_mode: Default::default(),
|
||||
model_provider: "openai".to_string(),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
recency_at: Some(0),
|
||||
status: codex_app_server_protocol::ThreadStatus::Idle,
|
||||
path: Some(PathBuf::from("/tmp/rollout.jsonl")),
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source: codex_app_server_protocol::SessionSource::Cli,
|
||||
can_accept_direct_input: None,
|
||||
thread_source: Some(codex_app_server_protocol::ThreadSource::User),
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: Some("thread".to_string()),
|
||||
turns: vec![],
|
||||
},
|
||||
model: "gpt-5.4".to_string(),
|
||||
model_provider: "openai".to_string(),
|
||||
service_tier: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
runtime_workspace_roots: Vec::new(),
|
||||
instruction_sources: Vec::new(),
|
||||
approval_policy: codex_app_server_protocol::AskForApproval::OnRequest,
|
||||
approvals_reviewer: codex_app_server_protocol::ApprovalsReviewer::AutoReview,
|
||||
sandbox: codex_app_server_protocol::SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots: vec![],
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: false,
|
||||
exclude_slash_tmp: false,
|
||||
},
|
||||
active_permission_profile: None,
|
||||
reasoning_effort: None,
|
||||
multi_agent_mode: Default::default(),
|
||||
}
|
||||
}
|
||||
48
codex-rs/exec/src/main.rs
Normal file
48
codex-rs/exec/src/main.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
// Release builds exceed rustc's default query depth when laying out the async
|
||||
// MessageProcessor::handle_initialized_client_request future.
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
//! Entry-point for the `codex-exec` binary.
|
||||
//!
|
||||
//! When this CLI is invoked normally, it parses the standard `codex-exec` CLI
|
||||
//! options and launches the non-interactive Codex agent. However, if it is
|
||||
//! invoked with arg0 as `codex-linux-sandbox`, we instead treat the invocation
|
||||
//! as a request to run the logic for the standalone `codex-linux-sandbox`
|
||||
//! executable (i.e., parse any -s args and then run a *sandboxed* command under
|
||||
//! Landlock + seccomp.
|
||||
//!
|
||||
//! This allows us to ship a completely separate set of functionality as part
|
||||
//! of the `codex-exec` binary.
|
||||
use clap::Parser;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_arg0::arg0_dispatch_or_else;
|
||||
use codex_exec::Cli;
|
||||
use codex_exec::run_main;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
struct TopCli {
|
||||
#[clap(flatten)]
|
||||
config_overrides: CliConfigOverrides,
|
||||
|
||||
#[clap(flatten)]
|
||||
inner: Cli,
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
arg0_dispatch_or_else(|arg0_paths: Arg0DispatchPaths| async move {
|
||||
let top_cli = TopCli::parse();
|
||||
// Merge root-level overrides into inner CLI struct so downstream logic remains unchanged.
|
||||
let mut inner = top_cli.inner;
|
||||
inner
|
||||
.config_overrides
|
||||
.prepend_root_overrides(top_cli.config_overrides);
|
||||
|
||||
run_main(inner, arg0_paths).await?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "main_tests.rs"]
|
||||
mod tests;
|
||||
43
codex-rs/exec/src/main_tests.rs
Normal file
43
codex-rs/exec/src/main_tests.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn top_cli_parses_resume_prompt_after_config_flag() {
|
||||
const PROMPT: &str = "echo resume-with-global-flags-after-subcommand";
|
||||
let cli = TopCli::parse_from([
|
||||
"codex-exec",
|
||||
"resume",
|
||||
"--strict-config",
|
||||
"--last",
|
||||
"--json",
|
||||
"--model",
|
||||
"gpt-5.2-codex",
|
||||
"--config",
|
||||
"reasoning_level=xhigh",
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"--skip-git-repo-check",
|
||||
PROMPT,
|
||||
]);
|
||||
let mut inner = cli.inner;
|
||||
inner
|
||||
.config_overrides
|
||||
.prepend_root_overrides(cli.config_overrides);
|
||||
|
||||
let Some(codex_exec::Command::Resume(args)) = inner.command.as_ref() else {
|
||||
panic!("expected resume command");
|
||||
};
|
||||
let effective_prompt = args.prompt.clone().or_else(|| {
|
||||
if args.last {
|
||||
args.session_id.clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
assert_eq!(effective_prompt.as_deref(), Some(PROMPT));
|
||||
assert_eq!(inner.config_overrides.raw_overrides.len(), 1);
|
||||
assert_eq!(
|
||||
inner.config_overrides.raw_overrides[0],
|
||||
"reasoning_level=xhigh"
|
||||
);
|
||||
assert!(inner.strict_config);
|
||||
}
|
||||
89
codex-rs/exec/src/worktree.rs
Normal file
89
codex-rs/exec/src/worktree.rs
Normal file
@@ -0,0 +1,89 @@
|
||||
//! Resolves managed fork sources through the existing name/ID lookup before final configuration.
|
||||
//! The temporary app-server never starts a thread or executes a turn.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) struct ForkNetwork {
|
||||
pub cloud_config_bundle: CloudConfigBundleLoader,
|
||||
pub policy: codex_app_server_client::EmbeddedNetworkPolicy,
|
||||
}
|
||||
|
||||
pub(super) async fn fork_source(
|
||||
args: &mut crate::cli::ForkArgs,
|
||||
config: &Config,
|
||||
arg0_paths: &Arg0DispatchPaths,
|
||||
cli_overrides: &[(String, codex_config::TomlValue)],
|
||||
loader_overrides: &LoaderOverrides,
|
||||
network: ForkNetwork,
|
||||
strict_config: bool,
|
||||
) -> anyhow::Result<std::path::PathBuf> {
|
||||
let state_db = codex_core::init_state_db(config).await;
|
||||
let environment_manager = EnvironmentManager::from_codex_home(
|
||||
config.codex_home.clone(),
|
||||
Some(ExecServerRuntimeOptions::from_optional_paths(
|
||||
arg0_paths.codex_self_exe.clone(),
|
||||
arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
)?),
|
||||
network.policy.bind(config.http_client_factory()),
|
||||
)
|
||||
.await?;
|
||||
let client = InProcessAppServerClient::start(InProcessClientStartArgs {
|
||||
required_human_approval: false,
|
||||
arg0_paths: arg0_paths.clone(),
|
||||
config: std::sync::Arc::new(config.clone()),
|
||||
cli_overrides: cli_overrides.to_vec(),
|
||||
loader_overrides: LoaderOverrides {
|
||||
ignore_project_config: true,
|
||||
..loader_overrides.clone()
|
||||
},
|
||||
strict_config,
|
||||
cloud_config_bundle: network.cloud_config_bundle,
|
||||
embedded_network_policy: network.policy,
|
||||
feedback: CodexFeedback::new(),
|
||||
log_db: None,
|
||||
state_db: state_db.clone(),
|
||||
environment_manager: std::sync::Arc::new(environment_manager),
|
||||
config_warnings: Vec::new(),
|
||||
session_source: SessionSource::Exec,
|
||||
enable_codex_api_key_env: true,
|
||||
client_name: "codex_exec".to_string(),
|
||||
client_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
experimental_api: true,
|
||||
mcp_server_openai_form_elicitation: false,
|
||||
opt_out_notification_methods: Vec::new(),
|
||||
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
|
||||
})
|
||||
.await?;
|
||||
let result = async {
|
||||
let lookup = crate::cli::ResumeArgs {
|
||||
session_id: Some(args.session_id.clone()),
|
||||
last: false,
|
||||
all: true,
|
||||
images: Vec::new(),
|
||||
prompt: None,
|
||||
};
|
||||
let thread_id = resolve_resume_thread_id(&client, config, state_db.as_ref(), &lookup)
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Session not found: {}", args.session_id))?;
|
||||
let source: ThreadReadResponse = send_request_with_response(
|
||||
&client,
|
||||
ClientRequest::ThreadRead {
|
||||
request_id: RequestId::Integer(1),
|
||||
params: ThreadReadParams {
|
||||
thread_id: thread_id.clone(),
|
||||
include_turns: false,
|
||||
},
|
||||
},
|
||||
"thread/read",
|
||||
)
|
||||
.await
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
args.session_id = thread_id;
|
||||
Ok::<_, anyhow::Error>(latest_thread_cwd(&source.thread).await)
|
||||
}
|
||||
.await;
|
||||
let shutdown = client.shutdown().await;
|
||||
let source_cwd = result?;
|
||||
shutdown?;
|
||||
Ok(source_cwd)
|
||||
}
|
||||
Reference in New Issue
Block a user