Allow --output-last-message to print to stdout

This commit is contained in:
pakrym-oai
2025-10-01 18:02:18 -07:00
parent c07fb71186
commit f8f66adeac
9 changed files with 198 additions and 77 deletions
+2 -2
View File
@@ -72,8 +72,8 @@ pub struct Cli {
pub include_plan_tool: bool,
/// Specifies file where the last message from the agent should be written.
#[arg(long = "output-last-message")]
pub last_message_file: Option<PathBuf>,
#[arg(long = "output-last-message", num_args(0..=1))]
pub last_message_file: Option<Option<PathBuf>>,
/// Initial instructions for the agent. If not provided as an argument (or
/// if `-` is used), instructions are read from stdin.
+21 -17
View File
@@ -1,4 +1,4 @@
use std::path::Path;
use std::path::PathBuf;
use codex_core::config::Config;
use codex_core::protocol::Event;
@@ -14,30 +14,34 @@ 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,
);
_config: &Config,
_prompt: &str,
_session_configured: &SessionConfiguredEvent,
) {
}
/// Handle a single event emitted by the agent.
fn process_event(&mut self, event: Event) -> CodexStatus;
}
pub(crate) fn handle_last_message(last_agent_message: Option<&str>, output_file: &Path) {
pub(crate) fn handle_last_message(
last_agent_message: Option<String>,
output_file: Option<Option<PathBuf>>,
) {
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()
);
if message.is_empty() && output_file.is_some() {
eprintln!("Warning: no last agent message; wrote empty content to {output_file:?}");
}
match output_file {
Some(Some(path)) => write_last_message_file(&message, &path),
Some(None) => println!("{message}"),
_ => (),
}
}
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}");
fn write_last_message_file(contents: &str, last_message_path: &PathBuf) {
if let Err(e) = std::fs::write(last_message_path, contents) {
eprintln!("Failed to write last message file {last_message_path:?}: {e}");
}
}
+18
View File
@@ -0,0 +1,18 @@
use codex_core::protocol::Event;
use codex_core::protocol::EventMsg;
use crate::event_processor::CodexStatus;
use crate::event_processor::EventProcessor;
pub(crate) struct EventProcessorNoop {}
impl EventProcessor for EventProcessorNoop {
fn process_event(&mut self, event: Event) -> CodexStatus {
let Event { id: _, msg } = event;
match msg {
EventMsg::ShutdownComplete => CodexStatus::Shutdown,
EventMsg::TaskComplete(_) => CodexStatus::InitiateShutdown,
_ => CodexStatus::Running,
}
}
}
@@ -21,7 +21,6 @@ use codex_core::protocol::PatchApplyBeginEvent;
use codex_core::protocol::PatchApplyEndEvent;
use codex_core::protocol::SessionConfiguredEvent;
use codex_core::protocol::StreamErrorEvent;
use codex_core::protocol::TaskCompleteEvent;
use codex_core::protocol::TurnAbortReason;
use codex_core::protocol::TurnDiffEvent;
use codex_core::protocol::WebSearchBeginEvent;
@@ -32,12 +31,10 @@ use owo_colors::Style;
use shlex::try_join;
use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;
use std::time::Instant;
use crate::event_processor::CodexStatus;
use crate::event_processor::EventProcessor;
use crate::event_processor::handle_last_message;
use codex_common::create_config_summary_entries;
/// This should be configurable. When used in CI, users may not want to impose
@@ -65,15 +62,10 @@ pub(crate) struct EventProcessorWithHumanOutput {
answer_started: bool,
reasoning_started: bool,
raw_reasoning_started: bool,
last_message_path: Option<PathBuf>,
}
impl EventProcessorWithHumanOutput {
pub(crate) fn create_with_ansi(
with_ansi: bool,
config: &Config,
last_message_path: Option<PathBuf>,
) -> Self {
pub(crate) fn create_with_ansi(with_ansi: bool, config: &Config) -> Self {
let call_id_to_command = HashMap::new();
let call_id_to_patch = HashMap::new();
@@ -93,7 +85,6 @@ impl EventProcessorWithHumanOutput {
answer_started: false,
reasoning_started: false,
raw_reasoning_started: false,
last_message_path,
}
} else {
Self {
@@ -111,7 +102,6 @@ impl EventProcessorWithHumanOutput {
answer_started: false,
reasoning_started: false,
raw_reasoning_started: false,
last_message_path,
}
}
}
@@ -184,12 +174,6 @@ impl EventProcessor for EventProcessorWithHumanOutput {
EventMsg::TaskStarted(_) => {
// Ignore.
}
EventMsg::TaskComplete(TaskCompleteEvent { last_agent_message }) => {
if let Some(output_file) = self.last_message_path.as_deref() {
handle_last_message(last_agent_message.as_deref(), output_file);
}
return CodexStatus::InitiateShutdown;
}
EventMsg::TokenCount(ev) => {
if let Some(usage_info) = ev.info {
ts_println!(
@@ -592,6 +576,7 @@ impl EventProcessor for EventProcessorWithHumanOutput {
}
},
EventMsg::ShutdownComplete => return CodexStatus::Shutdown,
EventMsg::TaskComplete(_) => return CodexStatus::InitiateShutdown,
EventMsg::ConversationPath(_) => {}
EventMsg::UserMessage(_) => {}
EventMsg::EnteredReviewMode(_) => {}
@@ -1,10 +1,8 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::AtomicU64;
use crate::event_processor::CodexStatus;
use crate::event_processor::EventProcessor;
use crate::event_processor::handle_last_message;
use crate::exec_events::AssistantMessageItem;
use crate::exec_events::CommandExecutionItem;
use crate::exec_events::CommandExecutionStatus;
@@ -45,14 +43,12 @@ use codex_core::protocol::McpToolCallEndEvent;
use codex_core::protocol::PatchApplyBeginEvent;
use codex_core::protocol::PatchApplyEndEvent;
use codex_core::protocol::SessionConfiguredEvent;
use codex_core::protocol::TaskCompleteEvent;
use codex_core::protocol::TaskStartedEvent;
use codex_core::protocol::WebSearchEndEvent;
use tracing::error;
use tracing::warn;
pub struct EventProcessorWithJsonOutput {
last_message_path: Option<PathBuf>,
next_event_id: AtomicU64,
// Tracks running commands by call_id, including the associated item id.
running_commands: HashMap<String, RunningCommand>,
@@ -84,19 +80,6 @@ struct RunningMcpToolCall {
}
impl EventProcessorWithJsonOutput {
pub fn new(last_message_path: Option<PathBuf>) -> Self {
Self {
last_message_path,
next_event_id: AtomicU64::new(0),
running_commands: HashMap::new(),
running_patch_applies: HashMap::new(),
running_todo_list: None,
last_total_token_usage: None,
running_mcp_tool_calls: HashMap::new(),
last_critical_error: None,
}
}
pub fn collect_thread_events(&mut self, event: &Event) -> Vec<ThreadEvent> {
match &event.msg {
EventMsg::SessionConfigured(ev) => self.handle_session_configured(ev),
@@ -420,6 +403,20 @@ impl EventProcessorWithJsonOutput {
}
}
impl Default for EventProcessorWithJsonOutput {
fn default() -> Self {
Self {
next_event_id: AtomicU64::new(0),
running_commands: HashMap::new(),
running_patch_applies: HashMap::new(),
running_todo_list: None,
last_total_token_usage: None,
running_mcp_tool_calls: HashMap::new(),
last_critical_error: None,
}
}
}
impl EventProcessor for EventProcessorWithJsonOutput {
fn print_config_summary(&mut self, _: &Config, _: &str, ev: &SessionConfiguredEvent) {
self.process_event(Event {
@@ -443,10 +440,7 @@ impl EventProcessor for EventProcessorWithJsonOutput {
let Event { msg, .. } = event;
if let EventMsg::TaskComplete(TaskCompleteEvent { last_agent_message }) = msg {
if let Some(output_file) = self.last_message_path.as_deref() {
handle_last_message(last_agent_message.as_deref(), output_file);
}
if matches!(msg, EventMsg::TaskComplete(_)) {
CodexStatus::InitiateShutdown
} else {
CodexStatus::Running
+15 -2
View File
@@ -1,5 +1,6 @@
mod cli;
mod event_processor;
pub mod event_processor_noop;
mod event_processor_with_human_output;
pub mod event_processor_with_jsonl_output;
pub mod exec_events;
@@ -36,6 +37,8 @@ use tracing_subscriber::prelude::*;
use crate::cli::Command as ExecCommand;
use crate::event_processor::CodexStatus;
use crate::event_processor::EventProcessor;
use crate::event_processor::handle_last_message;
use crate::event_processor_noop::EventProcessorNoop;
use codex_core::default_client::set_default_originator;
use codex_core::find_conversation_path_by_id_str;
@@ -210,14 +213,18 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option<PathBuf>) -> any
}
let mut event_processor: Box<dyn EventProcessor> = match json_mode {
true => Box::new(EventProcessorWithJsonOutput::new(last_message_file.clone())),
true => Box::new(EventProcessorWithJsonOutput::default()),
_ => Box::new(EventProcessorWithHumanOutput::create_with_ansi(
stdout_with_ansi,
&config,
last_message_file.clone(),
)),
};
// Output the last message to stdout
if let Some(None) = last_message_file {
event_processor = Box::new(EventProcessorNoop {});
}
if oss {
codex_ollama::ensure_oss_ready(&config)
.await
@@ -352,10 +359,14 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option<PathBuf>) -> any
// Track whether a fatal error was reported by the server so we can
// exit with a non-zero status for automation-friendly signaling.
let mut error_seen = false;
let mut last_message = None;
while let Some(event) = rx.recv().await {
if matches!(event.msg, EventMsg::Error(_)) {
error_seen = true;
}
if let EventMsg::TaskComplete(TaskCompleteEvent { last_agent_message }) = &event.msg {
last_message = last_agent_message.clone();
}
let shutdown: CodexStatus = event_processor.process_event(event);
match shutdown {
CodexStatus::Running => continue,
@@ -371,6 +382,8 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option<PathBuf>) -> any
std::process::exit(1);
}
handle_last_message(last_message, last_message_file);
Ok(())
}