Skip to content

An agent-managed museum exhibit, built in Rust with Gajae-Code / LazyCodex — developed and maintained with no human intervention.

Rust

Merge remote-tracking branch 'origin/rcc/git' into integration/dori-cleanroom

YeonGyu-Kim3bca74d44669
diff --cc rust/crates/rusty-claude-cli/src/main.rs
index 65aff8d5,d0787e00..66ed9e74
--- a/rust/crates/rusty-claude-cli/src/main.rs
+++ b/rust/crates/rusty-claude-cli/src/main.rs
@@@ -2098,253 -1852,77 +2140,277 @@@ fn render_diff_report_for(cwd: &Path) -
.to_string(),
);
}
- Ok(format!("Diff\n\n{}", diff.trim_end()))
+
+ let mut sections = Vec::new();
+ if !staged.trim().is_empty() {
+ sections.push(format!("Staged changes:\n{}", staged.trim_end()));
+ }
+ if !unstaged.trim().is_empty() {
+ sections.push(format!("Unstaged changes:\n{}", unstaged.trim_end()));
+ }
+
+ Ok(format!("Diff\n\n{}", sections.join("\n\n")))
+ }
+
+ fn run_git_diff_command_in(
+ cwd: &Path,
+ args: &[&str],
+ ) -> Result<String, Box<dyn std::error::Error>> {
+ let output = std::process::Command::new("git")
+ .args(args)
+ .current_dir(cwd)
+ .output()?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
+ return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
+ }
+ Ok(String::from_utf8(output.stdout)?)
}
-fn render_version_report() -> String {
- let git_sha = GIT_SHA.unwrap_or("unknown");
- let target = BUILD_TARGET.unwrap_or("unknown");
- format!(
- "Version\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
- )
-}
+fn render_teleport_report(target: &str) -> Result<String, Box<dyn std::error::Error>> {
+ let cwd = env::current_dir()?;
-fn render_export_text(session: &Session) -> String {
- let mut lines = vec!["# Conversation Export".to_string(), String::new()];
- for (index, message) in session.messages.iter().enumerate() {
- let role = match message.role {
- MessageRole::System => "system",
- MessageRole::User => "user",
- MessageRole::Assistant => "assistant",
- MessageRole::Tool => "tool",
- };
- lines.push(format!("## {}. {role}", index + 1));
- for block in &message.blocks {
- match block {
- ContentBlock::Text { text } => lines.push(text.clone()),
- ContentBlock::ToolUse { id, name, input } => {
- lines.push(format!("[tool_use id={id} name={name}] {input}"));
- }
- ContentBlock::ToolResult {
- tool_use_id,
- tool_name,
- output,
- is_error,
- } => {
- lines.push(format!(
- "[tool_result id={tool_use_id} name={tool_name} error={is_error}] {output}"
- ));
- }
- }
- }
+ let file_list = Command::new("rg")
+ .args(["--files"])
+ .current_dir(&cwd)
+ .output()?;
+ let file_matches = if file_list.status.success() {
+ String::from_utf8(file_list.stdout)?
+ .lines()
+ .filter(|line| line.contains(target))
+ .take(10)
+ .map(ToOwned::to_owned)
+ .collect::<Vec<_>>()
+ } else {
+ Vec::new()
+ };
+
+ let content_output = Command::new("rg")
+ .args(["-n", "-S", "--color", "never", target, "."])
+ .current_dir(&cwd)
+ .output()?;
+
+ let mut lines = vec![format!("Teleport\n Target {target}")];
+ if !file_matches.is_empty() {
lines.push(String::new());
+ lines.push("File matches".to_string());
+ lines.extend(file_matches.into_iter().map(|path| format!(" {path}")));
}
- lines.join("\n")
-}
-fn default_export_filename(session: &Session) -> String {
- let stem = session
- .messages
+ if content_output.status.success() {
+ let matches = String::from_utf8(content_output.stdout)?;
+ if !matches.trim().is_empty() {
+ lines.push(String::new());
+ lines.push("Content matches".to_string());
+ lines.push(truncate_for_prompt(&matches, 4_000));
+ }
+ }
+
+ if lines.len() == 1 {
+ lines.push(" Result no matches found".to_string());
+ }
+
+ Ok(lines.join("\n"))
+}
+
+fn render_last_tool_debug_report(session: &Session) -> Result<String, Box<dyn std::error::Error>> {
+ let last_tool_use = session
+ .messages
+ .iter()
+ .rev()
+ .find_map(|message| {
+ message.blocks.iter().rev().find_map(|block| match block {
+ ContentBlock::ToolUse { id, name, input } => {
+ Some((id.clone(), name.clone(), input.clone()))
+ }
+ _ => None,
+ })
+ })
+ .ok_or_else(|| "no prior tool call found in session".to_string())?;
+
+ let tool_result = session.messages.iter().rev().find_map(|message| {
+ message.blocks.iter().rev().find_map(|block| match block {
+ ContentBlock::ToolResult {
+ tool_use_id,
+ tool_name,
+ output,
+ is_error,
+ } if tool_use_id == &last_tool_use.0 => {
+ Some((tool_name.clone(), output.clone(), *is_error))
+ }
+ _ => None,
+ })
+ });
+
+ let mut lines = vec![
+ "Debug tool call".to_string(),
+ format!(" Tool id {}", last_tool_use.0),
+ format!(" Tool name {}", last_tool_use.1),
+ " Input".to_string(),
+ indent_block(&last_tool_use.2, 4),
+ ];
+
+ match tool_result {
+ Some((tool_name, output, is_error)) => {
+ lines.push(" Result".to_string());
+ lines.push(format!(" name {tool_name}"));
+ lines.push(format!(
+ " status {}",
+ if is_error { "error" } else { "ok" }
+ ));
+ lines.push(indent_block(&output, 4));
+ }
+ None => lines.push(" Result missing tool result".to_string()),
+ }
+
+ Ok(lines.join("\n"))
+}
+
+fn indent_block(value: &str, spaces: usize) -> String {
+ let indent = " ".repeat(spaces);
+ value
+ .lines()
+ .map(|line| format!("{indent}{line}"))
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+fn git_output(args: &[&str]) -> Result<String, Box<dyn std::error::Error>> {
+ let output = Command::new("git")
+ .args(args)
+ .current_dir(env::current_dir()?)
+ .output()?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
+ return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
+ }
+ Ok(String::from_utf8(output.stdout)?)
+}
+
+fn git_status_ok(args: &[&str]) -> Result<(), Box<dyn std::error::Error>> {
+ let output = Command::new("git")
+ .args(args)
+ .current_dir(env::current_dir()?)
+ .output()?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
+ return Err(format!("git {} failed: {stderr}", args.join(" ")).into());
+ }
+ Ok(())
+}
+
+fn command_exists(name: &str) -> bool {
+ Command::new("which")
+ .arg(name)
+ .output()
+ .map(|output| output.status.success())
+ .unwrap_or(false)
+}
+
+fn write_temp_text_file(
+ filename: &str,
+ contents: &str,
+) -> Result<PathBuf, Box<dyn std::error::Error>> {
+ let path = env::temp_dir().join(filename);
+ fs::write(&path, contents)?;
+ Ok(path)
+}
+
+fn recent_user_context(session: &Session, limit: usize) -> String {
+ let requests = session
+ .messages
+ .iter()
+ .filter(|message| message.role == MessageRole::User)
+ .filter_map(|message| {
+ message.blocks.iter().find_map(|block| match block {
+ ContentBlock::Text { text } => Some(text.trim().to_string()),
+ _ => None,
+ })
+ })
+ .rev()
+ .take(limit)
+ .collect::<Vec<_>>();
+
+ if requests.is_empty() {
+ "<no prior user messages>".to_string()
+ } else {
+ requests
+ .into_iter()
+ .rev()
+ .enumerate()
+ .map(|(index, text)| format!("{}. {}", index + 1, text))
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+}
+
+fn truncate_for_prompt(value: &str, limit: usize) -> String {
+ if value.chars().count() <= limit {
+ value.trim().to_string()
+ } else {
+ let truncated = value.chars().take(limit).collect::<String>();
+ format!("{}\n…[truncated]", truncated.trim_end())
+ }
+}
+
+fn sanitize_generated_message(value: &str) -> String {
+ value.trim().trim_matches('`').trim().replace("\r\n", "\n")
+}
+
+fn parse_titled_body(value: &str) -> Option<(String, String)> {
+ let normalized = sanitize_generated_message(value);
+ let title = normalized
+ .lines()
+ .find_map(|line| line.strip_prefix("TITLE:").map(str::trim))?;
+ let body_start = normalized.find("BODY:")?;
+ let body = normalized[body_start + "BODY:".len()..].trim();
+ Some((title.to_string(), body.to_string()))
+}
+
+fn render_version_report() -> String {
+ let git_sha = GIT_SHA.unwrap_or("unknown");
+ let target = BUILD_TARGET.unwrap_or("unknown");
+ format!(
+ "Claw Code\n Version {VERSION}\n Git SHA {git_sha}\n Target {target}\n Build date {DEFAULT_DATE}"
+ )
+}
+
+fn render_export_text(session: &Session) -> String {
+ let mut lines = vec!["# Conversation Export".to_string(), String::new()];
+ for (index, message) in session.messages.iter().enumerate() {
+ let role = match message.role {
+ MessageRole::System => "system",
+ MessageRole::User => "user",
+ MessageRole::Assistant => "assistant",
+ MessageRole::Tool => "tool",
+ };
+ lines.push(format!("## {}. {role}", index + 1));
+ for block in &message.blocks {
+ match block {
+ ContentBlock::Text { text } => lines.push(text.clone()),
+ ContentBlock::ToolUse { id, name, input } => {
+ lines.push(format!("[tool_use id={id} name={name}] {input}"));
+ }
+ ContentBlock::ToolResult {
+ tool_use_id,
+ tool_name,
+ output,
+ is_error,
+ } => {
+ lines.push(format!(
+ "[tool_result id={tool_use_id} name={tool_name} error={is_error}] {output}"
+ ));
+ }
+ }
+ }
+ lines.push(String::new());
+ }
+ lines.join("\n")
+}
+
+fn default_export_filename(session: &Session) -> String {
+ let stem = session
+ .messages
.iter()
.find_map(|message| match message.role {
MessageRole::User => message.blocks.iter().find_map(|block| match block {
@@@ -3810,48 -2455,58 +3876,91 @@@ fn print_help()
#[cfg(test)]
mod tests {
use super::{
- filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
- format_model_report, format_model_switch_report, format_permissions_report,
+ describe_tool_progress, filter_tool_specs, format_compact_report, format_cost_report,
- format_internal_prompt_progress_line, format_model_report, format_model_switch_report,
- format_permissions_report, format_permissions_switch_report, format_resume_report,
- format_status_report, format_tool_call_start, format_tool_result,
- normalize_permission_mode, parse_args, parse_git_status_metadata, permission_policy,
- print_help_to, push_output_block, render_config_report, render_memory_report,
- render_repl_help, resolve_model_alias, response_to_events, resume_supported_slash_commands,
- status_context, CliAction, CliOutputFormat, InternalPromptProgressEvent,
- InternalPromptProgressState, SlashCommand, StatusUsage, DEFAULT_MODEL,
++ format_init_report, format_internal_prompt_progress_line, format_model_report,
++ format_model_switch_report, format_permissions_report,
+ format_permissions_switch_report, format_resume_report, format_status_report,
+ format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
- parse_git_status_branch, parse_git_status_metadata, render_config_report,
- render_diff_report, render_init_claude_md, render_memory_report, render_repl_help,
++ parse_git_status_branch, parse_git_status_metadata, permission_policy, print_help_to,
++ push_output_block, render_config_report, render_diff_report, render_init_claude_md,
++ render_memory_report, render_repl_help, resolve_model_alias, response_to_events,
+ resume_supported_slash_commands, run_resume_command, status_context, CliAction,
- CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
++ CliOutputFormat, InternalPromptProgressEvent, InternalPromptProgressState, SlashCommand,
++ StatusUsage, DEFAULT_MODEL,
};
- use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session};
+ use api::{MessageResponse, OutputContentBlock, Usage};
+ use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};
- use runtime::{AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode};
++ use runtime::{
++ AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session,
++ };
+ use serde_json::json;
- use std::path::PathBuf;
- use std::time::Duration;
+ use std::fs;
+ use std::path::{Path, PathBuf};
+ use std::process::Command;
+ use std::sync::{Mutex, MutexGuard, OnceLock};
- use std::time::{SystemTime, UNIX_EPOCH};
++ use std::time::{Duration, SystemTime, UNIX_EPOCH};
+ use tools::GlobalToolRegistry;
+
+ fn registry_with_plugin_tool() -> GlobalToolRegistry {
+ GlobalToolRegistry::with_plugin_tools(vec![PluginTool::new(
+ "plugin-demo@external",
+ "plugin-demo",
+ PluginToolDefinition {
+ name: "plugin_echo".to_string(),
+ description: Some("Echo plugin payload".to_string()),
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "message": { "type": "string" }
+ },
+ "required": ["message"],
+ "additionalProperties": false
+ }),
+ },
+ "echo".to_string(),
+ Vec::new(),
+ PluginToolPermission::WorkspaceWrite,
+ None,
+ )])
+ .expect("plugin tool registry should build")
+ }
+ fn temp_dir() -> PathBuf {
+ let nanos = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("time should be after epoch")
+ .as_nanos();
+ std::env::temp_dir().join(format!("rusty-claude-cli-{nanos}"))
+ }
+
+ fn git(args: &[&str], cwd: &Path) {
+ let status = Command::new("git")
+ .args(args)
+ .current_dir(cwd)
+ .status()
+ .expect("git command should run");
+ assert!(
+ status.success(),
+ "git command failed: git {}",
+ args.join(" ")
+ );
+ }
+
+ fn env_lock() -> MutexGuard<'static, ()> {
+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ }
+
+ fn with_current_dir<T>(cwd: &Path, f: impl FnOnce() -> T) -> T {
+ let previous = std::env::current_dir().expect("cwd should load");
+ std::env::set_current_dir(cwd).expect("cwd should change");
+ let result = f();
+ std::env::set_current_dir(previous).expect("cwd should restore");
+ result
+ }
+
#[test]
fn defaults_to_repl_when_no_args() {
assert_eq!(