Compare commits
11 Commits
bec07658b8
...
ef48f58ef1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef48f58ef1 | ||
|
|
9a86aa6444 | ||
|
|
21b0887469 | ||
|
|
0d89231caa | ||
|
|
b445a3320f | ||
|
|
650a24b6e2 | ||
|
|
d018276fc1 | ||
|
|
387a8bb13f | ||
|
|
243a1ff74f | ||
|
|
583d191527 | ||
|
|
074bd5b7b7 |
1
.claude/sessions/session-1775007533836.json
Normal file
1
.claude/sessions/session-1775007533836.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
1
.claude/sessions/session-1775007622154.json
Normal file
1
.claude/sessions/session-1775007622154.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[{"blocks":[{"text":"What is 2+2? Reply with just the number.","type":"text"}],"role":"user"},{"blocks":[{"text":"4","type":"text"}],"role":"assistant","usage":{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":19,"output_tokens":5}}],"version":1}
|
||||||
1
.claude/sessions/session-1775007632904.json
Normal file
1
.claude/sessions/session-1775007632904.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[{"blocks":[{"text":"Say hello in exactly 3 words","type":"text"}],"role":"user"},{"blocks":[{"text":"Hello there, friend!","type":"text"}],"role":"assistant","usage":{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":14,"output_tokens":8}}],"version":1}
|
||||||
1
.claude/sessions/session-1775007846522.json
Normal file
1
.claude/sessions/session-1775007846522.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[{"blocks":[{"text":"Say hi in one sentence","type":"text"}],"role":"user"},{"blocks":[{"text":"Hi! I'm Claude, ready to help you with any software engineering tasks or questions you have.","type":"text"}],"role":"assistant","usage":{"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"input_tokens":11,"output_tokens":23}}],"version":1}
|
||||||
1
rust/.claude/sessions/session-1775007453382.json
Normal file
1
rust/.claude/sessions/session-1775007453382.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
1
rust/.claude/sessions/session-1775007484031.json
Normal file
1
rust/.claude/sessions/session-1775007484031.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
1
rust/.claude/sessions/session-1775007490104.json
Normal file
1
rust/.claude/sessions/session-1775007490104.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
1
rust/.claude/sessions/session-1775007981374.json
Normal file
1
rust/.claude/sessions/session-1775007981374.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
1
rust/.claude/sessions/session-1775008007069.json
Normal file
1
rust/.claude/sessions/session-1775008007069.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
1
rust/.claude/sessions/session-1775008071886.json
Normal file
1
rust/.claude/sessions/session-1775008071886.json
Normal file
@ -0,0 +1 @@
|
|||||||
|
{"messages":[],"version":1}
|
||||||
5
rust/Cargo.lock
generated
5
rust/Cargo.lock
generated
@ -1091,11 +1091,8 @@ dependencies = [
|
|||||||
"compat-harness",
|
"compat-harness",
|
||||||
"crossterm",
|
"crossterm",
|
||||||
"pulldown-cmark",
|
"pulldown-cmark",
|
||||||
"reqwest",
|
|
||||||
"runtime",
|
"runtime",
|
||||||
"serde",
|
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"sha2",
|
|
||||||
"syntect",
|
"syntect",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tools",
|
"tools",
|
||||||
@ -1434,12 +1431,10 @@ dependencies = [
|
|||||||
name = "tools"
|
name = "tools"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"api",
|
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"runtime",
|
"runtime",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@ -118,6 +118,13 @@ cd rust
|
|||||||
cargo run -p rusty-claude-cli -- --allowedTools read,glob
|
cargo run -p rusty-claude-cli -- --allowedTools read,glob
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Bootstrap Claude project files for the current repo:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd rust
|
||||||
|
cargo run -p rusty-claude-cli -- init
|
||||||
|
```
|
||||||
|
|
||||||
### 2) REPL mode
|
### 2) REPL mode
|
||||||
|
|
||||||
Start the interactive shell:
|
Start the interactive shell:
|
||||||
@ -190,7 +197,7 @@ cargo run -p rusty-claude-cli -- --resume ~/.claude/sessions/session-123456.json
|
|||||||
- `/resume <session-id-or-path>` — load a saved session into the REPL
|
- `/resume <session-id-or-path>` — load a saved session into the REPL
|
||||||
- `/config [env|hooks|model]` — inspect discovered Claude config
|
- `/config [env|hooks|model]` — inspect discovered Claude config
|
||||||
- `/memory` — inspect loaded instruction memory files
|
- `/memory` — inspect loaded instruction memory files
|
||||||
- `/init` — create a starter `CLAUDE.md`
|
- `/init` — bootstrap `.claude.json`, `.claude/`, `CLAUDE.md`, and local ignore rules
|
||||||
- `/diff` — show the current git diff for the workspace
|
- `/diff` — show the current git diff for the workspace
|
||||||
- `/version` — print version and build metadata locally
|
- `/version` — print version and build metadata locally
|
||||||
- `/export [file]` — export the current conversation transcript
|
- `/export [file]` — export the current conversation transcript
|
||||||
|
|||||||
@ -520,7 +520,7 @@ fn read_auth_token() -> Option<String> {
|
|||||||
.and_then(std::convert::identity)
|
.and_then(std::convert::identity)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_base_url() -> String {
|
pub fn read_base_url() -> String {
|
||||||
std::env::var("ANTHROPIC_BASE_URL").unwrap_or_else(|_| DEFAULT_BASE_URL.to_string())
|
std::env::var("ANTHROPIC_BASE_URL").unwrap_or_else(|_| DEFAULT_BASE_URL.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -906,13 +906,12 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn message_request_stream_helper_sets_stream_true() {
|
fn message_request_stream_helper_sets_stream_true() {
|
||||||
let request = MessageRequest {
|
let request = MessageRequest {
|
||||||
model: "claude-3-7-sonnet-latest".to_string(),
|
model: "claude-opus-4-6".to_string(),
|
||||||
max_tokens: 64,
|
max_tokens: 64,
|
||||||
messages: vec![],
|
messages: vec![],
|
||||||
system: None,
|
system: None,
|
||||||
tools: None,
|
tools: None,
|
||||||
tool_choice: None,
|
tool_choice: None,
|
||||||
thinking: None,
|
|
||||||
stream: false,
|
stream: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -4,14 +4,14 @@ mod sse;
|
|||||||
mod types;
|
mod types;
|
||||||
|
|
||||||
pub use client::{
|
pub use client::{
|
||||||
oauth_token_is_expired, resolve_saved_oauth_token, resolve_startup_auth_source,
|
oauth_token_is_expired, read_base_url, resolve_saved_oauth_token,
|
||||||
AnthropicClient, AuthSource, MessageStream, OAuthTokenSet,
|
resolve_startup_auth_source, AnthropicClient, AuthSource, MessageStream, OAuthTokenSet,
|
||||||
};
|
};
|
||||||
pub use error::ApiError;
|
pub use error::ApiError;
|
||||||
pub use sse::{parse_frame, SseParser};
|
pub use sse::{parse_frame, SseParser};
|
||||||
pub use types::{
|
pub use types::{
|
||||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||||
ImageSource, InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
||||||
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
|
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>>,
|
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,
|
||||||
}
|
}
|
||||||
@ -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)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct InputMessage {
|
pub struct InputMessage {
|
||||||
pub role: String,
|
pub role: String,
|
||||||
@ -83,9 +64,6 @@ pub enum InputContentBlock {
|
|||||||
Text {
|
Text {
|
||||||
text: String,
|
text: String,
|
||||||
},
|
},
|
||||||
Image {
|
|
||||||
source: ImageSource,
|
|
||||||
},
|
|
||||||
ToolUse {
|
ToolUse {
|
||||||
id: String,
|
id: String,
|
||||||
name: String,
|
name: String,
|
||||||
@ -99,14 +77,6 @@ pub enum InputContentBlock {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
pub struct ImageSource {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
pub kind: String,
|
|
||||||
pub media_type: String,
|
|
||||||
pub data: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
#[serde(tag = "type", rename_all = "snake_case")]
|
#[serde(tag = "type", rename_all = "snake_case")]
|
||||||
pub enum ToolResultContentBlock {
|
pub enum ToolResultContentBlock {
|
||||||
@ -160,11 +130,6 @@ 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,
|
||||||
@ -224,8 +189,6 @@ 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 },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -4,8 +4,8 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use api::{
|
use api::{
|
||||||
AnthropicClient, ApiError, ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent,
|
AnthropicClient, ApiError, ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent,
|
||||||
ImageSource, InputContentBlock, InputMessage, MessageDeltaEvent, MessageRequest,
|
InputContentBlock, InputMessage, MessageDeltaEvent, MessageRequest, OutputContentBlock,
|
||||||
OutputContentBlock, StreamEvent, ToolChoice, ToolDefinition,
|
StreamEvent, ToolChoice, ToolDefinition,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
@ -75,39 +75,6 @@ async fn send_message_posts_json_and_parses_response() {
|
|||||||
assert_eq!(body["tool_choice"]["type"], json!("auto"));
|
assert_eq!(body["tool_choice"]["type"], json!("auto"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn image_content_blocks_serialize_with_base64_source() {
|
|
||||||
let request = MessageRequest {
|
|
||||||
model: "claude-3-7-sonnet-latest".to_string(),
|
|
||||||
max_tokens: 64,
|
|
||||||
messages: vec![InputMessage {
|
|
||||||
role: "user".to_string(),
|
|
||||||
content: vec![InputContentBlock::Image {
|
|
||||||
source: ImageSource {
|
|
||||||
kind: "base64".to_string(),
|
|
||||||
media_type: "image/png".to_string(),
|
|
||||||
data: "AQID".to_string(),
|
|
||||||
},
|
|
||||||
}],
|
|
||||||
}],
|
|
||||||
system: None,
|
|
||||||
tools: None,
|
|
||||||
tool_choice: None,
|
|
||||||
stream: false,
|
|
||||||
};
|
|
||||||
|
|
||||||
let json = serde_json::to_value(request).expect("request should serialize");
|
|
||||||
assert_eq!(json["messages"][0]["content"][0]["type"], json!("image"));
|
|
||||||
assert_eq!(
|
|
||||||
json["messages"][0]["content"][0]["source"],
|
|
||||||
json!({
|
|
||||||
"type": "base64",
|
|
||||||
"media_type": "image/png",
|
|
||||||
"data": "AQID"
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn stream_message_parses_sse_events_with_tool_use() {
|
async fn stream_message_parses_sse_events_with_tool_use() {
|
||||||
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
@ -291,7 +258,6 @@ 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
|
||||||
@ -472,7 +438,6 @@ fn sample_request(stream: bool) -> MessageRequest {
|
|||||||
}),
|
}),
|
||||||
}]),
|
}]),
|
||||||
tool_choice: Some(ToolChoice::Auto),
|
tool_choice: Some(ToolChoice::Auto),
|
||||||
thinking: None,
|
|
||||||
stream,
|
stream,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -57,12 +57,6 @@ 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",
|
||||||
@ -142,9 +136,6 @@ pub enum SlashCommand {
|
|||||||
Help,
|
Help,
|
||||||
Status,
|
Status,
|
||||||
Compact,
|
Compact,
|
||||||
Thinking {
|
|
||||||
enabled: Option<bool>,
|
|
||||||
},
|
|
||||||
Model {
|
Model {
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
},
|
},
|
||||||
@ -189,13 +180,6 @@ 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),
|
||||||
},
|
},
|
||||||
@ -295,7 +279,6 @@ 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 { .. }
|
||||||
@ -324,22 +307,6 @@ 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 {
|
||||||
@ -407,7 +374,6 @@ 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]"));
|
||||||
@ -420,7 +386,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(), 16);
|
assert_eq!(slash_command_specs().len(), 15);
|
||||||
assert_eq!(resume_supported_slash_commands().len(), 11);
|
assert_eq!(resume_supported_slash_commands().len(), 11);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -468,9 +434,6 @@ 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,3 +1,4 @@
|
|||||||
|
use std::env;
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@ -7,6 +8,12 @@ use tokio::process::Command as TokioCommand;
|
|||||||
use tokio::runtime::Builder;
|
use tokio::runtime::Builder;
|
||||||
use tokio::time::timeout;
|
use tokio::time::timeout;
|
||||||
|
|
||||||
|
use crate::sandbox::{
|
||||||
|
build_linux_sandbox_command, resolve_sandbox_status_for_request, FilesystemIsolationMode,
|
||||||
|
SandboxConfig, SandboxStatus,
|
||||||
|
};
|
||||||
|
use crate::ConfigLoader;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
pub struct BashCommandInput {
|
pub struct BashCommandInput {
|
||||||
pub command: String,
|
pub command: String,
|
||||||
@ -16,6 +23,14 @@ pub struct BashCommandInput {
|
|||||||
pub run_in_background: Option<bool>,
|
pub run_in_background: Option<bool>,
|
||||||
#[serde(rename = "dangerouslyDisableSandbox")]
|
#[serde(rename = "dangerouslyDisableSandbox")]
|
||||||
pub dangerously_disable_sandbox: Option<bool>,
|
pub dangerously_disable_sandbox: Option<bool>,
|
||||||
|
#[serde(rename = "namespaceRestrictions")]
|
||||||
|
pub namespace_restrictions: Option<bool>,
|
||||||
|
#[serde(rename = "isolateNetwork")]
|
||||||
|
pub isolate_network: Option<bool>,
|
||||||
|
#[serde(rename = "filesystemMode")]
|
||||||
|
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
||||||
|
#[serde(rename = "allowedMounts")]
|
||||||
|
pub allowed_mounts: Option<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
@ -45,13 +60,17 @@ pub struct BashCommandOutput {
|
|||||||
pub persisted_output_path: Option<String>,
|
pub persisted_output_path: Option<String>,
|
||||||
#[serde(rename = "persistedOutputSize")]
|
#[serde(rename = "persistedOutputSize")]
|
||||||
pub persisted_output_size: Option<u64>,
|
pub persisted_output_size: Option<u64>,
|
||||||
|
#[serde(rename = "sandboxStatus")]
|
||||||
|
pub sandbox_status: Option<SandboxStatus>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
let sandbox_status = sandbox_status_for_input(&input, &cwd);
|
||||||
|
|
||||||
if input.run_in_background.unwrap_or(false) {
|
if input.run_in_background.unwrap_or(false) {
|
||||||
let child = Command::new("sh")
|
let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
|
||||||
.arg("-lc")
|
let child = child
|
||||||
.arg(&input.command)
|
|
||||||
.stdin(Stdio::null())
|
.stdin(Stdio::null())
|
||||||
.stdout(Stdio::null())
|
.stdout(Stdio::null())
|
||||||
.stderr(Stdio::null())
|
.stderr(Stdio::null())
|
||||||
@ -72,16 +91,20 @@ pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: Some(sandbox_status),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let runtime = Builder::new_current_thread().enable_all().build()?;
|
let runtime = Builder::new_current_thread().enable_all().build()?;
|
||||||
runtime.block_on(execute_bash_async(input))
|
runtime.block_on(execute_bash_async(input, sandbox_status, cwd))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
async fn execute_bash_async(
|
||||||
let mut command = TokioCommand::new("sh");
|
input: BashCommandInput,
|
||||||
command.arg("-lc").arg(&input.command);
|
sandbox_status: SandboxStatus,
|
||||||
|
cwd: std::path::PathBuf,
|
||||||
|
) -> io::Result<BashCommandOutput> {
|
||||||
|
let mut command = prepare_tokio_command(&input.command, &cwd, &sandbox_status, true);
|
||||||
|
|
||||||
let output_result = if let Some(timeout_ms) = input.timeout {
|
let output_result = if let Some(timeout_ms) = input.timeout {
|
||||||
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
||||||
@ -102,6 +125,7 @@ async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOu
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: Some(sandbox_status),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -136,12 +160,119 @@ async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOu
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: Some(sandbox_status),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sandbox_status_for_input(input: &BashCommandInput, cwd: &std::path::Path) -> SandboxStatus {
|
||||||
|
let config = ConfigLoader::default_for(cwd).load().map_or_else(
|
||||||
|
|_| SandboxConfig::default(),
|
||||||
|
|runtime_config| runtime_config.sandbox().clone(),
|
||||||
|
);
|
||||||
|
let request = config.resolve_request(
|
||||||
|
input.dangerously_disable_sandbox.map(|disabled| !disabled),
|
||||||
|
input.namespace_restrictions,
|
||||||
|
input.isolate_network,
|
||||||
|
input.filesystem_mode,
|
||||||
|
input.allowed_mounts.clone(),
|
||||||
|
);
|
||||||
|
resolve_sandbox_status_for_request(&request, cwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_command(
|
||||||
|
command: &str,
|
||||||
|
cwd: &std::path::Path,
|
||||||
|
sandbox_status: &SandboxStatus,
|
||||||
|
create_dirs: bool,
|
||||||
|
) -> Command {
|
||||||
|
if create_dirs {
|
||||||
|
prepare_sandbox_dirs(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
||||||
|
let mut prepared = Command::new(launcher.program);
|
||||||
|
prepared.args(launcher.args);
|
||||||
|
prepared.current_dir(cwd);
|
||||||
|
prepared.envs(launcher.env);
|
||||||
|
return prepared;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut prepared = if cfg!(target_os = "windows") && !sh_exists() {
|
||||||
|
let mut p = Command::new("cmd");
|
||||||
|
p.arg("/C").arg(command);
|
||||||
|
p
|
||||||
|
} else {
|
||||||
|
let mut p = Command::new("sh");
|
||||||
|
p.arg("-lc").arg(command);
|
||||||
|
p
|
||||||
|
};
|
||||||
|
prepared.current_dir(cwd);
|
||||||
|
if sandbox_status.filesystem_active {
|
||||||
|
prepared.env("HOME", cwd.join(".sandbox-home"));
|
||||||
|
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
||||||
|
}
|
||||||
|
prepared
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sh_exists() -> bool {
|
||||||
|
env::var_os("PATH").is_some_and(|paths| {
|
||||||
|
env::split_paths(&paths).any(|path| {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
path.join("sh.exe").exists() || path.join("sh.bat").exists() || path.join("sh").exists()
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
path.join("sh").exists()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_tokio_command(
|
||||||
|
command: &str,
|
||||||
|
cwd: &std::path::Path,
|
||||||
|
sandbox_status: &SandboxStatus,
|
||||||
|
create_dirs: bool,
|
||||||
|
) -> TokioCommand {
|
||||||
|
if create_dirs {
|
||||||
|
prepare_sandbox_dirs(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
||||||
|
let mut prepared = TokioCommand::new(launcher.program);
|
||||||
|
prepared.args(launcher.args);
|
||||||
|
prepared.current_dir(cwd);
|
||||||
|
prepared.envs(launcher.env);
|
||||||
|
return prepared;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut prepared = if cfg!(target_os = "windows") && !sh_exists() {
|
||||||
|
let mut p = TokioCommand::new("cmd");
|
||||||
|
p.arg("/C").arg(command);
|
||||||
|
p
|
||||||
|
} else {
|
||||||
|
let mut p = TokioCommand::new("sh");
|
||||||
|
p.arg("-lc").arg(command);
|
||||||
|
p
|
||||||
|
};
|
||||||
|
prepared.current_dir(cwd);
|
||||||
|
if sandbox_status.filesystem_active {
|
||||||
|
prepared.env("HOME", cwd.join(".sandbox-home"));
|
||||||
|
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
||||||
|
}
|
||||||
|
prepared
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare_sandbox_dirs(cwd: &std::path::Path) {
|
||||||
|
let _ = std::fs::create_dir_all(cwd.join(".sandbox-home"));
|
||||||
|
let _ = std::fs::create_dir_all(cwd.join(".sandbox-tmp"));
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{execute_bash, BashCommandInput};
|
use super::{execute_bash, BashCommandInput};
|
||||||
|
use crate::sandbox::FilesystemIsolationMode;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn executes_simple_command() {
|
fn executes_simple_command() {
|
||||||
@ -151,10 +282,33 @@ mod tests {
|
|||||||
description: None,
|
description: None,
|
||||||
run_in_background: Some(false),
|
run_in_background: Some(false),
|
||||||
dangerously_disable_sandbox: Some(false),
|
dangerously_disable_sandbox: Some(false),
|
||||||
|
namespace_restrictions: Some(false),
|
||||||
|
isolate_network: Some(false),
|
||||||
|
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
allowed_mounts: None,
|
||||||
})
|
})
|
||||||
.expect("bash command should execute");
|
.expect("bash command should execute");
|
||||||
|
|
||||||
assert_eq!(output.stdout, "hello");
|
assert_eq!(output.stdout, "hello");
|
||||||
assert!(!output.interrupted);
|
assert!(!output.interrupted);
|
||||||
|
assert!(output.sandbox_status.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn disables_sandbox_when_requested() {
|
||||||
|
let output = execute_bash(BashCommandInput {
|
||||||
|
command: String::from("printf 'hello'"),
|
||||||
|
timeout: Some(1_000),
|
||||||
|
description: None,
|
||||||
|
run_in_background: Some(false),
|
||||||
|
dangerously_disable_sandbox: Some(true),
|
||||||
|
namespace_restrictions: None,
|
||||||
|
isolate_network: None,
|
||||||
|
filesystem_mode: None,
|
||||||
|
allowed_mounts: None,
|
||||||
|
})
|
||||||
|
.expect("bash command should execute");
|
||||||
|
|
||||||
|
assert!(!output.sandbox_status.expect("sandbox status").enabled);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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 {
|
||||||
@ -109,41 +105,11 @@ pub fn compact_session(session: &Session, config: CompactionConfig) -> Compactio
|
|||||||
compacted_session: Session {
|
compacted_session: Session {
|
||||||
version: session.version,
|
version: session.version,
|
||||||
messages: compacted_messages,
|
messages: compacted_messages,
|
||||||
metadata: session.metadata.clone(),
|
|
||||||
},
|
},
|
||||||
removed_message_count: removed.len(),
|
removed_message_count: removed.len(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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()
|
||||||
@ -164,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 { .. } | ContentBlock::Thinking { .. } => None,
|
ContentBlock::Text { .. } => None,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
tool_names.sort_unstable();
|
tool_names.sort_unstable();
|
||||||
@ -234,7 +200,6 @@ 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,
|
||||||
@ -293,7 +258,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 } | ContentBlock::Thinking { text, .. } => text.as_str(),
|
ContentBlock::Text { 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(),
|
||||||
})
|
})
|
||||||
@ -315,15 +280,10 @@ 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 } | ContentBlock::Thinking { text, .. }
|
ContentBlock::Text { text } if !text.trim().is_empty() => Some(text.as_str()),
|
||||||
if !text.trim().is_empty() =>
|
|
||||||
{
|
|
||||||
Some(text.as_str())
|
|
||||||
}
|
|
||||||
ContentBlock::ToolUse { .. }
|
ContentBlock::ToolUse { .. }
|
||||||
| ContentBlock::ToolResult { .. }
|
| ContentBlock::ToolResult { .. }
|
||||||
| ContentBlock::Text { .. }
|
| ContentBlock::Text { .. } => None,
|
||||||
| ContentBlock::Thinking { .. } => None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -368,7 +328,7 @@ fn estimate_message_tokens(message: &ConversationMessage) -> usize {
|
|||||||
.blocks
|
.blocks
|
||||||
.iter()
|
.iter()
|
||||||
.map(|block| match block {
|
.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::ToolUse { name, input, .. } => (name.len() + input.len()) / 4 + 1,
|
||||||
ContentBlock::ToolResult {
|
ContentBlock::ToolResult {
|
||||||
tool_name, output, ..
|
tool_name, output, ..
|
||||||
@ -418,21 +378,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]
|
||||||
@ -440,7 +393,6 @@ mod tests {
|
|||||||
let session = Session {
|
let session = Session {
|
||||||
version: 1,
|
version: 1,
|
||||||
messages: vec![ConversationMessage::user_text("hello")],
|
messages: vec![ConversationMessage::user_text("hello")],
|
||||||
metadata: None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = compact_session(&session, CompactionConfig::default());
|
let result = compact_session(&session, CompactionConfig::default());
|
||||||
@ -450,63 +402,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 {
|
||||||
@ -525,7 +420,6 @@ mod tests {
|
|||||||
usage: None,
|
usage: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
metadata: None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = compact_session(
|
let result = compact_session(
|
||||||
|
|||||||
@ -4,6 +4,7 @@ use std::fs;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
|
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
||||||
|
|
||||||
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
||||||
|
|
||||||
@ -40,6 +41,7 @@ pub struct RuntimeFeatureConfig {
|
|||||||
oauth: Option<OAuthConfig>,
|
oauth: Option<OAuthConfig>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
permission_mode: Option<ResolvedPermissionMode>,
|
permission_mode: Option<ResolvedPermissionMode>,
|
||||||
|
sandbox: SandboxConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@ -168,6 +170,13 @@ impl ConfigLoader {
|
|||||||
let config_home = std::env::var_os("CLAUDE_CONFIG_HOME")
|
let config_home = std::env::var_os("CLAUDE_CONFIG_HOME")
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".claude")))
|
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".claude")))
|
||||||
|
.or_else(|| {
|
||||||
|
if cfg!(target_os = "windows") {
|
||||||
|
std::env::var_os("USERPROFILE").map(|home| PathBuf::from(home).join(".claude"))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
.unwrap_or_else(|| PathBuf::from(".claude"));
|
.unwrap_or_else(|| PathBuf::from(".claude"));
|
||||||
Self { cwd, config_home }
|
Self { cwd, config_home }
|
||||||
}
|
}
|
||||||
@ -225,6 +234,7 @@ impl ConfigLoader {
|
|||||||
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
||||||
model: parse_optional_model(&merged_value),
|
model: parse_optional_model(&merged_value),
|
||||||
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
||||||
|
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(RuntimeConfig {
|
Ok(RuntimeConfig {
|
||||||
@ -289,6 +299,11 @@ impl RuntimeConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.feature_config.permission_mode
|
self.feature_config.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn sandbox(&self) -> &SandboxConfig {
|
||||||
|
&self.feature_config.sandbox
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeFeatureConfig {
|
impl RuntimeFeatureConfig {
|
||||||
@ -311,6 +326,11 @@ impl RuntimeFeatureConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.permission_mode
|
self.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn sandbox(&self) -> &SandboxConfig {
|
||||||
|
&self.sandbox
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl McpConfigCollection {
|
impl McpConfigCollection {
|
||||||
@ -445,6 +465,42 @@ fn parse_permission_mode_label(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_optional_sandbox_config(root: &JsonValue) -> Result<SandboxConfig, ConfigError> {
|
||||||
|
let Some(object) = root.as_object() else {
|
||||||
|
return Ok(SandboxConfig::default());
|
||||||
|
};
|
||||||
|
let Some(sandbox_value) = object.get("sandbox") else {
|
||||||
|
return Ok(SandboxConfig::default());
|
||||||
|
};
|
||||||
|
let sandbox = expect_object(sandbox_value, "merged settings.sandbox")?;
|
||||||
|
let filesystem_mode = optional_string(sandbox, "filesystemMode", "merged settings.sandbox")?
|
||||||
|
.map(parse_filesystem_mode_label)
|
||||||
|
.transpose()?;
|
||||||
|
Ok(SandboxConfig {
|
||||||
|
enabled: optional_bool(sandbox, "enabled", "merged settings.sandbox")?,
|
||||||
|
namespace_restrictions: optional_bool(
|
||||||
|
sandbox,
|
||||||
|
"namespaceRestrictions",
|
||||||
|
"merged settings.sandbox",
|
||||||
|
)?,
|
||||||
|
network_isolation: optional_bool(sandbox, "networkIsolation", "merged settings.sandbox")?,
|
||||||
|
filesystem_mode,
|
||||||
|
allowed_mounts: optional_string_array(sandbox, "allowedMounts", "merged settings.sandbox")?
|
||||||
|
.unwrap_or_default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_filesystem_mode_label(value: &str) -> Result<FilesystemIsolationMode, ConfigError> {
|
||||||
|
match value {
|
||||||
|
"off" => Ok(FilesystemIsolationMode::Off),
|
||||||
|
"workspace-only" => Ok(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
"allow-list" => Ok(FilesystemIsolationMode::AllowList),
|
||||||
|
other => Err(ConfigError::Parse(format!(
|
||||||
|
"merged settings.sandbox.filesystemMode: unsupported filesystem mode {other}"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn parse_optional_oauth_config(
|
fn parse_optional_oauth_config(
|
||||||
root: &JsonValue,
|
root: &JsonValue,
|
||||||
context: &str,
|
context: &str,
|
||||||
@ -688,6 +744,7 @@ mod tests {
|
|||||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
||||||
};
|
};
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
|
use crate::sandbox::FilesystemIsolationMode;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
@ -792,6 +849,44 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_sandbox_config() {
|
||||||
|
let root = temp_dir();
|
||||||
|
let cwd = root.join("project");
|
||||||
|
let home = root.join("home").join(".claude");
|
||||||
|
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
||||||
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
|
fs::write(
|
||||||
|
cwd.join(".claude").join("settings.local.json"),
|
||||||
|
r#"{
|
||||||
|
"sandbox": {
|
||||||
|
"enabled": true,
|
||||||
|
"namespaceRestrictions": false,
|
||||||
|
"networkIsolation": true,
|
||||||
|
"filesystemMode": "allow-list",
|
||||||
|
"allowedMounts": ["logs", "tmp/cache"]
|
||||||
|
}
|
||||||
|
}"#,
|
||||||
|
)
|
||||||
|
.expect("write local settings");
|
||||||
|
|
||||||
|
let loaded = ConfigLoader::new(&cwd, &home)
|
||||||
|
.load()
|
||||||
|
.expect("config should load");
|
||||||
|
|
||||||
|
assert_eq!(loaded.sandbox().enabled, Some(true));
|
||||||
|
assert_eq!(loaded.sandbox().namespace_restrictions, Some(false));
|
||||||
|
assert_eq!(loaded.sandbox().network_isolation, Some(true));
|
||||||
|
assert_eq!(
|
||||||
|
loaded.sandbox().filesystem_mode,
|
||||||
|
Some(FilesystemIsolationMode::AllowList)
|
||||||
|
);
|
||||||
|
assert_eq!(loaded.sandbox().allowed_mounts, vec!["logs", "tmp/cache"]);
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_typed_mcp_and_oauth_config() {
|
fn parses_typed_mcp_and_oauth_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
|
|||||||
@ -17,8 +17,6 @@ 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,
|
||||||
@ -249,26 +247,15 @@ 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) => {
|
AssistantEvent::TextDelta(delta) => text.push_str(&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),
|
||||||
@ -279,7 +266,6 @@ 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(
|
||||||
@ -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>>;
|
type ToolHandler = Box<dyn FnMut(&str) -> Result<String, ToolError>>;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@ -352,8 +325,8 @@ impl ToolExecutor for StaticToolExecutor {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
build_assistant_message, ApiClient, ApiRequest, AssistantEvent, ConversationRuntime,
|
ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError,
|
||||||
RuntimeError, StaticToolExecutor,
|
StaticToolExecutor,
|
||||||
};
|
};
|
||||||
use crate::compact::CompactionConfig;
|
use crate::compact::CompactionConfig;
|
||||||
use crate::permissions::{
|
use crate::permissions::{
|
||||||
@ -441,8 +414,8 @@ mod tests {
|
|||||||
cwd: PathBuf::from("/tmp/project"),
|
cwd: PathBuf::from("/tmp/project"),
|
||||||
current_date: "2026-03-31".to_string(),
|
current_date: "2026-03-31".to_string(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
|
git_diff: 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();
|
||||||
@ -530,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]
|
#[test]
|
||||||
fn reconstructs_usage_tracker_from_restored_session() {
|
fn reconstructs_usage_tracker_from_restored_session() {
|
||||||
struct SimpleApi;
|
struct SimpleApi;
|
||||||
|
|||||||
@ -12,6 +12,7 @@ mod oauth;
|
|||||||
mod permissions;
|
mod permissions;
|
||||||
mod prompt;
|
mod prompt;
|
||||||
mod remote;
|
mod remote;
|
||||||
|
pub mod sandbox;
|
||||||
mod session;
|
mod session;
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
@ -73,9 +74,7 @@ pub use remote::{
|
|||||||
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
||||||
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
|
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
|
||||||
};
|
};
|
||||||
pub use session::{
|
pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError};
|
||||||
ContentBlock, ConversationMessage, MessageRole, Session, SessionError, SessionMetadata,
|
|
||||||
};
|
|
||||||
pub use usage::{
|
pub use usage::{
|
||||||
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
||||||
};
|
};
|
||||||
|
|||||||
@ -327,9 +327,15 @@ fn credentials_home_dir() -> io::Result<PathBuf> {
|
|||||||
if let Some(path) = std::env::var_os("CLAUDE_CONFIG_HOME") {
|
if let Some(path) = std::env::var_os("CLAUDE_CONFIG_HOME") {
|
||||||
return Ok(PathBuf::from(path));
|
return Ok(PathBuf::from(path));
|
||||||
}
|
}
|
||||||
let home = std::env::var_os("HOME")
|
if let Some(path) = std::env::var_os("HOME") {
|
||||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "HOME is not set"))?;
|
return Ok(PathBuf::from(path).join(".claude"));
|
||||||
Ok(PathBuf::from(home).join(".claude"))
|
}
|
||||||
|
if cfg!(target_os = "windows") {
|
||||||
|
if let Some(path) = std::env::var_os("USERPROFILE") {
|
||||||
|
return Ok(PathBuf::from(path).join(".claude"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(io::Error::new(io::ErrorKind::NotFound, "HOME or USERPROFILE is not set"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_credentials_root(path: &PathBuf) -> io::Result<Map<String, Value>> {
|
fn read_credentials_root(path: &PathBuf) -> io::Result<Map<String, Value>> {
|
||||||
|
|||||||
@ -5,6 +5,8 @@ pub enum PermissionMode {
|
|||||||
ReadOnly,
|
ReadOnly,
|
||||||
WorkspaceWrite,
|
WorkspaceWrite,
|
||||||
DangerFullAccess,
|
DangerFullAccess,
|
||||||
|
Prompt,
|
||||||
|
Allow,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PermissionMode {
|
impl PermissionMode {
|
||||||
@ -14,6 +16,8 @@ impl PermissionMode {
|
|||||||
Self::ReadOnly => "read-only",
|
Self::ReadOnly => "read-only",
|
||||||
Self::WorkspaceWrite => "workspace-write",
|
Self::WorkspaceWrite => "workspace-write",
|
||||||
Self::DangerFullAccess => "danger-full-access",
|
Self::DangerFullAccess => "danger-full-access",
|
||||||
|
Self::Prompt => "prompt",
|
||||||
|
Self::Allow => "allow",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -90,7 +94,7 @@ impl PermissionPolicy {
|
|||||||
) -> PermissionOutcome {
|
) -> PermissionOutcome {
|
||||||
let current_mode = self.active_mode();
|
let current_mode = self.active_mode();
|
||||||
let required_mode = self.required_mode_for(tool_name);
|
let required_mode = self.required_mode_for(tool_name);
|
||||||
if current_mode >= required_mode {
|
if current_mode == PermissionMode::Allow || current_mode >= required_mode {
|
||||||
return PermissionOutcome::Allow;
|
return PermissionOutcome::Allow;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,8 +105,9 @@ impl PermissionPolicy {
|
|||||||
required_mode,
|
required_mode,
|
||||||
};
|
};
|
||||||
|
|
||||||
if current_mode == PermissionMode::WorkspaceWrite
|
if current_mode == PermissionMode::Prompt
|
||||||
&& required_mode == PermissionMode::DangerFullAccess
|
|| (current_mode == PermissionMode::WorkspaceWrite
|
||||||
|
&& required_mode == PermissionMode::DangerFullAccess)
|
||||||
{
|
{
|
||||||
return match prompter.as_mut() {
|
return match prompter.as_mut() {
|
||||||
Some(prompter) => match prompter.decide(&request) {
|
Some(prompter) => match prompter.decide(&request) {
|
||||||
|
|||||||
@ -50,8 +50,8 @@ pub struct ProjectContext {
|
|||||||
pub cwd: PathBuf,
|
pub cwd: PathBuf,
|
||||||
pub current_date: String,
|
pub current_date: String,
|
||||||
pub git_status: Option<String>,
|
pub git_status: Option<String>,
|
||||||
|
pub git_diff: Option<String>,
|
||||||
pub instruction_files: Vec<ContextFile>,
|
pub instruction_files: Vec<ContextFile>,
|
||||||
pub memory_files: Vec<ContextFile>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ProjectContext {
|
impl ProjectContext {
|
||||||
@ -61,13 +61,12 @@ 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,
|
||||||
|
git_diff: None,
|
||||||
instruction_files,
|
instruction_files,
|
||||||
memory_files,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,6 +76,7 @@ impl ProjectContext {
|
|||||||
) -> std::io::Result<Self> {
|
) -> std::io::Result<Self> {
|
||||||
let mut context = Self::discover(cwd, current_date)?;
|
let mut context = Self::discover(cwd, current_date)?;
|
||||||
context.git_status = read_git_status(&context.cwd);
|
context.git_status = read_git_status(&context.cwd);
|
||||||
|
context.git_diff = read_git_diff(&context.cwd);
|
||||||
Ok(context)
|
Ok(context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -147,9 +147,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 +189,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 +197,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 +212,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() => {
|
||||||
@ -270,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 {
|
fn render_project_context(project_context: &ProjectContext) -> String {
|
||||||
let mut lines = vec!["# Project context".to_string()];
|
let mut lines = vec!["# Project context".to_string()];
|
||||||
let mut bullets = vec![
|
let mut bullets = vec![
|
||||||
@ -282,31 +286,22 @@ 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());
|
||||||
lines.push("Git status snapshot:".to_string());
|
lines.push("Git status snapshot:".to_string());
|
||||||
lines.push(status.clone());
|
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")
|
lines.join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
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 +493,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 +559,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();
|
||||||
@ -652,6 +617,49 @@ mod tests {
|
|||||||
assert!(status.contains("## No commits yet on") || status.contains("## "));
|
assert!(status.contains("## No commits yet on") || status.contains("## "));
|
||||||
assert!(status.contains("?? CLAUDE.md"));
|
assert!(status.contains("?? CLAUDE.md"));
|
||||||
assert!(status.contains("?? tracked.txt"));
|
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");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|||||||
376
rust/crates/runtime/src/sandbox.rs
Normal file
376
rust/crates/runtime/src/sandbox.rs
Normal file
@ -0,0 +1,376 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
pub enum FilesystemIsolationMode {
|
||||||
|
Off,
|
||||||
|
#[default]
|
||||||
|
WorkspaceOnly,
|
||||||
|
AllowList,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FilesystemIsolationMode {
|
||||||
|
#[must_use]
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Off => "off",
|
||||||
|
Self::WorkspaceOnly => "workspace-only",
|
||||||
|
Self::AllowList => "allow-list",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct SandboxConfig {
|
||||||
|
pub enabled: Option<bool>,
|
||||||
|
pub namespace_restrictions: Option<bool>,
|
||||||
|
pub network_isolation: Option<bool>,
|
||||||
|
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
||||||
|
pub allowed_mounts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct SandboxRequest {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub namespace_restrictions: bool,
|
||||||
|
pub network_isolation: bool,
|
||||||
|
pub filesystem_mode: FilesystemIsolationMode,
|
||||||
|
pub allowed_mounts: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct ContainerEnvironment {
|
||||||
|
pub in_container: bool,
|
||||||
|
pub markers: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::struct_excessive_bools)]
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
|
pub struct SandboxStatus {
|
||||||
|
pub enabled: bool,
|
||||||
|
pub requested: SandboxRequest,
|
||||||
|
pub supported: bool,
|
||||||
|
pub active: bool,
|
||||||
|
pub namespace_supported: bool,
|
||||||
|
pub namespace_active: bool,
|
||||||
|
pub network_supported: bool,
|
||||||
|
pub network_active: bool,
|
||||||
|
pub filesystem_mode: FilesystemIsolationMode,
|
||||||
|
pub filesystem_active: bool,
|
||||||
|
pub allowed_mounts: Vec<String>,
|
||||||
|
pub in_container: bool,
|
||||||
|
pub container_markers: Vec<String>,
|
||||||
|
pub fallback_reason: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SandboxDetectionInputs<'a> {
|
||||||
|
pub env_pairs: Vec<(String, String)>,
|
||||||
|
pub dockerenv_exists: bool,
|
||||||
|
pub containerenv_exists: bool,
|
||||||
|
pub proc_1_cgroup: Option<&'a str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct LinuxSandboxCommand {
|
||||||
|
pub program: String,
|
||||||
|
pub args: Vec<String>,
|
||||||
|
pub env: Vec<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SandboxConfig {
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_request(
|
||||||
|
&self,
|
||||||
|
enabled_override: Option<bool>,
|
||||||
|
namespace_override: Option<bool>,
|
||||||
|
network_override: Option<bool>,
|
||||||
|
filesystem_mode_override: Option<FilesystemIsolationMode>,
|
||||||
|
allowed_mounts_override: Option<Vec<String>>,
|
||||||
|
) -> SandboxRequest {
|
||||||
|
SandboxRequest {
|
||||||
|
enabled: enabled_override.unwrap_or(self.enabled.unwrap_or(true)),
|
||||||
|
namespace_restrictions: namespace_override
|
||||||
|
.unwrap_or(self.namespace_restrictions.unwrap_or(true)),
|
||||||
|
network_isolation: network_override.unwrap_or(self.network_isolation.unwrap_or(false)),
|
||||||
|
filesystem_mode: filesystem_mode_override
|
||||||
|
.or(self.filesystem_mode)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
allowed_mounts: allowed_mounts_override.unwrap_or_else(|| self.allowed_mounts.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn detect_container_environment() -> ContainerEnvironment {
|
||||||
|
let proc_1_cgroup = if cfg!(target_os = "linux") {
|
||||||
|
fs::read_to_string("/proc/1/cgroup").ok()
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
detect_container_environment_from(SandboxDetectionInputs {
|
||||||
|
env_pairs: env::vars().collect(),
|
||||||
|
dockerenv_exists: if cfg!(target_os = "linux") {
|
||||||
|
Path::new("/.dockerenv").exists()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
},
|
||||||
|
containerenv_exists: if cfg!(target_os = "linux") {
|
||||||
|
Path::new("/run/.containerenv").exists()
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
},
|
||||||
|
proc_1_cgroup: proc_1_cgroup.as_deref(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn detect_container_environment_from(
|
||||||
|
inputs: SandboxDetectionInputs<'_>,
|
||||||
|
) -> ContainerEnvironment {
|
||||||
|
let mut markers = Vec::new();
|
||||||
|
if inputs.dockerenv_exists {
|
||||||
|
markers.push("/.dockerenv".to_string());
|
||||||
|
}
|
||||||
|
if inputs.containerenv_exists {
|
||||||
|
markers.push("/run/.containerenv".to_string());
|
||||||
|
}
|
||||||
|
for (key, value) in inputs.env_pairs {
|
||||||
|
let normalized = key.to_ascii_lowercase();
|
||||||
|
if matches!(
|
||||||
|
normalized.as_str(),
|
||||||
|
"container" | "docker" | "podman" | "kubernetes_service_host"
|
||||||
|
) && !value.is_empty()
|
||||||
|
{
|
||||||
|
markers.push(format!("env:{key}={value}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(cgroup) = inputs.proc_1_cgroup {
|
||||||
|
for needle in ["docker", "containerd", "kubepods", "podman", "libpod"] {
|
||||||
|
if cgroup.contains(needle) {
|
||||||
|
markers.push(format!("/proc/1/cgroup:{needle}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
markers.sort();
|
||||||
|
markers.dedup();
|
||||||
|
ContainerEnvironment {
|
||||||
|
in_container: !markers.is_empty(),
|
||||||
|
markers,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_sandbox_status(config: &SandboxConfig, cwd: &Path) -> SandboxStatus {
|
||||||
|
let request = config.resolve_request(None, None, None, None, None);
|
||||||
|
resolve_sandbox_status_for_request(&request, cwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_sandbox_status_for_request(request: &SandboxRequest, cwd: &Path) -> SandboxStatus {
|
||||||
|
let container = detect_container_environment();
|
||||||
|
let namespace_supported = cfg!(target_os = "linux") && command_exists("unshare");
|
||||||
|
let network_supported = namespace_supported;
|
||||||
|
let filesystem_active =
|
||||||
|
request.enabled && request.filesystem_mode != FilesystemIsolationMode::Off;
|
||||||
|
let mut fallback_reasons = Vec::new();
|
||||||
|
|
||||||
|
if request.enabled && request.namespace_restrictions && !namespace_supported {
|
||||||
|
fallback_reasons
|
||||||
|
.push("namespace isolation unavailable (requires Linux with `unshare`)".to_string());
|
||||||
|
}
|
||||||
|
if request.enabled && request.network_isolation && !network_supported {
|
||||||
|
fallback_reasons
|
||||||
|
.push("network isolation unavailable (requires Linux with `unshare`)".to_string());
|
||||||
|
}
|
||||||
|
if request.enabled
|
||||||
|
&& request.filesystem_mode == FilesystemIsolationMode::AllowList
|
||||||
|
&& request.allowed_mounts.is_empty()
|
||||||
|
{
|
||||||
|
fallback_reasons
|
||||||
|
.push("filesystem allow-list requested without configured mounts".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let active = request.enabled
|
||||||
|
&& (!request.namespace_restrictions || namespace_supported)
|
||||||
|
&& (!request.network_isolation || network_supported);
|
||||||
|
|
||||||
|
let allowed_mounts = normalize_mounts(&request.allowed_mounts, cwd);
|
||||||
|
|
||||||
|
SandboxStatus {
|
||||||
|
enabled: request.enabled,
|
||||||
|
requested: request.clone(),
|
||||||
|
supported: namespace_supported,
|
||||||
|
active,
|
||||||
|
namespace_supported,
|
||||||
|
namespace_active: request.enabled && request.namespace_restrictions && namespace_supported,
|
||||||
|
network_supported,
|
||||||
|
network_active: request.enabled && request.network_isolation && network_supported,
|
||||||
|
filesystem_mode: request.filesystem_mode,
|
||||||
|
filesystem_active,
|
||||||
|
allowed_mounts,
|
||||||
|
in_container: container.in_container,
|
||||||
|
container_markers: container.markers,
|
||||||
|
fallback_reason: (!fallback_reasons.is_empty()).then(|| fallback_reasons.join("; ")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn build_linux_sandbox_command(
|
||||||
|
command: &str,
|
||||||
|
cwd: &Path,
|
||||||
|
status: &SandboxStatus,
|
||||||
|
) -> Option<LinuxSandboxCommand> {
|
||||||
|
if !cfg!(target_os = "linux")
|
||||||
|
|| !status.enabled
|
||||||
|
|| (!status.namespace_active && !status.network_active)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut args = vec![
|
||||||
|
"--user".to_string(),
|
||||||
|
"--map-root-user".to_string(),
|
||||||
|
"--mount".to_string(),
|
||||||
|
"--ipc".to_string(),
|
||||||
|
"--pid".to_string(),
|
||||||
|
"--uts".to_string(),
|
||||||
|
"--fork".to_string(),
|
||||||
|
];
|
||||||
|
if status.network_active {
|
||||||
|
args.push("--net".to_string());
|
||||||
|
}
|
||||||
|
args.push("sh".to_string());
|
||||||
|
args.push("-lc".to_string());
|
||||||
|
args.push(command.to_string());
|
||||||
|
|
||||||
|
let sandbox_home = cwd.join(".sandbox-home");
|
||||||
|
let sandbox_tmp = cwd.join(".sandbox-tmp");
|
||||||
|
let mut env = vec![
|
||||||
|
("HOME".to_string(), sandbox_home.display().to_string()),
|
||||||
|
("TMPDIR".to_string(), sandbox_tmp.display().to_string()),
|
||||||
|
(
|
||||||
|
"CLAWD_SANDBOX_FILESYSTEM_MODE".to_string(),
|
||||||
|
status.filesystem_mode.as_str().to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"CLAWD_SANDBOX_ALLOWED_MOUNTS".to_string(),
|
||||||
|
status.allowed_mounts.join(":"),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
if let Ok(path) = env::var("PATH") {
|
||||||
|
env.push(("PATH".to_string(), path));
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(LinuxSandboxCommand {
|
||||||
|
program: "unshare".to_string(),
|
||||||
|
args,
|
||||||
|
env,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_mounts(mounts: &[String], cwd: &Path) -> Vec<String> {
|
||||||
|
let cwd = cwd.to_path_buf();
|
||||||
|
mounts
|
||||||
|
.iter()
|
||||||
|
.map(|mount| {
|
||||||
|
let path = PathBuf::from(mount);
|
||||||
|
if path.is_absolute() {
|
||||||
|
path
|
||||||
|
} else {
|
||||||
|
cwd.join(path)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map(|path| path.display().to_string())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command_exists(command: &str) -> bool {
|
||||||
|
env::var_os("PATH")
|
||||||
|
.is_some_and(|paths| env::split_paths(&paths).any(|path| path.join(command).exists()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{
|
||||||
|
build_linux_sandbox_command, detect_container_environment_from, FilesystemIsolationMode,
|
||||||
|
SandboxConfig, SandboxDetectionInputs,
|
||||||
|
};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detects_container_markers_from_multiple_sources() {
|
||||||
|
let detected = detect_container_environment_from(SandboxDetectionInputs {
|
||||||
|
env_pairs: vec![("container".to_string(), "docker".to_string())],
|
||||||
|
dockerenv_exists: true,
|
||||||
|
containerenv_exists: false,
|
||||||
|
proc_1_cgroup: Some("12:memory:/docker/abc"),
|
||||||
|
});
|
||||||
|
|
||||||
|
assert!(detected.in_container);
|
||||||
|
assert!(detected
|
||||||
|
.markers
|
||||||
|
.iter()
|
||||||
|
.any(|marker| marker == "/.dockerenv"));
|
||||||
|
assert!(detected
|
||||||
|
.markers
|
||||||
|
.iter()
|
||||||
|
.any(|marker| marker == "env:container=docker"));
|
||||||
|
assert!(detected
|
||||||
|
.markers
|
||||||
|
.iter()
|
||||||
|
.any(|marker| marker == "/proc/1/cgroup:docker"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_request_with_overrides() {
|
||||||
|
let config = SandboxConfig {
|
||||||
|
enabled: Some(true),
|
||||||
|
namespace_restrictions: Some(true),
|
||||||
|
network_isolation: Some(false),
|
||||||
|
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
allowed_mounts: vec!["logs".to_string()],
|
||||||
|
};
|
||||||
|
|
||||||
|
let request = config.resolve_request(
|
||||||
|
Some(true),
|
||||||
|
Some(false),
|
||||||
|
Some(true),
|
||||||
|
Some(FilesystemIsolationMode::AllowList),
|
||||||
|
Some(vec!["tmp".to_string()]),
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(request.enabled);
|
||||||
|
assert!(!request.namespace_restrictions);
|
||||||
|
assert!(request.network_isolation);
|
||||||
|
assert_eq!(request.filesystem_mode, FilesystemIsolationMode::AllowList);
|
||||||
|
assert_eq!(request.allowed_mounts, vec!["tmp"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builds_linux_launcher_with_network_flag_when_requested() {
|
||||||
|
let config = SandboxConfig::default();
|
||||||
|
let status = super::resolve_sandbox_status_for_request(
|
||||||
|
&config.resolve_request(
|
||||||
|
Some(true),
|
||||||
|
Some(true),
|
||||||
|
Some(true),
|
||||||
|
Some(FilesystemIsolationMode::WorkspaceOnly),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
Path::new("/workspace"),
|
||||||
|
);
|
||||||
|
|
||||||
|
if let Some(launcher) =
|
||||||
|
build_linux_sandbox_command("printf hi", Path::new("/workspace"), &status)
|
||||||
|
{
|
||||||
|
assert_eq!(launcher.program, "unshare");
|
||||||
|
assert!(launcher.args.iter().any(|arg| arg == "--mount"));
|
||||||
|
assert!(launcher.args.iter().any(|arg| arg == "--net") == status.network_active);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -19,10 +19,6 @@ 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,
|
||||||
@ -43,19 +39,10 @@ pub struct ConversationMessage {
|
|||||||
pub usage: Option<TokenUsage>,
|
pub usage: Option<TokenUsage>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct SessionMetadata {
|
|
||||||
pub started_at: String,
|
|
||||||
pub model: String,
|
|
||||||
pub message_count: u32,
|
|
||||||
pub last_prompt: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Session {
|
pub struct Session {
|
||||||
pub version: u32,
|
pub version: u32,
|
||||||
pub messages: Vec<ConversationMessage>,
|
pub messages: Vec<ConversationMessage>,
|
||||||
pub metadata: Option<SessionMetadata>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -95,7 +82,6 @@ impl Session {
|
|||||||
Self {
|
Self {
|
||||||
version: 1,
|
version: 1,
|
||||||
messages: Vec::new(),
|
messages: Vec::new(),
|
||||||
metadata: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -125,9 +111,6 @@ impl Session {
|
|||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if let Some(metadata) = &self.metadata {
|
|
||||||
object.insert("metadata".to_string(), metadata.to_json());
|
|
||||||
}
|
|
||||||
JsonValue::Object(object)
|
JsonValue::Object(object)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -148,15 +131,7 @@ impl Session {
|
|||||||
.iter()
|
.iter()
|
||||||
.map(ConversationMessage::from_json)
|
.map(ConversationMessage::from_json)
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
let metadata = object
|
Ok(Self { version, messages })
|
||||||
.get("metadata")
|
|
||||||
.map(SessionMetadata::from_json)
|
|
||||||
.transpose()?;
|
|
||||||
Ok(Self {
|
|
||||||
version,
|
|
||||||
messages,
|
|
||||||
metadata,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -166,41 +141,6 @@ impl Default for Session {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionMetadata {
|
|
||||||
#[must_use]
|
|
||||||
pub fn to_json(&self) -> JsonValue {
|
|
||||||
let mut object = BTreeMap::new();
|
|
||||||
object.insert(
|
|
||||||
"started_at".to_string(),
|
|
||||||
JsonValue::String(self.started_at.clone()),
|
|
||||||
);
|
|
||||||
object.insert("model".to_string(), JsonValue::String(self.model.clone()));
|
|
||||||
object.insert(
|
|
||||||
"message_count".to_string(),
|
|
||||||
JsonValue::Number(i64::from(self.message_count)),
|
|
||||||
);
|
|
||||||
if let Some(last_prompt) = &self.last_prompt {
|
|
||||||
object.insert(
|
|
||||||
"last_prompt".to_string(),
|
|
||||||
JsonValue::String(last_prompt.clone()),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
JsonValue::Object(object)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_json(value: &JsonValue) -> Result<Self, SessionError> {
|
|
||||||
let object = value.as_object().ok_or_else(|| {
|
|
||||||
SessionError::Format("session metadata must be an object".to_string())
|
|
||||||
})?;
|
|
||||||
Ok(Self {
|
|
||||||
started_at: required_string(object, "started_at")?,
|
|
||||||
model: required_string(object, "model")?,
|
|
||||||
message_count: required_u32(object, "message_count")?,
|
|
||||||
last_prompt: optional_string(object, "last_prompt"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ConversationMessage {
|
impl ConversationMessage {
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn user_text(text: impl Into<String>) -> Self {
|
pub fn user_text(text: impl Into<String>) -> Self {
|
||||||
@ -317,19 +257,6 @@ 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(),
|
||||||
@ -376,13 +303,6 @@ 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")?,
|
||||||
@ -448,13 +368,6 @@ fn required_string(
|
|||||||
.ok_or_else(|| SessionError::Format(format!("missing {key}")))
|
.ok_or_else(|| SessionError::Format(format!("missing {key}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn optional_string(object: &BTreeMap<String, JsonValue>, key: &str) -> Option<String> {
|
|
||||||
object
|
|
||||||
.get(key)
|
|
||||||
.and_then(JsonValue::as_str)
|
|
||||||
.map(ToOwned::to_owned)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn required_u32(object: &BTreeMap<String, JsonValue>, key: &str) -> Result<u32, SessionError> {
|
fn required_u32(object: &BTreeMap<String, JsonValue>, key: &str) -> Result<u32, SessionError> {
|
||||||
let value = object
|
let value = object
|
||||||
.get(key)
|
.get(key)
|
||||||
@ -465,8 +378,7 @@ fn required_u32(object: &BTreeMap<String, JsonValue>, key: &str) -> Result<u32,
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{ContentBlock, ConversationMessage, MessageRole, Session, SessionMetadata};
|
use super::{ContentBlock, ConversationMessage, MessageRole, Session};
|
||||||
use crate::json::JsonValue;
|
|
||||||
use crate::usage::TokenUsage;
|
use crate::usage::TokenUsage;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
@ -474,12 +386,6 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn persists_and_restores_session_json() {
|
fn persists_and_restores_session_json() {
|
||||||
let mut session = Session::new();
|
let mut session = Session::new();
|
||||||
session.metadata = Some(SessionMetadata {
|
|
||||||
started_at: "2026-04-01T00:00:00Z".to_string(),
|
|
||||||
model: "claude-sonnet".to_string(),
|
|
||||||
message_count: 3,
|
|
||||||
last_prompt: Some("hello".to_string()),
|
|
||||||
});
|
|
||||||
session
|
session
|
||||||
.messages
|
.messages
|
||||||
.push(ConversationMessage::user_text("hello"));
|
.push(ConversationMessage::user_text("hello"));
|
||||||
@ -522,23 +428,5 @@ mod tests {
|
|||||||
restored.messages[1].usage.expect("usage").total_tokens(),
|
restored.messages[1].usage.expect("usage").total_tokens(),
|
||||||
17
|
17
|
||||||
);
|
);
|
||||||
assert_eq!(restored.metadata, session.metadata);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn loads_legacy_session_without_metadata() {
|
|
||||||
let legacy = r#"{
|
|
||||||
"version": 1,
|
|
||||||
"messages": [
|
|
||||||
{
|
|
||||||
"role": "user",
|
|
||||||
"blocks": [{"type": "text", "text": "hello"}]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}"#;
|
|
||||||
let restored = Session::from_json(&JsonValue::parse(legacy).expect("legacy json"))
|
|
||||||
.expect("legacy session should parse");
|
|
||||||
assert_eq!(restored.messages.len(), 1);
|
|
||||||
assert!(restored.metadata.is_none());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -300,7 +300,6 @@ mod tests {
|
|||||||
cache_read_input_tokens: 0,
|
cache_read_input_tokens: 0,
|
||||||
}),
|
}),
|
||||||
}],
|
}],
|
||||||
metadata: None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let tracker = UsageTracker::from_session(&session);
|
let tracker = UsageTracker::from_session(&session);
|
||||||
|
|||||||
@ -5,17 +5,18 @@ edition.workspace = true
|
|||||||
license.workspace = true
|
license.workspace = true
|
||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "claw"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
api = { path = "../api" }
|
api = { path = "../api" }
|
||||||
commands = { path = "../commands" }
|
commands = { path = "../commands" }
|
||||||
compat-harness = { path = "../compat-harness" }
|
compat-harness = { path = "../compat-harness" }
|
||||||
crossterm = "0.28"
|
crossterm = "0.28"
|
||||||
pulldown-cmark = "0.13"
|
pulldown-cmark = "0.13"
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "json", "rustls-tls"] }
|
|
||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
sha2 = "0.10"
|
|
||||||
syntect = "5"
|
syntect = "5"
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
|
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
|
||||||
tools = { path = "../tools" }
|
tools = { path = "../tools" }
|
||||||
|
|||||||
@ -9,7 +9,7 @@ use clap::{Parser, Subcommand, ValueEnum};
|
|||||||
about = "Rust Claude CLI prototype"
|
about = "Rust Claude CLI prototype"
|
||||||
)]
|
)]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
#[arg(long, default_value = "claude-3-7-sonnet")]
|
#[arg(long, default_value = "claude-opus-4-6")]
|
||||||
pub model: String,
|
pub model: String,
|
||||||
|
|
||||||
#[arg(long, value_enum, default_value_t = PermissionMode::WorkspaceWrite)]
|
#[arg(long, value_enum, default_value_t = PermissionMode::WorkspaceWrite)]
|
||||||
|
|||||||
433
rust/crates/rusty-claude-cli/src/init.rs
Normal file
433
rust/crates/rusty-claude-cli/src/init.rs
Normal file
@ -0,0 +1,433 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
const STARTER_CLAUDE_JSON: &str = concat!(
|
||||||
|
"{\n",
|
||||||
|
" \"permissions\": {\n",
|
||||||
|
" \"defaultMode\": \"acceptEdits\"\n",
|
||||||
|
" }\n",
|
||||||
|
"}\n",
|
||||||
|
);
|
||||||
|
const GITIGNORE_COMMENT: &str = "# Claude Code local artifacts";
|
||||||
|
const GITIGNORE_ENTRIES: [&str; 2] = [".claude/settings.local.json", ".claude/sessions/"];
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub(crate) enum InitStatus {
|
||||||
|
Created,
|
||||||
|
Updated,
|
||||||
|
Skipped,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InitStatus {
|
||||||
|
#[must_use]
|
||||||
|
pub(crate) fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Created => "created",
|
||||||
|
Self::Updated => "updated",
|
||||||
|
Self::Skipped => "skipped (already exists)",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct InitArtifact {
|
||||||
|
pub(crate) name: &'static str,
|
||||||
|
pub(crate) status: InitStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct InitReport {
|
||||||
|
pub(crate) project_root: PathBuf,
|
||||||
|
pub(crate) artifacts: Vec<InitArtifact>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InitReport {
|
||||||
|
#[must_use]
|
||||||
|
pub(crate) fn render(&self) -> String {
|
||||||
|
let mut lines = vec![
|
||||||
|
"Init".to_string(),
|
||||||
|
format!(" Project {}", self.project_root.display()),
|
||||||
|
];
|
||||||
|
for artifact in &self.artifacts {
|
||||||
|
lines.push(format!(
|
||||||
|
" {:<16} {}",
|
||||||
|
artifact.name,
|
||||||
|
artifact.status.label()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
lines.push(" Next step Review and tailor the generated guidance".to_string());
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
#[allow(clippy::struct_excessive_bools)]
|
||||||
|
struct RepoDetection {
|
||||||
|
rust_workspace: bool,
|
||||||
|
rust_root: bool,
|
||||||
|
python: bool,
|
||||||
|
package_json: bool,
|
||||||
|
typescript: bool,
|
||||||
|
nextjs: bool,
|
||||||
|
react: bool,
|
||||||
|
vite: bool,
|
||||||
|
nest: bool,
|
||||||
|
src_dir: bool,
|
||||||
|
tests_dir: bool,
|
||||||
|
rust_dir: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn initialize_repo(cwd: &Path) -> Result<InitReport, Box<dyn std::error::Error>> {
|
||||||
|
let mut artifacts = Vec::new();
|
||||||
|
|
||||||
|
let claude_dir = cwd.join(".claude");
|
||||||
|
artifacts.push(InitArtifact {
|
||||||
|
name: ".claude/",
|
||||||
|
status: ensure_dir(&claude_dir)?,
|
||||||
|
});
|
||||||
|
|
||||||
|
let claude_json = cwd.join(".claude.json");
|
||||||
|
artifacts.push(InitArtifact {
|
||||||
|
name: ".claude.json",
|
||||||
|
status: write_file_if_missing(&claude_json, STARTER_CLAUDE_JSON)?,
|
||||||
|
});
|
||||||
|
|
||||||
|
let gitignore = cwd.join(".gitignore");
|
||||||
|
artifacts.push(InitArtifact {
|
||||||
|
name: ".gitignore",
|
||||||
|
status: ensure_gitignore_entries(&gitignore)?,
|
||||||
|
});
|
||||||
|
|
||||||
|
let claude_md = cwd.join("CLAUDE.md");
|
||||||
|
let content = render_init_claude_md(cwd);
|
||||||
|
artifacts.push(InitArtifact {
|
||||||
|
name: "CLAUDE.md",
|
||||||
|
status: write_file_if_missing(&claude_md, &content)?,
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(InitReport {
|
||||||
|
project_root: cwd.to_path_buf(),
|
||||||
|
artifacts,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_dir(path: &Path) -> Result<InitStatus, std::io::Error> {
|
||||||
|
if path.is_dir() {
|
||||||
|
return Ok(InitStatus::Skipped);
|
||||||
|
}
|
||||||
|
fs::create_dir_all(path)?;
|
||||||
|
Ok(InitStatus::Created)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_file_if_missing(path: &Path, content: &str) -> Result<InitStatus, std::io::Error> {
|
||||||
|
if path.exists() {
|
||||||
|
return Ok(InitStatus::Skipped);
|
||||||
|
}
|
||||||
|
fs::write(path, content)?;
|
||||||
|
Ok(InitStatus::Created)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ensure_gitignore_entries(path: &Path) -> Result<InitStatus, std::io::Error> {
|
||||||
|
if !path.exists() {
|
||||||
|
let mut lines = vec![GITIGNORE_COMMENT.to_string()];
|
||||||
|
lines.extend(GITIGNORE_ENTRIES.iter().map(|entry| (*entry).to_string()));
|
||||||
|
fs::write(path, format!("{}\n", lines.join("\n")))?;
|
||||||
|
return Ok(InitStatus::Created);
|
||||||
|
}
|
||||||
|
|
||||||
|
let existing = fs::read_to_string(path)?;
|
||||||
|
let mut lines = existing.lines().map(ToOwned::to_owned).collect::<Vec<_>>();
|
||||||
|
let mut changed = false;
|
||||||
|
|
||||||
|
if !lines.iter().any(|line| line == GITIGNORE_COMMENT) {
|
||||||
|
lines.push(GITIGNORE_COMMENT.to_string());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for entry in GITIGNORE_ENTRIES {
|
||||||
|
if !lines.iter().any(|line| line == entry) {
|
||||||
|
lines.push(entry.to_string());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !changed {
|
||||||
|
return Ok(InitStatus::Skipped);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::write(path, format!("{}\n", lines.join("\n")))?;
|
||||||
|
Ok(InitStatus::Updated)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn render_init_claude_md(cwd: &Path) -> String {
|
||||||
|
let detection = detect_repo(cwd);
|
||||||
|
let mut lines = vec![
|
||||||
|
"# CLAUDE.md".to_string(),
|
||||||
|
String::new(),
|
||||||
|
"This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.".to_string(),
|
||||||
|
String::new(),
|
||||||
|
];
|
||||||
|
|
||||||
|
let detected_languages = detected_languages(&detection);
|
||||||
|
let detected_frameworks = detected_frameworks(&detection);
|
||||||
|
lines.push("## Detected stack".to_string());
|
||||||
|
if detected_languages.is_empty() {
|
||||||
|
lines.push("- No specific language markers were detected yet; document the primary language and verification commands once the project structure settles.".to_string());
|
||||||
|
} else {
|
||||||
|
lines.push(format!("- Languages: {}.", detected_languages.join(", ")));
|
||||||
|
}
|
||||||
|
if detected_frameworks.is_empty() {
|
||||||
|
lines.push("- Frameworks: none detected from the supported starter markers.".to_string());
|
||||||
|
} else {
|
||||||
|
lines.push(format!(
|
||||||
|
"- Frameworks/tooling markers: {}.",
|
||||||
|
detected_frameworks.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
lines.push(String::new());
|
||||||
|
|
||||||
|
let verification_lines = verification_lines(cwd, &detection);
|
||||||
|
if !verification_lines.is_empty() {
|
||||||
|
lines.push("## Verification".to_string());
|
||||||
|
lines.extend(verification_lines);
|
||||||
|
lines.push(String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let structure_lines = repository_shape_lines(&detection);
|
||||||
|
if !structure_lines.is_empty() {
|
||||||
|
lines.push("## Repository shape".to_string());
|
||||||
|
lines.extend(structure_lines);
|
||||||
|
lines.push(String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let framework_lines = framework_notes(&detection);
|
||||||
|
if !framework_lines.is_empty() {
|
||||||
|
lines.push("## Framework notes".to_string());
|
||||||
|
lines.extend(framework_lines);
|
||||||
|
lines.push(String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push("## Working agreement".to_string());
|
||||||
|
lines.push("- Prefer small, reviewable changes and keep generated bootstrap files aligned with actual repo workflows.".to_string());
|
||||||
|
lines.push("- Keep shared defaults in `.claude.json`; reserve `.claude/settings.local.json` for machine-local overrides.".to_string());
|
||||||
|
lines.push("- Do not overwrite existing `CLAUDE.md` content automatically; update it intentionally when repo workflows change.".to_string());
|
||||||
|
lines.push(String::new());
|
||||||
|
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detect_repo(cwd: &Path) -> RepoDetection {
|
||||||
|
let package_json_contents = fs::read_to_string(cwd.join("package.json"))
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_ascii_lowercase();
|
||||||
|
RepoDetection {
|
||||||
|
rust_workspace: cwd.join("rust").join("Cargo.toml").is_file(),
|
||||||
|
rust_root: cwd.join("Cargo.toml").is_file(),
|
||||||
|
python: cwd.join("pyproject.toml").is_file()
|
||||||
|
|| cwd.join("requirements.txt").is_file()
|
||||||
|
|| cwd.join("setup.py").is_file(),
|
||||||
|
package_json: cwd.join("package.json").is_file(),
|
||||||
|
typescript: cwd.join("tsconfig.json").is_file()
|
||||||
|
|| package_json_contents.contains("typescript"),
|
||||||
|
nextjs: package_json_contents.contains("\"next\""),
|
||||||
|
react: package_json_contents.contains("\"react\""),
|
||||||
|
vite: package_json_contents.contains("\"vite\""),
|
||||||
|
nest: package_json_contents.contains("@nestjs"),
|
||||||
|
src_dir: cwd.join("src").is_dir(),
|
||||||
|
tests_dir: cwd.join("tests").is_dir(),
|
||||||
|
rust_dir: cwd.join("rust").is_dir(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detected_languages(detection: &RepoDetection) -> Vec<&'static str> {
|
||||||
|
let mut languages = Vec::new();
|
||||||
|
if detection.rust_workspace || detection.rust_root {
|
||||||
|
languages.push("Rust");
|
||||||
|
}
|
||||||
|
if detection.python {
|
||||||
|
languages.push("Python");
|
||||||
|
}
|
||||||
|
if detection.typescript {
|
||||||
|
languages.push("TypeScript");
|
||||||
|
} else if detection.package_json {
|
||||||
|
languages.push("JavaScript/Node.js");
|
||||||
|
}
|
||||||
|
languages
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detected_frameworks(detection: &RepoDetection) -> Vec<&'static str> {
|
||||||
|
let mut frameworks = Vec::new();
|
||||||
|
if detection.nextjs {
|
||||||
|
frameworks.push("Next.js");
|
||||||
|
}
|
||||||
|
if detection.react {
|
||||||
|
frameworks.push("React");
|
||||||
|
}
|
||||||
|
if detection.vite {
|
||||||
|
frameworks.push("Vite");
|
||||||
|
}
|
||||||
|
if detection.nest {
|
||||||
|
frameworks.push("NestJS");
|
||||||
|
}
|
||||||
|
frameworks
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verification_lines(cwd: &Path, detection: &RepoDetection) -> Vec<String> {
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
if detection.rust_workspace {
|
||||||
|
lines.push("- Run Rust verification from `rust/`: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
||||||
|
} else if detection.rust_root {
|
||||||
|
lines.push("- Run Rust verification from the repo root: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
||||||
|
}
|
||||||
|
if detection.python {
|
||||||
|
if cwd.join("pyproject.toml").is_file() {
|
||||||
|
lines.push("- Run the Python project checks declared in `pyproject.toml` (for example: `pytest`, `ruff check`, and `mypy` when configured).".to_string());
|
||||||
|
} else {
|
||||||
|
lines.push(
|
||||||
|
"- Run the repo's Python test/lint commands before shipping changes.".to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if detection.package_json {
|
||||||
|
lines.push("- Run the JavaScript/TypeScript checks from `package.json` before shipping changes (`npm test`, `npm run lint`, `npm run build`, or the repo equivalent).".to_string());
|
||||||
|
}
|
||||||
|
if detection.tests_dir && detection.src_dir {
|
||||||
|
lines.push("- `src/` and `tests/` are both present; update both surfaces together when behavior changes.".to_string());
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repository_shape_lines(detection: &RepoDetection) -> Vec<String> {
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
if detection.rust_dir {
|
||||||
|
lines.push(
|
||||||
|
"- `rust/` contains the Rust workspace and active CLI/runtime implementation."
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if detection.src_dir {
|
||||||
|
lines.push("- `src/` contains source files that should stay consistent with generated guidance and tests.".to_string());
|
||||||
|
}
|
||||||
|
if detection.tests_dir {
|
||||||
|
lines.push("- `tests/` contains validation surfaces that should be reviewed alongside code changes.".to_string());
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
fn framework_notes(detection: &RepoDetection) -> Vec<String> {
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
if detection.nextjs {
|
||||||
|
lines.push("- Next.js detected: preserve routing/data-fetching conventions and verify production builds after changing app structure.".to_string());
|
||||||
|
}
|
||||||
|
if detection.react && !detection.nextjs {
|
||||||
|
lines.push("- React detected: keep component behavior covered with focused tests and avoid unnecessary prop/API churn.".to_string());
|
||||||
|
}
|
||||||
|
if detection.vite {
|
||||||
|
lines.push("- Vite detected: validate the production bundle after changing build-sensitive configuration or imports.".to_string());
|
||||||
|
}
|
||||||
|
if detection.nest {
|
||||||
|
lines.push("- NestJS detected: keep module/provider boundaries explicit and verify controller/service wiring after refactors.".to_string());
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{initialize_repo, render_init_claude_md};
|
||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
fn temp_dir() -> std::path::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-init-{nanos}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn initialize_repo_creates_expected_files_and_gitignore_entries() {
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(root.join("rust")).expect("create rust dir");
|
||||||
|
fs::write(root.join("rust").join("Cargo.toml"), "[workspace]\n").expect("write cargo");
|
||||||
|
|
||||||
|
let report = initialize_repo(&root).expect("init should succeed");
|
||||||
|
let rendered = report.render();
|
||||||
|
assert!(rendered.contains(".claude/ created"));
|
||||||
|
assert!(rendered.contains(".claude.json created"));
|
||||||
|
assert!(rendered.contains(".gitignore created"));
|
||||||
|
assert!(rendered.contains("CLAUDE.md created"));
|
||||||
|
assert!(root.join(".claude").is_dir());
|
||||||
|
assert!(root.join(".claude.json").is_file());
|
||||||
|
assert!(root.join("CLAUDE.md").is_file());
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(root.join(".claude.json")).expect("read claude json"),
|
||||||
|
concat!(
|
||||||
|
"{\n",
|
||||||
|
" \"permissions\": {\n",
|
||||||
|
" \"defaultMode\": \"acceptEdits\"\n",
|
||||||
|
" }\n",
|
||||||
|
"}\n",
|
||||||
|
)
|
||||||
|
);
|
||||||
|
let gitignore = fs::read_to_string(root.join(".gitignore")).expect("read gitignore");
|
||||||
|
assert!(gitignore.contains(".claude/settings.local.json"));
|
||||||
|
assert!(gitignore.contains(".claude/sessions/"));
|
||||||
|
let claude_md = fs::read_to_string(root.join("CLAUDE.md")).expect("read claude md");
|
||||||
|
assert!(claude_md.contains("Languages: Rust."));
|
||||||
|
assert!(claude_md.contains("cargo clippy --workspace --all-targets -- -D warnings"));
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn initialize_repo_is_idempotent_and_preserves_existing_files() {
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("create root");
|
||||||
|
fs::write(root.join("CLAUDE.md"), "custom guidance\n").expect("write existing claude md");
|
||||||
|
fs::write(root.join(".gitignore"), ".claude/settings.local.json\n")
|
||||||
|
.expect("write gitignore");
|
||||||
|
|
||||||
|
let first = initialize_repo(&root).expect("first init should succeed");
|
||||||
|
assert!(first
|
||||||
|
.render()
|
||||||
|
.contains("CLAUDE.md skipped (already exists)"));
|
||||||
|
let second = initialize_repo(&root).expect("second init should succeed");
|
||||||
|
let second_rendered = second.render();
|
||||||
|
assert!(second_rendered.contains(".claude/ skipped (already exists)"));
|
||||||
|
assert!(second_rendered.contains(".claude.json skipped (already exists)"));
|
||||||
|
assert!(second_rendered.contains(".gitignore skipped (already exists)"));
|
||||||
|
assert!(second_rendered.contains("CLAUDE.md skipped (already exists)"));
|
||||||
|
assert_eq!(
|
||||||
|
fs::read_to_string(root.join("CLAUDE.md")).expect("read existing claude md"),
|
||||||
|
"custom guidance\n"
|
||||||
|
);
|
||||||
|
let gitignore = fs::read_to_string(root.join(".gitignore")).expect("read gitignore");
|
||||||
|
assert_eq!(gitignore.matches(".claude/settings.local.json").count(), 1);
|
||||||
|
assert_eq!(gitignore.matches(".claude/sessions/").count(), 1);
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_init_template_mentions_detected_python_and_nextjs_markers() {
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("create root");
|
||||||
|
fs::write(root.join("pyproject.toml"), "[project]\nname = \"demo\"\n")
|
||||||
|
.expect("write pyproject");
|
||||||
|
fs::write(
|
||||||
|
root.join("package.json"),
|
||||||
|
r#"{"dependencies":{"next":"14.0.0","react":"18.0.0"},"devDependencies":{"typescript":"5.0.0"}}"#,
|
||||||
|
)
|
||||||
|
.expect("write package json");
|
||||||
|
|
||||||
|
let rendered = render_init_claude_md(Path::new(&root));
|
||||||
|
assert!(rendered.contains("Languages: Python, TypeScript."));
|
||||||
|
assert!(rendered.contains("Frameworks/tooling markers: Next.js, React."));
|
||||||
|
assert!(rendered.contains("pyproject.toml"));
|
||||||
|
assert!(rendered.contains("Next.js detected"));
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,9 +1,9 @@
|
|||||||
|
mod init;
|
||||||
mod input;
|
mod input;
|
||||||
mod render;
|
mod render;
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::fmt::Write as _;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{self, Read, Write};
|
use std::io::{self, Read, Write};
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
@ -21,8 +21,8 @@ use commands::{
|
|||||||
render_slash_command_help, resume_supported_slash_commands, slash_command_specs, SlashCommand,
|
render_slash_command_help, resume_supported_slash_commands, slash_command_specs, SlashCommand,
|
||||||
};
|
};
|
||||||
use compat_harness::{extract_manifest, UpstreamPaths};
|
use compat_harness::{extract_manifest, UpstreamPaths};
|
||||||
|
use init::initialize_repo;
|
||||||
use render::{Spinner, TerminalRenderer};
|
use render::{Spinner, TerminalRenderer};
|
||||||
use reqwest::blocking::Client;
|
|
||||||
use runtime::{
|
use runtime::{
|
||||||
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
||||||
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
||||||
@ -31,30 +31,16 @@ use runtime::{
|
|||||||
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
||||||
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
||||||
};
|
};
|
||||||
use serde::Deserialize;
|
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
||||||
|
|
||||||
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
const DEFAULT_MODEL: &str = "claude-opus-4-6";
|
||||||
const DEFAULT_MAX_TOKENS: u32 = 32;
|
const DEFAULT_MAX_TOKENS: u32 = 32;
|
||||||
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");
|
||||||
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
|
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
|
||||||
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
|
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
|
||||||
const SELF_UPDATE_REPOSITORY: &str = "instructkr/clawd-code";
|
|
||||||
const SELF_UPDATE_LATEST_RELEASE_URL: &str =
|
|
||||||
"https://api.github.com/repos/instructkr/clawd-code/releases/latest";
|
|
||||||
const SELF_UPDATE_USER_AGENT: &str = "rusty-claude-cli-self-update";
|
|
||||||
const CHECKSUM_ASSET_CANDIDATES: &[&str] = &[
|
|
||||||
"SHA256SUMS",
|
|
||||||
"SHA256SUMS.txt",
|
|
||||||
"sha256sums",
|
|
||||||
"sha256sums.txt",
|
|
||||||
"checksums.txt",
|
|
||||||
"checksums.sha256",
|
|
||||||
];
|
|
||||||
|
|
||||||
type AllowedToolSet = BTreeSet<String>;
|
type AllowedToolSet = BTreeSet<String>;
|
||||||
|
|
||||||
@ -63,7 +49,7 @@ fn main() {
|
|||||||
eprintln!(
|
eprintln!(
|
||||||
"error: {error}
|
"error: {error}
|
||||||
|
|
||||||
Run `rusty-claude-cli --help` for usage."
|
Run `claw --help` for usage."
|
||||||
);
|
);
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
}
|
}
|
||||||
@ -76,7 +62,6 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
CliAction::BootstrapPlan => print_bootstrap_plan(),
|
CliAction::BootstrapPlan => print_bootstrap_plan(),
|
||||||
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
|
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
|
||||||
CliAction::Version => print_version(),
|
CliAction::Version => print_version(),
|
||||||
CliAction::SelfUpdate => run_self_update()?,
|
|
||||||
CliAction::ResumeSession {
|
CliAction::ResumeSession {
|
||||||
session_path,
|
session_path,
|
||||||
commands,
|
commands,
|
||||||
@ -91,6 +76,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
.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()?,
|
||||||
|
CliAction::Init => run_init()?,
|
||||||
CliAction::Repl {
|
CliAction::Repl {
|
||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
@ -110,7 +96,6 @@ enum CliAction {
|
|||||||
date: String,
|
date: String,
|
||||||
},
|
},
|
||||||
Version,
|
Version,
|
||||||
SelfUpdate,
|
|
||||||
ResumeSession {
|
ResumeSession {
|
||||||
session_path: PathBuf,
|
session_path: PathBuf,
|
||||||
commands: Vec<String>,
|
commands: Vec<String>,
|
||||||
@ -124,6 +109,7 @@ enum CliAction {
|
|||||||
},
|
},
|
||||||
Login,
|
Login,
|
||||||
Logout,
|
Logout,
|
||||||
|
Init,
|
||||||
Repl {
|
Repl {
|
||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
@ -246,9 +232,9 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
"dump-manifests" => Ok(CliAction::DumpManifests),
|
"dump-manifests" => Ok(CliAction::DumpManifests),
|
||||||
"bootstrap-plan" => Ok(CliAction::BootstrapPlan),
|
"bootstrap-plan" => Ok(CliAction::BootstrapPlan),
|
||||||
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
||||||
"self-update" => Ok(CliAction::SelfUpdate),
|
|
||||||
"login" => Ok(CliAction::Login),
|
"login" => Ok(CliAction::Login),
|
||||||
"logout" => Ok(CliAction::Logout),
|
"logout" => Ok(CliAction::Logout),
|
||||||
|
"init" => Ok(CliAction::Init),
|
||||||
"prompt" => {
|
"prompt" => {
|
||||||
let prompt = rest[1..].join(" ");
|
let prompt = rest[1..].join(" ");
|
||||||
if prompt.trim().is_empty() {
|
if prompt.trim().is_empty() {
|
||||||
@ -464,7 +450,7 @@ fn run_login() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "oauth state mismatch").into());
|
return Err(io::Error::new(io::ErrorKind::InvalidData, "oauth state mismatch").into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let client = AnthropicClient::from_auth(AuthSource::None);
|
let client = AnthropicClient::from_auth(AuthSource::None).with_base_url(api::read_base_url());
|
||||||
let exchange_request =
|
let exchange_request =
|
||||||
OAuthTokenExchangeRequest::from_config(oauth, code, state, pkce.verifier, redirect_uri);
|
OAuthTokenExchangeRequest::from_config(oauth, code, state, pkce.verifier, redirect_uri);
|
||||||
let runtime = tokio::runtime::Runtime::new()?;
|
let runtime = tokio::runtime::Runtime::new()?;
|
||||||
@ -553,375 +539,6 @@ fn print_version() {
|
|||||||
println!("{}", render_version_report());
|
println!("{}", render_version_report());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
|
||||||
struct GitHubRelease {
|
|
||||||
tag_name: String,
|
|
||||||
#[serde(default)]
|
|
||||||
body: String,
|
|
||||||
#[serde(default)]
|
|
||||||
assets: Vec<GitHubReleaseAsset>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
|
||||||
struct GitHubReleaseAsset {
|
|
||||||
name: String,
|
|
||||||
browser_download_url: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
struct SelectedReleaseAssets {
|
|
||||||
binary: GitHubReleaseAsset,
|
|
||||||
checksum: GitHubReleaseAsset,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_self_update() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let Some(release) = fetch_latest_release()? else {
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
render_update_report(
|
|
||||||
"No published release available",
|
|
||||||
Some(VERSION),
|
|
||||||
None,
|
|
||||||
Some("GitHub latest release endpoint returned no published release for instructkr/clawd-code."),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
|
|
||||||
let latest_version = normalize_version_tag(&release.tag_name);
|
|
||||||
if !is_newer_version(VERSION, &latest_version) {
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
render_update_report(
|
|
||||||
"Already up to date",
|
|
||||||
Some(VERSION),
|
|
||||||
Some(&latest_version),
|
|
||||||
Some("Current binary already matches the latest published release."),
|
|
||||||
Some(&release.body),
|
|
||||||
)
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
let selected = match select_release_assets(&release) {
|
|
||||||
Ok(selected) => selected,
|
|
||||||
Err(message) => {
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
render_update_report(
|
|
||||||
"Release found, but no installable asset matched this platform",
|
|
||||||
Some(VERSION),
|
|
||||||
Some(&latest_version),
|
|
||||||
Some(&message),
|
|
||||||
Some(&release.body),
|
|
||||||
)
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let client = build_self_update_client()?;
|
|
||||||
let binary_bytes = download_bytes(&client, &selected.binary.browser_download_url)?;
|
|
||||||
let checksum_manifest = download_text(&client, &selected.checksum.browser_download_url)?;
|
|
||||||
let expected_checksum = parse_checksum_for_asset(&checksum_manifest, &selected.binary.name)
|
|
||||||
.ok_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"checksum manifest did not contain an entry for {}",
|
|
||||||
selected.binary.name
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
let actual_checksum = sha256_hex(&binary_bytes);
|
|
||||||
if actual_checksum != expected_checksum {
|
|
||||||
return Err(format!(
|
|
||||||
"downloaded asset checksum mismatch for {} (expected {}, got {})",
|
|
||||||
selected.binary.name, expected_checksum, actual_checksum
|
|
||||||
)
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
replace_current_executable(&binary_bytes)?;
|
|
||||||
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
render_update_report(
|
|
||||||
"Update installed",
|
|
||||||
Some(VERSION),
|
|
||||||
Some(&latest_version),
|
|
||||||
Some(&format!(
|
|
||||||
"Installed {} from GitHub release assets for {}.",
|
|
||||||
selected.binary.name,
|
|
||||||
current_target()
|
|
||||||
)),
|
|
||||||
Some(&release.body),
|
|
||||||
)
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fetch_latest_release() -> Result<Option<GitHubRelease>, Box<dyn std::error::Error>> {
|
|
||||||
let client = build_self_update_client()?;
|
|
||||||
let response = client
|
|
||||||
.get(SELF_UPDATE_LATEST_RELEASE_URL)
|
|
||||||
.header(reqwest::header::ACCEPT, "application/vnd.github+json")
|
|
||||||
.send()?;
|
|
||||||
|
|
||||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
let response = response.error_for_status()?;
|
|
||||||
Ok(Some(response.json()?))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_self_update_client() -> Result<Client, reqwest::Error> {
|
|
||||||
Client::builder().user_agent(SELF_UPDATE_USER_AGENT).build()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn download_bytes(client: &Client, url: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
|
|
||||||
let response = client.get(url).send()?.error_for_status()?;
|
|
||||||
Ok(response.bytes()?.to_vec())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn download_text(client: &Client, url: &str) -> Result<String, Box<dyn std::error::Error>> {
|
|
||||||
let response = client.get(url).send()?.error_for_status()?;
|
|
||||||
Ok(response.text()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn normalize_version_tag(version: &str) -> String {
|
|
||||||
version.trim().trim_start_matches('v').to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_newer_version(current: &str, latest: &str) -> bool {
|
|
||||||
compare_versions(latest, current).is_gt()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn current_target() -> String {
|
|
||||||
BUILD_TARGET.map_or_else(default_target_triple, str::to_string)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn release_asset_candidates() -> Vec<String> {
|
|
||||||
let mut candidates = target_name_candidates()
|
|
||||||
.into_iter()
|
|
||||||
.flat_map(|target| {
|
|
||||||
let mut names = vec![format!("rusty-claude-cli-{target}")];
|
|
||||||
if env::consts::OS == "windows" {
|
|
||||||
names.push(format!("rusty-claude-cli-{target}.exe"));
|
|
||||||
}
|
|
||||||
names
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if env::consts::OS == "windows" {
|
|
||||||
candidates.push("rusty-claude-cli.exe".to_string());
|
|
||||||
}
|
|
||||||
candidates.push("rusty-claude-cli".to_string());
|
|
||||||
candidates.sort();
|
|
||||||
candidates.dedup();
|
|
||||||
candidates
|
|
||||||
}
|
|
||||||
|
|
||||||
fn select_release_assets(release: &GitHubRelease) -> Result<SelectedReleaseAssets, String> {
|
|
||||||
let binary = release_asset_candidates()
|
|
||||||
.into_iter()
|
|
||||||
.find_map(|candidate| {
|
|
||||||
release
|
|
||||||
.assets
|
|
||||||
.iter()
|
|
||||||
.find(|asset| asset.name == candidate)
|
|
||||||
.cloned()
|
|
||||||
})
|
|
||||||
.ok_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"no binary asset matched target {} (expected one of: {})",
|
|
||||||
current_target(),
|
|
||||||
release_asset_candidates().join(", ")
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let checksum = CHECKSUM_ASSET_CANDIDATES
|
|
||||||
.iter()
|
|
||||||
.find_map(|candidate| {
|
|
||||||
release
|
|
||||||
.assets
|
|
||||||
.iter()
|
|
||||||
.find(|asset| asset.name == *candidate)
|
|
||||||
.cloned()
|
|
||||||
})
|
|
||||||
.ok_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"release did not include a checksum manifest (expected one of: {})",
|
|
||||||
CHECKSUM_ASSET_CANDIDATES.join(", ")
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(SelectedReleaseAssets { binary, checksum })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_checksum_for_asset(manifest: &str, asset_name: &str) -> Option<String> {
|
|
||||||
manifest.lines().find_map(|line| {
|
|
||||||
let trimmed = line.trim();
|
|
||||||
if trimmed.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
if let Some((left, right)) = trimmed.split_once(" = ") {
|
|
||||||
return left
|
|
||||||
.strip_prefix("SHA256 (")
|
|
||||||
.and_then(|value| value.strip_suffix(')'))
|
|
||||||
.filter(|file| *file == asset_name)
|
|
||||||
.map(|_| right.to_ascii_lowercase());
|
|
||||||
}
|
|
||||||
let mut parts = trimmed.split_whitespace();
|
|
||||||
let checksum = parts.next()?;
|
|
||||||
let file = parts
|
|
||||||
.next_back()
|
|
||||||
.or_else(|| parts.next())?
|
|
||||||
.trim_start_matches('*');
|
|
||||||
(file == asset_name).then(|| checksum.to_ascii_lowercase())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sha256_hex(bytes: &[u8]) -> String {
|
|
||||||
format!("{:x}", Sha256::digest(bytes))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn replace_current_executable(binary_bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let current = env::current_exe()?;
|
|
||||||
replace_executable_at(¤t, binary_bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn replace_executable_at(
|
|
||||||
current: &Path,
|
|
||||||
binary_bytes: &[u8],
|
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
let temp_path = current.with_extension("download");
|
|
||||||
let backup_path = current.with_extension("bak");
|
|
||||||
|
|
||||||
if backup_path.exists() {
|
|
||||||
fs::remove_file(&backup_path)?;
|
|
||||||
}
|
|
||||||
fs::write(&temp_path, binary_bytes)?;
|
|
||||||
copy_executable_permissions(current, &temp_path)?;
|
|
||||||
|
|
||||||
fs::rename(current, &backup_path)?;
|
|
||||||
if let Err(error) = fs::rename(&temp_path, current) {
|
|
||||||
let _ = fs::rename(&backup_path, current);
|
|
||||||
let _ = fs::remove_file(&temp_path);
|
|
||||||
return Err(format!("failed to replace current executable: {error}").into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Err(error) = fs::remove_file(&backup_path) {
|
|
||||||
eprintln!(
|
|
||||||
"warning: failed to remove self-update backup {}: {error}",
|
|
||||||
backup_path.display()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(unix)]
|
|
||||||
fn copy_executable_permissions(
|
|
||||||
source: &Path,
|
|
||||||
destination: &Path,
|
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
use std::os::unix::fs::PermissionsExt;
|
|
||||||
|
|
||||||
let mode = fs::metadata(source)?.permissions().mode();
|
|
||||||
fs::set_permissions(destination, fs::Permissions::from_mode(mode))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(unix))]
|
|
||||||
fn copy_executable_permissions(
|
|
||||||
_source: &Path,
|
|
||||||
_destination: &Path,
|
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_update_report(
|
|
||||||
result: &str,
|
|
||||||
current_version: Option<&str>,
|
|
||||||
latest_version: Option<&str>,
|
|
||||||
detail: Option<&str>,
|
|
||||||
changelog: Option<&str>,
|
|
||||||
) -> String {
|
|
||||||
let mut report = String::from(
|
|
||||||
"Self-update
|
|
||||||
",
|
|
||||||
);
|
|
||||||
let _ = writeln!(report, " Repository {SELF_UPDATE_REPOSITORY}");
|
|
||||||
let _ = writeln!(report, " Result {result}");
|
|
||||||
if let Some(current_version) = current_version {
|
|
||||||
let _ = writeln!(report, " Current version {current_version}");
|
|
||||||
}
|
|
||||||
if let Some(latest_version) = latest_version {
|
|
||||||
let _ = writeln!(report, " Latest version {latest_version}");
|
|
||||||
}
|
|
||||||
if let Some(detail) = detail {
|
|
||||||
let _ = writeln!(report, " Detail {detail}");
|
|
||||||
}
|
|
||||||
let trimmed = changelog.map(str::trim).filter(|value| !value.is_empty());
|
|
||||||
if let Some(changelog) = trimmed {
|
|
||||||
report.push_str(
|
|
||||||
"
|
|
||||||
Changelog
|
|
||||||
",
|
|
||||||
);
|
|
||||||
report.push_str(changelog);
|
|
||||||
}
|
|
||||||
report.trim_end().to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn compare_versions(left: &str, right: &str) -> std::cmp::Ordering {
|
|
||||||
let left = normalize_version_tag(left);
|
|
||||||
let right = normalize_version_tag(right);
|
|
||||||
let left_parts = version_components(&left);
|
|
||||||
let right_parts = version_components(&right);
|
|
||||||
let max_len = left_parts.len().max(right_parts.len());
|
|
||||||
for index in 0..max_len {
|
|
||||||
let left_part = *left_parts.get(index).unwrap_or(&0);
|
|
||||||
let right_part = *right_parts.get(index).unwrap_or(&0);
|
|
||||||
match left_part.cmp(&right_part) {
|
|
||||||
std::cmp::Ordering::Equal => {}
|
|
||||||
ordering => return ordering,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
std::cmp::Ordering::Equal
|
|
||||||
}
|
|
||||||
|
|
||||||
fn version_components(version: &str) -> Vec<u64> {
|
|
||||||
version
|
|
||||||
.split(['.', '-'])
|
|
||||||
.map(|part| {
|
|
||||||
part.chars()
|
|
||||||
.take_while(char::is_ascii_digit)
|
|
||||||
.collect::<String>()
|
|
||||||
})
|
|
||||||
.filter(|part| !part.is_empty())
|
|
||||||
.filter_map(|part| part.parse::<u64>().ok())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_target_triple() -> String {
|
|
||||||
let os = match env::consts::OS {
|
|
||||||
"linux" => "unknown-linux-gnu",
|
|
||||||
"macos" => "apple-darwin",
|
|
||||||
"windows" => "pc-windows-msvc",
|
|
||||||
other => other,
|
|
||||||
};
|
|
||||||
format!("{}-{os}", env::consts::ARCH)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn target_name_candidates() -> Vec<String> {
|
|
||||||
let mut candidates = Vec::new();
|
|
||||||
if let Some(target) = BUILD_TARGET {
|
|
||||||
candidates.push(target.to_string());
|
|
||||||
}
|
|
||||||
candidates.push(default_target_triple());
|
|
||||||
candidates.push(format!("{}-{}", env::consts::ARCH, env::consts::OS));
|
|
||||||
candidates
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resume_session(session_path: &Path, commands: &[String]) {
|
fn resume_session(session_path: &Path, commands: &[String]) {
|
||||||
let session = match Session::load_from_path(session_path) {
|
let session = match Session::load_from_path(session_path) {
|
||||||
Ok(session) => session,
|
Ok(session) => session,
|
||||||
@ -1091,26 +708,6 @@ fn format_resume_report(session_path: &str, message_count: usize, turns: u32) ->
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_init_report(path: &Path, created: bool) -> String {
|
|
||||||
if created {
|
|
||||||
format!(
|
|
||||||
"Init
|
|
||||||
CLAUDE.md {}
|
|
||||||
Result created
|
|
||||||
Next step Review and tailor the generated guidance",
|
|
||||||
path.display()
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
format!(
|
|
||||||
"Init
|
|
||||||
CLAUDE.md {}
|
|
||||||
Result skipped (already exists)
|
|
||||||
Next step Edit the existing file intentionally if workflows changed",
|
|
||||||
path.display()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn format_compact_report(removed: usize, resulting_messages: usize, skipped: bool) -> String {
|
fn format_compact_report(removed: usize, resulting_messages: usize, skipped: bool) -> String {
|
||||||
if skipped {
|
if skipped {
|
||||||
format!(
|
format!(
|
||||||
@ -1281,7 +878,7 @@ fn run_repl(
|
|||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
) -> 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)?;
|
||||||
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());
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
@ -1368,14 +965,26 @@ impl LiveCli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn startup_banner(&self) -> String {
|
fn startup_banner(&self) -> String {
|
||||||
|
let cwd = env::current_dir().map_or_else(
|
||||||
|
|_| "<unknown>".to_string(),
|
||||||
|
|path| path.display().to_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.",
|
"\x1b[38;5;196m\
|
||||||
|
██████╗██╗ █████╗ ██╗ ██╗\n\
|
||||||
|
██╔════╝██║ ██╔══██╗██║ ██║\n\
|
||||||
|
██║ ██║ ███████║██║ █╗ ██║\n\
|
||||||
|
██║ ██║ ██╔══██║██║███╗██║\n\
|
||||||
|
╚██████╗███████╗██║ ██║╚███╔███╔╝\n\
|
||||||
|
╚═════╝╚══════╝╚═╝ ╚═╝ ╚══╝╚══╝\x1b[0m \x1b[38;5;208mCode\x1b[0m 🦞\n\n\
|
||||||
|
\x1b[2mModel\x1b[0m {}\n\
|
||||||
|
\x1b[2mPermissions\x1b[0m {}\n\
|
||||||
|
\x1b[2mDirectory\x1b[0m {}\n\
|
||||||
|
\x1b[2mSession\x1b[0m {}\n\n\
|
||||||
|
Type \x1b[1m/help\x1b[0m for commands · \x1b[2mShift+Enter\x1b[0m for newline",
|
||||||
self.model,
|
self.model,
|
||||||
self.permission_mode.as_str(),
|
self.permission_mode.as_str(),
|
||||||
env::current_dir().map_or_else(
|
cwd,
|
||||||
|_| "<unknown>".to_string(),
|
|
||||||
|path| path.display().to_string(),
|
|
||||||
),
|
|
||||||
self.session.id,
|
self.session.id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -1384,7 +993,7 @@ impl LiveCli {
|
|||||||
let mut spinner = Spinner::new();
|
let mut spinner = Spinner::new();
|
||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
spinner.tick(
|
spinner.tick(
|
||||||
"Waiting for Claude",
|
"🦀 Thinking...",
|
||||||
TerminalRenderer::new().color_theme(),
|
TerminalRenderer::new().color_theme(),
|
||||||
&mut stdout,
|
&mut stdout,
|
||||||
)?;
|
)?;
|
||||||
@ -1393,7 +1002,7 @@ impl LiveCli {
|
|||||||
match result {
|
match result {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
spinner.finish(
|
spinner.finish(
|
||||||
"Claude response complete",
|
"✨ Done",
|
||||||
TerminalRenderer::new().color_theme(),
|
TerminalRenderer::new().color_theme(),
|
||||||
&mut stdout,
|
&mut stdout,
|
||||||
)?;
|
)?;
|
||||||
@ -1403,7 +1012,7 @@ impl LiveCli {
|
|||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
spinner.fail(
|
spinner.fail(
|
||||||
"Claude request failed",
|
"❌ Request failed",
|
||||||
TerminalRenderer::new().color_theme(),
|
TerminalRenderer::new().color_theme(),
|
||||||
&mut stdout,
|
&mut stdout,
|
||||||
)?;
|
)?;
|
||||||
@ -1424,7 +1033,7 @@ impl LiveCli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
|
fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = AnthropicClient::from_auth(resolve_cli_auth_source()?);
|
let client = AnthropicClient::from_auth(resolve_cli_auth_source()?).with_base_url(api::read_base_url());
|
||||||
let request = MessageRequest {
|
let request = MessageRequest {
|
||||||
model: self.model.clone(),
|
model: self.model.clone(),
|
||||||
max_tokens: DEFAULT_MAX_TOKENS,
|
max_tokens: DEFAULT_MAX_TOKENS,
|
||||||
@ -1500,7 +1109,7 @@ impl LiveCli {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Init => {
|
SlashCommand::Init => {
|
||||||
Self::run_init()?;
|
run_init()?;
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Diff => {
|
SlashCommand::Diff => {
|
||||||
@ -1708,11 +1317,6 @@ impl LiveCli {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run_init() -> Result<(), Box<dyn std::error::Error>> {
|
|
||||||
println!("{}", init_claude_md()?);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
|
fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("{}", render_diff_report()?);
|
println!("{}", render_diff_report()?);
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -2110,67 +1714,12 @@ fn render_memory_report() -> Result<String, Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
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()?;
|
||||||
let claude_md = cwd.join("CLAUDE.md");
|
Ok(initialize_repo(&cwd)?.render())
|
||||||
if claude_md.exists() {
|
|
||||||
return Ok(format_init_report(&claude_md, false));
|
|
||||||
}
|
|
||||||
|
|
||||||
let content = render_init_claude_md(&cwd);
|
|
||||||
fs::write(&claude_md, content)?;
|
|
||||||
Ok(format_init_report(&claude_md, true))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_init_claude_md(cwd: &Path) -> String {
|
fn run_init() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let mut lines = vec![
|
println!("{}", init_claude_md()?);
|
||||||
"# CLAUDE.md".to_string(),
|
Ok(())
|
||||||
String::new(),
|
|
||||||
"This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.".to_string(),
|
|
||||||
String::new(),
|
|
||||||
];
|
|
||||||
|
|
||||||
let mut command_lines = Vec::new();
|
|
||||||
if cwd.join("rust").join("Cargo.toml").is_file() {
|
|
||||||
command_lines.push("- Run Rust verification from `rust/`: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
|
||||||
} else if cwd.join("Cargo.toml").is_file() {
|
|
||||||
command_lines.push("- Run Rust verification from the repo root: `cargo fmt`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`".to_string());
|
|
||||||
}
|
|
||||||
if cwd.join("tests").is_dir() && cwd.join("src").is_dir() {
|
|
||||||
command_lines.push("- `src/` and `tests/` are also present; check those surfaces before removing or renaming Python-era compatibility assets.".to_string());
|
|
||||||
}
|
|
||||||
if !command_lines.is_empty() {
|
|
||||||
lines.push("## Verification".to_string());
|
|
||||||
lines.extend(command_lines);
|
|
||||||
lines.push(String::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut structure_lines = Vec::new();
|
|
||||||
if cwd.join("rust").is_dir() {
|
|
||||||
structure_lines.push(
|
|
||||||
"- `rust/` contains the Rust workspace and the active CLI/runtime implementation."
|
|
||||||
.to_string(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if cwd.join("src").is_dir() {
|
|
||||||
structure_lines.push("- `src/` contains the older Python-first workspace artifacts referenced by the repo history and tests.".to_string());
|
|
||||||
}
|
|
||||||
if cwd.join("tests").is_dir() {
|
|
||||||
structure_lines.push("- `tests/` exercises compatibility and porting behavior across the repository surfaces.".to_string());
|
|
||||||
}
|
|
||||||
if !structure_lines.is_empty() {
|
|
||||||
lines.push("## Repository shape".to_string());
|
|
||||||
lines.extend(structure_lines);
|
|
||||||
lines.push(String::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
lines.push("## Working agreement".to_string());
|
|
||||||
lines.push("- Prefer small, reviewable Rust changes and keep slash-command behavior aligned between the shared command registry and the CLI entrypoints.".to_string());
|
|
||||||
lines.push("- Do not overwrite existing CLAUDE.md content automatically; update it intentionally when repo workflows change.".to_string());
|
|
||||||
lines.push(String::new());
|
|
||||||
|
|
||||||
lines.join(
|
|
||||||
"
|
|
||||||
",
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
|
fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
|
||||||
@ -2205,7 +1754,7 @@ fn render_version_report() -> String {
|
|||||||
let git_sha = GIT_SHA.unwrap_or("unknown");
|
let git_sha = GIT_SHA.unwrap_or("unknown");
|
||||||
let target = BUILD_TARGET.unwrap_or("unknown");
|
let target = BUILD_TARGET.unwrap_or("unknown");
|
||||||
format!(
|
format!(
|
||||||
"Version\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
|
"Claw Code\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2385,7 +1934,7 @@ impl AnthropicRuntimeClient {
|
|||||||
) -> 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()?,
|
||||||
client: AnthropicClient::from_auth(resolve_cli_auth_source()?),
|
client: AnthropicClient::from_auth(resolve_cli_auth_source()?).with_base_url(api::read_base_url()),
|
||||||
model,
|
model,
|
||||||
enable_tools,
|
enable_tools,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
@ -2729,36 +2278,65 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_help() {
|
fn print_help_to(out: &mut impl Write) -> io::Result<()> {
|
||||||
println!("rusty-claude-cli v{VERSION}");
|
writeln!(out, "claw v{VERSION}")?;
|
||||||
println!();
|
writeln!(out)?;
|
||||||
println!("Usage:");
|
writeln!(out, "Usage:")?;
|
||||||
println!(" rusty-claude-cli [--model MODEL] [--allowedTools TOOL[,TOOL...]]");
|
writeln!(
|
||||||
println!(" Start the interactive REPL");
|
out,
|
||||||
println!(" rusty-claude-cli [--model MODEL] [--output-format text|json] prompt TEXT");
|
" claw [--model MODEL] [--allowedTools TOOL[,TOOL...]]"
|
||||||
println!(" Send one prompt and exit");
|
)?;
|
||||||
println!(" rusty-claude-cli [--model MODEL] [--output-format text|json] TEXT");
|
writeln!(out, " Start the interactive REPL")?;
|
||||||
println!(" Shorthand non-interactive prompt mode");
|
writeln!(
|
||||||
println!(" rusty-claude-cli --resume SESSION.json [/status] [/compact] [...]");
|
out,
|
||||||
println!(" Inspect or maintain a saved session without entering the REPL");
|
" claw [--model MODEL] [--output-format text|json] prompt TEXT"
|
||||||
println!(" rusty-claude-cli dump-manifests");
|
)?;
|
||||||
println!(" rusty-claude-cli bootstrap-plan");
|
writeln!(out, " Send one prompt and exit")?;
|
||||||
println!(" rusty-claude-cli system-prompt [--cwd PATH] [--date YYYY-MM-DD]");
|
writeln!(
|
||||||
println!(" rusty-claude-cli login");
|
out,
|
||||||
println!(" rusty-claude-cli logout");
|
" claw [--model MODEL] [--output-format text|json] TEXT"
|
||||||
println!(" rusty-claude-cli self-update");
|
)?;
|
||||||
println!(" Update the installed binary from the latest GitHub release");
|
writeln!(out, " Shorthand non-interactive prompt mode")?;
|
||||||
println!();
|
writeln!(
|
||||||
println!("Flags:");
|
out,
|
||||||
println!(" --model MODEL Override the active model");
|
" claw --resume SESSION.json [/status] [/compact] [...]"
|
||||||
println!(" --output-format FORMAT Non-interactive output format: text or json");
|
)?;
|
||||||
println!(" --permission-mode MODE Set read-only, workspace-write, or danger-full-access");
|
writeln!(
|
||||||
println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
|
out,
|
||||||
println!(" --version, -V Print version and build information locally");
|
" Inspect or maintain a saved session without entering the REPL"
|
||||||
println!();
|
)?;
|
||||||
println!("Interactive slash commands:");
|
writeln!(out, " claw dump-manifests")?;
|
||||||
println!("{}", render_slash_command_help());
|
writeln!(out, " claw bootstrap-plan")?;
|
||||||
println!();
|
writeln!(
|
||||||
|
out,
|
||||||
|
" claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]"
|
||||||
|
)?;
|
||||||
|
writeln!(out, " claw login")?;
|
||||||
|
writeln!(out, " claw logout")?;
|
||||||
|
writeln!(out, " claw init")?;
|
||||||
|
writeln!(out)?;
|
||||||
|
writeln!(out, "Flags:")?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" --model MODEL Override the active model"
|
||||||
|
)?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" --output-format FORMAT Non-interactive output format: text or json"
|
||||||
|
)?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" --permission-mode MODE Set read-only, workspace-write, or danger-full-access"
|
||||||
|
)?;
|
||||||
|
writeln!(out, " --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)")?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" --version, -V Print version and build information locally"
|
||||||
|
)?;
|
||||||
|
writeln!(out)?;
|
||||||
|
writeln!(out, "Interactive slash commands:")?;
|
||||||
|
writeln!(out, "{}", render_slash_command_help())?;
|
||||||
|
writeln!(out)?;
|
||||||
let resume_commands = resume_supported_slash_commands()
|
let resume_commands = resume_supported_slash_commands()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|spec| match spec.argument_hint {
|
.map(|spec| match spec.argument_hint {
|
||||||
@ -2767,30 +2345,46 @@ fn print_help() {
|
|||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join(", ");
|
.join(", ");
|
||||||
println!("Resume-safe commands: {resume_commands}");
|
writeln!(out, "Resume-safe commands: {resume_commands}")?;
|
||||||
println!("Examples:");
|
writeln!(out, "Examples:")?;
|
||||||
println!(" rusty-claude-cli --model claude-opus \"summarize this repo\"");
|
writeln!(
|
||||||
println!(" rusty-claude-cli --output-format json prompt \"explain src/main.rs\"");
|
out,
|
||||||
println!(" rusty-claude-cli --allowedTools read,glob \"summarize Cargo.toml\"");
|
" claw --model claude-opus \"summarize this repo\""
|
||||||
println!(" rusty-claude-cli --resume session.json /status /diff /export notes.txt");
|
)?;
|
||||||
println!(" rusty-claude-cli login");
|
writeln!(
|
||||||
println!(" rusty-claude-cli self-update");
|
out,
|
||||||
|
" claw --output-format json prompt \"explain src/main.rs\""
|
||||||
|
)?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" claw --allowedTools read,glob \"summarize Cargo.toml\""
|
||||||
|
)?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" claw --resume session.json /status /diff /export notes.txt"
|
||||||
|
)?;
|
||||||
|
writeln!(out, " claw login")?;
|
||||||
|
writeln!(out, " claw init")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_help() {
|
||||||
|
let _ = print_help_to(&mut io::stdout());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
|
filter_tool_specs, format_compact_report, format_cost_report, format_model_report,
|
||||||
format_model_report, format_model_switch_report, format_permissions_report,
|
format_model_switch_report, format_permissions_report, format_permissions_switch_report,
|
||||||
format_permissions_switch_report, format_resume_report, format_status_report,
|
format_resume_report, format_status_report, format_tool_call_start, format_tool_result,
|
||||||
format_tool_call_start, format_tool_result, is_newer_version, normalize_permission_mode,
|
normalize_permission_mode, parse_args, parse_git_status_metadata, print_help_to,
|
||||||
normalize_version_tag, parse_args, parse_checksum_for_asset, parse_git_status_metadata,
|
render_config_report, render_memory_report, render_repl_help,
|
||||||
render_config_report, render_init_claude_md, render_memory_report, render_repl_help,
|
resume_supported_slash_commands, status_context, CliAction, CliOutputFormat, SlashCommand,
|
||||||
render_update_report, resume_supported_slash_commands, select_release_assets,
|
StatusUsage, DEFAULT_MODEL,
|
||||||
status_context, CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
|
||||||
};
|
};
|
||||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn defaults_to_repl_when_no_args() {
|
fn defaults_to_repl_when_no_args() {
|
||||||
@ -2856,64 +2450,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_self_update_subcommand() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_args(&["self-update".to_string()]).expect("self-update should parse"),
|
|
||||||
CliAction::SelfUpdate
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn normalize_version_tag_trims_v_prefix() {
|
|
||||||
assert_eq!(normalize_version_tag("v0.1.0"), "0.1.0");
|
|
||||||
assert_eq!(normalize_version_tag("0.1.0"), "0.1.0");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn detects_when_latest_version_differs() {
|
|
||||||
assert!(!is_newer_version("0.1.0", "v0.1.0"));
|
|
||||||
assert!(is_newer_version("0.1.0", "v0.2.0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_checksum_manifest_for_named_asset() {
|
|
||||||
let manifest = "abc123 *rusty-claude-cli\ndef456 other-file\n";
|
|
||||||
assert_eq!(
|
|
||||||
parse_checksum_for_asset(manifest, "rusty-claude-cli"),
|
|
||||||
Some("abc123".to_string())
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn select_release_assets_requires_checksum_file() {
|
|
||||||
let release = super::GitHubRelease {
|
|
||||||
tag_name: "v0.2.0".to_string(),
|
|
||||||
body: String::new(),
|
|
||||||
assets: vec![super::GitHubReleaseAsset {
|
|
||||||
name: "rusty-claude-cli".to_string(),
|
|
||||||
browser_download_url: "https://example.invalid/rusty-claude-cli".to_string(),
|
|
||||||
}],
|
|
||||||
};
|
|
||||||
|
|
||||||
let error = select_release_assets(&release).expect_err("missing checksum should error");
|
|
||||||
assert!(error.contains("checksum manifest"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn update_report_includes_changelog_when_present() {
|
|
||||||
let report = render_update_report(
|
|
||||||
"Already up to date",
|
|
||||||
Some("0.1.0"),
|
|
||||||
Some("0.1.0"),
|
|
||||||
Some("No action taken."),
|
|
||||||
Some("- Added self-update"),
|
|
||||||
);
|
|
||||||
assert!(report.contains("Self-update"));
|
|
||||||
assert!(report.contains("Changelog"));
|
|
||||||
assert!(report.contains("- Added self-update"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_permission_mode_flag() {
|
fn parses_permission_mode_flag() {
|
||||||
let args = vec!["--permission-mode=read-only".to_string()];
|
let args = vec!["--permission-mode=read-only".to_string()];
|
||||||
@ -2984,6 +2520,10 @@ mod tests {
|
|||||||
parse_args(&["logout".to_string()]).expect("logout should parse"),
|
parse_args(&["logout".to_string()]).expect("logout should parse"),
|
||||||
CliAction::Logout
|
CliAction::Logout
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["init".to_string()]).expect("init should parse"),
|
||||||
|
CliAction::Init
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -3138,12 +2678,11 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn init_report_uses_structured_output() {
|
fn init_help_mentions_direct_subcommand() {
|
||||||
let created = format_init_report(Path::new("/tmp/CLAUDE.md"), true);
|
let mut help = Vec::new();
|
||||||
assert!(created.contains("Init"));
|
print_help_to(&mut help).expect("help should render");
|
||||||
assert!(created.contains("Result created"));
|
let help = String::from_utf8(help).expect("help should be utf8");
|
||||||
let skipped = format_init_report(Path::new("/tmp/CLAUDE.md"), false);
|
assert!(help.contains("claw init"));
|
||||||
assert!(skipped.contains("skipped (already exists)"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -3247,7 +2786,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_eq!(context.discovered_config_files, 5);
|
||||||
assert!(context.loaded_config_files <= context.discovered_config_files);
|
assert!(context.loaded_config_files <= context.discovered_config_files);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -3305,7 +2844,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn init_template_mentions_detected_rust_workspace() {
|
fn init_template_mentions_detected_rust_workspace() {
|
||||||
let rendered = render_init_claude_md(Path::new("."));
|
let rendered = crate::init::render_init_claude_md(std::path::Path::new("."));
|
||||||
assert!(rendered.contains("# CLAUDE.md"));
|
assert!(rendered.contains("# CLAUDE.md"));
|
||||||
assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
|
assert!(rendered.contains("cargo clippy --workspace --all-targets -- -D warnings"));
|
||||||
}
|
}
|
||||||
|
|||||||
@ -15,17 +15,13 @@ use syntect::util::{as_24_bit_terminal_escaped, LinesWithEndings};
|
|||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct ColorTheme {
|
pub struct ColorTheme {
|
||||||
enabled: bool,
|
|
||||||
heading: Color,
|
heading: Color,
|
||||||
emphasis: Color,
|
emphasis: Color,
|
||||||
strong: Color,
|
strong: Color,
|
||||||
inline_code: Color,
|
inline_code: Color,
|
||||||
link: Color,
|
link: Color,
|
||||||
quote: Color,
|
quote: Color,
|
||||||
info: Color,
|
table_border: Color,
|
||||||
warning: Color,
|
|
||||||
success: Color,
|
|
||||||
error: Color,
|
|
||||||
spinner_active: Color,
|
spinner_active: Color,
|
||||||
spinner_done: Color,
|
spinner_done: Color,
|
||||||
spinner_failed: Color,
|
spinner_failed: Color,
|
||||||
@ -34,17 +30,13 @@ pub struct ColorTheme {
|
|||||||
impl Default for ColorTheme {
|
impl Default for ColorTheme {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
enabled: true,
|
heading: Color::Cyan,
|
||||||
heading: Color::Blue,
|
emphasis: Color::Magenta,
|
||||||
emphasis: Color::Blue,
|
|
||||||
strong: Color::Yellow,
|
strong: Color::Yellow,
|
||||||
inline_code: Color::Green,
|
inline_code: Color::Green,
|
||||||
link: Color::Blue,
|
link: Color::Blue,
|
||||||
quote: Color::DarkGrey,
|
quote: Color::DarkGrey,
|
||||||
info: Color::Blue,
|
table_border: Color::DarkCyan,
|
||||||
warning: Color::Yellow,
|
|
||||||
success: Color::Green,
|
|
||||||
error: Color::Red,
|
|
||||||
spinner_active: Color::Blue,
|
spinner_active: Color::Blue,
|
||||||
spinner_done: Color::Green,
|
spinner_done: Color::Green,
|
||||||
spinner_failed: Color::Red,
|
spinner_failed: Color::Red,
|
||||||
@ -52,21 +44,6 @@ impl Default for ColorTheme {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ColorTheme {
|
|
||||||
#[must_use]
|
|
||||||
pub fn without_color() -> Self {
|
|
||||||
Self {
|
|
||||||
enabled: false,
|
|
||||||
..Self::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn enabled(&self) -> bool {
|
|
||||||
self.enabled
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||||
pub struct Spinner {
|
pub struct Spinner {
|
||||||
frame_index: usize,
|
frame_index: usize,
|
||||||
@ -92,19 +69,12 @@ impl Spinner {
|
|||||||
out,
|
out,
|
||||||
SavePosition,
|
SavePosition,
|
||||||
MoveToColumn(0),
|
MoveToColumn(0),
|
||||||
Clear(ClearType::CurrentLine)
|
Clear(ClearType::CurrentLine),
|
||||||
|
SetForegroundColor(theme.spinner_active),
|
||||||
|
Print(format!("{frame} {label}")),
|
||||||
|
ResetColor,
|
||||||
|
RestorePosition
|
||||||
)?;
|
)?;
|
||||||
if theme.enabled() {
|
|
||||||
queue!(
|
|
||||||
out,
|
|
||||||
SetForegroundColor(theme.spinner_active),
|
|
||||||
Print(format!("{frame} {label}")),
|
|
||||||
ResetColor,
|
|
||||||
RestorePosition
|
|
||||||
)?;
|
|
||||||
} else {
|
|
||||||
queue!(out, Print(format!("{frame} {label}")), RestorePosition)?;
|
|
||||||
}
|
|
||||||
out.flush()
|
out.flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,17 +85,14 @@ impl Spinner {
|
|||||||
out: &mut impl Write,
|
out: &mut impl Write,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
self.frame_index = 0;
|
self.frame_index = 0;
|
||||||
execute!(out, MoveToColumn(0), Clear(ClearType::CurrentLine))?;
|
execute!(
|
||||||
if theme.enabled() {
|
out,
|
||||||
execute!(
|
MoveToColumn(0),
|
||||||
out,
|
Clear(ClearType::CurrentLine),
|
||||||
SetForegroundColor(theme.spinner_done),
|
SetForegroundColor(theme.spinner_done),
|
||||||
Print(format!("✔ {label}\n")),
|
Print(format!("✔ {label}\n")),
|
||||||
ResetColor
|
ResetColor
|
||||||
)?;
|
)?;
|
||||||
} else {
|
|
||||||
execute!(out, Print(format!("✔ {label}\n")))?;
|
|
||||||
}
|
|
||||||
out.flush()
|
out.flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,42 +103,82 @@ impl Spinner {
|
|||||||
out: &mut impl Write,
|
out: &mut impl Write,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
self.frame_index = 0;
|
self.frame_index = 0;
|
||||||
execute!(out, MoveToColumn(0), Clear(ClearType::CurrentLine))?;
|
execute!(
|
||||||
if theme.enabled() {
|
out,
|
||||||
execute!(
|
MoveToColumn(0),
|
||||||
out,
|
Clear(ClearType::CurrentLine),
|
||||||
SetForegroundColor(theme.spinner_failed),
|
SetForegroundColor(theme.spinner_failed),
|
||||||
Print(format!("✘ {label}\n")),
|
Print(format!("✘ {label}\n")),
|
||||||
ResetColor
|
ResetColor
|
||||||
)?;
|
)?;
|
||||||
} else {
|
|
||||||
execute!(out, Print(format!("✘ {label}\n")))?;
|
|
||||||
}
|
|
||||||
out.flush()
|
out.flush()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
enum ListKind {
|
||||||
|
Unordered,
|
||||||
|
Ordered { next_index: u64 },
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||||
|
struct TableState {
|
||||||
|
headers: Vec<String>,
|
||||||
|
rows: Vec<Vec<String>>,
|
||||||
|
current_row: Vec<String>,
|
||||||
|
current_cell: String,
|
||||||
|
in_head: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableState {
|
||||||
|
fn push_cell(&mut self) {
|
||||||
|
let cell = self.current_cell.trim().to_string();
|
||||||
|
self.current_row.push(cell);
|
||||||
|
self.current_cell.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_row(&mut self) {
|
||||||
|
if self.current_row.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let row = std::mem::take(&mut self.current_row);
|
||||||
|
if self.in_head {
|
||||||
|
self.headers = row;
|
||||||
|
} else {
|
||||||
|
self.rows.push(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||||
struct RenderState {
|
struct RenderState {
|
||||||
emphasis: usize,
|
emphasis: usize,
|
||||||
strong: usize,
|
strong: usize,
|
||||||
quote: usize,
|
quote: usize,
|
||||||
list: usize,
|
list_stack: Vec<ListKind>,
|
||||||
|
table: Option<TableState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderState {
|
impl RenderState {
|
||||||
fn style_text(&self, text: &str, theme: &ColorTheme) -> String {
|
fn style_text(&self, text: &str, theme: &ColorTheme) -> String {
|
||||||
if !theme.enabled() {
|
let mut styled = text.to_string();
|
||||||
return text.to_string();
|
|
||||||
}
|
|
||||||
if self.strong > 0 {
|
if self.strong > 0 {
|
||||||
format!("{}", text.bold().with(theme.strong))
|
styled = format!("{}", styled.bold().with(theme.strong));
|
||||||
} else if self.emphasis > 0 {
|
}
|
||||||
format!("{}", text.italic().with(theme.emphasis))
|
if self.emphasis > 0 {
|
||||||
} else if self.quote > 0 {
|
styled = format!("{}", styled.italic().with(theme.emphasis));
|
||||||
format!("{}", text.with(theme.quote))
|
}
|
||||||
|
if self.quote > 0 {
|
||||||
|
styled = format!("{}", styled.with(theme.quote));
|
||||||
|
}
|
||||||
|
styled
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_target_mut<'a>(&'a mut self, output: &'a mut String) -> &'a mut String {
|
||||||
|
if let Some(table) = self.table.as_mut() {
|
||||||
|
&mut table.current_cell
|
||||||
} else {
|
} else {
|
||||||
text.to_string()
|
output
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -204,70 +211,11 @@ impl TerminalRenderer {
|
|||||||
Self::default()
|
Self::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn with_color(enabled: bool) -> Self {
|
|
||||||
if enabled {
|
|
||||||
Self::new()
|
|
||||||
} else {
|
|
||||||
Self {
|
|
||||||
color_theme: ColorTheme::without_color(),
|
|
||||||
..Self::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn color_theme(&self) -> &ColorTheme {
|
pub fn color_theme(&self) -> &ColorTheme {
|
||||||
&self.color_theme
|
&self.color_theme
|
||||||
}
|
}
|
||||||
|
|
||||||
fn paint(&self, text: impl AsRef<str>, color: Color) -> String {
|
|
||||||
let text = text.as_ref();
|
|
||||||
if self.color_theme.enabled() {
|
|
||||||
format!("{}", text.with(color))
|
|
||||||
} else {
|
|
||||||
text.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint_bold(&self, text: impl AsRef<str>, color: Color) -> String {
|
|
||||||
let text = text.as_ref();
|
|
||||||
if self.color_theme.enabled() {
|
|
||||||
format!("{}", text.bold().with(color))
|
|
||||||
} else {
|
|
||||||
text.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint_underlined(&self, text: impl AsRef<str>, color: Color) -> String {
|
|
||||||
let text = text.as_ref();
|
|
||||||
if self.color_theme.enabled() {
|
|
||||||
format!("{}", text.underlined().with(color))
|
|
||||||
} else {
|
|
||||||
text.to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn info(&self, text: impl AsRef<str>) -> String {
|
|
||||||
self.paint(text, self.color_theme.info)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn warning(&self, text: impl AsRef<str>) -> String {
|
|
||||||
self.paint(text, self.color_theme.warning)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn success(&self, text: impl AsRef<str>) -> String {
|
|
||||||
self.paint(text, self.color_theme.success)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn error(&self, text: impl AsRef<str>) -> String {
|
|
||||||
self.paint(text, self.color_theme.error)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn render_markdown(&self, markdown: &str) -> String {
|
pub fn render_markdown(&self, markdown: &str) -> String {
|
||||||
let mut output = String::new();
|
let mut output = String::new();
|
||||||
@ -290,6 +238,7 @@ impl TerminalRenderer {
|
|||||||
output.trim_end().to_string()
|
output.trim_end().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_lines)]
|
||||||
fn render_event(
|
fn render_event(
|
||||||
&self,
|
&self,
|
||||||
event: Event<'_>,
|
event: Event<'_>,
|
||||||
@ -303,12 +252,22 @@ impl TerminalRenderer {
|
|||||||
Event::Start(Tag::Heading { level, .. }) => self.start_heading(level as u8, output),
|
Event::Start(Tag::Heading { level, .. }) => self.start_heading(level as u8, output),
|
||||||
Event::End(TagEnd::Heading(..) | TagEnd::Paragraph) => output.push_str("\n\n"),
|
Event::End(TagEnd::Heading(..) | TagEnd::Paragraph) => output.push_str("\n\n"),
|
||||||
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
||||||
Event::End(TagEnd::BlockQuote(..) | TagEnd::Item)
|
Event::End(TagEnd::BlockQuote(..)) => {
|
||||||
| Event::SoftBreak
|
state.quote = state.quote.saturating_sub(1);
|
||||||
| Event::HardBreak => output.push('\n'),
|
output.push('\n');
|
||||||
Event::Start(Tag::List(_)) => state.list += 1,
|
}
|
||||||
|
Event::End(TagEnd::Item) | Event::SoftBreak | Event::HardBreak => {
|
||||||
|
state.capture_target_mut(output).push('\n');
|
||||||
|
}
|
||||||
|
Event::Start(Tag::List(first_item)) => {
|
||||||
|
let kind = match first_item {
|
||||||
|
Some(index) => ListKind::Ordered { next_index: index },
|
||||||
|
None => ListKind::Unordered,
|
||||||
|
};
|
||||||
|
state.list_stack.push(kind);
|
||||||
|
}
|
||||||
Event::End(TagEnd::List(..)) => {
|
Event::End(TagEnd::List(..)) => {
|
||||||
state.list = state.list.saturating_sub(1);
|
state.list_stack.pop();
|
||||||
output.push('\n');
|
output.push('\n');
|
||||||
}
|
}
|
||||||
Event::Start(Tag::Item) => Self::start_item(state, output),
|
Event::Start(Tag::Item) => Self::start_item(state, output),
|
||||||
@ -332,55 +291,85 @@ impl TerminalRenderer {
|
|||||||
Event::Start(Tag::Strong) => state.strong += 1,
|
Event::Start(Tag::Strong) => state.strong += 1,
|
||||||
Event::End(TagEnd::Strong) => state.strong = state.strong.saturating_sub(1),
|
Event::End(TagEnd::Strong) => state.strong = state.strong.saturating_sub(1),
|
||||||
Event::Code(code) => {
|
Event::Code(code) => {
|
||||||
let _ = write!(
|
let rendered =
|
||||||
output,
|
format!("{}", format!("`{code}`").with(self.color_theme.inline_code));
|
||||||
"{}",
|
state.capture_target_mut(output).push_str(&rendered);
|
||||||
self.paint(format!("`{code}`"), self.color_theme.inline_code)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Event::Rule => output.push_str("---\n"),
|
Event::Rule => output.push_str("---\n"),
|
||||||
Event::Text(text) => {
|
Event::Text(text) => {
|
||||||
self.push_text(text.as_ref(), state, output, code_buffer, *in_code_block);
|
self.push_text(text.as_ref(), state, output, code_buffer, *in_code_block);
|
||||||
}
|
}
|
||||||
Event::Html(html) | Event::InlineHtml(html) => output.push_str(&html),
|
Event::Html(html) | Event::InlineHtml(html) => {
|
||||||
Event::FootnoteReference(reference) => {
|
state.capture_target_mut(output).push_str(&html);
|
||||||
let _ = write!(output, "[{reference}]");
|
}
|
||||||
|
Event::FootnoteReference(reference) => {
|
||||||
|
let _ = write!(state.capture_target_mut(output), "[{reference}]");
|
||||||
|
}
|
||||||
|
Event::TaskListMarker(done) => {
|
||||||
|
state
|
||||||
|
.capture_target_mut(output)
|
||||||
|
.push_str(if done { "[x] " } else { "[ ] " });
|
||||||
|
}
|
||||||
|
Event::InlineMath(math) | Event::DisplayMath(math) => {
|
||||||
|
state.capture_target_mut(output).push_str(&math);
|
||||||
}
|
}
|
||||||
Event::TaskListMarker(done) => output.push_str(if done { "[x] " } else { "[ ] " }),
|
|
||||||
Event::InlineMath(math) | Event::DisplayMath(math) => output.push_str(&math),
|
|
||||||
Event::Start(Tag::Link { dest_url, .. }) => {
|
Event::Start(Tag::Link { dest_url, .. }) => {
|
||||||
let _ = write!(
|
let rendered = format!(
|
||||||
output,
|
|
||||||
"{}",
|
"{}",
|
||||||
self.paint_underlined(format!("[{dest_url}]"), self.color_theme.link)
|
format!("[{dest_url}]")
|
||||||
|
.underlined()
|
||||||
|
.with(self.color_theme.link)
|
||||||
);
|
);
|
||||||
|
state.capture_target_mut(output).push_str(&rendered);
|
||||||
}
|
}
|
||||||
Event::Start(Tag::Image { dest_url, .. }) => {
|
Event::Start(Tag::Image { dest_url, .. }) => {
|
||||||
let _ = write!(
|
let rendered = format!(
|
||||||
output,
|
|
||||||
"{}",
|
"{}",
|
||||||
self.paint(format!("[image:{dest_url}]"), self.color_theme.link)
|
format!("[image:{dest_url}]").with(self.color_theme.link)
|
||||||
);
|
);
|
||||||
|
state.capture_target_mut(output).push_str(&rendered);
|
||||||
}
|
}
|
||||||
Event::Start(
|
Event::Start(Tag::Table(..)) => state.table = Some(TableState::default()),
|
||||||
Tag::Paragraph
|
Event::End(TagEnd::Table) => {
|
||||||
| Tag::Table(..)
|
if let Some(table) = state.table.take() {
|
||||||
| Tag::TableHead
|
output.push_str(&self.render_table(&table));
|
||||||
| Tag::TableRow
|
output.push_str("\n\n");
|
||||||
| Tag::TableCell
|
}
|
||||||
| Tag::MetadataBlock(..)
|
}
|
||||||
| _,
|
Event::Start(Tag::TableHead) => {
|
||||||
)
|
if let Some(table) = state.table.as_mut() {
|
||||||
| Event::End(
|
table.in_head = true;
|
||||||
TagEnd::Link
|
}
|
||||||
| TagEnd::Image
|
}
|
||||||
| TagEnd::Table
|
Event::End(TagEnd::TableHead) => {
|
||||||
| TagEnd::TableHead
|
if let Some(table) = state.table.as_mut() {
|
||||||
| TagEnd::TableRow
|
table.finish_row();
|
||||||
| TagEnd::TableCell
|
table.in_head = false;
|
||||||
| TagEnd::MetadataBlock(..)
|
}
|
||||||
| _,
|
}
|
||||||
) => {}
|
Event::Start(Tag::TableRow) => {
|
||||||
|
if let Some(table) = state.table.as_mut() {
|
||||||
|
table.current_row.clear();
|
||||||
|
table.current_cell.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::End(TagEnd::TableRow) => {
|
||||||
|
if let Some(table) = state.table.as_mut() {
|
||||||
|
table.finish_row();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Start(Tag::TableCell) => {
|
||||||
|
if let Some(table) = state.table.as_mut() {
|
||||||
|
table.current_cell.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::End(TagEnd::TableCell) => {
|
||||||
|
if let Some(table) = state.table.as_mut() {
|
||||||
|
table.push_cell();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Start(Tag::Paragraph | Tag::MetadataBlock(..) | _)
|
||||||
|
| Event::End(TagEnd::Link | TagEnd::Image | TagEnd::MetadataBlock(..) | _) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -392,21 +381,27 @@ impl TerminalRenderer {
|
|||||||
3 => "### ",
|
3 => "### ",
|
||||||
_ => "#### ",
|
_ => "#### ",
|
||||||
};
|
};
|
||||||
let _ = write!(
|
let _ = write!(output, "{}", prefix.bold().with(self.color_theme.heading));
|
||||||
output,
|
|
||||||
"{}",
|
|
||||||
self.paint_bold(prefix, self.color_theme.heading)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_quote(&self, state: &mut RenderState, output: &mut String) {
|
fn start_quote(&self, state: &mut RenderState, output: &mut String) {
|
||||||
state.quote += 1;
|
state.quote += 1;
|
||||||
let _ = write!(output, "{}", self.paint("│ ", self.color_theme.quote));
|
let _ = write!(output, "{}", "│ ".with(self.color_theme.quote));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_item(state: &RenderState, output: &mut String) {
|
fn start_item(state: &mut RenderState, output: &mut String) {
|
||||||
output.push_str(&" ".repeat(state.list.saturating_sub(1)));
|
let depth = state.list_stack.len().saturating_sub(1);
|
||||||
output.push_str("• ");
|
output.push_str(&" ".repeat(depth));
|
||||||
|
|
||||||
|
let marker = match state.list_stack.last_mut() {
|
||||||
|
Some(ListKind::Ordered { next_index }) => {
|
||||||
|
let value = *next_index;
|
||||||
|
*next_index += 1;
|
||||||
|
format!("{value}. ")
|
||||||
|
}
|
||||||
|
_ => "• ".to_string(),
|
||||||
|
};
|
||||||
|
output.push_str(&marker);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_code_block(&self, code_language: &str, output: &mut String) {
|
fn start_code_block(&self, code_language: &str, output: &mut String) {
|
||||||
@ -414,7 +409,7 @@ impl TerminalRenderer {
|
|||||||
let _ = writeln!(
|
let _ = writeln!(
|
||||||
output,
|
output,
|
||||||
"{}",
|
"{}",
|
||||||
self.paint(format!("╭─ {code_language}"), self.color_theme.heading)
|
format!("╭─ {code_language}").with(self.color_theme.heading)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -422,7 +417,7 @@ impl TerminalRenderer {
|
|||||||
fn finish_code_block(&self, code_buffer: &str, code_language: &str, output: &mut String) {
|
fn finish_code_block(&self, code_buffer: &str, code_language: &str, output: &mut String) {
|
||||||
output.push_str(&self.highlight_code(code_buffer, code_language));
|
output.push_str(&self.highlight_code(code_buffer, code_language));
|
||||||
if !code_language.is_empty() {
|
if !code_language.is_empty() {
|
||||||
let _ = write!(output, "{}", self.paint("╰─", self.color_theme.heading));
|
let _ = write!(output, "{}", "╰─".with(self.color_theme.heading));
|
||||||
}
|
}
|
||||||
output.push_str("\n\n");
|
output.push_str("\n\n");
|
||||||
}
|
}
|
||||||
@ -430,7 +425,7 @@ impl TerminalRenderer {
|
|||||||
fn push_text(
|
fn push_text(
|
||||||
&self,
|
&self,
|
||||||
text: &str,
|
text: &str,
|
||||||
state: &RenderState,
|
state: &mut RenderState,
|
||||||
output: &mut String,
|
output: &mut String,
|
||||||
code_buffer: &mut String,
|
code_buffer: &mut String,
|
||||||
in_code_block: bool,
|
in_code_block: bool,
|
||||||
@ -438,16 +433,84 @@ impl TerminalRenderer {
|
|||||||
if in_code_block {
|
if in_code_block {
|
||||||
code_buffer.push_str(text);
|
code_buffer.push_str(text);
|
||||||
} else {
|
} else {
|
||||||
output.push_str(&state.style_text(text, &self.color_theme));
|
let rendered = state.style_text(text, &self.color_theme);
|
||||||
|
state.capture_target_mut(output).push_str(&rendered);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render_table(&self, table: &TableState) -> String {
|
||||||
|
let mut rows = Vec::new();
|
||||||
|
if !table.headers.is_empty() {
|
||||||
|
rows.push(table.headers.clone());
|
||||||
|
}
|
||||||
|
rows.extend(table.rows.iter().cloned());
|
||||||
|
|
||||||
|
if rows.is_empty() {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let column_count = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||||
|
let widths = (0..column_count)
|
||||||
|
.map(|column| {
|
||||||
|
rows.iter()
|
||||||
|
.filter_map(|row| row.get(column))
|
||||||
|
.map(|cell| visible_width(cell))
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let border = format!("{}", "│".with(self.color_theme.table_border));
|
||||||
|
let separator = widths
|
||||||
|
.iter()
|
||||||
|
.map(|width| "─".repeat(*width + 2))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(&format!("{}", "┼".with(self.color_theme.table_border)));
|
||||||
|
let separator = format!("{border}{separator}{border}");
|
||||||
|
|
||||||
|
let mut output = String::new();
|
||||||
|
if !table.headers.is_empty() {
|
||||||
|
output.push_str(&self.render_table_row(&table.headers, &widths, true));
|
||||||
|
output.push('\n');
|
||||||
|
output.push_str(&separator);
|
||||||
|
if !table.rows.is_empty() {
|
||||||
|
output.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index, row) in table.rows.iter().enumerate() {
|
||||||
|
output.push_str(&self.render_table_row(row, &widths, false));
|
||||||
|
if index + 1 < table.rows.len() {
|
||||||
|
output.push('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
output
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_table_row(&self, row: &[String], widths: &[usize], is_header: bool) -> String {
|
||||||
|
let border = format!("{}", "│".with(self.color_theme.table_border));
|
||||||
|
let mut line = String::new();
|
||||||
|
line.push_str(&border);
|
||||||
|
|
||||||
|
for (index, width) in widths.iter().enumerate() {
|
||||||
|
let cell = row.get(index).map_or("", String::as_str);
|
||||||
|
line.push(' ');
|
||||||
|
if is_header {
|
||||||
|
let _ = write!(line, "{}", cell.bold().with(self.color_theme.heading));
|
||||||
|
} else {
|
||||||
|
line.push_str(cell);
|
||||||
|
}
|
||||||
|
let padding = width.saturating_sub(visible_width(cell));
|
||||||
|
line.push_str(&" ".repeat(padding + 1));
|
||||||
|
line.push_str(&border);
|
||||||
|
}
|
||||||
|
|
||||||
|
line
|
||||||
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn highlight_code(&self, code: &str, language: &str) -> String {
|
pub fn highlight_code(&self, code: &str, language: &str) -> String {
|
||||||
if !self.color_theme.enabled() {
|
|
||||||
return code.to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
let syntax = self
|
let syntax = self
|
||||||
.syntax_set
|
.syntax_set
|
||||||
.find_syntax_by_token(language)
|
.find_syntax_by_token(language)
|
||||||
@ -476,43 +539,37 @@ impl TerminalRenderer {
|
|||||||
}
|
}
|
||||||
writeln!(out)
|
writeln!(out)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[must_use]
|
fn visible_width(input: &str) -> usize {
|
||||||
pub fn token_usage_summary(&self, input_tokens: u64, output_tokens: u64) -> String {
|
strip_ansi(input).chars().count()
|
||||||
format!(
|
}
|
||||||
"{} {} input / {} output",
|
|
||||||
self.info("Token usage:"),
|
fn strip_ansi(input: &str) -> String {
|
||||||
input_tokens,
|
let mut output = String::new();
|
||||||
output_tokens
|
let mut chars = input.chars().peekable();
|
||||||
)
|
|
||||||
|
while let Some(ch) = chars.next() {
|
||||||
|
if ch == '\u{1b}' {
|
||||||
|
if chars.peek() == Some(&'[') {
|
||||||
|
chars.next();
|
||||||
|
for next in chars.by_ref() {
|
||||||
|
if next.is_ascii_alphabetic() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
output.push(ch);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
output
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{Spinner, TerminalRenderer};
|
use super::{strip_ansi, Spinner, TerminalRenderer};
|
||||||
|
|
||||||
fn strip_ansi(input: &str) -> String {
|
|
||||||
let mut output = String::new();
|
|
||||||
let mut chars = input.chars().peekable();
|
|
||||||
|
|
||||||
while let Some(ch) = chars.next() {
|
|
||||||
if ch == '\u{1b}' {
|
|
||||||
if chars.peek() == Some(&'[') {
|
|
||||||
chars.next();
|
|
||||||
for next in chars.by_ref() {
|
|
||||||
if next.is_ascii_alphabetic() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
output.push(ch);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
output
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn renders_markdown_with_styling_and_lists() {
|
fn renders_markdown_with_styling_and_lists() {
|
||||||
@ -538,6 +595,34 @@ mod tests {
|
|||||||
assert!(markdown_output.contains('\u{1b}'));
|
assert!(markdown_output.contains('\u{1b}'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renders_ordered_and_nested_lists() {
|
||||||
|
let terminal_renderer = TerminalRenderer::new();
|
||||||
|
let markdown_output =
|
||||||
|
terminal_renderer.render_markdown("1. first\n2. second\n - nested\n - child");
|
||||||
|
let plain_text = strip_ansi(&markdown_output);
|
||||||
|
|
||||||
|
assert!(plain_text.contains("1. first"));
|
||||||
|
assert!(plain_text.contains("2. second"));
|
||||||
|
assert!(plain_text.contains(" • nested"));
|
||||||
|
assert!(plain_text.contains(" • child"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renders_tables_with_alignment() {
|
||||||
|
let terminal_renderer = TerminalRenderer::new();
|
||||||
|
let markdown_output = terminal_renderer
|
||||||
|
.render_markdown("| Name | Value |\n| ---- | ----- |\n| alpha | 1 |\n| beta | 22 |");
|
||||||
|
let plain_text = strip_ansi(&markdown_output);
|
||||||
|
let lines = plain_text.lines().collect::<Vec<_>>();
|
||||||
|
|
||||||
|
assert_eq!(lines[0], "│ Name │ Value │");
|
||||||
|
assert_eq!(lines[1], "│───────┼───────│");
|
||||||
|
assert_eq!(lines[2], "│ alpha │ 1 │");
|
||||||
|
assert_eq!(lines[3], "│ beta │ 22 │");
|
||||||
|
assert!(markdown_output.contains('\u{1b}'));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn spinner_advances_frames() {
|
fn spinner_advances_frames() {
|
||||||
let terminal_renderer = TerminalRenderer::new();
|
let terminal_renderer = TerminalRenderer::new();
|
||||||
@ -553,25 +638,4 @@ mod tests {
|
|||||||
let output = String::from_utf8_lossy(&out);
|
let output = String::from_utf8_lossy(&out);
|
||||||
assert!(output.contains("Working"));
|
assert!(output.contains("Working"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn renderer_can_disable_color_output() {
|
|
||||||
let terminal_renderer = TerminalRenderer::with_color(false);
|
|
||||||
let markdown_output = terminal_renderer.render_markdown(
|
|
||||||
"# Heading\n\nThis is **bold** and `code`.\n\n```rust\nfn hi() {}\n```",
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(!markdown_output.contains('\u{1b}'));
|
|
||||||
assert!(markdown_output.contains("Heading"));
|
|
||||||
assert!(markdown_output.contains("fn hi() {}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn token_usage_summary_uses_plain_text_without_color() {
|
|
||||||
let terminal_renderer = TerminalRenderer::with_color(false);
|
|
||||||
assert_eq!(
|
|
||||||
terminal_renderer.token_usage_summary(12, 34),
|
|
||||||
"Token usage: 12 input / 34 output"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,12 +6,10 @@ license.workspace = true
|
|||||||
publish.workspace = true
|
publish.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
api = { path = "../api" }
|
|
||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio = { version = "1", features = ["rt-multi-thread"] }
|
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@ -3,17 +3,10 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use api::{
|
|
||||||
resolve_startup_auth_source, AnthropicClient, ContentBlockDelta, InputContentBlock,
|
|
||||||
InputMessage, MessageRequest, OutputContentBlock, StreamEvent as ApiStreamEvent, ToolChoice,
|
|
||||||
ToolDefinition, ToolResultContentBlock,
|
|
||||||
};
|
|
||||||
use reqwest::blocking::Client;
|
use reqwest::blocking::Client;
|
||||||
use runtime::{
|
use runtime::{
|
||||||
edit_file, execute_bash, glob_search, grep_search, load_system_prompt, read_file, write_file,
|
edit_file, execute_bash, glob_search, grep_search, read_file, write_file, BashCommandInput,
|
||||||
ApiClient, ApiRequest, AssistantEvent, BashCommandInput, ConfigLoader, ContentBlock,
|
GrepSearchInput, PermissionMode,
|
||||||
ConversationMessage, ConversationRuntime, GrepSearchInput, MessageRole, PermissionMode,
|
|
||||||
PermissionPolicy, RuntimeError, Session, TokenUsage, ToolError, ToolExecutor,
|
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
@ -241,8 +234,7 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
|||||||
},
|
},
|
||||||
ToolSpec {
|
ToolSpec {
|
||||||
name: "Agent",
|
name: "Agent",
|
||||||
description:
|
description: "Launch a specialized agent task and persist its handoff metadata.",
|
||||||
"Launch and execute a specialized child agent conversation with bounded recursion.",
|
|
||||||
input_schema: json!({
|
input_schema: json!({
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
@ -250,8 +242,7 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
|||||||
"prompt": { "type": "string" },
|
"prompt": { "type": "string" },
|
||||||
"subagent_type": { "type": "string" },
|
"subagent_type": { "type": "string" },
|
||||||
"name": { "type": "string" },
|
"name": { "type": "string" },
|
||||||
"model": { "type": "string" },
|
"model": { "type": "string" }
|
||||||
"max_depth": { "type": "integer", "minimum": 0 }
|
|
||||||
},
|
},
|
||||||
"required": ["description", "prompt"],
|
"required": ["description", "prompt"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@ -588,7 +579,6 @@ struct AgentInput {
|
|||||||
subagent_type: Option<String>,
|
subagent_type: Option<String>,
|
||||||
name: Option<String>,
|
name: Option<String>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
max_depth: Option<usize>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
@ -722,16 +712,6 @@ struct AgentOutput {
|
|||||||
subagent_type: Option<String>,
|
subagent_type: Option<String>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
status: String,
|
status: String,
|
||||||
#[serde(rename = "maxDepth")]
|
|
||||||
max_depth: usize,
|
|
||||||
#[serde(rename = "depth")]
|
|
||||||
depth: usize,
|
|
||||||
#[serde(rename = "result")]
|
|
||||||
result: Option<String>,
|
|
||||||
#[serde(rename = "assistantMessages")]
|
|
||||||
assistant_messages: Vec<String>,
|
|
||||||
#[serde(rename = "toolResults")]
|
|
||||||
tool_results: Vec<AgentToolResult>,
|
|
||||||
#[serde(rename = "outputFile")]
|
#[serde(rename = "outputFile")]
|
||||||
output_file: String,
|
output_file: String,
|
||||||
#[serde(rename = "manifestFile")]
|
#[serde(rename = "manifestFile")]
|
||||||
@ -740,15 +720,6 @@ struct AgentOutput {
|
|||||||
created_at: String,
|
created_at: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
||||||
struct AgentToolResult {
|
|
||||||
#[serde(rename = "toolName")]
|
|
||||||
tool_name: String,
|
|
||||||
output: String,
|
|
||||||
#[serde(rename = "isError")]
|
|
||||||
is_error: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize)]
|
#[derive(Debug, Serialize)]
|
||||||
struct ToolSearchOutput {
|
struct ToolSearchOutput {
|
||||||
matches: Vec<String>,
|
matches: Vec<String>,
|
||||||
@ -1228,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()
|
||||||
};
|
};
|
||||||
@ -1248,8 +1220,11 @@ 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(
|
||||||
.map_err(|error| error.to_string())?;
|
&store_path,
|
||||||
|
serde_json::to_string_pretty(&persisted).map_err(|error| error.to_string())?,
|
||||||
|
)
|
||||||
|
.map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
let verification_nudge_needed = (all_done
|
let verification_nudge_needed = (all_done
|
||||||
&& input.todos.len() >= 3
|
&& input.todos.len() >= 3
|
||||||
@ -1307,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> {
|
||||||
@ -1407,14 +1331,6 @@ fn execute_agent(input: AgentInput) -> Result<AgentOutput, String> {
|
|||||||
return Err(String::from("prompt must not be empty"));
|
return Err(String::from("prompt must not be empty"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let depth = current_agent_depth()?;
|
|
||||||
let max_depth = input.max_depth.unwrap_or(3);
|
|
||||||
if depth >= max_depth {
|
|
||||||
return Err(format!(
|
|
||||||
"Agent max_depth exceeded: current depth {depth} reached limit {max_depth}"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let agent_id = make_agent_id();
|
let agent_id = make_agent_id();
|
||||||
let output_dir = agent_store_dir()?;
|
let output_dir = agent_store_dir()?;
|
||||||
std::fs::create_dir_all(&output_dir).map_err(|error| error.to_string())?;
|
std::fs::create_dir_all(&output_dir).map_err(|error| error.to_string())?;
|
||||||
@ -1428,31 +1344,35 @@ fn execute_agent(input: AgentInput) -> Result<AgentOutput, String> {
|
|||||||
.filter(|name| !name.is_empty())
|
.filter(|name| !name.is_empty())
|
||||||
.unwrap_or_else(|| slugify_agent_name(&input.description));
|
.unwrap_or_else(|| slugify_agent_name(&input.description));
|
||||||
let created_at = iso8601_now();
|
let created_at = iso8601_now();
|
||||||
let model = input.model.clone().or_else(agent_default_model);
|
|
||||||
|
|
||||||
let child_result = with_agent_depth(depth + 1, || {
|
let output_contents = format!(
|
||||||
run_child_agent_conversation(&input.prompt, model.clone(), max_depth)
|
"# Agent Task
|
||||||
})?;
|
|
||||||
|
- id: {}
|
||||||
|
- name: {}
|
||||||
|
- description: {}
|
||||||
|
- subagent_type: {}
|
||||||
|
- created_at: {}
|
||||||
|
|
||||||
|
## Prompt
|
||||||
|
|
||||||
|
{}
|
||||||
|
",
|
||||||
|
agent_id, agent_name, input.description, normalized_subagent_type, created_at, input.prompt
|
||||||
|
);
|
||||||
|
std::fs::write(&output_file, output_contents).map_err(|error| error.to_string())?;
|
||||||
|
|
||||||
let manifest = AgentOutput {
|
let manifest = AgentOutput {
|
||||||
agent_id,
|
agent_id,
|
||||||
name: agent_name,
|
name: agent_name,
|
||||||
description: input.description,
|
description: input.description,
|
||||||
subagent_type: Some(normalized_subagent_type),
|
subagent_type: Some(normalized_subagent_type),
|
||||||
model,
|
model: input.model,
|
||||||
status: String::from("completed"),
|
status: String::from("queued"),
|
||||||
max_depth,
|
|
||||||
depth,
|
|
||||||
result: child_result.result.clone(),
|
|
||||||
assistant_messages: child_result.assistant_messages.clone(),
|
|
||||||
tool_results: child_result.tool_results.clone(),
|
|
||||||
output_file: output_file.display().to_string(),
|
output_file: output_file.display().to_string(),
|
||||||
manifest_file: manifest_file.display().to_string(),
|
manifest_file: manifest_file.display().to_string(),
|
||||||
created_at,
|
created_at,
|
||||||
};
|
};
|
||||||
|
|
||||||
let output_contents = render_agent_output(&manifest);
|
|
||||||
std::fs::write(&output_file, output_contents).map_err(|error| error.to_string())?;
|
|
||||||
std::fs::write(
|
std::fs::write(
|
||||||
&manifest_file,
|
&manifest_file,
|
||||||
serde_json::to_string_pretty(&manifest).map_err(|error| error.to_string())?,
|
serde_json::to_string_pretty(&manifest).map_err(|error| error.to_string())?,
|
||||||
@ -1462,461 +1382,6 @@ fn execute_agent(input: AgentInput) -> Result<AgentOutput, String> {
|
|||||||
Ok(manifest)
|
Ok(manifest)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
struct ChildConversationResult {
|
|
||||||
result: Option<String>,
|
|
||||||
assistant_messages: Vec<String>,
|
|
||||||
tool_results: Vec<AgentToolResult>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_child_agent_conversation(
|
|
||||||
prompt: &str,
|
|
||||||
model: Option<String>,
|
|
||||||
_max_depth: usize,
|
|
||||||
) -> Result<ChildConversationResult, String> {
|
|
||||||
let mut runtime = ConversationRuntime::new(
|
|
||||||
Session::new(),
|
|
||||||
build_agent_api_client(model.unwrap_or_else(default_agent_model))?,
|
|
||||||
AgentToolExecutor,
|
|
||||||
agent_permission_policy(),
|
|
||||||
build_agent_system_prompt()?,
|
|
||||||
)
|
|
||||||
.with_max_iterations(16);
|
|
||||||
|
|
||||||
let summary = runtime
|
|
||||||
.run_turn(prompt, None)
|
|
||||||
.map_err(|error| error.to_string())?;
|
|
||||||
|
|
||||||
let assistant_messages = summary
|
|
||||||
.assistant_messages
|
|
||||||
.iter()
|
|
||||||
.filter_map(extract_message_text)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let tool_results = summary
|
|
||||||
.tool_results
|
|
||||||
.iter()
|
|
||||||
.filter_map(extract_agent_tool_result)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let result = assistant_messages.last().cloned();
|
|
||||||
|
|
||||||
Ok(ChildConversationResult {
|
|
||||||
result,
|
|
||||||
assistant_messages,
|
|
||||||
tool_results,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_agent_output(output: &AgentOutput) -> String {
|
|
||||||
let mut lines = vec![
|
|
||||||
"# Agent Task".to_string(),
|
|
||||||
String::new(),
|
|
||||||
format!("- id: {}", output.agent_id),
|
|
||||||
format!("- name: {}", output.name),
|
|
||||||
format!("- description: {}", output.description),
|
|
||||||
format!(
|
|
||||||
"- subagent_type: {}",
|
|
||||||
output.subagent_type.as_deref().unwrap_or("general-purpose")
|
|
||||||
),
|
|
||||||
format!("- status: {}", output.status),
|
|
||||||
format!("- depth: {}", output.depth),
|
|
||||||
format!("- max_depth: {}", output.max_depth),
|
|
||||||
format!("- created_at: {}", output.created_at),
|
|
||||||
String::new(),
|
|
||||||
"## Result".to_string(),
|
|
||||||
String::new(),
|
|
||||||
output
|
|
||||||
.result
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| String::from("<no final assistant text>")),
|
|
||||||
];
|
|
||||||
|
|
||||||
if !output.tool_results.is_empty() {
|
|
||||||
lines.push(String::new());
|
|
||||||
lines.push("## Tool Results".to_string());
|
|
||||||
lines.push(String::new());
|
|
||||||
lines.extend(output.tool_results.iter().map(|result| {
|
|
||||||
format!(
|
|
||||||
"- {} [{}]: {}",
|
|
||||||
result.tool_name,
|
|
||||||
if result.is_error { "error" } else { "ok" },
|
|
||||||
result.output
|
|
||||||
)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
lines.join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn current_agent_depth() -> Result<usize, String> {
|
|
||||||
std::env::var("CLAWD_AGENT_DEPTH")
|
|
||||||
.ok()
|
|
||||||
.map(|value| {
|
|
||||||
value
|
|
||||||
.parse::<usize>()
|
|
||||||
.map_err(|error| format!("invalid CLAWD_AGENT_DEPTH: {error}"))
|
|
||||||
})
|
|
||||||
.transpose()
|
|
||||||
.map(|value| value.unwrap_or(0))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn with_agent_depth<T>(depth: usize, f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
|
|
||||||
let previous = std::env::var("CLAWD_AGENT_DEPTH").ok();
|
|
||||||
std::env::set_var("CLAWD_AGENT_DEPTH", depth.to_string());
|
|
||||||
let result = f();
|
|
||||||
if let Some(previous) = previous {
|
|
||||||
std::env::set_var("CLAWD_AGENT_DEPTH", previous);
|
|
||||||
} else {
|
|
||||||
std::env::remove_var("CLAWD_AGENT_DEPTH");
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
fn agent_default_model() -> Option<String> {
|
|
||||||
std::env::var("CLAWD_MODEL")
|
|
||||||
.ok()
|
|
||||||
.filter(|value| !value.trim().is_empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_agent_model() -> String {
|
|
||||||
agent_default_model().unwrap_or_else(|| String::from("claude-sonnet-4-20250514"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_agent_system_prompt() -> Result<Vec<String>, String> {
|
|
||||||
let cwd = std::env::current_dir().map_err(|error| error.to_string())?;
|
|
||||||
let date = std::env::var("CLAWD_CURRENT_DATE").unwrap_or_else(|_| String::from("2026-04-01"));
|
|
||||||
load_system_prompt(cwd, &date, std::env::consts::OS, "unknown")
|
|
||||||
.map_err(|error| error.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn agent_permission_policy() -> PermissionPolicy {
|
|
||||||
mvp_tool_specs().into_iter().fold(
|
|
||||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
|
||||||
|policy, spec| policy.with_tool_requirement(spec.name, spec.required_permission),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct AgentToolExecutor;
|
|
||||||
|
|
||||||
impl ToolExecutor for AgentToolExecutor {
|
|
||||||
fn execute(&mut self, tool_name: &str, input: &str) -> Result<String, ToolError> {
|
|
||||||
let value = serde_json::from_str(input)
|
|
||||||
.map_err(|error| ToolError::new(format!("invalid tool input JSON: {error}")))?;
|
|
||||||
execute_tool(tool_name, &value).map_err(ToolError::new)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
enum AgentApiClient {
|
|
||||||
Scripted(ScriptedAgentApiClient),
|
|
||||||
Anthropic(AnthropicAgentApiClient),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApiClient for AgentApiClient {
|
|
||||||
fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
match self {
|
|
||||||
Self::Scripted(client) => client.stream(request),
|
|
||||||
Self::Anthropic(client) => client.stream(request),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_agent_api_client(model: String) -> Result<AgentApiClient, String> {
|
|
||||||
if let Some(script) = std::env::var("CLAWD_AGENT_TEST_SCRIPT")
|
|
||||||
.ok()
|
|
||||||
.filter(|value| !value.trim().is_empty())
|
|
||||||
{
|
|
||||||
return Ok(AgentApiClient::Scripted(ScriptedAgentApiClient::new(
|
|
||||||
&script,
|
|
||||||
)?));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(AgentApiClient::Anthropic(AnthropicAgentApiClient::new(
|
|
||||||
model,
|
|
||||||
)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
struct AnthropicAgentApiClient {
|
|
||||||
runtime: tokio::runtime::Runtime,
|
|
||||||
client: AnthropicClient,
|
|
||||||
model: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AnthropicAgentApiClient {
|
|
||||||
fn new(model: String) -> Result<Self, String> {
|
|
||||||
Ok(Self {
|
|
||||||
runtime: tokio::runtime::Runtime::new().map_err(|error| error.to_string())?,
|
|
||||||
client: AnthropicClient::from_auth(resolve_agent_auth_source()?),
|
|
||||||
model,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApiClient for AnthropicAgentApiClient {
|
|
||||||
fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
let message_request = MessageRequest {
|
|
||||||
model: self.model.clone(),
|
|
||||||
max_tokens: 32,
|
|
||||||
messages: convert_agent_messages(&request.messages),
|
|
||||||
system: (!request.system_prompt.is_empty()).then(|| {
|
|
||||||
request.system_prompt.join(
|
|
||||||
"
|
|
||||||
|
|
||||||
",
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
tools: Some(agent_tool_definitions()),
|
|
||||||
tool_choice: Some(ToolChoice::Auto),
|
|
||||||
stream: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
self.runtime.block_on(async {
|
|
||||||
let mut stream = self
|
|
||||||
.client
|
|
||||||
.stream_message(&message_request)
|
|
||||||
.await
|
|
||||||
.map_err(|error| RuntimeError::new(error.to_string()))?;
|
|
||||||
let mut events = Vec::new();
|
|
||||||
let mut pending_tool: Option<(String, String, String)> = None;
|
|
||||||
let mut saw_stop = false;
|
|
||||||
|
|
||||||
while let Some(event) = stream
|
|
||||||
.next_event()
|
|
||||||
.await
|
|
||||||
.map_err(|error| RuntimeError::new(error.to_string()))?
|
|
||||||
{
|
|
||||||
match event {
|
|
||||||
ApiStreamEvent::MessageStart(start) => {
|
|
||||||
push_agent_output_blocks(
|
|
||||||
start.message.content,
|
|
||||||
&mut events,
|
|
||||||
&mut pending_tool,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
ApiStreamEvent::ContentBlockStart(start) => {
|
|
||||||
push_agent_output_block(
|
|
||||||
start.content_block,
|
|
||||||
&mut events,
|
|
||||||
&mut pending_tool,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
|
|
||||||
ContentBlockDelta::TextDelta { text } => {
|
|
||||||
if !text.is_empty() {
|
|
||||||
events.push(AssistantEvent::TextDelta(text));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ContentBlockDelta::InputJsonDelta { partial_json } => {
|
|
||||||
if let Some((_, _, input)) = &mut pending_tool {
|
|
||||||
input.push_str(&partial_json);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
ApiStreamEvent::ContentBlockStop(_) => {
|
|
||||||
if let Some((id, name, input)) = pending_tool.take() {
|
|
||||||
events.push(AssistantEvent::ToolUse { id, name, input });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ApiStreamEvent::MessageDelta(delta) => {
|
|
||||||
events.push(AssistantEvent::Usage(TokenUsage {
|
|
||||||
input_tokens: delta.usage.input_tokens,
|
|
||||||
output_tokens: delta.usage.output_tokens,
|
|
||||||
cache_creation_input_tokens: delta.usage.cache_creation_input_tokens,
|
|
||||||
cache_read_input_tokens: delta.usage.cache_read_input_tokens,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
ApiStreamEvent::MessageStop(_) => {
|
|
||||||
saw_stop = true;
|
|
||||||
events.push(AssistantEvent::MessageStop);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !saw_stop {
|
|
||||||
events.push(AssistantEvent::MessageStop);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(events)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_agent_auth_source() -> Result<api::AuthSource, String> {
|
|
||||||
resolve_startup_auth_source(|| {
|
|
||||||
let cwd = std::env::current_dir().map_err(api::ApiError::from)?;
|
|
||||||
let config = ConfigLoader::default_for(&cwd).load().map_err(|error| {
|
|
||||||
api::ApiError::Auth(format!("failed to load runtime OAuth config: {error}"))
|
|
||||||
})?;
|
|
||||||
Ok(config.oauth().cloned())
|
|
||||||
})
|
|
||||||
.map_err(|error| error.to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn agent_tool_definitions() -> Vec<ToolDefinition> {
|
|
||||||
mvp_tool_specs()
|
|
||||||
.into_iter()
|
|
||||||
.map(|spec| ToolDefinition {
|
|
||||||
name: spec.name.to_string(),
|
|
||||||
description: Some(spec.description.to_string()),
|
|
||||||
input_schema: spec.input_schema,
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn convert_agent_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
|
|
||||||
messages
|
|
||||||
.iter()
|
|
||||||
.filter_map(|message| {
|
|
||||||
let role = match message.role {
|
|
||||||
MessageRole::System | MessageRole::User | MessageRole::Tool => "user",
|
|
||||||
MessageRole::Assistant => "assistant",
|
|
||||||
};
|
|
||||||
let content = message
|
|
||||||
.blocks
|
|
||||||
.iter()
|
|
||||||
.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,
|
|
||||||
..
|
|
||||||
} => 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 {
|
|
||||||
role: role.to_string(),
|
|
||||||
content,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push_agent_output_blocks(
|
|
||||||
blocks: Vec<OutputContentBlock>,
|
|
||||||
events: &mut Vec<AssistantEvent>,
|
|
||||||
pending_tool: &mut Option<(String, String, String)>,
|
|
||||||
) {
|
|
||||||
for block in blocks {
|
|
||||||
push_agent_output_block(block, events, pending_tool);
|
|
||||||
if let Some((id, name, input)) = pending_tool.take() {
|
|
||||||
events.push(AssistantEvent::ToolUse { id, name, input });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push_agent_output_block(
|
|
||||||
block: OutputContentBlock,
|
|
||||||
events: &mut Vec<AssistantEvent>,
|
|
||||||
pending_tool: &mut Option<(String, String, String)>,
|
|
||||||
) {
|
|
||||||
match block {
|
|
||||||
OutputContentBlock::Text { text } => {
|
|
||||||
if !text.is_empty() {
|
|
||||||
events.push(AssistantEvent::TextDelta(text));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
OutputContentBlock::ToolUse { id, name, input } => {
|
|
||||||
*pending_tool = Some((id, name, input.to_string()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct ScriptedAgentApiClient {
|
|
||||||
turns: Vec<Vec<ScriptedAgentEvent>>,
|
|
||||||
call_count: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ScriptedAgentApiClient {
|
|
||||||
fn new(script: &str) -> Result<Self, String> {
|
|
||||||
let turns = serde_json::from_str(script).map_err(|error| error.to_string())?;
|
|
||||||
Ok(Self {
|
|
||||||
turns,
|
|
||||||
call_count: 0,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApiClient for ScriptedAgentApiClient {
|
|
||||||
fn stream(&mut self, _request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
if self.call_count >= self.turns.len() {
|
|
||||||
return Err(RuntimeError::new("scripted agent client exhausted"));
|
|
||||||
}
|
|
||||||
let events = self.turns[self.call_count]
|
|
||||||
.iter()
|
|
||||||
.map(ScriptedAgentEvent::to_runtime_event)
|
|
||||||
.chain(std::iter::once(AssistantEvent::MessageStop))
|
|
||||||
.collect();
|
|
||||||
self.call_count += 1;
|
|
||||||
Ok(events)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Deserialize)]
|
|
||||||
#[serde(tag = "type", rename_all = "snake_case")]
|
|
||||||
enum ScriptedAgentEvent {
|
|
||||||
Text {
|
|
||||||
text: String,
|
|
||||||
},
|
|
||||||
ToolUse {
|
|
||||||
id: String,
|
|
||||||
name: String,
|
|
||||||
input: Value,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ScriptedAgentEvent {
|
|
||||||
fn to_runtime_event(&self) -> AssistantEvent {
|
|
||||||
match self {
|
|
||||||
Self::Text { text } => AssistantEvent::TextDelta(text.clone()),
|
|
||||||
Self::ToolUse { id, name, input } => AssistantEvent::ToolUse {
|
|
||||||
id: id.clone(),
|
|
||||||
name: name.clone(),
|
|
||||||
input: input.to_string(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_message_text(message: &ConversationMessage) -> Option<String> {
|
|
||||||
let text = message
|
|
||||||
.blocks
|
|
||||||
.iter()
|
|
||||||
.filter_map(|block| match block {
|
|
||||||
ContentBlock::Text { text } => Some(text.as_str()),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<String>();
|
|
||||||
(!text.is_empty()).then_some(text)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_agent_tool_result(message: &ConversationMessage) -> Option<AgentToolResult> {
|
|
||||||
message.blocks.iter().find_map(|block| match block {
|
|
||||||
ContentBlock::ToolResult {
|
|
||||||
tool_name,
|
|
||||||
output,
|
|
||||||
is_error,
|
|
||||||
..
|
|
||||||
} => Some(AgentToolResult {
|
|
||||||
tool_name: tool_name.clone(),
|
|
||||||
output: output.clone(),
|
|
||||||
is_error: *is_error,
|
|
||||||
}),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::needless_pass_by_value)]
|
#[allow(clippy::needless_pass_by_value)]
|
||||||
fn execute_tool_search(input: ToolSearchInput) -> ToolSearchOutput {
|
fn execute_tool_search(input: ToolSearchInput) -> ToolSearchOutput {
|
||||||
let deferred = deferred_tool_specs();
|
let deferred = deferred_tool_specs();
|
||||||
@ -2749,7 +2214,8 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
});
|
sandbox_status: None,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut process = std::process::Command::new(shell);
|
let mut process = std::process::Command::new(shell);
|
||||||
@ -2786,6 +2252,7 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
||||||
@ -2816,7 +2283,8 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
});
|
sandbox_status: None,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
std::thread::sleep(Duration::from_millis(10));
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
}
|
}
|
||||||
@ -2842,6 +2310,7 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
|
sandbox_status: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -3173,37 +2642,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()
|
||||||
@ -3329,28 +2767,12 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn agent_executes_child_conversation_and_persists_results() {
|
fn agent_persists_handoff_metadata() {
|
||||||
let _guard = env_lock()
|
let _guard = env_lock()
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
let dir = temp_path("agent-store");
|
let dir = temp_path("agent-store");
|
||||||
std::env::set_var("CLAWD_AGENT_STORE", &dir);
|
std::env::set_var("CLAWD_AGENT_STORE", &dir);
|
||||||
std::env::set_var(
|
|
||||||
"CLAWD_AGENT_TEST_SCRIPT",
|
|
||||||
serde_json::to_string(&vec![
|
|
||||||
vec![json!({
|
|
||||||
"type": "tool_use",
|
|
||||||
"id": "tool-1",
|
|
||||||
"name": "StructuredOutput",
|
|
||||||
"input": {"ok": true, "items": [1, 2, 3]}
|
|
||||||
})],
|
|
||||||
vec![json!({
|
|
||||||
"type": "text",
|
|
||||||
"text": "Child agent completed successfully."
|
|
||||||
})],
|
|
||||||
])
|
|
||||||
.expect("script json"),
|
|
||||||
);
|
|
||||||
|
|
||||||
let result = execute_tool(
|
let result = execute_tool(
|
||||||
"Agent",
|
"Agent",
|
||||||
@ -3362,35 +2784,22 @@ mod tests {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.expect("Agent should succeed");
|
.expect("Agent should succeed");
|
||||||
std::env::remove_var("CLAWD_AGENT_TEST_SCRIPT");
|
|
||||||
std::env::remove_var("CLAWD_AGENT_STORE");
|
std::env::remove_var("CLAWD_AGENT_STORE");
|
||||||
|
|
||||||
let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
|
let output: serde_json::Value = serde_json::from_str(&result).expect("valid json");
|
||||||
assert_eq!(output["name"], "ship-audit");
|
assert_eq!(output["name"], "ship-audit");
|
||||||
assert_eq!(output["subagentType"], "Explore");
|
assert_eq!(output["subagentType"], "Explore");
|
||||||
assert_eq!(output["status"], "completed");
|
assert_eq!(output["status"], "queued");
|
||||||
assert_eq!(output["depth"], 0);
|
assert!(output["createdAt"].as_str().is_some());
|
||||||
assert_eq!(output["maxDepth"], 3);
|
|
||||||
assert_eq!(output["result"], "Child agent completed successfully.");
|
|
||||||
assert_eq!(output["toolResults"][0]["toolName"], "StructuredOutput");
|
|
||||||
assert_eq!(output["toolResults"][0]["isError"], false);
|
|
||||||
let manifest_file = output["manifestFile"].as_str().expect("manifest file");
|
let manifest_file = output["manifestFile"].as_str().expect("manifest file");
|
||||||
let output_file = output["outputFile"].as_str().expect("output file");
|
let output_file = output["outputFile"].as_str().expect("output file");
|
||||||
let contents = std::fs::read_to_string(output_file).expect("agent file exists");
|
let contents = std::fs::read_to_string(output_file).expect("agent file exists");
|
||||||
let manifest_contents =
|
let manifest_contents =
|
||||||
std::fs::read_to_string(manifest_file).expect("manifest file exists");
|
std::fs::read_to_string(manifest_file).expect("manifest file exists");
|
||||||
assert!(contents.contains("Child agent completed successfully."));
|
assert!(contents.contains("Audit the branch"));
|
||||||
assert!(contents.contains("StructuredOutput [ok]"));
|
assert!(contents.contains("Check tests and outstanding work."));
|
||||||
assert!(manifest_contents.contains("\"subagentType\": \"Explore\""));
|
assert!(manifest_contents.contains("\"subagentType\": \"Explore\""));
|
||||||
|
|
||||||
std::env::set_var(
|
|
||||||
"CLAWD_AGENT_TEST_SCRIPT",
|
|
||||||
serde_json::to_string(&vec![vec![json!({
|
|
||||||
"type": "text",
|
|
||||||
"text": "Normalized alias check."
|
|
||||||
})]])
|
|
||||||
.expect("script json"),
|
|
||||||
);
|
|
||||||
let normalized = execute_tool(
|
let normalized = execute_tool(
|
||||||
"Agent",
|
"Agent",
|
||||||
&json!({
|
&json!({
|
||||||
@ -3400,19 +2809,10 @@ mod tests {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.expect("Agent should normalize built-in aliases");
|
.expect("Agent should normalize built-in aliases");
|
||||||
std::env::remove_var("CLAWD_AGENT_TEST_SCRIPT");
|
|
||||||
let normalized_output: serde_json::Value =
|
let normalized_output: serde_json::Value =
|
||||||
serde_json::from_str(&normalized).expect("valid json");
|
serde_json::from_str(&normalized).expect("valid json");
|
||||||
assert_eq!(normalized_output["subagentType"], "Explore");
|
assert_eq!(normalized_output["subagentType"], "Explore");
|
||||||
|
|
||||||
std::env::set_var(
|
|
||||||
"CLAWD_AGENT_TEST_SCRIPT",
|
|
||||||
serde_json::to_string(&vec![vec![json!({
|
|
||||||
"type": "text",
|
|
||||||
"text": "Name normalization check."
|
|
||||||
})]])
|
|
||||||
.expect("script json"),
|
|
||||||
);
|
|
||||||
let named = execute_tool(
|
let named = execute_tool(
|
||||||
"Agent",
|
"Agent",
|
||||||
&json!({
|
&json!({
|
||||||
@ -3422,14 +2822,13 @@ mod tests {
|
|||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.expect("Agent should normalize explicit names");
|
.expect("Agent should normalize explicit names");
|
||||||
std::env::remove_var("CLAWD_AGENT_TEST_SCRIPT");
|
|
||||||
let named_output: serde_json::Value = serde_json::from_str(&named).expect("valid json");
|
let named_output: serde_json::Value = serde_json::from_str(&named).expect("valid json");
|
||||||
assert_eq!(named_output["name"], "ship-audit");
|
assert_eq!(named_output["name"], "ship-audit");
|
||||||
let _ = std::fs::remove_dir_all(dir);
|
let _ = std::fs::remove_dir_all(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn agent_rejects_blank_required_fields_and_enforces_max_depth() {
|
fn agent_rejects_blank_required_fields() {
|
||||||
let missing_description = execute_tool(
|
let missing_description = execute_tool(
|
||||||
"Agent",
|
"Agent",
|
||||||
&json!({
|
&json!({
|
||||||
@ -3449,22 +2848,6 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.expect_err("blank prompt should fail");
|
.expect_err("blank prompt should fail");
|
||||||
assert!(missing_prompt.contains("prompt must not be empty"));
|
assert!(missing_prompt.contains("prompt must not be empty"));
|
||||||
|
|
||||||
let _guard = env_lock()
|
|
||||||
.lock()
|
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
|
||||||
std::env::set_var("CLAWD_AGENT_DEPTH", "1");
|
|
||||||
let depth_error = execute_tool(
|
|
||||||
"Agent",
|
|
||||||
&json!({
|
|
||||||
"description": "Nested agent",
|
|
||||||
"prompt": "Do nested work.",
|
|
||||||
"max_depth": 1
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.expect_err("max depth should fail");
|
|
||||||
std::env::remove_var("CLAWD_AGENT_DEPTH");
|
|
||||||
assert!(depth_error.contains("max_depth exceeded"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user