diff --git a/docs/formats/pi.md b/docs/formats/pi.md index 7199294..9ffd7f7 100644 --- a/docs/formats/pi.md +++ b/docs/formats/pi.md @@ -115,6 +115,11 @@ out is not implemented yet — `from_common` never emits it. thinking), re-derives entry ids deterministically (8 chars, matching pi's truncated-uuid convention), guesses `provider`/`api` from the model id, zeroes cost, and collapses `StopSequence`/`Other` stop reasons to `"stop"`. +- **User commands become text.** pi has no user-side tool call, so a + `Tool::Command` (e.g. a Claude Code `/rename`) is written as the user + text that was typed, and its output as user text too. More generally a + `toolResult` is only written when its `toolCall` was: an orphan result + makes providers reject the session on resume (#105). - **bashExecution honors pi's context rule**: runs flagged `excludeFromContext` (pi's `!!` prefix) produce no turn. - **Two timestamps per line.** The envelope carries ISO-8601, the message diff --git a/src/harness/pi.rs b/src/harness/pi.rs index 5105966..fec0153 100644 --- a/src/harness/pi.rs +++ b/src/harness/pi.rs @@ -340,18 +340,35 @@ fn pi_payloads_for( content: result, is_error, } => { - let tool_name = tool_names - .get(tool_use_id) - .cloned() - .unwrap_or_else(|| "tool".to_string()); - out.push(json!({ - "role": "toolResult", - "toolCallId": tool_use_id, - "toolName": tool_name, - "content": [{"type": "text", "text": tool_output_text(result)}], - "isError": is_error, - "timestamp": ts_ms, - })); + // A `toolResult` is only valid answering a `toolCall` + // pi already holds; providers reject an orphan and + // refuse the whole session on resume (#105). Output + // with no call written — a user command's, or one + // that never had a call — stays user-visible text. + if let Some(tool_name) = tool_names.get(tool_use_id) { + out.push(json!({ + "role": "toolResult", + "toolCallId": tool_use_id, + "toolName": tool_name, + "content": [{"type": "text", "text": tool_output_text(result)}], + "isError": is_error, + "timestamp": ts_ms, + })); + } else { + content.push(json!({"type": "text", "text": tool_output_text(result)})); + } + } + // pi has no user-side tool call: a slash command the user + // ran becomes the text they typed. + Block::ToolUse { + tool: Tool::Command { command, args }, + .. + } => { + let text = match args.as_deref().map(str::trim) { + Some(args) if !args.is_empty() => format!("{command} {args}"), + _ => command.clone(), + }; + content.push(json!({"type": "text", "text": text})); } // Not expressible in a pi user message. Block::Thinking { .. } | Block::ToolUse { .. } => {} diff --git a/tests/regression/main.rs b/tests/regression/main.rs index acb3441..aac874f 100644 --- a/tests/regression/main.rs +++ b/tests/regression/main.rs @@ -11,6 +11,7 @@ mod claude_tool_result; mod codex_compressed; mod codex_pairing; mod fx_tool_result; +mod pi_slash_command; use chrono::{DateTime, Utc}; use txcript::common::{Block, Message, Meta, Role, Tool, ToolOutput}; diff --git a/tests/regression/pi_slash_command.rs b/tests/regression/pi_slash_command.rs new file mode 100644 index 0000000..edd6cfa --- /dev/null +++ b/tests/regression/pi_slash_command.rs @@ -0,0 +1,150 @@ +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + +use std::collections::HashSet; + +use serde_json::{Value, json}; +use txcript::harness::claude_code::ClaudeCode; +use txcript::harness::pi::Pi; +use txcript::{Codec, TextCodec}; + +/// Issue #105. A Claude Code local slash command (`/rename`) is a +/// `Tool::Command` call on a *user* turn plus its printed output as the +/// paired `ToolResult`. The pi writer dropped every user-side `ToolUse` but +/// kept the result, so the copy carried a `toolResult` whose `toolCallId` +/// no assistant `toolCall` ever opened — and pi's Anthropic provider +/// refused the whole session on resume (`unexpected tool_use_id found in +/// tool_result blocks`). Output with no command of its own (a `!`-run, or a +/// command whose line was never written) hit the same path. +/// +/// pi has no user-side tool call, so the command and its output must land +/// as plain user text, and every `toolResult` that remains must answer a +/// `toolCall` from the assistant message right before it. +#[test] +fn claude_slash_command_converts_to_pi_without_orphan_tool_results() { + let jsonl = slash_command_session(); + + let common = ClaudeCode::to_common(&ClaudeCode::from_text(&jsonl).unwrap()).unwrap(); + let pi_text = Pi::to_text(&Pi::from_common(&common).unwrap()).unwrap(); + let payloads: Vec = pi_text + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .filter(|v| v["type"] == "message") + .map(|v| v["message"].clone()) + .collect(); + + // pi's resume rule (the Anthropic API's, which pi forwards verbatim): + // each run of `toolResult`s answers `toolCall`s from the assistant + // message immediately before the run. + let mut open: HashSet = HashSet::new(); + for payload in &payloads { + match payload["role"].as_str().unwrap() { + "assistant" => { + open = payload["content"] + .as_array() + .unwrap() + .iter() + .filter(|b| b["type"] == "toolCall") + .map(|b| b["id"].as_str().unwrap().to_string()) + .collect(); + } + "toolResult" => { + let id = payload["toolCallId"].as_str().unwrap(); + assert!( + open.contains(id), + "orphan toolResult {id}: no toolCall in the previous assistant message\n{pi_text}" + ); + } + _ => open.clear(), + } + } + + // The real tool call still pairs as a call/result. + assert!(payloads.iter().any(|p| p["role"] == "toolResult" + && p["toolCallId"] == "toolu_ls" + && p["toolName"] == "bash")); + + // The command and both outputs survive as user-visible text. + let user_text: Vec<&str> = payloads + .iter() + .filter(|p| p["role"] == "user") + .flat_map(|p| p["content"].as_array().unwrap()) + .filter_map(|b| b["text"].as_str()) + .collect(); + for expected in [ + "/rename something", + "Session renamed to: something", + "Export cancelled", + ] { + assert!( + user_text.iter().any(|t| t.contains(expected)), + "{expected:?} missing from pi user text: {user_text:?}" + ); + } +} + +/// A Claude Code session with an ordinary tool call, a `/rename` slash +/// command (newer CLIs' `system` line shape, as in the issue) with its +/// output, and a stray output line with no command of its own. +fn slash_command_session() -> String { + let lines = [ + json!({ + "type": "user", "uuid": "u1", "parentUuid": null, + "sessionId": "sess-105", "cwd": "/work/repo", "timestamp": "2026-01-02T03:04:05.000Z", + "message": {"role": "user", "content": "list the files"}, + }), + json!({ + "type": "assistant", "uuid": "a1", "parentUuid": "u1", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:06.000Z", + "message": {"role": "assistant", "model": "claude-opus-4-8", "content": [ + {"type": "tool_use", "id": "toolu_ls", "name": "Bash", "input": {"command": "ls"}}, + ]}, + }), + json!({ + "type": "user", "uuid": "u2", "parentUuid": "a1", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:07.000Z", + "message": {"role": "user", "content": [ + {"type": "tool_result", "tool_use_id": "toolu_ls", "content": "Cargo.toml\nsrc"}, + ]}, + }), + json!({ + "type": "assistant", "uuid": "a2", "parentUuid": "u2", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:08.000Z", + "message": {"role": "assistant", "model": "claude-opus-4-8", "content": [ + {"type": "text", "text": "Two entries."}, + ]}, + }), + json!({ + "type": "user", "uuid": "u3", "parentUuid": "a2", "isMeta": true, + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:09.000Z", + "message": {"role": "user", "content": + "Caveat: The messages below were generated by the user while running local commands."}, + }), + json!({ + "type": "system", "subtype": "local_command", "uuid": "8fa153f4-572f-48d9-bea6-74ac00dd32f3", "parentUuid": "u3", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:10.000Z", + "content": "/rename\nrename\nsomething", + }), + json!({ + "type": "system", "subtype": "local_command", "uuid": "s2", "parentUuid": "8fa153f4-572f-48d9-bea6-74ac00dd32f3", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:11.000Z", + "content": "Session renamed to: something", + }), + // Output with no command line to pair with. + json!({ + "type": "system", "subtype": "local_command", "uuid": "s3", "parentUuid": "s2", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:12.000Z", + "content": "Export cancelled", + }), + json!({ + "type": "user", "uuid": "u4", "parentUuid": "s3", + "sessionId": "sess-105", "timestamp": "2026-01-02T03:04:13.000Z", + "message": {"role": "user", "content": "one more thing"}, + }), + ]; + lines + .iter() + .map(Value::to_string) + .collect::>() + .join("\n") + + "\n" +}