Vendor Codex and land Phase 1 Epiphany state slice
This commit is contained in:
parent
130e074c69
commit
2042687e30
3959 changed files with 953751 additions and 7 deletions
285
vendor/codex/codex-rs/exec/src/cli.rs
vendored
Normal file
285
vendor/codex/codex-rs/exec/src/cli.rs
vendored
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
use clap::Args;
|
||||
use clap::FromArgMatches;
|
||||
use clap::Parser;
|
||||
use clap::ValueEnum;
|
||||
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>,
|
||||
|
||||
#[clap(flatten)]
|
||||
pub shared: ExecSharedCliOptions,
|
||||
|
||||
/// 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,
|
||||
|
||||
/// 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")]
|
||||
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>,
|
||||
}
|
||||
|
||||
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("full_auto", |arg| arg.global(true))
|
||||
.mut_arg("dangerously_bypass_approvals_and_sandbox", |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),
|
||||
|
||||
/// Run a code review against the current repository.
|
||||
Review(ReviewArgs),
|
||||
}
|
||||
|
||||
#[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(Parser, 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;
|
||||
72
vendor/codex/codex-rs/exec/src/cli_tests.rs
vendored
Normal file
72
vendor/codex/codex-rs/exec/src/cli_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
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",
|
||||
"--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);
|
||||
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_last_message_flag_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",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
cli.last_message_file,
|
||||
Some(PathBuf::from("/tmp/resume-output.md"))
|
||||
);
|
||||
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 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);
|
||||
}
|
||||
48
vendor/codex/codex-rs/exec/src/event_processor.rs
vendored
Normal file
48
vendor/codex/codex-rs/exec/src/event_processor.rs
vendored
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
use std::path::Path;
|
||||
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_core::config::Config;
|
||||
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) {}
|
||||
}
|
||||
|
||||
pub(crate) fn handle_last_message(last_agent_message: Option<&str>, output_file: &Path) {
|
||||
let message = last_agent_message.unwrap_or_default();
|
||||
write_last_message_file(message, Some(output_file));
|
||||
if last_agent_message.is_none() {
|
||||
eprintln!(
|
||||
"Warning: no last agent message; wrote empty content to {}",
|
||||
output_file.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_last_message_file(contents: &str, last_message_path: Option<&Path>) {
|
||||
if let Some(path) = last_message_path
|
||||
&& let Err(e) = std::fs::write(path, contents)
|
||||
{
|
||||
eprintln!("Failed to write last message file {path:?}: {e}");
|
||||
}
|
||||
}
|
||||
568
vendor/codex/codex-rs/exec/src/event_processor_with_human_output.rs
vendored
Normal file
568
vendor/codex/codex-rs/exec/src/event_processor_with_human_output.rs
vendored
Normal file
|
|
@ -0,0 +1,568 @@
|
|||
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::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadTokenUsage;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::config::Config;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use codex_protocol::num_format::format_with_separators;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionConfiguredEvent;
|
||||
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>,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
fn render_item_started(&self, item: &ThreadItem) {
|
||||
match item {
|
||||
ThreadItem::CommandExecution { command, cwd, .. } => {
|
||||
eprintln!(
|
||||
"{}\n{} in {}",
|
||||
"exec".style(self.italic).style(self.magenta),
|
||||
command.style(self.bold),
|
||||
cwd.display()
|
||||
);
|
||||
}
|
||||
ThreadItem::McpToolCall { server, tool, .. } => {
|
||||
eprintln!(
|
||||
"{} {} {}",
|
||||
"mcp:".style(self.bold),
|
||||
format!("{server}/{tool}").style(self.cyan),
|
||||
"started".style(self.dimmed)
|
||||
);
|
||||
}
|
||||
ThreadItem::WebSearch { query, .. } => {
|
||||
eprintln!("{} {}", "web search:".style(self.bold), query);
|
||||
}
|
||||
ThreadItem::FileChange { .. } => {
|
||||
eprintln!("{}", "apply patch".style(self.bold));
|
||||
}
|
||||
ThreadItem::CollabAgentToolCall { tool, .. } => {
|
||||
eprintln!("{} {:?}", "collab:".style(self.bold), tool);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_item_completed(&mut self, item: ThreadItem) {
|
||||
match item {
|
||||
ThreadItem::AgentMessage { text, .. } => {
|
||||
eprintln!(
|
||||
"{}\n{}",
|
||||
"codex".style(self.italic).style(self.magenta),
|
||||
text
|
||||
);
|
||||
self.final_message = Some(text);
|
||||
self.final_message_rendered = true;
|
||||
}
|
||||
ThreadItem::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));
|
||||
}
|
||||
}
|
||||
ThreadItem::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}");
|
||||
}
|
||||
}
|
||||
ThreadItem::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));
|
||||
}
|
||||
}
|
||||
ThreadItem::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));
|
||||
}
|
||||
}
|
||||
ThreadItem::WebSearch { query, .. } => {
|
||||
eprintln!("{} {}", "web search:".style(self.bold), query);
|
||||
}
|
||||
ThreadItem::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} (research preview)\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::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);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => {
|
||||
self.render_item_completed(notification.item);
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ModelRerouted(notification) => {
|
||||
eprintln!(
|
||||
"{} {} -> {}",
|
||||
"model rerouted:".style(self.yellow).style(self.bold),
|
||||
notification.from_model,
|
||||
notification.to_model
|
||||
);
|
||||
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.trim().is_empty() {
|
||||
eprintln!("{}", 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(_) => 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) {
|
||||
if self.emit_final_message_on_shutdown
|
||||
&& let Some(path) = self.last_message_path.as_deref()
|
||||
{
|
||||
handle_last_message(self.final_message.as_deref(), path);
|
||||
}
|
||||
|
||||
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 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 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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn config_summary_entries(
|
||||
config: &Config,
|
||||
session_configured_event: &SessionConfiguredEvent,
|
||||
) -> Vec<(&'static str, String)> {
|
||||
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_sandbox_policy(config.permissions.sandbox_policy.get()),
|
||||
),
|
||||
];
|
||||
if config.model_provider.wire_api == WireApi::Responses {
|
||||
entries.push((
|
||||
"reasoning effort",
|
||||
config
|
||||
.model_reasoning_effort
|
||||
.map(|effort| effort.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 summarize_sandbox_policy(sandbox_policy: &SandboxPolicy) -> String {
|
||||
match sandbox_policy {
|
||||
SandboxPolicy::DangerFullAccess => "danger-full-access".to_string(),
|
||||
SandboxPolicy::ReadOnly { network_access, .. } => {
|
||||
let mut summary = "read-only".to_string();
|
||||
if *network_access {
|
||||
summary.push_str(" (network access enabled)");
|
||||
}
|
||||
summary
|
||||
}
|
||||
SandboxPolicy::ExternalSandbox { network_access } => {
|
||||
let mut summary = "external-sandbox".to_string();
|
||||
if matches!(
|
||||
network_access,
|
||||
codex_protocol::protocol::NetworkAccess::Enabled
|
||||
) {
|
||||
summary.push_str(" (network access enabled)");
|
||||
}
|
||||
summary
|
||||
}
|
||||
SandboxPolicy::WorkspaceWrite {
|
||||
writable_roots,
|
||||
network_access,
|
||||
exclude_tmpdir_env_var,
|
||||
exclude_slash_tmp,
|
||||
read_only_access: _,
|
||||
} => {
|
||||
let mut summary = "workspace-write".to_string();
|
||||
let mut writable_entries = vec!["workdir".to_string()];
|
||||
if !*exclude_slash_tmp {
|
||||
writable_entries.push("/tmp".to_string());
|
||||
}
|
||||
if !*exclude_tmpdir_env_var {
|
||||
writable_entries.push("$TMPDIR".to_string());
|
||||
}
|
||||
writable_entries.extend(
|
||||
writable_roots
|
||||
.iter()
|
||||
.map(|path| path.to_string_lossy().to_string()),
|
||||
);
|
||||
summary.push_str(&format!(" [{}]", writable_entries.join(", ")));
|
||||
if *network_access {
|
||||
summary.push_str(" (network access enabled)");
|
||||
}
|
||||
summary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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: &[ThreadItem]) -> Option<String> {
|
||||
items
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| match item {
|
||||
ThreadItem::AgentMessage { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().rev().find_map(|item| match item {
|
||||
ThreadItem::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;
|
||||
361
vendor/codex/codex-rs/exec/src/event_processor_with_human_output_tests.rs
vendored
Normal file
361
vendor/codex/codex-rs/exec/src/event_processor_with_human_output_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use owo_colors::Style;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::EventProcessorWithHumanOutput;
|
||||
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 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 final_message_from_turn_items_uses_latest_agent_message() {
|
||||
let message = final_message_from_turn_items(&[
|
||||
ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "first".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
},
|
||||
ThreadItem::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "plan".to_string(),
|
||||
},
|
||||
ThreadItem::AgentMessage {
|
||||
id: "msg-2".to_string(),
|
||||
text: "second".to_string(),
|
||||
phase: None,
|
||||
memory_citation: 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(&[
|
||||
ThreadItem::Reasoning {
|
||||
id: "reasoning-1".to_string(),
|
||||
summary: vec!["inspect".to_string()],
|
||||
content: Vec::new(),
|
||||
},
|
||||
ThreadItem::Plan {
|
||||
id: "plan-1".to_string(),
|
||||
text: "first plan".to_string(),
|
||||
},
|
||||
ThreadItem::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,
|
||||
};
|
||||
|
||||
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(),
|
||||
items: vec![ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "final answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: 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,
|
||||
};
|
||||
|
||||
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(),
|
||||
items: vec![ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "final answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: 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,
|
||||
};
|
||||
|
||||
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(),
|
||||
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,
|
||||
};
|
||||
|
||||
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(),
|
||||
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,
|
||||
};
|
||||
|
||||
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(),
|
||||
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);
|
||||
}
|
||||
625
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output.rs
vendored
Normal file
625
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output.rs
vendored
Normal file
|
|
@ -0,0 +1,625 @@
|
|||
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::ThreadItem;
|
||||
use codex_app_server_protocol::ThreadTokenUsage;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_core::config::Config;
|
||||
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,
|
||||
output_tokens: usage.total.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: ThreadItem,
|
||||
make_id: impl FnOnce() -> String,
|
||||
) -> Option<ExecThreadItem> {
|
||||
match item {
|
||||
ThreadItem::AgentMessage { text, .. } => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::AgentMessage(AgentMessageItem { text }),
|
||||
}),
|
||||
ThreadItem::Reasoning { summary, .. } => {
|
||||
let text = summary.join("\n");
|
||||
if text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::Reasoning(ReasoningItem { text }),
|
||||
})
|
||||
}
|
||||
ThreadItem::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,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItem::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
|
||||
}
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItem::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,
|
||||
structured_content: result.structured_content,
|
||||
}),
|
||||
error: error.map(|error| McpToolCallItemError {
|
||||
message: error.message,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
ThreadItem::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::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,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
ThreadItem::WebSearch {
|
||||
id: raw_id,
|
||||
query,
|
||||
action,
|
||||
} => Some(ExecThreadItem {
|
||||
id: make_id(),
|
||||
details: ThreadItemDetails::WebSearch(WebSearchItem {
|
||||
id: raw_id,
|
||||
query,
|
||||
action: match action {
|
||||
Some(action) => serde_json::from_value(
|
||||
serde_json::to_value(action).unwrap_or_else(|_| json!("other")),
|
||||
)
|
||||
.unwrap_or(WebSearchAction::Other),
|
||||
None => WebSearchAction::Other,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
_ => 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: ThreadItem) -> Option<ExecThreadItem> {
|
||||
match item {
|
||||
ThreadItem::AgentMessage { .. } | ThreadItem::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: ThreadItem) -> Option<ExecThreadItem> {
|
||||
if let ThreadItem::Reasoning { summary, .. } = &item
|
||||
&& summary.join("\n").trim().is_empty()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
match &item {
|
||||
ThreadItem::AgentMessage { .. } | ThreadItem::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: &[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.clone())
|
||||
.map(|item| ThreadEvent::ItemCompleted(ItemCompletedEvent { item }))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn final_message_from_turn_items(items: &[ThreadItem]) -> Option<String> {
|
||||
items
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|item| match item {
|
||||
ThreadItem::AgentMessage { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.or_else(|| {
|
||||
items.iter().rev().find_map(|item| match item {
|
||||
ThreadItem::Plan { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn thread_started_event(session_configured: &SessionConfiguredEvent) -> ThreadEvent {
|
||||
ThreadEvent::ThreadStarted(ThreadStartedEvent {
|
||||
thread_id: session_configured.session_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::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) {
|
||||
events.push(ThreadEvent::ItemStarted(ItemStartedEvent { item }));
|
||||
}
|
||||
CodexStatus::Running
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => {
|
||||
if let Some(item) = self.map_completed_item_mut(notification.item) {
|
||||
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::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) {
|
||||
if self.emit_final_message_on_shutdown
|
||||
&& let Some(path) = self.last_message_path.as_deref()
|
||||
{
|
||||
handle_last_message(self.final_message.as_deref(), path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "event_processor_with_jsonl_output_tests.rs"]
|
||||
mod tests;
|
||||
57
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs
vendored
Normal file
57
vendor/codex/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
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 {
|
||||
item: ThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "partial answer".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
},
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: "turn-1".to_string(),
|
||||
},
|
||||
));
|
||||
|
||||
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(),
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Failed,
|
||||
error: Some(codex_app_server_protocol::TurnError {
|
||||
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);
|
||||
|
||||
EventProcessor::print_final_output(&mut processor);
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&output_path).expect("read output file"),
|
||||
"keep existing contents"
|
||||
);
|
||||
}
|
||||
312
vendor/codex/codex-rs/exec/src/exec_events.rs
vendored
Normal file
312
vendor/codex/codex-rs/exec/src/exec_events.rs
vendored
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
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 output tokens used during the turn.
|
||||
pub 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>,
|
||||
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,
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
}
|
||||
1799
vendor/codex/codex-rs/exec/src/lib.rs
vendored
Normal file
1799
vendor/codex/codex-rs/exec/src/lib.rs
vendored
Normal file
File diff suppressed because it is too large
Load diff
444
vendor/codex/codex-rs/exec/src/lib_tests.rs
vendored
Normal file
444
vendor/codex/codex-rs/exec/src/lib_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,444 @@
|
|||
use super::*;
|
||||
use codex_otel::set_parent_from_w3c_trace_context;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
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 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))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_defaults_analytics_to_enabled() {
|
||||
assert_eq!(DEFAULT_ANALYTICS_ENABLED, true);
|
||||
}
|
||||
|
||||
#[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()
|
||||
);
|
||||
}
|
||||
|
||||
#[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 {
|
||||
id: "thread-1".to_string(),
|
||||
forked_from_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 0,
|
||||
updated_at: 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(),
|
||||
source: codex_app_server_protocol::SessionSource::Exec,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: None,
|
||||
turns: vec![
|
||||
codex_app_server_protocol::Turn {
|
||||
id: "turn-1".to_string(),
|
||||
items: vec![AppServerThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "hello".to_string(),
|
||||
phase: None,
|
||||
memory_citation: 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(),
|
||||
items: vec![AppServerThreadItem::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![AppServerThreadItem::AgentMessage {
|
||||
id: "msg-1".to_string(),
|
||||
text: "hello".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
}])
|
||||
);
|
||||
assert_eq!(turn_items_for_thread(&thread, "missing-turn"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_backfill_turn_completed_items_skips_ephemeral_threads() {
|
||||
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(),
|
||||
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
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canceled_mcp_server_elicitation_response_uses_cancel_action() {
|
||||
let value = canceled_mcp_server_elicitation_response()
|
||||
.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: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[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()
|
||||
.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);
|
||||
|
||||
assert_eq!(
|
||||
params.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::User)
|
||||
);
|
||||
assert_eq!(params.sandbox, None);
|
||||
assert_eq!(
|
||||
params.permission_profile,
|
||||
Some(config.permissions.permission_profile().into())
|
||||
);
|
||||
}
|
||||
|
||||
#[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);
|
||||
|
||||
assert_eq!(
|
||||
params.approvals_reviewer,
|
||||
Some(codex_app_server_protocol::ApprovalsReviewer::AutoReview)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_configured_from_thread_response_uses_review_policy_from_response() {
|
||||
let response = ThreadStartResponse {
|
||||
thread: codex_app_server_protocol::Thread {
|
||||
id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
|
||||
forked_from_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
model_provider: "openai".to_string(),
|
||||
created_at: 0,
|
||||
updated_at: 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,
|
||||
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(),
|
||||
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![],
|
||||
read_only_access: codex_app_server_protocol::ReadOnlyAccess::FullAccess,
|
||||
network_access: false,
|
||||
exclude_tmpdir_env_var: false,
|
||||
exclude_slash_tmp: false,
|
||||
},
|
||||
permission_profile: Some(
|
||||
codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy(
|
||||
&codex_protocol::protocol::SandboxPolicy::new_workspace_write_policy(),
|
||||
&test_path_buf("/tmp"),
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
reasoning_effort: None,
|
||||
};
|
||||
|
||||
let event = session_configured_from_thread_start_response(&response)
|
||||
.expect("build bootstrap session configured event");
|
||||
|
||||
assert_eq!(event.approvals_reviewer, ApprovalsReviewer::AutoReview);
|
||||
}
|
||||
45
vendor/codex/codex-rs/exec/src/main.rs
vendored
Normal file
45
vendor/codex/codex-rs/exec/src/main.rs
vendored
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
//! 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
|
||||
.raw_overrides
|
||||
.splice(0..0, top_cli.config_overrides.raw_overrides);
|
||||
|
||||
run_main(inner, arg0_paths).await?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "main_tests.rs"]
|
||||
mod tests;
|
||||
37
vendor/codex/codex-rs/exec/src/main_tests.rs
vendored
Normal file
37
vendor/codex/codex-rs/exec/src/main_tests.rs
vendored
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
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",
|
||||
"--last",
|
||||
"--json",
|
||||
"--model",
|
||||
"gpt-5.2-codex",
|
||||
"--config",
|
||||
"reasoning_level=xhigh",
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"--skip-git-repo-check",
|
||||
PROMPT,
|
||||
]);
|
||||
|
||||
let Some(codex_exec::Command::Resume(args)) = cli.inner.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));
|
||||
assert_eq!(cli.config_overrides.raw_overrides.len(), 1);
|
||||
assert_eq!(
|
||||
cli.config_overrides.raw_overrides[0],
|
||||
"reasoning_level=xhigh"
|
||||
);
|
||||
}
|
||||
Reference in a new issue