mirror of
https://github.com/instructkr/claw-code.git
synced 2026-04-07 00:24:50 +08:00
Compare commits
2 Commits
rcc/thinki
...
rcc/api
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
962292dd27 | ||
|
|
074bd5b7b7 |
127
rust/.omc/project-memory.json
Normal file
127
rust/.omc/project-memory.json
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
{
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lastScanned": 1774971516826,
|
||||||
|
"projectRoot": "/home/bellman/Workspace/clawd-code-worktrees/api/rust",
|
||||||
|
"techStack": {
|
||||||
|
"languages": [
|
||||||
|
{
|
||||||
|
"name": "Rust",
|
||||||
|
"version": null,
|
||||||
|
"confidence": "high",
|
||||||
|
"markers": [
|
||||||
|
"Cargo.toml"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"frameworks": [],
|
||||||
|
"packageManager": "cargo",
|
||||||
|
"runtime": null
|
||||||
|
},
|
||||||
|
"build": {
|
||||||
|
"buildCommand": "cargo build",
|
||||||
|
"testCommand": "cargo test",
|
||||||
|
"lintCommand": "cargo clippy",
|
||||||
|
"devCommand": "cargo run",
|
||||||
|
"scripts": {}
|
||||||
|
},
|
||||||
|
"conventions": {
|
||||||
|
"namingStyle": null,
|
||||||
|
"importStyle": null,
|
||||||
|
"testPattern": null,
|
||||||
|
"fileOrganization": null
|
||||||
|
},
|
||||||
|
"structure": {
|
||||||
|
"isMonorepo": false,
|
||||||
|
"workspaces": [],
|
||||||
|
"mainDirectories": [],
|
||||||
|
"gitBranches": {
|
||||||
|
"defaultBranch": "main",
|
||||||
|
"branchingStrategy": null
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"customNotes": [],
|
||||||
|
"directoryMap": {
|
||||||
|
"crates": {
|
||||||
|
"path": "crates",
|
||||||
|
"purpose": null,
|
||||||
|
"fileCount": 0,
|
||||||
|
"lastAccessed": 1774971516823,
|
||||||
|
"keyFiles": []
|
||||||
|
},
|
||||||
|
"target": {
|
||||||
|
"path": "target",
|
||||||
|
"purpose": null,
|
||||||
|
"fileCount": 2,
|
||||||
|
"lastAccessed": 1774971516823,
|
||||||
|
"keyFiles": [
|
||||||
|
"CACHEDIR.TAG"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"crates/api": {
|
||||||
|
"path": "crates/api",
|
||||||
|
"purpose": "API routes",
|
||||||
|
"fileCount": 1,
|
||||||
|
"lastAccessed": 1774971516824,
|
||||||
|
"keyFiles": [
|
||||||
|
"Cargo.toml"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"hotPaths": [
|
||||||
|
{
|
||||||
|
"path": "crates/api/Cargo.toml",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971547109,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/api/src/lib.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971547624,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/api/src/client.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971548001,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/api/src/error.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971548503,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/api/src/sse.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971549311,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/api/src/types.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971549472,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/api/tests/client_integration.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971550143,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "Cargo.toml",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971550539,
|
||||||
|
"type": "file"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "crates/rusty-claude-cli/src/main.rs",
|
||||||
|
"accessCount": 1,
|
||||||
|
"lastAccessed": 1774971551474,
|
||||||
|
"type": "file"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"userDirectives": []
|
||||||
|
}
|
||||||
3
rust/.omc/state/idle-notif-cooldown.json
Normal file
3
rust/.omc/state/idle-notif-cooldown.json
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"lastSentAt": "2026-03-31T15:39:44.771Z"
|
||||||
|
}
|
||||||
@@ -109,6 +109,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:
|
||||||
@@ -179,7 +186,7 @@ cargo run -p rusty-claude-cli -- --resume session.json /memory /config
|
|||||||
- `/resume <session-path>` — load a saved session into the REPL
|
- `/resume <session-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
|
||||||
|
|||||||
@@ -912,7 +912,6 @@ mod tests {
|
|||||||
system: None,
|
system: None,
|
||||||
tools: None,
|
tools: None,
|
||||||
tool_choice: None,
|
tool_choice: None,
|
||||||
thinking: None,
|
|
||||||
stream: false,
|
stream: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -13,5 +13,5 @@ pub use types::{
|
|||||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||||
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
|
||||||
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
|
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
|
||||||
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,
|
||||||
@@ -149,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,
|
||||||
@@ -213,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 },
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -258,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
|
||||||
@@ -439,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",
|
||||||
@@ -107,7 +101,7 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
},
|
},
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "init",
|
name: "init",
|
||||||
summary: "Create a starter CLAUDE.md for this repo",
|
summary: "Bootstrap Claude project files for this repo",
|
||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: true,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
@@ -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()
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -130,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();
|
||||||
@@ -200,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,
|
||||||
@@ -259,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(),
|
||||||
})
|
})
|
||||||
@@ -281,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,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,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, ..
|
||||||
|
|||||||
@@ -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::{
|
||||||
@@ -529,29 +502,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;
|
||||||
|
|||||||
@@ -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,
|
||||||
@@ -261,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(),
|
||||||
@@ -320,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")?,
|
||||||
|
|||||||
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,3 +1,4 @@
|
|||||||
|
mod init;
|
||||||
mod input;
|
mod input;
|
||||||
mod render;
|
mod render;
|
||||||
|
|
||||||
@@ -13,14 +14,14 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
|||||||
use api::{
|
use api::{
|
||||||
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
|
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
|
||||||
InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
|
InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
|
||||||
StreamEvent as ApiStreamEvent, ThinkingConfig, ToolChoice, ToolDefinition,
|
StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
|
||||||
ToolResultContentBlock,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use commands::{
|
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 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,
|
||||||
@@ -35,7 +36,6 @@ use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
|||||||
|
|
||||||
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
|
||||||
const DEFAULT_MAX_TOKENS: u32 = 32;
|
const DEFAULT_MAX_TOKENS: u32 = 32;
|
||||||
const DEFAULT_THINKING_BUDGET_TOKENS: u32 = 2_048;
|
|
||||||
const DEFAULT_DATE: &str = "2026-03-31";
|
const DEFAULT_DATE: &str = "2026-03-31";
|
||||||
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
|
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
|
||||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
@@ -72,17 +72,16 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking,
|
} => LiveCli::new(model, false, allowed_tools, permission_mode)?
|
||||||
} => LiveCli::new(model, false, allowed_tools, permission_mode, thinking)?
|
|
||||||
.run_turn_with_output(&prompt, output_format)?,
|
.run_turn_with_output(&prompt, output_format)?,
|
||||||
CliAction::Login => run_login()?,
|
CliAction::Login => run_login()?,
|
||||||
CliAction::Logout => run_logout()?,
|
CliAction::Logout => run_logout()?,
|
||||||
|
CliAction::Init => run_init()?,
|
||||||
CliAction::Repl {
|
CliAction::Repl {
|
||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking,
|
} => run_repl(model, allowed_tools, permission_mode)?,
|
||||||
} => run_repl(model, allowed_tools, permission_mode, thinking)?,
|
|
||||||
CliAction::Help => print_help(),
|
CliAction::Help => print_help(),
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -107,15 +106,14 @@ enum CliAction {
|
|||||||
output_format: CliOutputFormat,
|
output_format: CliOutputFormat,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
thinking: bool,
|
|
||||||
},
|
},
|
||||||
Login,
|
Login,
|
||||||
Logout,
|
Logout,
|
||||||
|
Init,
|
||||||
Repl {
|
Repl {
|
||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
thinking: bool,
|
|
||||||
},
|
},
|
||||||
// prompt-mode formatting is only supported for non-interactive runs
|
// prompt-mode formatting is only supported for non-interactive runs
|
||||||
Help,
|
Help,
|
||||||
@@ -145,7 +143,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
let mut output_format = CliOutputFormat::Text;
|
let mut output_format = CliOutputFormat::Text;
|
||||||
let mut permission_mode = default_permission_mode();
|
let mut permission_mode = default_permission_mode();
|
||||||
let mut wants_version = false;
|
let mut wants_version = false;
|
||||||
let mut thinking = false;
|
|
||||||
let mut allowed_tool_values = Vec::new();
|
let mut allowed_tool_values = Vec::new();
|
||||||
let mut rest = Vec::new();
|
let mut rest = Vec::new();
|
||||||
let mut index = 0;
|
let mut index = 0;
|
||||||
@@ -156,10 +153,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
wants_version = true;
|
wants_version = true;
|
||||||
index += 1;
|
index += 1;
|
||||||
}
|
}
|
||||||
"--thinking" => {
|
|
||||||
thinking = true;
|
|
||||||
index += 1;
|
|
||||||
}
|
|
||||||
"--model" => {
|
"--model" => {
|
||||||
let value = args
|
let value = args
|
||||||
.get(index + 1)
|
.get(index + 1)
|
||||||
@@ -226,7 +219,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
|
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
|
||||||
@@ -242,6 +234,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
||||||
"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() {
|
||||||
@@ -253,7 +246,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
other if !other.starts_with('/') => Ok(CliAction::Prompt {
|
other if !other.starts_with('/') => Ok(CliAction::Prompt {
|
||||||
@@ -262,7 +254,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking,
|
|
||||||
}),
|
}),
|
||||||
other => Err(format!("unknown subcommand: {other}")),
|
other => Err(format!("unknown subcommand: {other}")),
|
||||||
}
|
}
|
||||||
@@ -614,7 +605,6 @@ struct StatusUsage {
|
|||||||
latest: TokenUsage,
|
latest: TokenUsage,
|
||||||
cumulative: TokenUsage,
|
cumulative: TokenUsage,
|
||||||
estimated_tokens: usize,
|
estimated_tokens: usize,
|
||||||
thinking_enabled: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
|
fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
|
||||||
@@ -682,39 +672,6 @@ Usage
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_thinking_report(enabled: bool) -> String {
|
|
||||||
let state = if enabled { "on" } else { "off" };
|
|
||||||
let budget = if enabled {
|
|
||||||
DEFAULT_THINKING_BUDGET_TOKENS.to_string()
|
|
||||||
} else {
|
|
||||||
"disabled".to_string()
|
|
||||||
};
|
|
||||||
format!(
|
|
||||||
"Thinking
|
|
||||||
Active mode {state}
|
|
||||||
Budget tokens {budget}
|
|
||||||
|
|
||||||
Usage
|
|
||||||
Inspect current mode with /thinking
|
|
||||||
Toggle with /thinking on or /thinking off"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn format_thinking_switch_report(enabled: bool) -> String {
|
|
||||||
let state = if enabled { "enabled" } else { "disabled" };
|
|
||||||
format!(
|
|
||||||
"Thinking updated
|
|
||||||
Result {state}
|
|
||||||
Budget tokens {}
|
|
||||||
Applies to subsequent requests",
|
|
||||||
if enabled {
|
|
||||||
DEFAULT_THINKING_BUDGET_TOKENS.to_string()
|
|
||||||
} else {
|
|
||||||
"disabled".to_string()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn format_permissions_switch_report(previous: &str, next: &str) -> String {
|
fn format_permissions_switch_report(previous: &str, next: &str) -> String {
|
||||||
format!(
|
format!(
|
||||||
"Permissions updated
|
"Permissions updated
|
||||||
@@ -751,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!(
|
||||||
@@ -882,7 +819,6 @@ fn run_resume_command(
|
|||||||
latest: tracker.current_turn_usage(),
|
latest: tracker.current_turn_usage(),
|
||||||
cumulative: usage,
|
cumulative: usage,
|
||||||
estimated_tokens: 0,
|
estimated_tokens: 0,
|
||||||
thinking_enabled: false,
|
|
||||||
},
|
},
|
||||||
default_permission_mode().as_str(),
|
default_permission_mode().as_str(),
|
||||||
&status_context(Some(session_path))?,
|
&status_context(Some(session_path))?,
|
||||||
@@ -929,7 +865,6 @@ fn run_resume_command(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
SlashCommand::Resume { .. }
|
SlashCommand::Resume { .. }
|
||||||
| SlashCommand::Thinking { .. }
|
|
||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Session { .. }
|
| SlashCommand::Session { .. }
|
||||||
@@ -941,15 +876,8 @@ fn run_repl(
|
|||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
thinking_enabled: bool,
|
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let mut cli = LiveCli::new(
|
let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
|
||||||
model,
|
|
||||||
true,
|
|
||||||
allowed_tools,
|
|
||||||
permission_mode,
|
|
||||||
thinking_enabled,
|
|
||||||
)?;
|
|
||||||
let mut editor = input::LineEditor::new("› ", slash_command_completion_candidates());
|
let mut editor = input::LineEditor::new("› ", slash_command_completion_candidates());
|
||||||
println!("{}", cli.startup_banner());
|
println!("{}", cli.startup_banner());
|
||||||
|
|
||||||
@@ -1002,7 +930,6 @@ struct LiveCli {
|
|||||||
model: String,
|
model: String,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
thinking_enabled: bool,
|
|
||||||
system_prompt: Vec<String>,
|
system_prompt: Vec<String>,
|
||||||
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
|
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
|
||||||
session: SessionHandle,
|
session: SessionHandle,
|
||||||
@@ -1014,7 +941,6 @@ impl LiveCli {
|
|||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
thinking_enabled: bool,
|
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
let system_prompt = build_system_prompt()?;
|
let system_prompt = build_system_prompt()?;
|
||||||
let session = create_managed_session_handle()?;
|
let session = create_managed_session_handle()?;
|
||||||
@@ -1025,13 +951,11 @@ impl LiveCli {
|
|||||||
enable_tools,
|
enable_tools,
|
||||||
allowed_tools.clone(),
|
allowed_tools.clone(),
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
let cli = Self {
|
let cli = Self {
|
||||||
model,
|
model,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
thinking_enabled,
|
|
||||||
system_prompt,
|
system_prompt,
|
||||||
runtime,
|
runtime,
|
||||||
session,
|
session,
|
||||||
@@ -1042,10 +966,9 @@ impl LiveCli {
|
|||||||
|
|
||||||
fn startup_banner(&self) -> String {
|
fn startup_banner(&self) -> String {
|
||||||
format!(
|
format!(
|
||||||
"Rusty Claude CLI\n Model {}\n Permission mode {}\n Thinking {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.",
|
"Rusty Claude CLI\n Model {}\n Permission mode {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.",
|
||||||
self.model,
|
self.model,
|
||||||
self.permission_mode.as_str(),
|
self.permission_mode.as_str(),
|
||||||
if self.thinking_enabled { "on" } else { "off" },
|
|
||||||
env::current_dir().map_or_else(
|
env::current_dir().map_or_else(
|
||||||
|_| "<unknown>".to_string(),
|
|_| "<unknown>".to_string(),
|
||||||
|path| path.display().to_string(),
|
|path| path.display().to_string(),
|
||||||
@@ -1111,9 +1034,6 @@ impl LiveCli {
|
|||||||
system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")),
|
system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")),
|
||||||
tools: None,
|
tools: None,
|
||||||
tool_choice: None,
|
tool_choice: None,
|
||||||
thinking: self
|
|
||||||
.thinking_enabled
|
|
||||||
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
|
|
||||||
stream: false,
|
stream: false,
|
||||||
};
|
};
|
||||||
let runtime = tokio::runtime::Runtime::new()?;
|
let runtime = tokio::runtime::Runtime::new()?;
|
||||||
@@ -1123,7 +1043,7 @@ impl LiveCli {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter_map(|block| match block {
|
.filter_map(|block| match block {
|
||||||
OutputContentBlock::Text { text } => Some(text.as_str()),
|
OutputContentBlock::Text { text } => Some(text.as_str()),
|
||||||
OutputContentBlock::Thinking { .. } | OutputContentBlock::ToolUse { .. } => None,
|
OutputContentBlock::ToolUse { .. } => None,
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>()
|
.collect::<Vec<_>>()
|
||||||
.join("");
|
.join("");
|
||||||
@@ -1160,7 +1080,6 @@ impl LiveCli {
|
|||||||
self.compact()?;
|
self.compact()?;
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Thinking { enabled } => self.set_thinking(enabled)?,
|
|
||||||
SlashCommand::Model { model } => self.set_model(model)?,
|
SlashCommand::Model { model } => self.set_model(model)?,
|
||||||
SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
|
SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
|
||||||
SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
|
SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
|
||||||
@@ -1178,7 +1097,7 @@ impl LiveCli {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Init => {
|
SlashCommand::Init => {
|
||||||
Self::run_init()?;
|
run_init()?;
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Diff => {
|
SlashCommand::Diff => {
|
||||||
@@ -1221,7 +1140,6 @@ impl LiveCli {
|
|||||||
latest,
|
latest,
|
||||||
cumulative,
|
cumulative,
|
||||||
estimated_tokens: self.runtime.estimated_tokens(),
|
estimated_tokens: self.runtime.estimated_tokens(),
|
||||||
thinking_enabled: self.thinking_enabled,
|
|
||||||
},
|
},
|
||||||
self.permission_mode.as_str(),
|
self.permission_mode.as_str(),
|
||||||
&status_context(Some(&self.session.path)).expect("status context should load"),
|
&status_context(Some(&self.session.path)).expect("status context should load"),
|
||||||
@@ -1264,7 +1182,6 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
self.model.clone_from(&model);
|
self.model.clone_from(&model);
|
||||||
println!(
|
println!(
|
||||||
@@ -1274,32 +1191,6 @@ impl LiveCli {
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_thinking(&mut self, enabled: Option<bool>) -> Result<bool, Box<dyn std::error::Error>> {
|
|
||||||
let Some(enabled) = enabled else {
|
|
||||||
println!("{}", format_thinking_report(self.thinking_enabled));
|
|
||||||
return Ok(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
if enabled == self.thinking_enabled {
|
|
||||||
println!("{}", format_thinking_report(self.thinking_enabled));
|
|
||||||
return Ok(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
let session = self.runtime.session().clone();
|
|
||||||
self.thinking_enabled = enabled;
|
|
||||||
self.runtime = build_runtime(
|
|
||||||
session,
|
|
||||||
self.model.clone(),
|
|
||||||
self.system_prompt.clone(),
|
|
||||||
true,
|
|
||||||
self.allowed_tools.clone(),
|
|
||||||
self.permission_mode,
|
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
|
||||||
println!("{}", format_thinking_switch_report(self.thinking_enabled));
|
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_permissions(
|
fn set_permissions(
|
||||||
&mut self,
|
&mut self,
|
||||||
mode: Option<String>,
|
mode: Option<String>,
|
||||||
@@ -1333,7 +1224,6 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
println!(
|
println!(
|
||||||
"{}",
|
"{}",
|
||||||
@@ -1358,7 +1248,6 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
println!(
|
println!(
|
||||||
"Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
|
"Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
|
||||||
@@ -1393,7 +1282,6 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
self.session = handle;
|
self.session = handle;
|
||||||
println!(
|
println!(
|
||||||
@@ -1417,11 +1305,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(())
|
||||||
@@ -1470,7 +1353,6 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
self.session = handle;
|
self.session = handle;
|
||||||
println!(
|
println!(
|
||||||
@@ -1500,7 +1382,6 @@ impl LiveCli {
|
|||||||
true,
|
true,
|
||||||
self.allowed_tools.clone(),
|
self.allowed_tools.clone(),
|
||||||
self.permission_mode,
|
self.permission_mode,
|
||||||
self.thinking_enabled,
|
|
||||||
)?;
|
)?;
|
||||||
self.persist_session()?;
|
self.persist_session()?;
|
||||||
println!("{}", format_compact_report(removed, kept, skipped));
|
println!("{}", format_compact_report(removed, kept, skipped));
|
||||||
@@ -1612,7 +1493,6 @@ fn render_repl_help() -> String {
|
|||||||
[
|
[
|
||||||
"REPL".to_string(),
|
"REPL".to_string(),
|
||||||
" /exit Quit the REPL".to_string(),
|
" /exit Quit the REPL".to_string(),
|
||||||
" /thinking [on|off] Show or toggle extended thinking".to_string(),
|
|
||||||
" /quit Quit the REPL".to_string(),
|
" /quit Quit the REPL".to_string(),
|
||||||
" Up/Down Navigate prompt history".to_string(),
|
" Up/Down Navigate prompt history".to_string(),
|
||||||
" Tab Complete slash commands".to_string(),
|
" Tab Complete slash commands".to_string(),
|
||||||
@@ -1659,14 +1539,10 @@ fn format_status_report(
|
|||||||
"Status
|
"Status
|
||||||
Model {model}
|
Model {model}
|
||||||
Permission mode {permission_mode}
|
Permission mode {permission_mode}
|
||||||
Thinking {}
|
|
||||||
Messages {}
|
Messages {}
|
||||||
Turns {}
|
Turns {}
|
||||||
Estimated tokens {}",
|
Estimated tokens {}",
|
||||||
if usage.thinking_enabled { "on" } else { "off" },
|
usage.message_count, usage.turns, usage.estimated_tokens,
|
||||||
usage.message_count,
|
|
||||||
usage.turns,
|
|
||||||
usage.estimated_tokens,
|
|
||||||
),
|
),
|
||||||
format!(
|
format!(
|
||||||
"Usage
|
"Usage
|
||||||
@@ -1826,67 +1702,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);
|
fn run_init() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
fs::write(&claude_md, content)?;
|
println!("{}", init_claude_md()?);
|
||||||
Ok(format_init_report(&claude_md, true))
|
Ok(())
|
||||||
}
|
|
||||||
|
|
||||||
fn render_init_claude_md(cwd: &Path) -> String {
|
|
||||||
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 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> {
|
||||||
@@ -1938,15 +1759,6 @@ fn render_export_text(session: &Session) -> String {
|
|||||||
for block in &message.blocks {
|
for block in &message.blocks {
|
||||||
match block {
|
match block {
|
||||||
ContentBlock::Text { text } => lines.push(text.clone()),
|
ContentBlock::Text { text } => lines.push(text.clone()),
|
||||||
ContentBlock::Thinking { text, signature } => {
|
|
||||||
lines.push(format!(
|
|
||||||
"[thinking{}] {}",
|
|
||||||
signature
|
|
||||||
.as_ref()
|
|
||||||
.map_or(String::new(), |value| format!(" signature={value}")),
|
|
||||||
text
|
|
||||||
));
|
|
||||||
}
|
|
||||||
ContentBlock::ToolUse { id, name, input } => {
|
ContentBlock::ToolUse { id, name, input } => {
|
||||||
lines.push(format!("[tool_use id={id} name={name}] {input}"));
|
lines.push(format!("[tool_use id={id} name={name}] {input}"));
|
||||||
}
|
}
|
||||||
@@ -2037,12 +1849,11 @@ fn build_runtime(
|
|||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
thinking_enabled: bool,
|
|
||||||
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
|
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
|
||||||
{
|
{
|
||||||
Ok(ConversationRuntime::new(
|
Ok(ConversationRuntime::new(
|
||||||
session,
|
session,
|
||||||
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone(), thinking_enabled)?,
|
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone())?,
|
||||||
CliToolExecutor::new(allowed_tools),
|
CliToolExecutor::new(allowed_tools),
|
||||||
permission_policy(permission_mode),
|
permission_policy(permission_mode),
|
||||||
system_prompt,
|
system_prompt,
|
||||||
@@ -2101,7 +1912,6 @@ struct AnthropicRuntimeClient {
|
|||||||
model: String,
|
model: String,
|
||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
thinking_enabled: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AnthropicRuntimeClient {
|
impl AnthropicRuntimeClient {
|
||||||
@@ -2109,7 +1919,6 @@ impl AnthropicRuntimeClient {
|
|||||||
model: String,
|
model: String,
|
||||||
enable_tools: bool,
|
enable_tools: bool,
|
||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
thinking_enabled: bool,
|
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
runtime: tokio::runtime::Runtime::new()?,
|
runtime: tokio::runtime::Runtime::new()?,
|
||||||
@@ -2117,7 +1926,6 @@ impl AnthropicRuntimeClient {
|
|||||||
model,
|
model,
|
||||||
enable_tools,
|
enable_tools,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
thinking_enabled,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2151,9 +1959,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
.collect()
|
.collect()
|
||||||
}),
|
}),
|
||||||
tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
|
tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
|
||||||
thinking: self
|
|
||||||
.thinking_enabled
|
|
||||||
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
|
|
||||||
stream: true,
|
stream: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -2166,7 +1971,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
let mut events = Vec::new();
|
let mut events = Vec::new();
|
||||||
let mut pending_tool: Option<(String, String, String)> = None;
|
let mut pending_tool: Option<(String, String, String)> = None;
|
||||||
let mut pending_thinking_signature: Option<String> = None;
|
|
||||||
let mut saw_stop = false;
|
let mut saw_stop = false;
|
||||||
|
|
||||||
while let Some(event) = stream
|
while let Some(event) = stream
|
||||||
@@ -2177,13 +1981,7 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
match event {
|
match event {
|
||||||
ApiStreamEvent::MessageStart(start) => {
|
ApiStreamEvent::MessageStart(start) => {
|
||||||
for block in start.message.content {
|
for block in start.message.content {
|
||||||
push_output_block(
|
push_output_block(block, &mut stdout, &mut events, &mut pending_tool)?;
|
||||||
block,
|
|
||||||
&mut stdout,
|
|
||||||
&mut events,
|
|
||||||
&mut pending_tool,
|
|
||||||
&mut pending_thinking_signature,
|
|
||||||
)?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ApiStreamEvent::ContentBlockStart(start) => {
|
ApiStreamEvent::ContentBlockStart(start) => {
|
||||||
@@ -2192,7 +1990,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
&mut stdout,
|
&mut stdout,
|
||||||
&mut events,
|
&mut events,
|
||||||
&mut pending_tool,
|
&mut pending_tool,
|
||||||
&mut pending_thinking_signature,
|
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
|
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
|
||||||
@@ -2204,14 +2001,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
events.push(AssistantEvent::TextDelta(text));
|
events.push(AssistantEvent::TextDelta(text));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ContentBlockDelta::ThinkingDelta { thinking } => {
|
|
||||||
if !thinking.is_empty() {
|
|
||||||
events.push(AssistantEvent::ThinkingDelta(thinking));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ContentBlockDelta::SignatureDelta { signature } => {
|
|
||||||
events.push(AssistantEvent::ThinkingSignature(signature));
|
|
||||||
}
|
|
||||||
ContentBlockDelta::InputJsonDelta { partial_json } => {
|
ContentBlockDelta::InputJsonDelta { partial_json } => {
|
||||||
if let Some((_, _, input)) = &mut pending_tool {
|
if let Some((_, _, input)) = &mut pending_tool {
|
||||||
input.push_str(&partial_json);
|
input.push_str(&partial_json);
|
||||||
@@ -2241,8 +2030,6 @@ impl ApiClient for AnthropicRuntimeClient {
|
|||||||
if !saw_stop
|
if !saw_stop
|
||||||
&& events.iter().any(|event| {
|
&& events.iter().any(|event| {
|
||||||
matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
|
matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
|
||||||
|| matches!(event, AssistantEvent::ThinkingDelta(text) if !text.is_empty())
|
|
||||||
|| matches!(event, AssistantEvent::ThinkingSignature(_))
|
|
||||||
|| matches!(event, AssistantEvent::ToolUse { .. })
|
|| matches!(event, AssistantEvent::ToolUse { .. })
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
@@ -2326,19 +2113,11 @@ fn truncate_for_summary(value: &str, limit: usize) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn render_thinking_block_summary(text: &str, out: &mut impl Write) -> Result<(), RuntimeError> {
|
|
||||||
let summary = format!("▶ Thinking ({} chars hidden)", text.chars().count());
|
|
||||||
writeln!(out, "\n{summary}")
|
|
||||||
.and_then(|()| out.flush())
|
|
||||||
.map_err(|error| RuntimeError::new(error.to_string()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push_output_block(
|
fn push_output_block(
|
||||||
block: OutputContentBlock,
|
block: OutputContentBlock,
|
||||||
out: &mut impl Write,
|
out: &mut impl Write,
|
||||||
events: &mut Vec<AssistantEvent>,
|
events: &mut Vec<AssistantEvent>,
|
||||||
pending_tool: &mut Option<(String, String, String)>,
|
pending_tool: &mut Option<(String, String, String)>,
|
||||||
pending_thinking_signature: &mut Option<String>,
|
|
||||||
) -> Result<(), RuntimeError> {
|
) -> Result<(), RuntimeError> {
|
||||||
match block {
|
match block {
|
||||||
OutputContentBlock::Text { text } => {
|
OutputContentBlock::Text { text } => {
|
||||||
@@ -2349,19 +2128,6 @@ fn push_output_block(
|
|||||||
events.push(AssistantEvent::TextDelta(text));
|
events.push(AssistantEvent::TextDelta(text));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OutputContentBlock::Thinking {
|
|
||||||
thinking,
|
|
||||||
signature,
|
|
||||||
} => {
|
|
||||||
render_thinking_block_summary(&thinking, out)?;
|
|
||||||
if !thinking.is_empty() {
|
|
||||||
events.push(AssistantEvent::ThinkingDelta(thinking));
|
|
||||||
}
|
|
||||||
if let Some(signature) = signature {
|
|
||||||
*pending_thinking_signature = Some(signature.clone());
|
|
||||||
events.push(AssistantEvent::ThinkingSignature(signature));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
OutputContentBlock::ToolUse { id, name, input } => {
|
OutputContentBlock::ToolUse { id, name, input } => {
|
||||||
writeln!(
|
writeln!(
|
||||||
out,
|
out,
|
||||||
@@ -2383,16 +2149,9 @@ fn response_to_events(
|
|||||||
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
||||||
let mut events = Vec::new();
|
let mut events = Vec::new();
|
||||||
let mut pending_tool = None;
|
let mut pending_tool = None;
|
||||||
let mut pending_thinking_signature = None;
|
|
||||||
|
|
||||||
for block in response.content {
|
for block in response.content {
|
||||||
push_output_block(
|
push_output_block(block, out, &mut events, &mut pending_tool)?;
|
||||||
block,
|
|
||||||
out,
|
|
||||||
&mut events,
|
|
||||||
&mut pending_tool,
|
|
||||||
&mut pending_thinking_signature,
|
|
||||||
)?;
|
|
||||||
if let Some((id, name, input)) = pending_tool.take() {
|
if let Some((id, name, input)) = pending_tool.take() {
|
||||||
events.push(AssistantEvent::ToolUse { id, name, input });
|
events.push(AssistantEvent::ToolUse { id, name, input });
|
||||||
}
|
}
|
||||||
@@ -2477,29 +2236,26 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
|
|||||||
let content = message
|
let content = message
|
||||||
.blocks
|
.blocks
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|block| match block {
|
.map(|block| match block {
|
||||||
ContentBlock::Text { text } => {
|
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
|
||||||
Some(InputContentBlock::Text { text: text.clone() })
|
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
|
||||||
}
|
|
||||||
ContentBlock::Thinking { .. } => None,
|
|
||||||
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
|
|
||||||
id: id.clone(),
|
id: id.clone(),
|
||||||
name: name.clone(),
|
name: name.clone(),
|
||||||
input: serde_json::from_str(input)
|
input: serde_json::from_str(input)
|
||||||
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
|
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
|
||||||
}),
|
},
|
||||||
ContentBlock::ToolResult {
|
ContentBlock::ToolResult {
|
||||||
tool_use_id,
|
tool_use_id,
|
||||||
output,
|
output,
|
||||||
is_error,
|
is_error,
|
||||||
..
|
..
|
||||||
} => Some(InputContentBlock::ToolResult {
|
} => InputContentBlock::ToolResult {
|
||||||
tool_use_id: tool_use_id.clone(),
|
tool_use_id: tool_use_id.clone(),
|
||||||
content: vec![ToolResultContentBlock::Text {
|
content: vec![ToolResultContentBlock::Text {
|
||||||
text: output.clone(),
|
text: output.clone(),
|
||||||
}],
|
}],
|
||||||
is_error: *is_error,
|
is_error: *is_error,
|
||||||
}),
|
},
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
(!content.is_empty()).then(|| InputMessage {
|
(!content.is_empty()).then(|| InputMessage {
|
||||||
@@ -2510,35 +2266,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, "rusty-claude-cli 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");
|
" rusty-claude-cli [--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");
|
" rusty-claude-cli [--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");
|
" rusty-claude-cli [--model MODEL] [--output-format text|json] TEXT"
|
||||||
println!();
|
)?;
|
||||||
println!("Flags:");
|
writeln!(out, " Shorthand non-interactive prompt mode")?;
|
||||||
println!(" --model MODEL Override the active model");
|
writeln!(
|
||||||
println!(" --output-format FORMAT Non-interactive output format: text or json");
|
out,
|
||||||
println!(" --permission-mode MODE Set read-only, workspace-write, or danger-full-access");
|
" rusty-claude-cli --resume SESSION.json [/status] [/compact] [...]"
|
||||||
println!(" --thinking Enable extended thinking with the default budget");
|
)?;
|
||||||
println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
|
writeln!(
|
||||||
println!(" --version, -V Print version and build information locally");
|
out,
|
||||||
println!();
|
" Inspect or maintain a saved session without entering the REPL"
|
||||||
println!("Interactive slash commands:");
|
)?;
|
||||||
println!("{}", render_slash_command_help());
|
writeln!(out, " rusty-claude-cli dump-manifests")?;
|
||||||
println!();
|
writeln!(out, " rusty-claude-cli bootstrap-plan")?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" rusty-claude-cli system-prompt [--cwd PATH] [--date YYYY-MM-DD]"
|
||||||
|
)?;
|
||||||
|
writeln!(out, " rusty-claude-cli login")?;
|
||||||
|
writeln!(out, " rusty-claude-cli logout")?;
|
||||||
|
writeln!(out, " rusty-claude-cli 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 {
|
||||||
@@ -2547,28 +2333,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\"");
|
" rusty-claude-cli --model claude-opus \"summarize this repo\""
|
||||||
println!(" rusty-claude-cli --resume session.json /status /diff /export notes.txt");
|
)?;
|
||||||
println!(" rusty-claude-cli login");
|
writeln!(
|
||||||
|
out,
|
||||||
|
" rusty-claude-cli --output-format json prompt \"explain src/main.rs\""
|
||||||
|
)?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" rusty-claude-cli --allowedTools read,glob \"summarize Cargo.toml\""
|
||||||
|
)?;
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
" rusty-claude-cli --resume session.json /status /diff /export notes.txt"
|
||||||
|
)?;
|
||||||
|
writeln!(out, " rusty-claude-cli login")?;
|
||||||
|
writeln!(out, " rusty-claude-cli 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, normalize_permission_mode, parse_args,
|
normalize_permission_mode, parse_args, parse_git_status_metadata, print_help_to,
|
||||||
parse_git_status_metadata, render_config_report, render_init_claude_md,
|
render_config_report, render_memory_report, render_repl_help,
|
||||||
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
|
resume_supported_slash_commands, status_context, CliAction, CliOutputFormat, SlashCommand,
|
||||||
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
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() {
|
||||||
@@ -2578,7 +2382,6 @@ mod tests {
|
|||||||
model: DEFAULT_MODEL.to_string(),
|
model: DEFAULT_MODEL.to_string(),
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
thinking: false,
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2598,7 +2401,6 @@ mod tests {
|
|||||||
output_format: CliOutputFormat::Text,
|
output_format: CliOutputFormat::Text,
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
thinking: false,
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2620,7 +2422,6 @@ mod tests {
|
|||||||
output_format: CliOutputFormat::Json,
|
output_format: CliOutputFormat::Json,
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
thinking: false,
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2646,7 +2447,6 @@ mod tests {
|
|||||||
model: DEFAULT_MODEL.to_string(),
|
model: DEFAULT_MODEL.to_string(),
|
||||||
allowed_tools: None,
|
allowed_tools: None,
|
||||||
permission_mode: PermissionMode::ReadOnly,
|
permission_mode: PermissionMode::ReadOnly,
|
||||||
thinking: false,
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2669,7 +2469,6 @@ mod tests {
|
|||||||
.collect()
|
.collect()
|
||||||
),
|
),
|
||||||
permission_mode: PermissionMode::WorkspaceWrite,
|
permission_mode: PermissionMode::WorkspaceWrite,
|
||||||
thinking: false,
|
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2709,6 +2508,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]
|
||||||
@@ -2863,12 +2666,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("rusty-claude-cli init"));
|
||||||
assert!(skipped.contains("skipped (already exists)"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -2909,7 +2711,6 @@ mod tests {
|
|||||||
cache_read_input_tokens: 1,
|
cache_read_input_tokens: 1,
|
||||||
},
|
},
|
||||||
estimated_tokens: 128,
|
estimated_tokens: 128,
|
||||||
thinking_enabled: true,
|
|
||||||
},
|
},
|
||||||
"workspace-write",
|
"workspace-write",
|
||||||
&super::StatusContext {
|
&super::StatusContext {
|
||||||
@@ -2973,7 +2774,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 >= context.loaded_config_files);
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3031,7 +2832,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"));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user