Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 73 additions & 12 deletions src/harness/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,17 +331,16 @@ fn lines_to_messages(lines: &[Line], fallback_ts: DateTime<Utc>) -> Vec<Message>
.and_then(Value::as_str)
.map(String::from)
{
let content = payload
.get("output")
.and_then(Value::as_str)
.map_or(ToolOutput::Text(String::new()), |s| {
ToolOutput::Text(s.to_string())
});
let (content, is_error) = match payload.get("output") {
Some(Value::String(s)) => (ToolOutput::Text(s.clone()), false),
Some(Value::Array(items)) => parse_content_items_output(items),
_ => (ToolOutput::Text(String::new()), false),
};
queued.push(tool_result(
ts,
result_key(&call_id),
content,
false,
is_error,
true,
));
}
Expand Down Expand Up @@ -382,11 +381,15 @@ fn lines_to_messages(lines: &[Line], fallback_ts: DateTime<Utc>) -> Vec<Message>
.and_then(Value::as_str)
.map(String::from)
{
let raw = payload
.get("output")
.and_then(Value::as_str)
.unwrap_or_default();
let (content, is_error) = parse_custom_tool_output(raw);
// Code mode (`exec`) writes the output as an
// array of `input_text` content items rather
// than a string; reading only strings dropped
// the whole result.
let (content, is_error) = match payload.get("output") {
Some(Value::String(raw)) => parse_custom_tool_output(raw),
Some(Value::Array(items)) => parse_content_items_output(items),
_ => parse_custom_tool_output(""),
};
canonical_results.insert(result_key(&call_id));
queued.push(tool_result(
ts,
Expand Down Expand Up @@ -1654,6 +1657,64 @@ fn format_exec_output(payload: &Value) -> String {
}
}

/// A tool output written as a list of content items (`input_text`,
/// `output_text`, `input_image`, ...). All-text lists collapse to their text,
/// one item per line; anything else is kept verbatim as JSON so no part of the
/// result is lost.
/// Read a content-item list output together with its error bit.
///
/// Codex keeps a call's `success` flag as internal metadata and never writes
/// it to the rollout: a content-item list serializes as the bare array. The
/// only on-disk failure signal is the status header code mode inserts as the
/// first item, `"{status}\nWall time ...\nOutput:\n"`, where `status` is
/// `Script failed` exactly when the script raised (`error_text` is set, so
/// `success` is false). `Script completed`, `Script terminated`, and
/// `Script running with cell ID ...` all carry `success: true`. Lists without
/// that header (MCP results, images) have no error signal and stay
/// non-errors, as string `function_call_output`s do.
fn parse_content_items_output(items: &[Value]) -> (ToolOutput, bool) {
let is_error = items.first().is_some_and(|first| {
first.get("type").and_then(Value::as_str) == Some("input_text")
&& first
.get("text")
.and_then(Value::as_str)
.is_some_and(is_failed_script_header)
});
(content_items_output(items), is_error)
}

/// `Script failed\nWall time <timing> seconds[ (...)]\nOutput:\n`, the
/// whole item and nothing else, so script output that merely starts with
/// those words is not mistaken for the header.
fn is_failed_script_header(text: &str) -> bool {
text.strip_prefix("Script failed\nWall time ")
.and_then(|rest| rest.strip_suffix("\nOutput:\n"))
.is_some_and(|timing| !timing.contains('\n') && timing.contains(" seconds"))
}

fn content_items_output(items: &[Value]) -> ToolOutput {
let texts: Option<Vec<&str>> = items
.iter()
.map(|item| match item.get("type").and_then(Value::as_str) {
Some("input_text" | "output_text" | "text") => item.get("text").and_then(Value::as_str),
_ => None,
})
.collect();
match texts {
Some(texts) => {
let mut out = String::new();
for text in texts {
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
out.push_str(text);
}
ToolOutput::Text(out)
}
None => ToolOutput::Json(Value::Array(items.to_vec())),
}
}

fn parse_custom_tool_output(raw: &str) -> (ToolOutput, bool) {
match parse_json_string_or_raw(raw) {
Value::Object(ref obj) => {
Expand Down
40 changes: 39 additions & 1 deletion src/harness/opencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ fn parse_tool(part: &Value) -> Option<(Block, Option<Block>)> {
.and_then(|s| s.get("input"))
.cloned()
.unwrap_or(Value::Object(Map::new()));
let raw_input = unwrap_freeform_input(state, raw_input);
let (name, input) = normalize_tool(tool, raw_input);
let use_block = Block::ToolUse {
id: call_id.clone(),
Expand Down Expand Up @@ -567,12 +568,26 @@ fn assistant_part(
Block::ToolUse { id, tool } => {
let (name, input) = tool.to_canonical();
let (oc_name, oc_input) = denormalize_tool(&name, input);
// `opencode import` rejects a non-object `state.input` ("Expected
// object"), and Codex freeform calls (code-mode `exec`,
// `apply_patch`) carry a raw string. Keep the payload inside an
// object, as the Claude Code export does.
// The wrap is flagged in `state.metadata` so the reader can undo
// exactly this wrap and never a genuine `{"input": ...}` input.
let (oc_input, oc_metadata) = if oc_input.is_object() {
(oc_input, json!({}))
} else {
(
json!({ "input": oc_input }),
json!({ (WRAPPED_INPUT_KEY): true }),
)
};
let mut state = json!({
"status": "completed",
"input": oc_input,
"output": "",
"title": oc_name,
"metadata": {},
"metadata": oc_metadata,
"time": time,
});
// Fold the matching ToolResult into state.output.
Expand Down Expand Up @@ -674,6 +689,29 @@ fn normalize_tool(tool: &str, input: Value) -> (String, Value) {
}
}

/// `state.metadata` flag set when the writer wrapped a non-object tool input
/// (for example a Codex code-mode script) as `{"input": <value>}`, since
/// `opencode import` only accepts object inputs.
const WRAPPED_INPUT_KEY: &str = "txcriptWrappedInput";

/// Undo the writer's `{"input": <value>}` wrap. Only parts that carry the
/// metadata flag are unwrapped, and only when the input is still exactly
/// that one-key object: a real tool whose input happens to be
/// `{"input": ...}` has no flag and passes through untouched.
fn unwrap_freeform_input(state: Option<&Value>, input: Value) -> Value {
let flagged = state
.and_then(|s| s.get("metadata"))
.and_then(|m| m.get(WRAPPED_INPUT_KEY))
.and_then(Value::as_bool)
.unwrap_or(false);
match input {
Value::Object(mut obj) if flagged && obj.len() == 1 && obj.contains_key("input") => {
obj.remove("input").unwrap_or(Value::Null)
}
other => other,
}
}

fn denormalize_tool(name: &str, input: Value) -> (String, Value) {
match name {
"Bash" => ("bash".to_string(), input),
Expand Down
Loading
Loading