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
45 changes: 44 additions & 1 deletion src/harness/claude_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ pub(crate) fn messages_to_records(meta: &Meta, messages: &[Message]) -> Vec<Reco
_ => None,
})
.collect();
let response_ids = response_message_ids(&session_id, messages);
let mut parent_uuid: Option<String> = None;
for (i, msg) in messages.iter().enumerate() {
let uuid = entry_uuid(&session_id, i);
Expand Down Expand Up @@ -294,7 +295,10 @@ pub(crate) fn messages_to_records(meta: &Meta, messages: &[Message]) -> Vec<Reco
model: msg.model.clone(),
stop_reason: msg.stop_reason.as_ref().map(stop_reason_str),
usage: msg.usage.as_ref().map(serialize_usage),
extra: Map::new(),
extra: response_ids[i]
.as_ref()
.map(|id| Map::from_iter([("id".to_string(), Value::String(id.clone()))]))
.unwrap_or_default(),
};
let entry = EntryLine {
parent_uuid: parent_uuid.clone(),
Expand Down Expand Up @@ -344,6 +348,45 @@ pub(crate) fn messages_to_records(meta: &Meta, messages: &[Message]) -> Vec<Reco
records
}

/// The `message.id` each assistant line carries, shared by the lines of one
/// model response.
///
/// Claude Code writes a response one content block per line, every line with
/// the response's `message.id`, and on resume merges consecutive assistant
/// lines with the same id back into one API message. Sources that record one
/// block per message (Codex's `function_call` items, Claude Code itself) give
/// a parallel call batch as consecutive assistant messages with every result
/// after them. Written without an id, each call replays as its own assistant
/// message, so the first is no longer followed by its result: Claude Code
/// then swaps that result for "[Tool result missing due to internal error]"
/// and the real output never reaches the model.
///
/// A run of consecutive assistant messages is one response when a tool call
/// sits anywhere before its last message: exactly the runs that would
/// otherwise break. Those lines share a deterministic id; every other line
/// keeps writing none, as before.
fn response_message_ids(session_id: &str, messages: &[Message]) -> Vec<Option<String>> {
let mut ids = vec![None; messages.len()];
let mut start = 0;
while start < messages.len() {
let mut end = start + 1;
if messages[start].role == Role::Assistant {
while end < messages.len() && messages[end].role == Role::Assistant {
end += 1;
}
let calls_before_last = messages[start..end - 1]
.iter()
.any(|m| m.content.iter().any(|b| matches!(b, Block::ToolUse { .. })));
if calls_before_last {
let id = format!("msg_{}", entry_uuid(session_id, start).replace('-', ""));
ids[start..end].fill(Some(id));
}
}
start = end;
}
ids
}

/// Claude Code's native artifact is a normal `Artifact` tool call followed
/// by a tool result. Lower path-backed Common artifacts into that observed
/// shape while leaving the rest of the serializer unchanged.
Expand Down
67 changes: 67 additions & 0 deletions src/harness/pi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,21 @@ pub(crate) fn messages_to_records(meta: &Meta, messages: &[Message]) -> Vec<Reco
let mut tool_names: HashMap<String, String> = HashMap::new();
let mut parent_id: Option<String> = None;

let joins = joins_previous_response(messages);

for (i, msg) in messages.iter().enumerate() {
// Written as part of the response that starts before it.
if joins[i] {
continue;
}
let run_end = i + 1 + joins[i + 1..].iter().take_while(|&&j| j).count();
let merged;
let msg = if run_end > i + 1 {
merged = merge_response(&messages[i..run_end]);
&merged
} else {
msg
};
let ts_iso = msg.timestamp.to_rfc3339_opts(SecondsFormat::Millis, true);
let ts_ms = msg.timestamp.timestamp_millis();
for (j, payload) in pi_payloads_for(msg, ts_ms, &mut tool_names)
Expand All @@ -317,6 +331,59 @@ pub(crate) fn messages_to_records(meta: &Meta, messages: &[Message]) -> Vec<Reco
records
}

/// `joins[i]`: message `i` belongs to the same model response as message
/// `i - 1` and is written into the same pi assistant message.
///
/// Sources that record one block per message (Codex's `function_call` items,
/// Claude Code's one-line-per-block JSONL) give a parallel call batch as
/// consecutive assistant messages with every result after them. pi keeps a
/// response's tool calls in one assistant message; replaying call A in a
/// message of its own, followed by another assistant message, makes pi pair A
/// with a synthetic "No result provided" error and leaves A's real result
/// orphaned. So a run of consecutive assistant messages is one response when
/// a tool call sits anywhere before its last message: exactly the runs pi
/// would otherwise break. Other runs (thinking then text) are left as is.
fn joins_previous_response(messages: &[Message]) -> Vec<bool> {
let mut joins = vec![false; messages.len()];
let mut start = 0;
while start < messages.len() {
let mut end = start + 1;
if messages[start].role == Role::Assistant {
while end < messages.len() && messages[end].role == Role::Assistant {
end += 1;
}
let calls_before_last = messages[start..end - 1]
.iter()
.any(|m| m.content.iter().any(|b| matches!(b, Block::ToolUse { .. })));
if calls_before_last {
joins[start + 1..end].fill(true);
}
}
start = end;
}
joins
}

/// One assistant message for a response recorded over several: the blocks in
/// order, the first timestamp and model, and the last stop reason and usage
/// (a response's final ones).
fn merge_response(run: &[Message]) -> Message {
let mut merged = run[0].clone();
for msg in &run[1..] {
merged.content.extend(msg.content.iter().cloned());
if merged.model.is_none() {
merged.model.clone_from(&msg.model);
}
if msg.stop_reason.is_some() {
merged.stop_reason.clone_from(&msg.stop_reason);
}
if msg.usage.is_some() {
merged.usage.clone_from(&msg.usage);
}
}
merged
}

fn pi_payloads_for(
msg: &Message,
ts_ms: i64,
Expand Down
1 change: 1 addition & 0 deletions tests/regression/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod codex_code_mode;
mod codex_compressed;
mod codex_pairing;
mod fx_tool_result;
mod parallel_tool_calls;
mod pi_slash_command;

use chrono::{DateTime, Utc};
Expand Down
Loading
Loading