Compare commits
1 Commits
rcc/thinki
...
rcc/git
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82018e8184 |
@@ -912,7 +912,6 @@ mod tests {
|
||||
system: None,
|
||||
tools: None,
|
||||
tool_choice: None,
|
||||
thinking: None,
|
||||
stream: false,
|
||||
};
|
||||
|
||||
|
||||
@@ -13,5 +13,5 @@ pub use types::{
|
||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
||||
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
|
||||
ThinkingConfig, ToolChoice, ToolDefinition, ToolResultContentBlock, Usage,
|
||||
ToolChoice, ToolDefinition, ToolResultContentBlock, Usage,
|
||||
};
|
||||
|
||||
@@ -12,8 +12,6 @@ pub struct MessageRequest {
|
||||
pub tools: Option<Vec<ToolDefinition>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tool_choice: Option<ToolChoice>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub thinking: Option<ThinkingConfig>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub stream: bool,
|
||||
}
|
||||
@@ -26,23 +24,6 @@ impl MessageRequest {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ThinkingConfig {
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
pub budget_tokens: u32,
|
||||
}
|
||||
|
||||
impl ThinkingConfig {
|
||||
#[must_use]
|
||||
pub fn enabled(budget_tokens: u32) -> Self {
|
||||
Self {
|
||||
kind: "enabled".to_string(),
|
||||
budget_tokens,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct InputMessage {
|
||||
pub role: String,
|
||||
@@ -149,11 +130,6 @@ pub enum OutputContentBlock {
|
||||
Text {
|
||||
text: String,
|
||||
},
|
||||
Thinking {
|
||||
thinking: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
signature: Option<String>,
|
||||
},
|
||||
ToolUse {
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -213,8 +189,6 @@ pub struct ContentBlockDeltaEvent {
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum ContentBlockDelta {
|
||||
TextDelta { text: String },
|
||||
ThinkingDelta { thinking: String },
|
||||
SignatureDelta { signature: String },
|
||||
InputJsonDelta { partial_json: String },
|
||||
}
|
||||
|
||||
|
||||
@@ -258,7 +258,6 @@ async fn live_stream_smoke_test() {
|
||||
system: None,
|
||||
tools: None,
|
||||
tool_choice: None,
|
||||
thinking: None,
|
||||
stream: false,
|
||||
})
|
||||
.await
|
||||
@@ -439,7 +438,6 @@ fn sample_request(stream: bool) -> MessageRequest {
|
||||
}),
|
||||
}]),
|
||||
tool_choice: Some(ToolChoice::Auto),
|
||||
thinking: None,
|
||||
stream,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,12 +57,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
||||
argument_hint: None,
|
||||
resume_supported: true,
|
||||
},
|
||||
SlashCommandSpec {
|
||||
name: "thinking",
|
||||
summary: "Show or toggle extended thinking",
|
||||
argument_hint: Some("[on|off]"),
|
||||
resume_supported: false,
|
||||
},
|
||||
SlashCommandSpec {
|
||||
name: "model",
|
||||
summary: "Show or switch the active model",
|
||||
@@ -142,9 +136,6 @@ pub enum SlashCommand {
|
||||
Help,
|
||||
Status,
|
||||
Compact,
|
||||
Thinking {
|
||||
enabled: Option<bool>,
|
||||
},
|
||||
Model {
|
||||
model: Option<String>,
|
||||
},
|
||||
@@ -189,13 +180,6 @@ impl SlashCommand {
|
||||
"help" => Self::Help,
|
||||
"status" => Self::Status,
|
||||
"compact" => Self::Compact,
|
||||
"thinking" => Self::Thinking {
|
||||
enabled: match parts.next() {
|
||||
Some("on") => Some(true),
|
||||
Some("off") => Some(false),
|
||||
Some(_) | None => None,
|
||||
},
|
||||
},
|
||||
"model" => Self::Model {
|
||||
model: parts.next().map(ToOwned::to_owned),
|
||||
},
|
||||
@@ -295,7 +279,6 @@ pub fn handle_slash_command(
|
||||
session: session.clone(),
|
||||
}),
|
||||
SlashCommand::Status
|
||||
| SlashCommand::Thinking { .. }
|
||||
| SlashCommand::Model { .. }
|
||||
| SlashCommand::Permissions { .. }
|
||||
| SlashCommand::Clear { .. }
|
||||
@@ -324,22 +307,6 @@ mod tests {
|
||||
fn parses_supported_slash_commands() {
|
||||
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
||||
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
||||
assert_eq!(
|
||||
SlashCommand::parse("/thinking on"),
|
||||
Some(SlashCommand::Thinking {
|
||||
enabled: Some(true),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
SlashCommand::parse("/thinking off"),
|
||||
Some(SlashCommand::Thinking {
|
||||
enabled: Some(false),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
SlashCommand::parse("/thinking"),
|
||||
Some(SlashCommand::Thinking { enabled: None })
|
||||
);
|
||||
assert_eq!(
|
||||
SlashCommand::parse("/model claude-opus"),
|
||||
Some(SlashCommand::Model {
|
||||
@@ -407,7 +374,6 @@ mod tests {
|
||||
assert!(help.contains("/help"));
|
||||
assert!(help.contains("/status"));
|
||||
assert!(help.contains("/compact"));
|
||||
assert!(help.contains("/thinking [on|off]"));
|
||||
assert!(help.contains("/model [model]"));
|
||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||
assert!(help.contains("/clear [--confirm]"));
|
||||
@@ -420,7 +386,7 @@ mod tests {
|
||||
assert!(help.contains("/version"));
|
||||
assert!(help.contains("/export [file]"));
|
||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||
assert_eq!(slash_command_specs().len(), 16);
|
||||
assert_eq!(slash_command_specs().len(), 15);
|
||||
assert_eq!(resume_supported_slash_commands().len(), 11);
|
||||
}
|
||||
|
||||
@@ -468,9 +434,6 @@ mod tests {
|
||||
let session = Session::new();
|
||||
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
||||
assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
|
||||
assert!(
|
||||
handle_slash_command("/thinking on", &session, CompactionConfig::default()).is_none()
|
||||
);
|
||||
assert!(
|
||||
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
||||
);
|
||||
|
||||
@@ -130,7 +130,7 @@ fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
||||
.filter_map(|block| match block {
|
||||
ContentBlock::ToolUse { name, .. } => Some(name.as_str()),
|
||||
ContentBlock::ToolResult { tool_name, .. } => Some(tool_name.as_str()),
|
||||
ContentBlock::Text { .. } | ContentBlock::Thinking { .. } => None,
|
||||
ContentBlock::Text { .. } => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
tool_names.sort_unstable();
|
||||
@@ -200,7 +200,6 @@ fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
||||
fn summarize_block(block: &ContentBlock) -> String {
|
||||
let raw = match block {
|
||||
ContentBlock::Text { text } => text.clone(),
|
||||
ContentBlock::Thinking { text, .. } => format!("thinking: {text}"),
|
||||
ContentBlock::ToolUse { name, input, .. } => format!("tool_use {name}({input})"),
|
||||
ContentBlock::ToolResult {
|
||||
tool_name,
|
||||
@@ -259,7 +258,7 @@ fn collect_key_files(messages: &[ConversationMessage]) -> Vec<String> {
|
||||
.iter()
|
||||
.flat_map(|message| message.blocks.iter())
|
||||
.map(|block| match block {
|
||||
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } => text.as_str(),
|
||||
ContentBlock::Text { text } => text.as_str(),
|
||||
ContentBlock::ToolUse { input, .. } => input.as_str(),
|
||||
ContentBlock::ToolResult { output, .. } => output.as_str(),
|
||||
})
|
||||
@@ -281,15 +280,10 @@ fn infer_current_work(messages: &[ConversationMessage]) -> Option<String> {
|
||||
|
||||
fn first_text_block(message: &ConversationMessage) -> Option<&str> {
|
||||
message.blocks.iter().find_map(|block| match block {
|
||||
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. }
|
||||
if !text.trim().is_empty() =>
|
||||
{
|
||||
Some(text.as_str())
|
||||
}
|
||||
ContentBlock::Text { text } if !text.trim().is_empty() => Some(text.as_str()),
|
||||
ContentBlock::ToolUse { .. }
|
||||
| ContentBlock::ToolResult { .. }
|
||||
| ContentBlock::Text { .. }
|
||||
| ContentBlock::Thinking { .. } => None,
|
||||
| ContentBlock::Text { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -334,7 +328,7 @@ fn estimate_message_tokens(message: &ConversationMessage) -> usize {
|
||||
.blocks
|
||||
.iter()
|
||||
.map(|block| match block {
|
||||
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } => text.len() / 4 + 1,
|
||||
ContentBlock::Text { text } => text.len() / 4 + 1,
|
||||
ContentBlock::ToolUse { name, input, .. } => (name.len() + input.len()) / 4 + 1,
|
||||
ContentBlock::ToolResult {
|
||||
tool_name, output, ..
|
||||
|
||||
@@ -17,8 +17,6 @@ pub struct ApiRequest {
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AssistantEvent {
|
||||
TextDelta(String),
|
||||
ThinkingDelta(String),
|
||||
ThinkingSignature(String),
|
||||
ToolUse {
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -249,26 +247,15 @@ fn build_assistant_message(
|
||||
events: Vec<AssistantEvent>,
|
||||
) -> Result<(ConversationMessage, Option<TokenUsage>), RuntimeError> {
|
||||
let mut text = String::new();
|
||||
let mut thinking = String::new();
|
||||
let mut thinking_signature: Option<String> = None;
|
||||
let mut blocks = Vec::new();
|
||||
let mut finished = false;
|
||||
let mut usage = None;
|
||||
|
||||
for event in events {
|
||||
match event {
|
||||
AssistantEvent::TextDelta(delta) => {
|
||||
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
|
||||
text.push_str(&delta);
|
||||
}
|
||||
AssistantEvent::ThinkingDelta(delta) => {
|
||||
flush_text_block(&mut text, &mut blocks);
|
||||
thinking.push_str(&delta);
|
||||
}
|
||||
AssistantEvent::ThinkingSignature(signature) => thinking_signature = Some(signature),
|
||||
AssistantEvent::TextDelta(delta) => text.push_str(&delta),
|
||||
AssistantEvent::ToolUse { id, name, input } => {
|
||||
flush_text_block(&mut text, &mut blocks);
|
||||
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
|
||||
blocks.push(ContentBlock::ToolUse { id, name, input });
|
||||
}
|
||||
AssistantEvent::Usage(value) => usage = Some(value),
|
||||
@@ -279,7 +266,6 @@ fn build_assistant_message(
|
||||
}
|
||||
|
||||
flush_text_block(&mut text, &mut blocks);
|
||||
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
|
||||
|
||||
if !finished {
|
||||
return Err(RuntimeError::new(
|
||||
@@ -304,19 +290,6 @@ fn flush_text_block(text: &mut String, blocks: &mut Vec<ContentBlock>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn flush_thinking_block(
|
||||
thinking: &mut String,
|
||||
signature: &mut Option<String>,
|
||||
blocks: &mut Vec<ContentBlock>,
|
||||
) {
|
||||
if !thinking.is_empty() || signature.is_some() {
|
||||
blocks.push(ContentBlock::Thinking {
|
||||
text: std::mem::take(thinking),
|
||||
signature: signature.take(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
type ToolHandler = Box<dyn FnMut(&str) -> Result<String, ToolError>>;
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -352,8 +325,8 @@ impl ToolExecutor for StaticToolExecutor {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
build_assistant_message, ApiClient, ApiRequest, AssistantEvent, ConversationRuntime,
|
||||
RuntimeError, StaticToolExecutor,
|
||||
ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError,
|
||||
StaticToolExecutor,
|
||||
};
|
||||
use crate::compact::CompactionConfig;
|
||||
use crate::permissions::{
|
||||
@@ -441,6 +414,7 @@ mod tests {
|
||||
cwd: PathBuf::from("/tmp/project"),
|
||||
current_date: "2026-03-31".to_string(),
|
||||
git_status: None,
|
||||
git_diff: None,
|
||||
instruction_files: Vec::new(),
|
||||
})
|
||||
.with_os("linux", "6.8")
|
||||
@@ -529,29 +503,6 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thinking_blocks_are_preserved_separately_from_text() {
|
||||
let (message, usage) = build_assistant_message(vec![
|
||||
AssistantEvent::ThinkingDelta("first ".to_string()),
|
||||
AssistantEvent::ThinkingDelta("second".to_string()),
|
||||
AssistantEvent::ThinkingSignature("sig-1".to_string()),
|
||||
AssistantEvent::TextDelta("final".to_string()),
|
||||
AssistantEvent::MessageStop,
|
||||
])
|
||||
.expect("assistant message should build");
|
||||
|
||||
assert_eq!(usage, None);
|
||||
assert!(matches!(
|
||||
&message.blocks[0],
|
||||
ContentBlock::Thinking { text, signature }
|
||||
if text == "first second" && signature.as_deref() == Some("sig-1")
|
||||
));
|
||||
assert!(matches!(
|
||||
&message.blocks[1],
|
||||
ContentBlock::Text { text } if text == "final"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconstructs_usage_tracker_from_restored_session() {
|
||||
struct SimpleApi;
|
||||
|
||||
@@ -50,6 +50,7 @@ pub struct ProjectContext {
|
||||
pub cwd: PathBuf,
|
||||
pub current_date: String,
|
||||
pub git_status: Option<String>,
|
||||
pub git_diff: Option<String>,
|
||||
pub instruction_files: Vec<ContextFile>,
|
||||
}
|
||||
|
||||
@@ -64,6 +65,7 @@ impl ProjectContext {
|
||||
cwd,
|
||||
current_date: current_date.into(),
|
||||
git_status: None,
|
||||
git_diff: None,
|
||||
instruction_files,
|
||||
})
|
||||
}
|
||||
@@ -74,6 +76,7 @@ impl ProjectContext {
|
||||
) -> std::io::Result<Self> {
|
||||
let mut context = Self::discover(cwd, current_date)?;
|
||||
context.git_status = read_git_status(&context.cwd);
|
||||
context.git_diff = read_git_diff(&context.cwd);
|
||||
Ok(context)
|
||||
}
|
||||
}
|
||||
@@ -239,6 +242,38 @@ fn read_git_status(cwd: &Path) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_git_diff(cwd: &Path) -> Option<String> {
|
||||
let mut sections = Vec::new();
|
||||
|
||||
let staged = read_git_output(cwd, &["diff", "--cached"])?;
|
||||
if !staged.trim().is_empty() {
|
||||
sections.push(format!("Staged changes:\n{}", staged.trim_end()));
|
||||
}
|
||||
|
||||
let unstaged = read_git_output(cwd, &["diff"])?;
|
||||
if !unstaged.trim().is_empty() {
|
||||
sections.push(format!("Unstaged changes:\n{}", unstaged.trim_end()));
|
||||
}
|
||||
|
||||
if sections.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(sections.join("\n\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn read_git_output(cwd: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(output.stdout).ok()
|
||||
}
|
||||
|
||||
fn render_project_context(project_context: &ProjectContext) -> String {
|
||||
let mut lines = vec!["# Project context".to_string()];
|
||||
let mut bullets = vec![
|
||||
@@ -257,6 +292,11 @@ fn render_project_context(project_context: &ProjectContext) -> String {
|
||||
lines.push("Git status snapshot:".to_string());
|
||||
lines.push(status.clone());
|
||||
}
|
||||
if let Some(diff) = &project_context.git_diff {
|
||||
lines.push(String::new());
|
||||
lines.push("Git diff snapshot:".to_string());
|
||||
lines.push(diff.clone());
|
||||
}
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
@@ -577,6 +617,49 @@ mod tests {
|
||||
assert!(status.contains("## No commits yet on") || status.contains("## "));
|
||||
assert!(status.contains("?? CLAUDE.md"));
|
||||
assert!(status.contains("?? tracked.txt"));
|
||||
assert!(context.git_diff.is_none());
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discover_with_git_includes_diff_snapshot_for_tracked_changes() {
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("root dir");
|
||||
std::process::Command::new("git")
|
||||
.args(["init", "--quiet"])
|
||||
.current_dir(&root)
|
||||
.status()
|
||||
.expect("git init should run");
|
||||
std::process::Command::new("git")
|
||||
.args(["config", "user.email", "tests@example.com"])
|
||||
.current_dir(&root)
|
||||
.status()
|
||||
.expect("git config email should run");
|
||||
std::process::Command::new("git")
|
||||
.args(["config", "user.name", "Runtime Prompt Tests"])
|
||||
.current_dir(&root)
|
||||
.status()
|
||||
.expect("git config name should run");
|
||||
fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked file");
|
||||
std::process::Command::new("git")
|
||||
.args(["add", "tracked.txt"])
|
||||
.current_dir(&root)
|
||||
.status()
|
||||
.expect("git add should run");
|
||||
std::process::Command::new("git")
|
||||
.args(["commit", "-m", "init", "--quiet"])
|
||||
.current_dir(&root)
|
||||
.status()
|
||||
.expect("git commit should run");
|
||||
fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("rewrite tracked file");
|
||||
|
||||
let context =
|
||||
ProjectContext::discover_with_git(&root, "2026-03-31").expect("context should load");
|
||||
|
||||
let diff = context.git_diff.expect("git diff should be present");
|
||||
assert!(diff.contains("Unstaged changes:"));
|
||||
assert!(diff.contains("tracked.txt"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
@@ -19,10 +19,6 @@ pub enum ContentBlock {
|
||||
Text {
|
||||
text: String,
|
||||
},
|
||||
Thinking {
|
||||
text: String,
|
||||
signature: Option<String>,
|
||||
},
|
||||
ToolUse {
|
||||
id: String,
|
||||
name: String,
|
||||
@@ -261,19 +257,6 @@ impl ContentBlock {
|
||||
object.insert("type".to_string(), JsonValue::String("text".to_string()));
|
||||
object.insert("text".to_string(), JsonValue::String(text.clone()));
|
||||
}
|
||||
Self::Thinking { text, signature } => {
|
||||
object.insert(
|
||||
"type".to_string(),
|
||||
JsonValue::String("thinking".to_string()),
|
||||
);
|
||||
object.insert("text".to_string(), JsonValue::String(text.clone()));
|
||||
if let Some(signature) = signature {
|
||||
object.insert(
|
||||
"signature".to_string(),
|
||||
JsonValue::String(signature.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
Self::ToolUse { id, name, input } => {
|
||||
object.insert(
|
||||
"type".to_string(),
|
||||
@@ -320,13 +303,6 @@ impl ContentBlock {
|
||||
"text" => Ok(Self::Text {
|
||||
text: required_string(object, "text")?,
|
||||
}),
|
||||
"thinking" => Ok(Self::Thinking {
|
||||
text: required_string(object, "text")?,
|
||||
signature: object
|
||||
.get("signature")
|
||||
.and_then(JsonValue::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
}),
|
||||
"tool_use" => Ok(Self::ToolUse {
|
||||
id: required_string(object, "id")?,
|
||||
name: required_string(object, "name")?,
|
||||
|
||||
@@ -13,8 +13,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use api::{
|
||||
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
|
||||
InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
|
||||
StreamEvent as ApiStreamEvent, ThinkingConfig, ToolChoice, ToolDefinition,
|
||||
ToolResultContentBlock,
|
||||
StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
|
||||
};
|
||||
|
||||
use commands::{
|
||||
@@ -35,7 +34,6 @@ use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
||||
|
||||
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
||||
const DEFAULT_MAX_TOKENS: u32 = 32;
|
||||
const DEFAULT_THINKING_BUDGET_TOKENS: u32 = 2_048;
|
||||
const DEFAULT_DATE: &str = "2026-03-31";
|
||||
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
@@ -72,8 +70,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
output_format,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking,
|
||||
} => LiveCli::new(model, false, allowed_tools, permission_mode, thinking)?
|
||||
} => LiveCli::new(model, false, allowed_tools, permission_mode)?
|
||||
.run_turn_with_output(&prompt, output_format)?,
|
||||
CliAction::Login => run_login()?,
|
||||
CliAction::Logout => run_logout()?,
|
||||
@@ -81,8 +78,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
model,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking,
|
||||
} => run_repl(model, allowed_tools, permission_mode, thinking)?,
|
||||
} => run_repl(model, allowed_tools, permission_mode)?,
|
||||
CliAction::Help => print_help(),
|
||||
}
|
||||
Ok(())
|
||||
@@ -107,7 +103,6 @@ enum CliAction {
|
||||
output_format: CliOutputFormat,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
permission_mode: PermissionMode,
|
||||
thinking: bool,
|
||||
},
|
||||
Login,
|
||||
Logout,
|
||||
@@ -115,7 +110,6 @@ enum CliAction {
|
||||
model: String,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
permission_mode: PermissionMode,
|
||||
thinking: bool,
|
||||
},
|
||||
// prompt-mode formatting is only supported for non-interactive runs
|
||||
Help,
|
||||
@@ -145,7 +139,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
let mut output_format = CliOutputFormat::Text;
|
||||
let mut permission_mode = default_permission_mode();
|
||||
let mut wants_version = false;
|
||||
let mut thinking = false;
|
||||
let mut allowed_tool_values = Vec::new();
|
||||
let mut rest = Vec::new();
|
||||
let mut index = 0;
|
||||
@@ -156,10 +149,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
wants_version = true;
|
||||
index += 1;
|
||||
}
|
||||
"--thinking" => {
|
||||
thinking = true;
|
||||
index += 1;
|
||||
}
|
||||
"--model" => {
|
||||
let value = args
|
||||
.get(index + 1)
|
||||
@@ -226,7 +215,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
model,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking,
|
||||
});
|
||||
}
|
||||
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
|
||||
@@ -253,7 +241,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
output_format,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking,
|
||||
})
|
||||
}
|
||||
other if !other.starts_with('/') => Ok(CliAction::Prompt {
|
||||
@@ -262,7 +249,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
||||
output_format,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking,
|
||||
}),
|
||||
other => Err(format!("unknown subcommand: {other}")),
|
||||
}
|
||||
@@ -614,7 +600,6 @@ struct StatusUsage {
|
||||
latest: TokenUsage,
|
||||
cumulative: TokenUsage,
|
||||
estimated_tokens: usize,
|
||||
thinking_enabled: bool,
|
||||
}
|
||||
|
||||
fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
|
||||
@@ -682,39 +667,6 @@ Usage
|
||||
)
|
||||
}
|
||||
|
||||
fn format_thinking_report(enabled: bool) -> String {
|
||||
let state = if enabled { "on" } else { "off" };
|
||||
let budget = if enabled {
|
||||
DEFAULT_THINKING_BUDGET_TOKENS.to_string()
|
||||
} else {
|
||||
"disabled".to_string()
|
||||
};
|
||||
format!(
|
||||
"Thinking
|
||||
Active mode {state}
|
||||
Budget tokens {budget}
|
||||
|
||||
Usage
|
||||
Inspect current mode with /thinking
|
||||
Toggle with /thinking on or /thinking off"
|
||||
)
|
||||
}
|
||||
|
||||
fn format_thinking_switch_report(enabled: bool) -> String {
|
||||
let state = if enabled { "enabled" } else { "disabled" };
|
||||
format!(
|
||||
"Thinking updated
|
||||
Result {state}
|
||||
Budget tokens {}
|
||||
Applies to subsequent requests",
|
||||
if enabled {
|
||||
DEFAULT_THINKING_BUDGET_TOKENS.to_string()
|
||||
} else {
|
||||
"disabled".to_string()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn format_permissions_switch_report(previous: &str, next: &str) -> String {
|
||||
format!(
|
||||
"Permissions updated
|
||||
@@ -790,27 +742,61 @@ fn format_compact_report(removed: usize, resulting_messages: usize, skipped: boo
|
||||
}
|
||||
|
||||
fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
|
||||
let Some(status) = status else {
|
||||
return (None, None);
|
||||
};
|
||||
let branch = status.lines().next().and_then(|line| {
|
||||
line.strip_prefix("## ")
|
||||
.map(|line| {
|
||||
line.split(['.', ' '])
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
})
|
||||
.filter(|value| !value.is_empty())
|
||||
});
|
||||
let project_root = find_git_root().ok();
|
||||
(project_root, branch)
|
||||
parse_git_status_metadata_for(
|
||||
&env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||
status,
|
||||
)
|
||||
}
|
||||
|
||||
fn find_git_root() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
fn parse_git_status_branch(status: Option<&str>) -> Option<String> {
|
||||
let status = status?;
|
||||
let first_line = status.lines().next()?;
|
||||
let line = first_line.strip_prefix("## ")?;
|
||||
if line.starts_with("HEAD") {
|
||||
return Some("detached HEAD".to_string());
|
||||
}
|
||||
let branch = line.split(['.', ' ']).next().unwrap_or_default().trim();
|
||||
if branch.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(branch.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_git_branch_for(cwd: &Path) -> Option<String> {
|
||||
let branch = run_git_capture_in(cwd, &["branch", "--show-current"])?;
|
||||
let branch = branch.trim();
|
||||
if !branch.is_empty() {
|
||||
return Some(branch.to_string());
|
||||
}
|
||||
|
||||
let fallback = run_git_capture_in(cwd, &["rev-parse", "--abbrev-ref", "HEAD"])?;
|
||||
let fallback = fallback.trim();
|
||||
if fallback.is_empty() {
|
||||
None
|
||||
} else if fallback == "HEAD" {
|
||||
Some("detached HEAD".to_string())
|
||||
} else {
|
||||
Some(fallback.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn run_git_capture_in(cwd: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(output.stdout).ok()
|
||||
}
|
||||
|
||||
fn find_git_root_in(cwd: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["rev-parse", "--show-toplevel"])
|
||||
.current_dir(env::current_dir()?)
|
||||
.current_dir(cwd)
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
return Err("not a git repository".into());
|
||||
@@ -822,6 +808,15 @@ fn find_git_root() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
Ok(PathBuf::from(path))
|
||||
}
|
||||
|
||||
fn parse_git_status_metadata_for(
|
||||
cwd: &Path,
|
||||
status: Option<&str>,
|
||||
) -> (Option<PathBuf>, Option<String>) {
|
||||
let branch = resolve_git_branch_for(cwd).or_else(|| parse_git_status_branch(status));
|
||||
let project_root = find_git_root_in(cwd).ok();
|
||||
(project_root, branch)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_lines)]
|
||||
fn run_resume_command(
|
||||
session_path: &Path,
|
||||
@@ -882,7 +877,6 @@ fn run_resume_command(
|
||||
latest: tracker.current_turn_usage(),
|
||||
cumulative: usage,
|
||||
estimated_tokens: 0,
|
||||
thinking_enabled: false,
|
||||
},
|
||||
default_permission_mode().as_str(),
|
||||
&status_context(Some(session_path))?,
|
||||
@@ -910,7 +904,9 @@ fn run_resume_command(
|
||||
}),
|
||||
SlashCommand::Diff => Ok(ResumeCommandOutcome {
|
||||
session: session.clone(),
|
||||
message: Some(render_diff_report()?),
|
||||
message: Some(render_diff_report_for(
|
||||
session_path.parent().unwrap_or_else(|| Path::new(".")),
|
||||
)?),
|
||||
}),
|
||||
SlashCommand::Version => Ok(ResumeCommandOutcome {
|
||||
session: session.clone(),
|
||||
@@ -929,7 +925,6 @@ fn run_resume_command(
|
||||
})
|
||||
}
|
||||
SlashCommand::Resume { .. }
|
||||
| SlashCommand::Thinking { .. }
|
||||
| SlashCommand::Model { .. }
|
||||
| SlashCommand::Permissions { .. }
|
||||
| SlashCommand::Session { .. }
|
||||
@@ -941,15 +936,8 @@ fn run_repl(
|
||||
model: String,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
permission_mode: PermissionMode,
|
||||
thinking_enabled: bool,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut cli = LiveCli::new(
|
||||
model,
|
||||
true,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking_enabled,
|
||||
)?;
|
||||
let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
|
||||
let mut editor = input::LineEditor::new("› ", slash_command_completion_candidates());
|
||||
println!("{}", cli.startup_banner());
|
||||
|
||||
@@ -1002,7 +990,6 @@ struct LiveCli {
|
||||
model: String,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
permission_mode: PermissionMode,
|
||||
thinking_enabled: bool,
|
||||
system_prompt: Vec<String>,
|
||||
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
|
||||
session: SessionHandle,
|
||||
@@ -1014,7 +1001,6 @@ impl LiveCli {
|
||||
enable_tools: bool,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
permission_mode: PermissionMode,
|
||||
thinking_enabled: bool,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let system_prompt = build_system_prompt()?;
|
||||
let session = create_managed_session_handle()?;
|
||||
@@ -1025,13 +1011,11 @@ impl LiveCli {
|
||||
enable_tools,
|
||||
allowed_tools.clone(),
|
||||
permission_mode,
|
||||
thinking_enabled,
|
||||
)?;
|
||||
let cli = Self {
|
||||
model,
|
||||
allowed_tools,
|
||||
permission_mode,
|
||||
thinking_enabled,
|
||||
system_prompt,
|
||||
runtime,
|
||||
session,
|
||||
@@ -1042,10 +1026,9 @@ impl LiveCli {
|
||||
|
||||
fn startup_banner(&self) -> String {
|
||||
format!(
|
||||
"Rusty Claude CLI\n Model {}\n Permission mode {}\n Thinking {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.",
|
||||
"Rusty Claude CLI\n Model {}\n Permission mode {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.",
|
||||
self.model,
|
||||
self.permission_mode.as_str(),
|
||||
if self.thinking_enabled { "on" } else { "off" },
|
||||
env::current_dir().map_or_else(
|
||||
|_| "<unknown>".to_string(),
|
||||
|path| path.display().to_string(),
|
||||
@@ -1111,9 +1094,6 @@ impl LiveCli {
|
||||
system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")),
|
||||
tools: None,
|
||||
tool_choice: None,
|
||||
thinking: self
|
||||
.thinking_enabled
|
||||
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
|
||||
stream: false,
|
||||
};
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
@@ -1123,7 +1103,7 @@ impl LiveCli {
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
OutputContentBlock::Text { text } => Some(text.as_str()),
|
||||
OutputContentBlock::Thinking { .. } | OutputContentBlock::ToolUse { .. } => None,
|
||||
OutputContentBlock::ToolUse { .. } => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("");
|
||||
@@ -1160,7 +1140,6 @@ impl LiveCli {
|
||||
self.compact()?;
|
||||
false
|
||||
}
|
||||
SlashCommand::Thinking { enabled } => self.set_thinking(enabled)?,
|
||||
SlashCommand::Model { model } => self.set_model(model)?,
|
||||
SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
|
||||
SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
|
||||
@@ -1221,7 +1200,6 @@ impl LiveCli {
|
||||
latest,
|
||||
cumulative,
|
||||
estimated_tokens: self.runtime.estimated_tokens(),
|
||||
thinking_enabled: self.thinking_enabled,
|
||||
},
|
||||
self.permission_mode.as_str(),
|
||||
&status_context(Some(&self.session.path)).expect("status context should load"),
|
||||
@@ -1264,7 +1242,6 @@ impl LiveCli {
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
self.model.clone_from(&model);
|
||||
println!(
|
||||
@@ -1274,32 +1251,6 @@ impl LiveCli {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn set_thinking(&mut self, enabled: Option<bool>) -> Result<bool, Box<dyn std::error::Error>> {
|
||||
let Some(enabled) = enabled else {
|
||||
println!("{}", format_thinking_report(self.thinking_enabled));
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
if enabled == self.thinking_enabled {
|
||||
println!("{}", format_thinking_report(self.thinking_enabled));
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let session = self.runtime.session().clone();
|
||||
self.thinking_enabled = enabled;
|
||||
self.runtime = build_runtime(
|
||||
session,
|
||||
self.model.clone(),
|
||||
self.system_prompt.clone(),
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
println!("{}", format_thinking_switch_report(self.thinking_enabled));
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn set_permissions(
|
||||
&mut self,
|
||||
mode: Option<String>,
|
||||
@@ -1333,7 +1284,6 @@ impl LiveCli {
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
println!(
|
||||
"{}",
|
||||
@@ -1358,7 +1308,6 @@ impl LiveCli {
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
println!(
|
||||
"Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
|
||||
@@ -1393,7 +1342,6 @@ impl LiveCli {
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
self.session = handle;
|
||||
println!(
|
||||
@@ -1470,7 +1418,6 @@ impl LiveCli {
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
self.session = handle;
|
||||
println!(
|
||||
@@ -1500,7 +1447,6 @@ impl LiveCli {
|
||||
true,
|
||||
self.allowed_tools.clone(),
|
||||
self.permission_mode,
|
||||
self.thinking_enabled,
|
||||
)?;
|
||||
self.persist_session()?;
|
||||
println!("{}", format_compact_report(removed, kept, skipped));
|
||||
@@ -1612,7 +1558,6 @@ fn render_repl_help() -> String {
|
||||
[
|
||||
"REPL".to_string(),
|
||||
" /exit Quit the REPL".to_string(),
|
||||
" /thinking [on|off] Show or toggle extended thinking".to_string(),
|
||||
" /quit Quit the REPL".to_string(),
|
||||
" Up/Down Navigate prompt history".to_string(),
|
||||
" Tab Complete slash commands".to_string(),
|
||||
@@ -1659,14 +1604,10 @@ fn format_status_report(
|
||||
"Status
|
||||
Model {model}
|
||||
Permission mode {permission_mode}
|
||||
Thinking {}
|
||||
Messages {}
|
||||
Turns {}
|
||||
Estimated tokens {}",
|
||||
if usage.thinking_enabled { "on" } else { "off" },
|
||||
usage.message_count,
|
||||
usage.turns,
|
||||
usage.estimated_tokens,
|
||||
usage.message_count, usage.turns, usage.estimated_tokens,
|
||||
),
|
||||
format!(
|
||||
"Usage
|
||||
@@ -1899,22 +1840,43 @@ fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
fn render_diff_report() -> Result<String, Box<dyn std::error::Error>> {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(["diff", "--", ":(exclude).omx"])
|
||||
.current_dir(env::current_dir()?)
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(format!("git diff failed: {stderr}").into());
|
||||
}
|
||||
let diff = String::from_utf8(output.stdout)?;
|
||||
if diff.trim().is_empty() {
|
||||
render_diff_report_for(&env::current_dir()?)
|
||||
}
|
||||
|
||||
fn render_diff_report_for(cwd: &Path) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let staged = run_git_diff_command_in(cwd, &["diff", "--cached"])?;
|
||||
let unstaged = run_git_diff_command_in(cwd, &["diff"])?;
|
||||
if staged.trim().is_empty() && unstaged.trim().is_empty() {
|
||||
return Ok(
|
||||
"Diff\n Result clean working tree\n Detail no current changes"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Ok(format!("Diff\n\n{}", diff.trim_end()))
|
||||
|
||||
let mut sections = Vec::new();
|
||||
if !staged.trim().is_empty() {
|
||||
sections.push(format!("Staged changes:\n{}", staged.trim_end()));
|
||||
}
|
||||
if !unstaged.trim().is_empty() {
|
||||
sections.push(format!("Unstaged changes:\n{}", unstaged.trim_end()));
|
||||
}
|
||||
|
||||
Ok(format!("Diff\n\n{}", sections.join("\n\n")))
|
||||
}
|
||||
|
||||
fn run_git_diff_command_in(
|
||||
cwd: &Path,
|
||||
args: &[&str],
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
let output = std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
|
||||
}
|
||||
Ok(String::from_utf8(output.stdout)?)
|
||||
}
|
||||
|
||||
fn render_version_report() -> String {
|
||||
@@ -1938,15 +1900,6 @@ fn render_export_text(session: &Session) -> String {
|
||||
for block in &message.blocks {
|
||||
match block {
|
||||
ContentBlock::Text { text } => lines.push(text.clone()),
|
||||
ContentBlock::Thinking { text, signature } => {
|
||||
lines.push(format!(
|
||||
"[thinking{}] {}",
|
||||
signature
|
||||
.as_ref()
|
||||
.map_or(String::new(), |value| format!(" signature={value}")),
|
||||
text
|
||||
));
|
||||
}
|
||||
ContentBlock::ToolUse { id, name, input } => {
|
||||
lines.push(format!("[tool_use id={id} name={name}] {input}"));
|
||||
}
|
||||
@@ -2037,12 +1990,11 @@ fn build_runtime(
|
||||
enable_tools: bool,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
permission_mode: PermissionMode,
|
||||
thinking_enabled: bool,
|
||||
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
|
||||
{
|
||||
Ok(ConversationRuntime::new(
|
||||
session,
|
||||
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone(), thinking_enabled)?,
|
||||
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone())?,
|
||||
CliToolExecutor::new(allowed_tools),
|
||||
permission_policy(permission_mode),
|
||||
system_prompt,
|
||||
@@ -2101,7 +2053,6 @@ struct AnthropicRuntimeClient {
|
||||
model: String,
|
||||
enable_tools: bool,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
thinking_enabled: bool,
|
||||
}
|
||||
|
||||
impl AnthropicRuntimeClient {
|
||||
@@ -2109,7 +2060,6 @@ impl AnthropicRuntimeClient {
|
||||
model: String,
|
||||
enable_tools: bool,
|
||||
allowed_tools: Option<AllowedToolSet>,
|
||||
thinking_enabled: bool,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
Ok(Self {
|
||||
runtime: tokio::runtime::Runtime::new()?,
|
||||
@@ -2117,7 +2067,6 @@ impl AnthropicRuntimeClient {
|
||||
model,
|
||||
enable_tools,
|
||||
allowed_tools,
|
||||
thinking_enabled,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2151,9 +2100,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
.collect()
|
||||
}),
|
||||
tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
|
||||
thinking: self
|
||||
.thinking_enabled
|
||||
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
|
||||
stream: true,
|
||||
};
|
||||
|
||||
@@ -2166,7 +2112,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
let mut stdout = io::stdout();
|
||||
let mut events = Vec::new();
|
||||
let mut pending_tool: Option<(String, String, String)> = None;
|
||||
let mut pending_thinking_signature: Option<String> = None;
|
||||
let mut saw_stop = false;
|
||||
|
||||
while let Some(event) = stream
|
||||
@@ -2177,13 +2122,7 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
match event {
|
||||
ApiStreamEvent::MessageStart(start) => {
|
||||
for block in start.message.content {
|
||||
push_output_block(
|
||||
block,
|
||||
&mut stdout,
|
||||
&mut events,
|
||||
&mut pending_tool,
|
||||
&mut pending_thinking_signature,
|
||||
)?;
|
||||
push_output_block(block, &mut stdout, &mut events, &mut pending_tool)?;
|
||||
}
|
||||
}
|
||||
ApiStreamEvent::ContentBlockStart(start) => {
|
||||
@@ -2192,7 +2131,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
&mut stdout,
|
||||
&mut events,
|
||||
&mut pending_tool,
|
||||
&mut pending_thinking_signature,
|
||||
)?;
|
||||
}
|
||||
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
|
||||
@@ -2204,14 +2142,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
events.push(AssistantEvent::TextDelta(text));
|
||||
}
|
||||
}
|
||||
ContentBlockDelta::ThinkingDelta { thinking } => {
|
||||
if !thinking.is_empty() {
|
||||
events.push(AssistantEvent::ThinkingDelta(thinking));
|
||||
}
|
||||
}
|
||||
ContentBlockDelta::SignatureDelta { signature } => {
|
||||
events.push(AssistantEvent::ThinkingSignature(signature));
|
||||
}
|
||||
ContentBlockDelta::InputJsonDelta { partial_json } => {
|
||||
if let Some((_, _, input)) = &mut pending_tool {
|
||||
input.push_str(&partial_json);
|
||||
@@ -2241,8 +2171,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
||||
if !saw_stop
|
||||
&& events.iter().any(|event| {
|
||||
matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
|
||||
|| matches!(event, AssistantEvent::ThinkingDelta(text) if !text.is_empty())
|
||||
|| matches!(event, AssistantEvent::ThinkingSignature(_))
|
||||
|| matches!(event, AssistantEvent::ToolUse { .. })
|
||||
})
|
||||
{
|
||||
@@ -2326,19 +2254,11 @@ fn truncate_for_summary(value: &str, limit: usize) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn render_thinking_block_summary(text: &str, out: &mut impl Write) -> Result<(), RuntimeError> {
|
||||
let summary = format!("▶ Thinking ({} chars hidden)", text.chars().count());
|
||||
writeln!(out, "\n{summary}")
|
||||
.and_then(|()| out.flush())
|
||||
.map_err(|error| RuntimeError::new(error.to_string()))
|
||||
}
|
||||
|
||||
fn push_output_block(
|
||||
block: OutputContentBlock,
|
||||
out: &mut impl Write,
|
||||
events: &mut Vec<AssistantEvent>,
|
||||
pending_tool: &mut Option<(String, String, String)>,
|
||||
pending_thinking_signature: &mut Option<String>,
|
||||
) -> Result<(), RuntimeError> {
|
||||
match block {
|
||||
OutputContentBlock::Text { text } => {
|
||||
@@ -2349,19 +2269,6 @@ fn push_output_block(
|
||||
events.push(AssistantEvent::TextDelta(text));
|
||||
}
|
||||
}
|
||||
OutputContentBlock::Thinking {
|
||||
thinking,
|
||||
signature,
|
||||
} => {
|
||||
render_thinking_block_summary(&thinking, out)?;
|
||||
if !thinking.is_empty() {
|
||||
events.push(AssistantEvent::ThinkingDelta(thinking));
|
||||
}
|
||||
if let Some(signature) = signature {
|
||||
*pending_thinking_signature = Some(signature.clone());
|
||||
events.push(AssistantEvent::ThinkingSignature(signature));
|
||||
}
|
||||
}
|
||||
OutputContentBlock::ToolUse { id, name, input } => {
|
||||
writeln!(
|
||||
out,
|
||||
@@ -2383,16 +2290,9 @@ fn response_to_events(
|
||||
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
||||
let mut events = Vec::new();
|
||||
let mut pending_tool = None;
|
||||
let mut pending_thinking_signature = None;
|
||||
|
||||
for block in response.content {
|
||||
push_output_block(
|
||||
block,
|
||||
out,
|
||||
&mut events,
|
||||
&mut pending_tool,
|
||||
&mut pending_thinking_signature,
|
||||
)?;
|
||||
push_output_block(block, out, &mut events, &mut pending_tool)?;
|
||||
if let Some((id, name, input)) = pending_tool.take() {
|
||||
events.push(AssistantEvent::ToolUse { id, name, input });
|
||||
}
|
||||
@@ -2477,29 +2377,26 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
|
||||
let content = message
|
||||
.blocks
|
||||
.iter()
|
||||
.filter_map(|block| match block {
|
||||
ContentBlock::Text { text } => {
|
||||
Some(InputContentBlock::Text { text: text.clone() })
|
||||
}
|
||||
ContentBlock::Thinking { .. } => None,
|
||||
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
|
||||
.map(|block| match block {
|
||||
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
|
||||
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
input: serde_json::from_str(input)
|
||||
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
|
||||
}),
|
||||
},
|
||||
ContentBlock::ToolResult {
|
||||
tool_use_id,
|
||||
output,
|
||||
is_error,
|
||||
..
|
||||
} => Some(InputContentBlock::ToolResult {
|
||||
} => InputContentBlock::ToolResult {
|
||||
tool_use_id: tool_use_id.clone(),
|
||||
content: vec![ToolResultContentBlock::Text {
|
||||
text: output.clone(),
|
||||
}],
|
||||
is_error: *is_error,
|
||||
}),
|
||||
},
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(!content.is_empty()).then(|| InputMessage {
|
||||
@@ -2532,7 +2429,6 @@ fn print_help() {
|
||||
println!(" --model MODEL Override the active model");
|
||||
println!(" --output-format FORMAT Non-interactive output format: text or json");
|
||||
println!(" --permission-mode MODE Set read-only, workspace-write, or danger-full-access");
|
||||
println!(" --thinking Enable extended thinking with the default budget");
|
||||
println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
|
||||
println!(" --version, -V Print version and build information locally");
|
||||
println!();
|
||||
@@ -2563,12 +2459,53 @@ mod tests {
|
||||
format_model_report, format_model_switch_report, format_permissions_report,
|
||||
format_permissions_switch_report, format_resume_report, format_status_report,
|
||||
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
|
||||
parse_git_status_metadata, render_config_report, render_init_claude_md,
|
||||
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
|
||||
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||
parse_git_status_branch, parse_git_status_metadata, render_config_report,
|
||||
render_diff_report, render_init_claude_md, render_memory_report, render_repl_help,
|
||||
resume_supported_slash_commands, run_resume_command, status_context, CliAction,
|
||||
CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||
};
|
||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
fn temp_dir() -> PathBuf {
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("time should be after epoch")
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!("rusty-claude-cli-{nanos}"))
|
||||
}
|
||||
|
||||
fn git(args: &[&str], cwd: &Path) {
|
||||
let status = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.status()
|
||||
.expect("git command should run");
|
||||
assert!(
|
||||
status.success(),
|
||||
"git command failed: git {}",
|
||||
args.join(" ")
|
||||
);
|
||||
}
|
||||
|
||||
fn env_lock() -> MutexGuard<'static, ()> {
|
||||
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
LOCK.get_or_init(|| Mutex::new(()))
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn with_current_dir<T>(cwd: &Path, f: impl FnOnce() -> T) -> T {
|
||||
let previous = std::env::current_dir().expect("cwd should load");
|
||||
std::env::set_current_dir(cwd).expect("cwd should change");
|
||||
let result = f();
|
||||
std::env::set_current_dir(previous).expect("cwd should restore");
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_to_repl_when_no_args() {
|
||||
@@ -2578,7 +2515,6 @@ mod tests {
|
||||
model: DEFAULT_MODEL.to_string(),
|
||||
allowed_tools: None,
|
||||
permission_mode: PermissionMode::WorkspaceWrite,
|
||||
thinking: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2598,7 +2534,6 @@ mod tests {
|
||||
output_format: CliOutputFormat::Text,
|
||||
allowed_tools: None,
|
||||
permission_mode: PermissionMode::WorkspaceWrite,
|
||||
thinking: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2620,7 +2555,6 @@ mod tests {
|
||||
output_format: CliOutputFormat::Json,
|
||||
allowed_tools: None,
|
||||
permission_mode: PermissionMode::WorkspaceWrite,
|
||||
thinking: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2646,7 +2580,6 @@ mod tests {
|
||||
model: DEFAULT_MODEL.to_string(),
|
||||
allowed_tools: None,
|
||||
permission_mode: PermissionMode::ReadOnly,
|
||||
thinking: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2669,7 +2602,6 @@ mod tests {
|
||||
.collect()
|
||||
),
|
||||
permission_mode: PermissionMode::WorkspaceWrite,
|
||||
thinking: false,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2909,7 +2841,6 @@ mod tests {
|
||||
cache_read_input_tokens: 1,
|
||||
},
|
||||
estimated_tokens: 128,
|
||||
thinking_enabled: true,
|
||||
},
|
||||
"workspace-write",
|
||||
&super::StatusContext {
|
||||
@@ -2961,12 +2892,133 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parses_git_status_metadata() {
|
||||
let (root, branch) = parse_git_status_metadata(Some(
|
||||
"## rcc/cli...origin/rcc/cli
|
||||
let _guard = env_lock();
|
||||
let temp_root = temp_dir();
|
||||
fs::create_dir_all(&temp_root).expect("root dir");
|
||||
let (project_root, branch) = with_current_dir(&temp_root, || {
|
||||
parse_git_status_metadata(Some(
|
||||
"## rcc/cli...origin/rcc/cli
|
||||
M src/main.rs",
|
||||
));
|
||||
))
|
||||
});
|
||||
assert_eq!(branch.as_deref(), Some("rcc/cli"));
|
||||
let _ = root;
|
||||
assert!(project_root.is_none());
|
||||
fs::remove_dir_all(temp_root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_detached_head_from_status_snapshot() {
|
||||
let _guard = env_lock();
|
||||
assert_eq!(
|
||||
parse_git_status_branch(Some(
|
||||
"## HEAD (no branch)
|
||||
M src/main.rs"
|
||||
)),
|
||||
Some("detached HEAD".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_diff_report_shows_clean_tree_for_committed_repo() {
|
||||
let _guard = env_lock();
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("root dir");
|
||||
git(&["init", "--quiet"], &root);
|
||||
git(&["config", "user.email", "tests@example.com"], &root);
|
||||
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||
fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
|
||||
git(&["add", "tracked.txt"], &root);
|
||||
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||
|
||||
let report = with_current_dir(&root, || {
|
||||
render_diff_report().expect("diff report should render")
|
||||
});
|
||||
assert!(report.contains("clean working tree"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_diff_report_includes_staged_and_unstaged_sections() {
|
||||
let _guard = env_lock();
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("root dir");
|
||||
git(&["init", "--quiet"], &root);
|
||||
git(&["config", "user.email", "tests@example.com"], &root);
|
||||
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||
fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
|
||||
git(&["add", "tracked.txt"], &root);
|
||||
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||
|
||||
fs::write(root.join("tracked.txt"), "hello\nstaged\n").expect("update file");
|
||||
git(&["add", "tracked.txt"], &root);
|
||||
fs::write(root.join("tracked.txt"), "hello\nstaged\nunstaged\n")
|
||||
.expect("update file twice");
|
||||
|
||||
let report = with_current_dir(&root, || {
|
||||
render_diff_report().expect("diff report should render")
|
||||
});
|
||||
assert!(report.contains("Staged changes:"));
|
||||
assert!(report.contains("Unstaged changes:"));
|
||||
assert!(report.contains("tracked.txt"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_diff_report_omits_ignored_files() {
|
||||
let _guard = env_lock();
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("root dir");
|
||||
git(&["init", "--quiet"], &root);
|
||||
git(&["config", "user.email", "tests@example.com"], &root);
|
||||
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||
fs::write(root.join(".gitignore"), ".omx/\nignored.txt\n").expect("write gitignore");
|
||||
fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
|
||||
git(&["add", ".gitignore", "tracked.txt"], &root);
|
||||
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||
fs::create_dir_all(root.join(".omx")).expect("write omx dir");
|
||||
fs::write(root.join(".omx").join("state.json"), "{}").expect("write ignored omx");
|
||||
fs::write(root.join("ignored.txt"), "secret\n").expect("write ignored file");
|
||||
fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("write tracked change");
|
||||
|
||||
let report = with_current_dir(&root, || {
|
||||
render_diff_report().expect("diff report should render")
|
||||
});
|
||||
assert!(report.contains("tracked.txt"));
|
||||
assert!(!report.contains("+++ b/ignored.txt"));
|
||||
assert!(!report.contains("+++ b/.omx/state.json"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_diff_command_renders_report_for_saved_session() {
|
||||
let _guard = env_lock();
|
||||
let root = temp_dir();
|
||||
fs::create_dir_all(&root).expect("root dir");
|
||||
git(&["init", "--quiet"], &root);
|
||||
git(&["config", "user.email", "tests@example.com"], &root);
|
||||
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||
fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
|
||||
git(&["add", "tracked.txt"], &root);
|
||||
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||
fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("modify tracked");
|
||||
let session_path = root.join("session.json");
|
||||
Session::new()
|
||||
.save_to_path(&session_path)
|
||||
.expect("session should save");
|
||||
|
||||
let session = Session::load_from_path(&session_path).expect("session should load");
|
||||
let outcome = with_current_dir(&root, || {
|
||||
run_resume_command(&session_path, &session, &SlashCommand::Diff)
|
||||
.expect("resume diff should work")
|
||||
});
|
||||
let message = outcome.message.expect("diff message should exist");
|
||||
assert!(message.contains("Unstaged changes:"));
|
||||
assert!(message.contains("tracked.txt"));
|
||||
|
||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user