mirror of
https://github.com/instructkr/claw-code.git
synced 2026-04-03 20:44:48 +08:00
Compare commits
1 Commits
rcc/memory
...
rcc/thinki
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c14196c730 |
@@ -912,6 +912,7 @@ mod tests {
|
|||||||
system: None,
|
system: None,
|
||||||
tools: None,
|
tools: None,
|
||||||
tool_choice: None,
|
tool_choice: None,
|
||||||
|
thinking: None,
|
||||||
stream: false,
|
stream: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -13,5 +13,5 @@ pub use types::{
|
|||||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||||
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
||||||
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
|
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
|
||||||
ToolChoice, ToolDefinition, ToolResultContentBlock, Usage,
|
ThinkingConfig, ToolChoice, ToolDefinition, ToolResultContentBlock, Usage,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ pub struct MessageRequest {
|
|||||||
pub tools: Option<Vec<ToolDefinition>>,
|
pub tools: Option<Vec<ToolDefinition>>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub tool_choice: Option<ToolChoice>,
|
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")]
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
pub stream: bool,
|
pub stream: bool,
|
||||||
}
|
}
|
||||||
@@ -24,6 +26,23 @@ 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)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct InputMessage {
|
pub struct InputMessage {
|
||||||
pub role: String,
|
pub role: String,
|
||||||
@@ -130,6 +149,11 @@ pub enum OutputContentBlock {
|
|||||||
Text {
|
Text {
|
||||||
text: String,
|
text: String,
|
||||||
},
|
},
|
||||||
|
Thinking {
|
||||||
|
thinking: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
signature: Option<String>,
|
||||||
|
},
|
||||||
ToolUse {
|
ToolUse {
|
||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
@@ -189,6 +213,8 @@ pub struct ContentBlockDeltaEvent {
|
|||||||
#[serde(tag = "type", rename_all = "snake_case")]
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
pub enum ContentBlockDelta {
|
pub enum ContentBlockDelta {
|
||||||
TextDelta { text: String },
|
TextDelta { text: String },
|
||||||
|
ThinkingDelta { thinking: String },
|
||||||
|
SignatureDelta { signature: String },
|
||||||
InputJsonDelta { partial_json: String },
|
InputJsonDelta { partial_json: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -258,6 +258,7 @@ async fn live_stream_smoke_test() {
|
|||||||
system: None,
|
system: None,
|
||||||
tools: None,
|
tools: None,
|
||||||
tool_choice: None,
|
tool_choice: None,
|
||||||
|
thinking: None,
|
||||||
stream: false,
|
stream: false,
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
@@ -438,6 +439,7 @@ fn sample_request(stream: bool) -> MessageRequest {
|
|||||||
}),
|
}),
|
||||||
}]),
|
}]),
|
||||||
tool_choice: Some(ToolChoice::Auto),
|
tool_choice: Some(ToolChoice::Auto),
|
||||||
|
thinking: None,
|
||||||
stream,
|
stream,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -57,6 +57,12 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: true,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
|
SlashCommandSpec {
|
||||||
|
name: "thinking",
|
||||||
|
summary: "Show or toggle extended thinking",
|
||||||
|
argument_hint: Some("[on|off]"),
|
||||||
|
resume_supported: false,
|
||||||
|
},
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "model",
|
name: "model",
|
||||||
summary: "Show or switch the active model",
|
summary: "Show or switch the active model",
|
||||||
@@ -136,6 +142,9 @@ pub enum SlashCommand {
|
|||||||
Help,
|
Help,
|
||||||
Status,
|
Status,
|
||||||
Compact,
|
Compact,
|
||||||
|
Thinking {
|
||||||
|
enabled: Option<bool>,
|
||||||
|
},
|
||||||
Model {
|
Model {
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
},
|
},
|
||||||
@@ -180,6 +189,13 @@ impl SlashCommand {
|
|||||||
"help" => Self::Help,
|
"help" => Self::Help,
|
||||||
"status" => Self::Status,
|
"status" => Self::Status,
|
||||||
"compact" => Self::Compact,
|
"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" => Self::Model {
|
||||||
model: parts.next().map(ToOwned::to_owned),
|
model: parts.next().map(ToOwned::to_owned),
|
||||||
},
|
},
|
||||||
@@ -279,6 +295,7 @@ pub fn handle_slash_command(
|
|||||||
session: session.clone(),
|
session: session.clone(),
|
||||||
}),
|
}),
|
||||||
SlashCommand::Status
|
SlashCommand::Status
|
||||||
|
| SlashCommand::Thinking { .. }
|
||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Clear { .. }
|
| SlashCommand::Clear { .. }
|
||||||
@@ -307,6 +324,22 @@ mod tests {
|
|||||||
fn parses_supported_slash_commands() {
|
fn parses_supported_slash_commands() {
|
||||||
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
||||||
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
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!(
|
assert_eq!(
|
||||||
SlashCommand::parse("/model claude-opus"),
|
SlashCommand::parse("/model claude-opus"),
|
||||||
Some(SlashCommand::Model {
|
Some(SlashCommand::Model {
|
||||||
@@ -374,6 +407,7 @@ mod tests {
|
|||||||
assert!(help.contains("/help"));
|
assert!(help.contains("/help"));
|
||||||
assert!(help.contains("/status"));
|
assert!(help.contains("/status"));
|
||||||
assert!(help.contains("/compact"));
|
assert!(help.contains("/compact"));
|
||||||
|
assert!(help.contains("/thinking [on|off]"));
|
||||||
assert!(help.contains("/model [model]"));
|
assert!(help.contains("/model [model]"));
|
||||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||||
assert!(help.contains("/clear [--confirm]"));
|
assert!(help.contains("/clear [--confirm]"));
|
||||||
@@ -386,7 +420,7 @@ mod tests {
|
|||||||
assert!(help.contains("/version"));
|
assert!(help.contains("/version"));
|
||||||
assert!(help.contains("/export [file]"));
|
assert!(help.contains("/export [file]"));
|
||||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||||
assert_eq!(slash_command_specs().len(), 15);
|
assert_eq!(slash_command_specs().len(), 16);
|
||||||
assert_eq!(resume_supported_slash_commands().len(), 11);
|
assert_eq!(resume_supported_slash_commands().len(), 11);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -434,6 +468,9 @@ mod tests {
|
|||||||
let session = Session::new();
|
let session = Session::new();
|
||||||
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
||||||
assert!(handle_slash_command("/status", &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!(
|
assert!(
|
||||||
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
use std::fs;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -93,7 +90,6 @@ pub fn compact_session(session: &Session, config: CompactionConfig) -> Compactio
|
|||||||
let preserved = session.messages[keep_from..].to_vec();
|
let preserved = session.messages[keep_from..].to_vec();
|
||||||
let summary = summarize_messages(removed);
|
let summary = summarize_messages(removed);
|
||||||
let formatted_summary = format_compact_summary(&summary);
|
let formatted_summary = format_compact_summary(&summary);
|
||||||
persist_compact_summary(&formatted_summary);
|
|
||||||
let continuation = get_compact_continuation_message(&summary, true, !preserved.is_empty());
|
let continuation = get_compact_continuation_message(&summary, true, !preserved.is_empty());
|
||||||
|
|
||||||
let mut compacted_messages = vec![ConversationMessage {
|
let mut compacted_messages = vec![ConversationMessage {
|
||||||
@@ -114,35 +110,6 @@ pub fn compact_session(session: &Session, config: CompactionConfig) -> Compactio
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn persist_compact_summary(formatted_summary: &str) {
|
|
||||||
if formatted_summary.trim().is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let Ok(cwd) = std::env::current_dir() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let memory_dir = cwd.join(".claude").join("memory");
|
|
||||||
if fs::create_dir_all(&memory_dir).is_err() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let path = memory_dir.join(compact_summary_filename());
|
|
||||||
let _ = fs::write(path, render_memory_file(formatted_summary));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compact_summary_filename() -> String {
|
|
||||||
let timestamp = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs();
|
|
||||||
format!("summary-{timestamp}.md")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_memory_file(formatted_summary: &str) -> String {
|
|
||||||
format!("# Project memory\n\n{}\n", formatted_summary.trim())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
||||||
let user_messages = messages
|
let user_messages = messages
|
||||||
.iter()
|
.iter()
|
||||||
@@ -163,7 +130,7 @@ fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
|||||||
.filter_map(|block| match block {
|
.filter_map(|block| match block {
|
||||||
ContentBlock::ToolUse { name, .. } => Some(name.as_str()),
|
ContentBlock::ToolUse { name, .. } => Some(name.as_str()),
|
||||||
ContentBlock::ToolResult { tool_name, .. } => Some(tool_name.as_str()),
|
ContentBlock::ToolResult { tool_name, .. } => Some(tool_name.as_str()),
|
||||||
ContentBlock::Text { .. } => None,
|
ContentBlock::Text { .. } | ContentBlock::Thinking { .. } => None,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
tool_names.sort_unstable();
|
tool_names.sort_unstable();
|
||||||
@@ -233,6 +200,7 @@ fn summarize_messages(messages: &[ConversationMessage]) -> String {
|
|||||||
fn summarize_block(block: &ContentBlock) -> String {
|
fn summarize_block(block: &ContentBlock) -> String {
|
||||||
let raw = match block {
|
let raw = match block {
|
||||||
ContentBlock::Text { text } => text.clone(),
|
ContentBlock::Text { text } => text.clone(),
|
||||||
|
ContentBlock::Thinking { text, .. } => format!("thinking: {text}"),
|
||||||
ContentBlock::ToolUse { name, input, .. } => format!("tool_use {name}({input})"),
|
ContentBlock::ToolUse { name, input, .. } => format!("tool_use {name}({input})"),
|
||||||
ContentBlock::ToolResult {
|
ContentBlock::ToolResult {
|
||||||
tool_name,
|
tool_name,
|
||||||
@@ -291,7 +259,7 @@ fn collect_key_files(messages: &[ConversationMessage]) -> Vec<String> {
|
|||||||
.iter()
|
.iter()
|
||||||
.flat_map(|message| message.blocks.iter())
|
.flat_map(|message| message.blocks.iter())
|
||||||
.map(|block| match block {
|
.map(|block| match block {
|
||||||
ContentBlock::Text { text } => text.as_str(),
|
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } => text.as_str(),
|
||||||
ContentBlock::ToolUse { input, .. } => input.as_str(),
|
ContentBlock::ToolUse { input, .. } => input.as_str(),
|
||||||
ContentBlock::ToolResult { output, .. } => output.as_str(),
|
ContentBlock::ToolResult { output, .. } => output.as_str(),
|
||||||
})
|
})
|
||||||
@@ -313,10 +281,15 @@ fn infer_current_work(messages: &[ConversationMessage]) -> Option<String> {
|
|||||||
|
|
||||||
fn first_text_block(message: &ConversationMessage) -> Option<&str> {
|
fn first_text_block(message: &ConversationMessage) -> Option<&str> {
|
||||||
message.blocks.iter().find_map(|block| match block {
|
message.blocks.iter().find_map(|block| match block {
|
||||||
ContentBlock::Text { text } if !text.trim().is_empty() => Some(text.as_str()),
|
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. }
|
||||||
|
if !text.trim().is_empty() =>
|
||||||
|
{
|
||||||
|
Some(text.as_str())
|
||||||
|
}
|
||||||
ContentBlock::ToolUse { .. }
|
ContentBlock::ToolUse { .. }
|
||||||
| ContentBlock::ToolResult { .. }
|
| ContentBlock::ToolResult { .. }
|
||||||
| ContentBlock::Text { .. } => None,
|
| ContentBlock::Text { .. }
|
||||||
|
| ContentBlock::Thinking { .. } => None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -361,7 +334,7 @@ fn estimate_message_tokens(message: &ConversationMessage) -> usize {
|
|||||||
.blocks
|
.blocks
|
||||||
.iter()
|
.iter()
|
||||||
.map(|block| match block {
|
.map(|block| match block {
|
||||||
ContentBlock::Text { text } => text.len() / 4 + 1,
|
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } => text.len() / 4 + 1,
|
||||||
ContentBlock::ToolUse { name, input, .. } => (name.len() + input.len()) / 4 + 1,
|
ContentBlock::ToolUse { name, input, .. } => (name.len() + input.len()) / 4 + 1,
|
||||||
ContentBlock::ToolResult {
|
ContentBlock::ToolResult {
|
||||||
tool_name, output, ..
|
tool_name, output, ..
|
||||||
@@ -411,21 +384,14 @@ fn collapse_blank_lines(content: &str) -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
collect_key_files, compact_session, estimate_session_tokens, format_compact_summary,
|
collect_key_files, compact_session, estimate_session_tokens, format_compact_summary,
|
||||||
infer_pending_work, render_memory_file, should_compact, CompactionConfig,
|
infer_pending_work, should_compact, CompactionConfig,
|
||||||
};
|
};
|
||||||
use std::fs;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
use crate::session::{ContentBlock, ConversationMessage, MessageRole, Session};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn formats_compact_summary_like_upstream() {
|
fn formats_compact_summary_like_upstream() {
|
||||||
let summary = "<analysis>scratch</analysis>\n<summary>Kept work</summary>";
|
let summary = "<analysis>scratch</analysis>\n<summary>Kept work</summary>";
|
||||||
assert_eq!(format_compact_summary(summary), "Summary:\nKept work");
|
assert_eq!(format_compact_summary(summary), "Summary:\nKept work");
|
||||||
assert_eq!(
|
|
||||||
render_memory_file("Summary:\nKept work"),
|
|
||||||
"# Project memory\n\nSummary:\nKept work\n"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -442,63 +408,6 @@ mod tests {
|
|||||||
assert!(result.formatted_summary.is_empty());
|
assert!(result.formatted_summary.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn persists_compacted_summaries_under_dot_claude_memory() {
|
|
||||||
let _guard = crate::test_env_lock();
|
|
||||||
let temp = std::env::temp_dir().join(format!(
|
|
||||||
"runtime-compact-memory-{}",
|
|
||||||
SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.expect("time after epoch")
|
|
||||||
.as_nanos()
|
|
||||||
));
|
|
||||||
fs::create_dir_all(&temp).expect("temp dir");
|
|
||||||
let previous = std::env::current_dir().expect("cwd");
|
|
||||||
std::env::set_current_dir(&temp).expect("set cwd");
|
|
||||||
|
|
||||||
let session = Session {
|
|
||||||
version: 1,
|
|
||||||
messages: vec![
|
|
||||||
ConversationMessage::user_text("one ".repeat(200)),
|
|
||||||
ConversationMessage::assistant(vec![ContentBlock::Text {
|
|
||||||
text: "two ".repeat(200),
|
|
||||||
}]),
|
|
||||||
ConversationMessage::tool_result("1", "bash", "ok ".repeat(200), false),
|
|
||||||
ConversationMessage {
|
|
||||||
role: MessageRole::Assistant,
|
|
||||||
blocks: vec![ContentBlock::Text {
|
|
||||||
text: "recent".to_string(),
|
|
||||||
}],
|
|
||||||
usage: None,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = compact_session(
|
|
||||||
&session,
|
|
||||||
CompactionConfig {
|
|
||||||
preserve_recent_messages: 2,
|
|
||||||
max_estimated_tokens: 1,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let memory_dir = temp.join(".claude").join("memory");
|
|
||||||
let files = fs::read_dir(&memory_dir)
|
|
||||||
.expect("memory dir exists")
|
|
||||||
.flatten()
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
assert_eq!(result.removed_message_count, 2);
|
|
||||||
assert_eq!(files.len(), 1);
|
|
||||||
let persisted = fs::read_to_string(&files[0]).expect("memory file readable");
|
|
||||||
|
|
||||||
std::env::set_current_dir(previous).expect("restore cwd");
|
|
||||||
fs::remove_dir_all(temp).expect("cleanup temp dir");
|
|
||||||
|
|
||||||
assert!(persisted.contains("# Project memory"));
|
|
||||||
assert!(persisted.contains("Summary:"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn compacts_older_messages_into_a_system_summary() {
|
fn compacts_older_messages_into_a_system_summary() {
|
||||||
let session = Session {
|
let session = Session {
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ pub struct ApiRequest {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum AssistantEvent {
|
pub enum AssistantEvent {
|
||||||
TextDelta(String),
|
TextDelta(String),
|
||||||
|
ThinkingDelta(String),
|
||||||
|
ThinkingSignature(String),
|
||||||
ToolUse {
|
ToolUse {
|
||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
@@ -247,15 +249,26 @@ fn build_assistant_message(
|
|||||||
events: Vec<AssistantEvent>,
|
events: Vec<AssistantEvent>,
|
||||||
) -> Result<(ConversationMessage, Option<TokenUsage>), RuntimeError> {
|
) -> Result<(ConversationMessage, Option<TokenUsage>), RuntimeError> {
|
||||||
let mut text = String::new();
|
let mut text = String::new();
|
||||||
|
let mut thinking = String::new();
|
||||||
|
let mut thinking_signature: Option<String> = None;
|
||||||
let mut blocks = Vec::new();
|
let mut blocks = Vec::new();
|
||||||
let mut finished = false;
|
let mut finished = false;
|
||||||
let mut usage = None;
|
let mut usage = None;
|
||||||
|
|
||||||
for event in events {
|
for event in events {
|
||||||
match event {
|
match event {
|
||||||
AssistantEvent::TextDelta(delta) => text.push_str(&delta),
|
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::ToolUse { id, name, input } => {
|
AssistantEvent::ToolUse { id, name, input } => {
|
||||||
flush_text_block(&mut text, &mut blocks);
|
flush_text_block(&mut text, &mut blocks);
|
||||||
|
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
|
||||||
blocks.push(ContentBlock::ToolUse { id, name, input });
|
blocks.push(ContentBlock::ToolUse { id, name, input });
|
||||||
}
|
}
|
||||||
AssistantEvent::Usage(value) => usage = Some(value),
|
AssistantEvent::Usage(value) => usage = Some(value),
|
||||||
@@ -266,6 +279,7 @@ fn build_assistant_message(
|
|||||||
}
|
}
|
||||||
|
|
||||||
flush_text_block(&mut text, &mut blocks);
|
flush_text_block(&mut text, &mut blocks);
|
||||||
|
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
|
||||||
|
|
||||||
if !finished {
|
if !finished {
|
||||||
return Err(RuntimeError::new(
|
return Err(RuntimeError::new(
|
||||||
@@ -290,6 +304,19 @@ 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>>;
|
type ToolHandler = Box<dyn FnMut(&str) -> Result<String, ToolError>>;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -325,8 +352,8 @@ impl ToolExecutor for StaticToolExecutor {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError,
|
build_assistant_message, ApiClient, ApiRequest, AssistantEvent, ConversationRuntime,
|
||||||
StaticToolExecutor,
|
RuntimeError, StaticToolExecutor,
|
||||||
};
|
};
|
||||||
use crate::compact::CompactionConfig;
|
use crate::compact::CompactionConfig;
|
||||||
use crate::permissions::{
|
use crate::permissions::{
|
||||||
@@ -415,7 +442,6 @@ mod tests {
|
|||||||
current_date: "2026-03-31".to_string(),
|
current_date: "2026-03-31".to_string(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
instruction_files: Vec::new(),
|
instruction_files: Vec::new(),
|
||||||
memory_files: Vec::new(),
|
|
||||||
})
|
})
|
||||||
.with_os("linux", "6.8")
|
.with_os("linux", "6.8")
|
||||||
.build();
|
.build();
|
||||||
@@ -503,6 +529,29 @@ 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]
|
#[test]
|
||||||
fn reconstructs_usage_tracker_from_restored_session() {
|
fn reconstructs_usage_tracker_from_restored_session() {
|
||||||
struct SimpleApi;
|
struct SimpleApi;
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ pub struct ProjectContext {
|
|||||||
pub current_date: String,
|
pub current_date: String,
|
||||||
pub git_status: Option<String>,
|
pub git_status: Option<String>,
|
||||||
pub instruction_files: Vec<ContextFile>,
|
pub instruction_files: Vec<ContextFile>,
|
||||||
pub memory_files: Vec<ContextFile>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProjectContext {
|
impl ProjectContext {
|
||||||
@@ -61,13 +60,11 @@ impl ProjectContext {
|
|||||||
) -> std::io::Result<Self> {
|
) -> std::io::Result<Self> {
|
||||||
let cwd = cwd.into();
|
let cwd = cwd.into();
|
||||||
let instruction_files = discover_instruction_files(&cwd)?;
|
let instruction_files = discover_instruction_files(&cwd)?;
|
||||||
let memory_files = discover_memory_files(&cwd)?;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
cwd,
|
cwd,
|
||||||
current_date: current_date.into(),
|
current_date: current_date.into(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
instruction_files,
|
instruction_files,
|
||||||
memory_files,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,9 +144,6 @@ impl SystemPromptBuilder {
|
|||||||
if !project_context.instruction_files.is_empty() {
|
if !project_context.instruction_files.is_empty() {
|
||||||
sections.push(render_instruction_files(&project_context.instruction_files));
|
sections.push(render_instruction_files(&project_context.instruction_files));
|
||||||
}
|
}
|
||||||
if !project_context.memory_files.is_empty() {
|
|
||||||
sections.push(render_memory_files(&project_context.memory_files));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if let Some(config) = &self.config {
|
if let Some(config) = &self.config {
|
||||||
sections.push(render_config_section(config));
|
sections.push(render_config_section(config));
|
||||||
@@ -192,7 +186,7 @@ pub fn prepend_bullets(items: Vec<String>) -> Vec<String> {
|
|||||||
items.into_iter().map(|item| format!(" - {item}")).collect()
|
items.into_iter().map(|item| format!(" - {item}")).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn discover_context_directories(cwd: &Path) -> Vec<PathBuf> {
|
fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
||||||
let mut directories = Vec::new();
|
let mut directories = Vec::new();
|
||||||
let mut cursor = Some(cwd);
|
let mut cursor = Some(cwd);
|
||||||
while let Some(dir) = cursor {
|
while let Some(dir) = cursor {
|
||||||
@@ -200,11 +194,6 @@ fn discover_context_directories(cwd: &Path) -> Vec<PathBuf> {
|
|||||||
cursor = dir.parent();
|
cursor = dir.parent();
|
||||||
}
|
}
|
||||||
directories.reverse();
|
directories.reverse();
|
||||||
directories
|
|
||||||
}
|
|
||||||
|
|
||||||
fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|
||||||
let directories = discover_context_directories(cwd);
|
|
||||||
|
|
||||||
let mut files = Vec::new();
|
let mut files = Vec::new();
|
||||||
for dir in directories {
|
for dir in directories {
|
||||||
@@ -220,26 +209,6 @@ fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|||||||
Ok(dedupe_instruction_files(files))
|
Ok(dedupe_instruction_files(files))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn discover_memory_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|
||||||
let mut files = Vec::new();
|
|
||||||
for dir in discover_context_directories(cwd) {
|
|
||||||
let memory_dir = dir.join(".claude").join("memory");
|
|
||||||
let Ok(entries) = fs::read_dir(&memory_dir) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let mut paths = entries
|
|
||||||
.flatten()
|
|
||||||
.map(|entry| entry.path())
|
|
||||||
.filter(|path| path.is_file())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
paths.sort();
|
|
||||||
for path in paths {
|
|
||||||
push_context_file(&mut files, path)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(dedupe_instruction_files(files))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push_context_file(files: &mut Vec<ContextFile>, path: PathBuf) -> std::io::Result<()> {
|
fn push_context_file(files: &mut Vec<ContextFile>, path: PathBuf) -> std::io::Result<()> {
|
||||||
match fs::read_to_string(&path) {
|
match fs::read_to_string(&path) {
|
||||||
Ok(content) if !content.trim().is_empty() => {
|
Ok(content) if !content.trim().is_empty() => {
|
||||||
@@ -282,12 +251,6 @@ fn render_project_context(project_context: &ProjectContext) -> String {
|
|||||||
project_context.instruction_files.len()
|
project_context.instruction_files.len()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !project_context.memory_files.is_empty() {
|
|
||||||
bullets.push(format!(
|
|
||||||
"Project memory files discovered: {}.",
|
|
||||||
project_context.memory_files.len()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
lines.extend(prepend_bullets(bullets));
|
lines.extend(prepend_bullets(bullets));
|
||||||
if let Some(status) = &project_context.git_status {
|
if let Some(status) = &project_context.git_status {
|
||||||
lines.push(String::new());
|
lines.push(String::new());
|
||||||
@@ -298,15 +261,7 @@ fn render_project_context(project_context: &ProjectContext) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn render_instruction_files(files: &[ContextFile]) -> String {
|
fn render_instruction_files(files: &[ContextFile]) -> String {
|
||||||
render_context_file_section("# Claude instructions", files)
|
let mut sections = vec!["# Claude instructions".to_string()];
|
||||||
}
|
|
||||||
|
|
||||||
fn render_memory_files(files: &[ContextFile]) -> String {
|
|
||||||
render_context_file_section("# Project memory", files)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_context_file_section(title: &str, files: &[ContextFile]) -> String {
|
|
||||||
let mut sections = vec![title.to_string()];
|
|
||||||
let mut remaining_chars = MAX_TOTAL_INSTRUCTION_CHARS;
|
let mut remaining_chars = MAX_TOTAL_INSTRUCTION_CHARS;
|
||||||
for file in files {
|
for file in files {
|
||||||
if remaining_chars == 0 {
|
if remaining_chars == 0 {
|
||||||
@@ -498,9 +453,8 @@ fn get_actions_section() -> String {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
collapse_blank_lines, display_context_path, normalize_instruction_content,
|
collapse_blank_lines, display_context_path, normalize_instruction_content,
|
||||||
render_instruction_content, render_instruction_files, render_memory_files,
|
render_instruction_content, render_instruction_files, truncate_instruction_content,
|
||||||
truncate_instruction_content, ContextFile, ProjectContext, SystemPromptBuilder,
|
ContextFile, ProjectContext, SystemPromptBuilder, SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
|
||||||
SYSTEM_PROMPT_DYNAMIC_BOUNDARY,
|
|
||||||
};
|
};
|
||||||
use crate::config::ConfigLoader;
|
use crate::config::ConfigLoader;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -565,35 +519,6 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn discovers_project_memory_files_from_ancestor_chain() {
|
|
||||||
let root = temp_dir();
|
|
||||||
let nested = root.join("apps").join("api");
|
|
||||||
fs::create_dir_all(root.join(".claude").join("memory")).expect("root memory dir");
|
|
||||||
fs::create_dir_all(nested.join(".claude").join("memory")).expect("nested memory dir");
|
|
||||||
fs::write(
|
|
||||||
root.join(".claude").join("memory").join("2026-03-30.md"),
|
|
||||||
"root memory",
|
|
||||||
)
|
|
||||||
.expect("write root memory");
|
|
||||||
fs::write(
|
|
||||||
nested.join(".claude").join("memory").join("2026-03-31.md"),
|
|
||||||
"nested memory",
|
|
||||||
)
|
|
||||||
.expect("write nested memory");
|
|
||||||
|
|
||||||
let context = ProjectContext::discover(&nested, "2026-03-31").expect("context should load");
|
|
||||||
let contents = context
|
|
||||||
.memory_files
|
|
||||||
.iter()
|
|
||||||
.map(|file| file.content.as_str())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
assert_eq!(contents, vec!["root memory", "nested memory"]);
|
|
||||||
assert!(render_memory_files(&context.memory_files).contains("# Project memory"));
|
|
||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dedupes_identical_instruction_content_across_scopes() {
|
fn dedupes_identical_instruction_content_across_scopes() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ pub enum ContentBlock {
|
|||||||
Text {
|
Text {
|
||||||
text: String,
|
text: String,
|
||||||
},
|
},
|
||||||
|
Thinking {
|
||||||
|
text: String,
|
||||||
|
signature: Option<String>,
|
||||||
|
},
|
||||||
ToolUse {
|
ToolUse {
|
||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
@@ -257,6 +261,19 @@ impl ContentBlock {
|
|||||||
object.insert("type".to_string(), JsonValue::String("text".to_string()));
|
object.insert("type".to_string(), JsonValue::String("text".to_string()));
|
||||||
object.insert("text".to_string(), JsonValue::String(text.clone()));
|
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 } => {
|
Self::ToolUse { id, name, input } => {
|
||||||
object.insert(
|
object.insert(
|
||||||
"type".to_string(),
|
"type".to_string(),
|
||||||
@@ -303,6 +320,13 @@ impl ContentBlock {
|
|||||||
"text" => Ok(Self::Text {
|
"text" => Ok(Self::Text {
|
||||||
text: required_string(object, "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 {
|
"tool_use" => Ok(Self::ToolUse {
|
||||||
id: required_string(object, "id")?,
|
id: required_string(object, "id")?,
|
||||||
name: required_string(object, "name")?,
|
name: required_string(object, "name")?,
|
||||||
|
|||||||
@@ -13,7 +13,8 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
|||||||
use api::{
|
use api::{
|
||||||
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
|
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
|
||||||
InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
|
InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
|
||||||
StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
|
StreamEvent as ApiStreamEvent, ThinkingConfig, ToolChoice, ToolDefinition,
|
||||||
|
ToolResultContentBlock,
|
||||||
};
|
};
|
||||||
|
|
||||||
use commands::{
|
use commands::{
|
||||||
@@ -34,6 +35,7 @@ use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
|||||||
|
|
||||||
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
||||||
const DEFAULT_MAX_TOKENS: u32 = 32;
|
const DEFAULT_MAX_TOKENS: u32 = 32;
|
||||||
|
const DEFAULT_THINKING_BUDGET_TOKENS: u32 = 2_048;
|
||||||
const DEFAULT_DATE: &str = "2026-03-31";
|
const DEFAULT_DATE: &str = "2026-03-31";
|
||||||
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
|
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
|
||||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
@@ -70,7 +72,8 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
} => LiveCli::new(model, false, allowed_tools, permission_mode)?
|
thinking,
|
||||||
|
} => LiveCli::new(model, false, allowed_tools, permission_mode, thinking)?
|
||||||
.run_turn_with_output(&prompt, output_format)?,
|
.run_turn_with_output(&prompt, output_format)?,
|
||||||
CliAction::Login => run_login()?,
|
CliAction::Login => run_login()?,
|
||||||
CliAction::Logout => run_logout()?,
|
CliAction::Logout => run_logout()?,
|
||||||
@@ -78,7 +81,8 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
} => run_repl(model, allowed_tools, permission_mode)?,
|
thinking,
|
||||||
|
} => run_repl(model, allowed_tools, permission_mode, thinking)?,
|
||||||
CliAction::Help => print_help(),
|
CliAction::Help => print_help(),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -103,6 +107,7 @@ enum CliAction {
|
|||||||
output_format: CliOutputFormat,
|
output_format: CliOutputFormat,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
|
thinking: bool,
|
||||||
},
|
},
|
||||||
Login,
|
Login,
|
||||||
Logout,
|
Logout,
|
||||||
@@ -110,6 +115,7 @@ enum CliAction {
|
|||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
|
thinking: bool,
|
||||||
},
|
},
|
||||||
// prompt-mode formatting is only supported for non-interactive runs
|
// prompt-mode formatting is only supported for non-interactive runs
|
||||||
Help,
|
Help,
|
||||||
@@ -139,6 +145,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
let mut output_format = CliOutputFormat::Text;
|
let mut output_format = CliOutputFormat::Text;
|
||||||
let mut permission_mode = default_permission_mode();
|
let mut permission_mode = default_permission_mode();
|
||||||
let mut wants_version = false;
|
let mut wants_version = false;
|
||||||
|
let mut thinking = false;
|
||||||
let mut allowed_tool_values = Vec::new();
|
let mut allowed_tool_values = Vec::new();
|
||||||
let mut rest = Vec::new();
|
let mut rest = Vec::new();
|
||||||
let mut index = 0;
|
let mut index = 0;
|
||||||
@@ -149,6 +156,10 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
wants_version = true;
|
wants_version = true;
|
||||||
index += 1;
|
index += 1;
|
||||||
}
|
}
|
||||||
|
"--thinking" => {
|
||||||
|
thinking = true;
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
"--model" => {
|
"--model" => {
|
||||||
let value = args
|
let value = args
|
||||||
.get(index + 1)
|
.get(index + 1)
|
||||||
@@ -215,6 +226,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
|
thinking,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
|
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
|
||||||
@@ -241,6 +253,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
|
thinking,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
other if !other.starts_with('/') => Ok(CliAction::Prompt {
|
other if !other.starts_with('/') => Ok(CliAction::Prompt {
|
||||||
@@ -249,6 +262,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
|
thinking,
|
||||||
}),
|
}),
|
||||||
other => Err(format!("unknown subcommand: {other}")),
|
other => Err(format!("unknown subcommand: {other}")),
|
||||||
}
|
}
|
||||||
@@ -600,6 +614,7 @@ struct StatusUsage {
|
|||||||
latest: TokenUsage,
|
latest: TokenUsage,
|
||||||
cumulative: TokenUsage,
|
cumulative: TokenUsage,
|
||||||
estimated_tokens: usize,
|
estimated_tokens: usize,
|
||||||
|
thinking_enabled: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
|
fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
|
||||||
@@ -667,6 +682,39 @@ 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 {
|
fn format_permissions_switch_report(previous: &str, next: &str) -> String {
|
||||||
format!(
|
format!(
|
||||||
"Permissions updated
|
"Permissions updated
|
||||||
@@ -834,6 +882,7 @@ fn run_resume_command(
|
|||||||
latest: tracker.current_turn_usage(),
|
latest: tracker.current_turn_usage(),
|
||||||
cumulative: usage,
|
cumulative: usage,
|
||||||
estimated_tokens: 0,
|
estimated_tokens: 0,
|
||||||
|
thinking_enabled: false,
|
||||||
},
|
},
|
||||||
default_permission_mode().as_str(),
|
default_permission_mode().as_str(),
|
||||||
&status_context(Some(session_path))?,
|
&status_context(Some(session_path))?,
|
||||||
@@ -880,6 +929,7 @@ fn run_resume_command(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
SlashCommand::Resume { .. }
|
SlashCommand::Resume { .. }
|
||||||
|
| SlashCommand::Thinking { .. }
|
||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Session { .. }
|
| SlashCommand::Session { .. }
|
||||||
@@ -891,8 +941,15 @@ fn run_repl(
|
|||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
|
thinking_enabled: bool,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
|
let mut cli = LiveCli::new(
|
||||||
|
model,
|
||||||
|
true,
|
||||||
|
allowed_tools,
|
||||||
|
permission_mode,
|
||||||
|
thinking_enabled,
|
||||||
|
)?;
|
||||||
let mut editor = input::LineEditor::new("› ", slash_command_completion_candidates());
|
let mut editor = input::LineEditor::new("› ", slash_command_completion_candidates());
|
||||||
println!("{}", cli.startup_banner());
|
println!("{}", cli.startup_banner());
|
||||||
|
|
||||||
@@ -945,6 +1002,7 @@ struct LiveCli {
|
|||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
|
thinking_enabled: bool,
|
||||||
system_prompt: Vec<String>,
|
system_prompt: Vec<String>,
|
||||||
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
|
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
|
||||||
session: SessionHandle,
|
session: SessionHandle,
|
||||||
@@ -956,6 +1014,7 @@ impl LiveCli {
|
|||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
|
thinking_enabled: bool,
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
let system_prompt = build_system_prompt()?;
|
let system_prompt = build_system_prompt()?;
|
||||||
let session = create_managed_session_handle()?;
|
let session = create_managed_session_handle()?;
|
||||||
@@ -966,11 +1025,13 @@ impl LiveCli {
|
|||||||
enable_tools,
|
enable_tools,
|
||||||
allowed_tools.clone(),
|
allowed_tools.clone(),
|
||||||
permission_mode,
|
permission_mode,
|
||||||
|
thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
let cli = Self {
|
let cli = Self {
|
||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
|
thinking_enabled,
|
||||||
system_prompt,
|
system_prompt,
|
||||||
runtime,
|
runtime,
|
||||||
session,
|
session,
|
||||||
@@ -981,9 +1042,10 @@ impl LiveCli {
|
|||||||
|
|
||||||
fn startup_banner(&self) -> String {
|
fn startup_banner(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
"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.",
|
"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.",
|
||||||
self.model,
|
self.model,
|
||||||
self.permission_mode.as_str(),
|
self.permission_mode.as_str(),
|
||||||
|
if self.thinking_enabled { "on" } else { "off" },
|
||||||
env::current_dir().map_or_else(
|
env::current_dir().map_or_else(
|
||||||
|_| "<unknown>".to_string(),
|
|_| "<unknown>".to_string(),
|
||||||
|path| path.display().to_string(),
|
|path| path.display().to_string(),
|
||||||
@@ -1049,6 +1111,9 @@ impl LiveCli {
|
|||||||
system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")),
|
system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")),
|
||||||
tools: None,
|
tools: None,
|
||||||
tool_choice: None,
|
tool_choice: None,
|
||||||
|
thinking: self
|
||||||
|
.thinking_enabled
|
||||||
|
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
|
||||||
stream: false,
|
stream: false,
|
||||||
};
|
};
|
||||||
let runtime = tokio::runtime::Runtime::new()?;
|
let runtime = tokio::runtime::Runtime::new()?;
|
||||||
@@ -1058,7 +1123,7 @@ impl LiveCli {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter_map(|block| match block {
|
.filter_map(|block| match block {
|
||||||
OutputContentBlock::Text { text } => Some(text.as_str()),
|
OutputContentBlock::Text { text } => Some(text.as_str()),
|
||||||
OutputContentBlock::ToolUse { .. } => None,
|
OutputContentBlock::Thinking { .. } | OutputContentBlock::ToolUse { .. } => None,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("");
|
.join("");
|
||||||
@@ -1095,6 +1160,7 @@ impl LiveCli {
|
|||||||
self.compact()?;
|
self.compact()?;
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
SlashCommand::Thinking { enabled } => self.set_thinking(enabled)?,
|
||||||
SlashCommand::Model { model } => self.set_model(model)?,
|
SlashCommand::Model { model } => self.set_model(model)?,
|
||||||
SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
|
SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
|
||||||
SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
|
SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
|
||||||
@@ -1155,6 +1221,7 @@ impl LiveCli {
|
|||||||
latest,
|
latest,
|
||||||
cumulative,
|
cumulative,
|
||||||
estimated_tokens: self.runtime.estimated_tokens(),
|
estimated_tokens: self.runtime.estimated_tokens(),
|
||||||
|
thinking_enabled: self.thinking_enabled,
|
||||||
},
|
},
|
||||||
self.permission_mode.as_str(),
|
self.permission_mode.as_str(),
|
||||||
&status_context(Some(&self.session.path)).expect("status context should load"),
|
&status_context(Some(&self.session.path)).expect("status context should load"),
|
||||||
@@ -1197,6 +1264,7 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
|
self.thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
self.model.clone_from(&model);
|
self.model.clone_from(&model);
|
||||||
println!(
|
println!(
|
||||||
@@ -1206,6 +1274,32 @@ impl LiveCli {
|
|||||||
Ok(true)
|
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(
|
fn set_permissions(
|
||||||
&mut self,
|
&mut self,
|
||||||
mode: Option<String>,
|
mode: Option<String>,
|
||||||
@@ -1239,6 +1333,7 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
|
self.thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
println!(
|
println!(
|
||||||
"{}",
|
"{}",
|
||||||
@@ -1263,6 +1358,7 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
|
self.thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
println!(
|
println!(
|
||||||
"Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
|
"Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
|
||||||
@@ -1297,6 +1393,7 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
|
self.thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
self.session = handle;
|
self.session = handle;
|
||||||
println!(
|
println!(
|
||||||
@@ -1373,6 +1470,7 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
|
self.thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
self.session = handle;
|
self.session = handle;
|
||||||
println!(
|
println!(
|
||||||
@@ -1402,6 +1500,7 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
|
self.thinking_enabled,
|
||||||
)?;
|
)?;
|
||||||
self.persist_session()?;
|
self.persist_session()?;
|
||||||
println!("{}", format_compact_report(removed, kept, skipped));
|
println!("{}", format_compact_report(removed, kept, skipped));
|
||||||
@@ -1513,6 +1612,7 @@ fn render_repl_help() -> String {
|
|||||||
[
|
[
|
||||||
"REPL".to_string(),
|
"REPL".to_string(),
|
||||||
" /exit Quit the 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(),
|
" /quit Quit the REPL".to_string(),
|
||||||
" Up/Down Navigate prompt history".to_string(),
|
" Up/Down Navigate prompt history".to_string(),
|
||||||
" Tab Complete slash commands".to_string(),
|
" Tab Complete slash commands".to_string(),
|
||||||
@@ -1542,8 +1642,7 @@ fn status_context(
|
|||||||
session_path: session_path.map(Path::to_path_buf),
|
session_path: session_path.map(Path::to_path_buf),
|
||||||
loaded_config_files: runtime_config.loaded_entries().len(),
|
loaded_config_files: runtime_config.loaded_entries().len(),
|
||||||
discovered_config_files,
|
discovered_config_files,
|
||||||
memory_file_count: project_context.instruction_files.len()
|
memory_file_count: project_context.instruction_files.len(),
|
||||||
+ project_context.memory_files.len(),
|
|
||||||
project_root,
|
project_root,
|
||||||
git_branch,
|
git_branch,
|
||||||
})
|
})
|
||||||
@@ -1560,10 +1659,14 @@ fn format_status_report(
|
|||||||
"Status
|
"Status
|
||||||
Model {model}
|
Model {model}
|
||||||
Permission mode {permission_mode}
|
Permission mode {permission_mode}
|
||||||
|
Thinking {}
|
||||||
Messages {}
|
Messages {}
|
||||||
Turns {}
|
Turns {}
|
||||||
Estimated tokens {}",
|
Estimated tokens {}",
|
||||||
usage.message_count, usage.turns, usage.estimated_tokens,
|
if usage.thinking_enabled { "on" } else { "off" },
|
||||||
|
usage.message_count,
|
||||||
|
usage.turns,
|
||||||
|
usage.estimated_tokens,
|
||||||
),
|
),
|
||||||
format!(
|
format!(
|
||||||
"Usage
|
"Usage
|
||||||
@@ -1688,50 +1791,26 @@ fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
|
|||||||
let mut lines = vec![format!(
|
let mut lines = vec![format!(
|
||||||
"Memory
|
"Memory
|
||||||
Working directory {}
|
Working directory {}
|
||||||
Instruction files {}
|
Instruction files {}",
|
||||||
Project memory files {}",
|
|
||||||
cwd.display(),
|
cwd.display(),
|
||||||
project_context.instruction_files.len(),
|
project_context.instruction_files.len()
|
||||||
project_context.memory_files.len()
|
|
||||||
)];
|
)];
|
||||||
append_memory_section(
|
if project_context.instruction_files.is_empty() {
|
||||||
&mut lines,
|
lines.push("Discovered files".to_string());
|
||||||
"Instruction files",
|
lines.push(
|
||||||
&project_context.instruction_files,
|
" No CLAUDE instruction files discovered in the current directory ancestry."
|
||||||
"No CLAUDE instruction files discovered in the current directory ancestry.",
|
.to_string(),
|
||||||
);
|
);
|
||||||
append_memory_section(
|
} else {
|
||||||
&mut lines,
|
lines.push("Discovered files".to_string());
|
||||||
"Project memory files",
|
for (index, file) in project_context.instruction_files.iter().enumerate() {
|
||||||
&project_context.memory_files,
|
|
||||||
"No persisted project memory files discovered in .claude/memory.",
|
|
||||||
);
|
|
||||||
Ok(lines.join(
|
|
||||||
"
|
|
||||||
",
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn append_memory_section(
|
|
||||||
lines: &mut Vec<String>,
|
|
||||||
title: &str,
|
|
||||||
files: &[runtime::ContextFile],
|
|
||||||
empty_message: &str,
|
|
||||||
) {
|
|
||||||
lines.push(title.to_string());
|
|
||||||
if files.is_empty() {
|
|
||||||
lines.push(format!(" {empty_message}"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (index, file) in files.iter().enumerate() {
|
|
||||||
let preview = file.content.lines().next().unwrap_or("").trim();
|
let preview = file.content.lines().next().unwrap_or("").trim();
|
||||||
let preview = if preview.is_empty() {
|
let preview = if preview.is_empty() {
|
||||||
"<empty>"
|
"<empty>"
|
||||||
} else {
|
} else {
|
||||||
preview
|
preview
|
||||||
};
|
};
|
||||||
lines.push(format!(" {}. {}", index + 1, file.path.display()));
|
lines.push(format!(" {}. {}", index + 1, file.path.display(),));
|
||||||
lines.push(format!(
|
lines.push(format!(
|
||||||
" lines={} preview={}",
|
" lines={} preview={}",
|
||||||
file.content.lines().count(),
|
file.content.lines().count(),
|
||||||
@@ -1739,6 +1818,11 @@ fn append_memory_section(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Ok(lines.join(
|
||||||
|
"
|
||||||
|
",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
|
fn init_claude_md() -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let cwd = env::current_dir()?;
|
let cwd = env::current_dir()?;
|
||||||
@@ -1854,6 +1938,15 @@ fn render_export_text(session: &Session) -> String {
|
|||||||
for block in &message.blocks {
|
for block in &message.blocks {
|
||||||
match block {
|
match block {
|
||||||
ContentBlock::Text { text } => lines.push(text.clone()),
|
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 } => {
|
ContentBlock::ToolUse { id, name, input } => {
|
||||||
lines.push(format!("[tool_use id={id} name={name}] {input}"));
|
lines.push(format!("[tool_use id={id} name={name}] {input}"));
|
||||||
}
|
}
|
||||||
@@ -1944,11 +2037,12 @@ fn build_runtime(
|
|||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
|
thinking_enabled: bool,
|
||||||
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
|
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
|
||||||
{
|
{
|
||||||
Ok(ConversationRuntime::new(
|
Ok(ConversationRuntime::new(
|
||||||
session,
|
session,
|
||||||
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone())?,
|
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone(), thinking_enabled)?,
|
||||||
CliToolExecutor::new(allowed_tools),
|
CliToolExecutor::new(allowed_tools),
|
||||||
permission_policy(permission_mode),
|
permission_policy(permission_mode),
|
||||||
system_prompt,
|
system_prompt,
|
||||||
@@ -2007,6 +2101,7 @@ struct AnthropicRuntimeClient {
|
|||||||
model: String,
|
model: String,
|
||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
|
thinking_enabled: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AnthropicRuntimeClient {
|
impl AnthropicRuntimeClient {
|
||||||
@@ -2014,6 +2109,7 @@ impl AnthropicRuntimeClient {
|
|||||||
model: String,
|
model: String,
|
||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
|
thinking_enabled: bool,
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
runtime: tokio::runtime::Runtime::new()?,
|
runtime: tokio::runtime::Runtime::new()?,
|
||||||
@@ -2021,6 +2117,7 @@ impl AnthropicRuntimeClient {
|
|||||||
model,
|
model,
|
||||||
enable_tools,
|
enable_tools,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
|
thinking_enabled,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2054,6 +2151,9 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
.collect()
|
.collect()
|
||||||
}),
|
}),
|
||||||
tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
|
tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
|
||||||
|
thinking: self
|
||||||
|
.thinking_enabled
|
||||||
|
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
|
||||||
stream: true,
|
stream: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2066,6 +2166,7 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
let mut events = Vec::new();
|
let mut events = Vec::new();
|
||||||
let mut pending_tool: Option<(String, String, String)> = None;
|
let mut pending_tool: Option<(String, String, String)> = None;
|
||||||
|
let mut pending_thinking_signature: Option<String> = None;
|
||||||
let mut saw_stop = false;
|
let mut saw_stop = false;
|
||||||
|
|
||||||
while let Some(event) = stream
|
while let Some(event) = stream
|
||||||
@@ -2076,7 +2177,13 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
match event {
|
match event {
|
||||||
ApiStreamEvent::MessageStart(start) => {
|
ApiStreamEvent::MessageStart(start) => {
|
||||||
for block in start.message.content {
|
for block in start.message.content {
|
||||||
push_output_block(block, &mut stdout, &mut events, &mut pending_tool)?;
|
push_output_block(
|
||||||
|
block,
|
||||||
|
&mut stdout,
|
||||||
|
&mut events,
|
||||||
|
&mut pending_tool,
|
||||||
|
&mut pending_thinking_signature,
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ApiStreamEvent::ContentBlockStart(start) => {
|
ApiStreamEvent::ContentBlockStart(start) => {
|
||||||
@@ -2085,6 +2192,7 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
&mut stdout,
|
&mut stdout,
|
||||||
&mut events,
|
&mut events,
|
||||||
&mut pending_tool,
|
&mut pending_tool,
|
||||||
|
&mut pending_thinking_signature,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
|
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
|
||||||
@@ -2096,6 +2204,14 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
events.push(AssistantEvent::TextDelta(text));
|
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 } => {
|
ContentBlockDelta::InputJsonDelta { partial_json } => {
|
||||||
if let Some((_, _, input)) = &mut pending_tool {
|
if let Some((_, _, input)) = &mut pending_tool {
|
||||||
input.push_str(&partial_json);
|
input.push_str(&partial_json);
|
||||||
@@ -2125,6 +2241,8 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
if !saw_stop
|
if !saw_stop
|
||||||
&& events.iter().any(|event| {
|
&& events.iter().any(|event| {
|
||||||
matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
|
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 { .. })
|
|| matches!(event, AssistantEvent::ToolUse { .. })
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
@@ -2208,11 +2326,19 @@ 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(
|
fn push_output_block(
|
||||||
block: OutputContentBlock,
|
block: OutputContentBlock,
|
||||||
out: &mut impl Write,
|
out: &mut impl Write,
|
||||||
events: &mut Vec<AssistantEvent>,
|
events: &mut Vec<AssistantEvent>,
|
||||||
pending_tool: &mut Option<(String, String, String)>,
|
pending_tool: &mut Option<(String, String, String)>,
|
||||||
|
pending_thinking_signature: &mut Option<String>,
|
||||||
) -> Result<(), RuntimeError> {
|
) -> Result<(), RuntimeError> {
|
||||||
match block {
|
match block {
|
||||||
OutputContentBlock::Text { text } => {
|
OutputContentBlock::Text { text } => {
|
||||||
@@ -2223,6 +2349,19 @@ fn push_output_block(
|
|||||||
events.push(AssistantEvent::TextDelta(text));
|
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 } => {
|
OutputContentBlock::ToolUse { id, name, input } => {
|
||||||
writeln!(
|
writeln!(
|
||||||
out,
|
out,
|
||||||
@@ -2244,9 +2383,16 @@ fn response_to_events(
|
|||||||
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
||||||
let mut events = Vec::new();
|
let mut events = Vec::new();
|
||||||
let mut pending_tool = None;
|
let mut pending_tool = None;
|
||||||
|
let mut pending_thinking_signature = None;
|
||||||
|
|
||||||
for block in response.content {
|
for block in response.content {
|
||||||
push_output_block(block, out, &mut events, &mut pending_tool)?;
|
push_output_block(
|
||||||
|
block,
|
||||||
|
out,
|
||||||
|
&mut events,
|
||||||
|
&mut pending_tool,
|
||||||
|
&mut pending_thinking_signature,
|
||||||
|
)?;
|
||||||
if let Some((id, name, input)) = pending_tool.take() {
|
if let Some((id, name, input)) = pending_tool.take() {
|
||||||
events.push(AssistantEvent::ToolUse { id, name, input });
|
events.push(AssistantEvent::ToolUse { id, name, input });
|
||||||
}
|
}
|
||||||
@@ -2331,26 +2477,29 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
|
|||||||
let content = message
|
let content = message
|
||||||
.blocks
|
.blocks
|
||||||
.iter()
|
.iter()
|
||||||
.map(|block| match block {
|
.filter_map(|block| match block {
|
||||||
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
|
ContentBlock::Text { text } => {
|
||||||
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
|
Some(InputContentBlock::Text { text: text.clone() })
|
||||||
|
}
|
||||||
|
ContentBlock::Thinking { .. } => None,
|
||||||
|
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
name: name.clone(),
|
name: name.clone(),
|
||||||
input: serde_json::from_str(input)
|
input: serde_json::from_str(input)
|
||||||
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
|
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
|
||||||
},
|
}),
|
||||||
ContentBlock::ToolResult {
|
ContentBlock::ToolResult {
|
||||||
tool_use_id,
|
tool_use_id,
|
||||||
output,
|
output,
|
||||||
is_error,
|
is_error,
|
||||||
..
|
..
|
||||||
} => InputContentBlock::ToolResult {
|
} => Some(InputContentBlock::ToolResult {
|
||||||
tool_use_id: tool_use_id.clone(),
|
tool_use_id: tool_use_id.clone(),
|
||||||
content: vec![ToolResultContentBlock::Text {
|
content: vec![ToolResultContentBlock::Text {
|
||||||
text: output.clone(),
|
text: output.clone(),
|
||||||
}],
|
}],
|
||||||
is_error: *is_error,
|
is_error: *is_error,
|
||||||
},
|
}),
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
(!content.is_empty()).then(|| InputMessage {
|
(!content.is_empty()).then(|| InputMessage {
|
||||||
@@ -2383,6 +2532,7 @@ fn print_help() {
|
|||||||
println!(" --model MODEL Override the active model");
|
println!(" --model MODEL Override the active model");
|
||||||
println!(" --output-format FORMAT Non-interactive output format: text or json");
|
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!(" --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!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
|
||||||
println!(" --version, -V Print version and build information locally");
|
println!(" --version, -V Print version and build information locally");
|
||||||
println!();
|
println!();
|
||||||
@@ -2428,6 +2578,7 @@ mod tests {
|
|||||||
model: DEFAULT_MODEL.to_string(),
|
model: DEFAULT_MODEL.to_string(),
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
|
thinking: false,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2447,6 +2598,7 @@ mod tests {
|
|||||||
output_format: CliOutputFormat::Text,
|
output_format: CliOutputFormat::Text,
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
|
thinking: false,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2468,6 +2620,7 @@ mod tests {
|
|||||||
output_format: CliOutputFormat::Json,
|
output_format: CliOutputFormat::Json,
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
|
thinking: false,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2493,6 +2646,7 @@ mod tests {
|
|||||||
model: DEFAULT_MODEL.to_string(),
|
model: DEFAULT_MODEL.to_string(),
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::ReadOnly,
|
permission_mode: PermissionMode::ReadOnly,
|
||||||
|
thinking: false,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2515,6 +2669,7 @@ mod tests {
|
|||||||
.collect()
|
.collect()
|
||||||
),
|
),
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
|
thinking: false,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2754,6 +2909,7 @@ mod tests {
|
|||||||
cache_read_input_tokens: 1,
|
cache_read_input_tokens: 1,
|
||||||
},
|
},
|
||||||
estimated_tokens: 128,
|
estimated_tokens: 128,
|
||||||
|
thinking_enabled: true,
|
||||||
},
|
},
|
||||||
"workspace-write",
|
"workspace-write",
|
||||||
&super::StatusContext {
|
&super::StatusContext {
|
||||||
@@ -2792,7 +2948,7 @@ mod tests {
|
|||||||
assert!(report.contains("Memory"));
|
assert!(report.contains("Memory"));
|
||||||
assert!(report.contains("Working directory"));
|
assert!(report.contains("Working directory"));
|
||||||
assert!(report.contains("Instruction files"));
|
assert!(report.contains("Instruction files"));
|
||||||
assert!(report.contains("Project memory files"));
|
assert!(report.contains("Discovered files"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -2817,7 +2973,7 @@ mod tests {
|
|||||||
fn status_context_reads_real_workspace_metadata() {
|
fn status_context_reads_real_workspace_metadata() {
|
||||||
let context = status_context(None).expect("status context should load");
|
let context = status_context(None).expect("status context should load");
|
||||||
assert!(context.cwd.is_absolute());
|
assert!(context.cwd.is_absolute());
|
||||||
assert!(context.discovered_config_files >= 3);
|
assert!(context.discovered_config_files >= context.loaded_config_files);
|
||||||
assert!(context.loaded_config_files <= context.discovered_config_files);
|
assert!(context.loaded_config_files <= context.discovered_config_files);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1199,9 +1199,10 @@ fn execute_todo_write(input: TodoWriteInput) -> Result<TodoWriteOutput, String>
|
|||||||
validate_todos(&input.todos)?;
|
validate_todos(&input.todos)?;
|
||||||
let store_path = todo_store_path()?;
|
let store_path = todo_store_path()?;
|
||||||
let old_todos = if store_path.exists() {
|
let old_todos = if store_path.exists() {
|
||||||
parse_todo_markdown(
|
serde_json::from_str::<Vec<TodoItem>>(
|
||||||
&std::fs::read_to_string(&store_path).map_err(|error| error.to_string())?,
|
&std::fs::read_to_string(&store_path).map_err(|error| error.to_string())?,
|
||||||
)?
|
)
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
@@ -1219,7 +1220,10 @@ fn execute_todo_write(input: TodoWriteInput) -> Result<TodoWriteOutput, String>
|
|||||||
if let Some(parent) = store_path.parent() {
|
if let Some(parent) = store_path.parent() {
|
||||||
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||||
}
|
}
|
||||||
std::fs::write(&store_path, render_todo_markdown(&persisted))
|
std::fs::write(
|
||||||
|
&store_path,
|
||||||
|
serde_json::to_string_pretty(&persisted).map_err(|error| error.to_string())?,
|
||||||
|
)
|
||||||
.map_err(|error| error.to_string())?;
|
.map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
let verification_nudge_needed = (all_done
|
let verification_nudge_needed = (all_done
|
||||||
@@ -1278,58 +1282,7 @@ fn todo_store_path() -> Result<std::path::PathBuf, String> {
|
|||||||
return Ok(std::path::PathBuf::from(path));
|
return Ok(std::path::PathBuf::from(path));
|
||||||
}
|
}
|
||||||
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
||||||
Ok(cwd.join(".claude").join("todos.md"))
|
Ok(cwd.join(".clawd-todos.json"))
|
||||||
}
|
|
||||||
|
|
||||||
fn render_todo_markdown(todos: &[TodoItem]) -> String {
|
|
||||||
let mut lines = vec!["# Todo list".to_string(), String::new()];
|
|
||||||
for todo in todos {
|
|
||||||
let marker = match todo.status {
|
|
||||||
TodoStatus::Pending => "[ ]",
|
|
||||||
TodoStatus::InProgress => "[~]",
|
|
||||||
TodoStatus::Completed => "[x]",
|
|
||||||
};
|
|
||||||
lines.push(format!(
|
|
||||||
"- {marker} {} :: {}",
|
|
||||||
todo.content, todo.active_form
|
|
||||||
));
|
|
||||||
}
|
|
||||||
lines.push(String::new());
|
|
||||||
lines.join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_todo_markdown(content: &str) -> Result<Vec<TodoItem>, String> {
|
|
||||||
let mut todos = Vec::new();
|
|
||||||
for line in content.lines() {
|
|
||||||
let trimmed = line.trim();
|
|
||||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Some(rest) = trimmed.strip_prefix("- [") else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let mut chars = rest.chars();
|
|
||||||
let status = match chars.next() {
|
|
||||||
Some(' ') => TodoStatus::Pending,
|
|
||||||
Some('~') => TodoStatus::InProgress,
|
|
||||||
Some('x' | 'X') => TodoStatus::Completed,
|
|
||||||
Some(other) => return Err(format!("unsupported todo status marker: {other}")),
|
|
||||||
None => return Err(String::from("malformed todo line")),
|
|
||||||
};
|
|
||||||
let remainder = chars.as_str();
|
|
||||||
let Some(body) = remainder.strip_prefix("] ") else {
|
|
||||||
return Err(String::from("malformed todo line"));
|
|
||||||
};
|
|
||||||
let Some((content, active_form)) = body.split_once(" :: ") else {
|
|
||||||
return Err(String::from("todo line missing active form separator"));
|
|
||||||
};
|
|
||||||
todos.push(TodoItem {
|
|
||||||
content: content.trim().to_string(),
|
|
||||||
active_form: active_form.trim().to_string(),
|
|
||||||
status,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Ok(todos)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
|
fn resolve_skill_path(skill: &str) -> Result<std::path::PathBuf, String> {
|
||||||
@@ -2685,37 +2638,6 @@ mod tests {
|
|||||||
assert!(second_output["verificationNudgeNeeded"].is_null());
|
assert!(second_output["verificationNudgeNeeded"].is_null());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn todo_write_persists_markdown_in_claude_directory() {
|
|
||||||
let _guard = env_lock()
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
|
||||||
let temp = temp_path("todos-md-dir");
|
|
||||||
std::fs::create_dir_all(&temp).expect("temp dir");
|
|
||||||
let previous = std::env::current_dir().expect("cwd");
|
|
||||||
std::env::set_current_dir(&temp).expect("set cwd");
|
|
||||||
|
|
||||||
execute_tool(
|
|
||||||
"TodoWrite",
|
|
||||||
&json!({
|
|
||||||
"todos": [
|
|
||||||
{"content": "Add tool", "activeForm": "Adding tool", "status": "in_progress"},
|
|
||||||
{"content": "Run tests", "activeForm": "Running tests", "status": "pending"}
|
|
||||||
]
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.expect("TodoWrite should succeed");
|
|
||||||
|
|
||||||
let persisted = std::fs::read_to_string(temp.join(".claude").join("todos.md"))
|
|
||||||
.expect("todo markdown exists");
|
|
||||||
std::env::set_current_dir(previous).expect("restore cwd");
|
|
||||||
let _ = std::fs::remove_dir_all(temp);
|
|
||||||
|
|
||||||
assert!(persisted.contains("# Todo list"));
|
|
||||||
assert!(persisted.contains("- [~] Add tool :: Adding tool"));
|
|
||||||
assert!(persisted.contains("- [ ] Run tests :: Running tests"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn todo_write_rejects_invalid_payloads_and_sets_verification_nudge() {
|
fn todo_write_rejects_invalid_payloads_and_sets_verification_nudge() {
|
||||||
let _guard = env_lock()
|
let _guard = env_lock()
|
||||||
|
|||||||
Reference in New Issue
Block a user