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/hook-pipeline' into integration/dori-cleanroom
YeonGyu-Kim9e06ea58f0a7
diff --cc rust/crates/runtime/src/config.rsindex d41fefb1,bb914744..cc885be5--- a/rust/crates/runtime/src/config.rs+++ b/rust/crates/runtime/src/config.rs@@@ -379,56 -370,13 +399,60 @@@ impl RuntimeFeatureConfig}}+impl RuntimePluginConfig {+ #[must_use]+ pub fn enabled_plugins(&self) -> &BTreeMap<String, bool> {+ &self.enabled_plugins+ }++ #[must_use]+ pub fn external_directories(&self) -> &[String] {+ &self.external_directories+ }++ #[must_use]+ pub fn install_root(&self) -> Option<&str> {+ self.install_root.as_deref()+ }++ #[must_use]+ pub fn registry_path(&self) -> Option<&str> {+ self.registry_path.as_deref()+ }++ #[must_use]+ pub fn bundled_root(&self) -> Option<&str> {+ self.bundled_root.as_deref()+ }++ pub fn set_plugin_state(&mut self, plugin_id: String, enabled: bool) {+ self.enabled_plugins.insert(plugin_id, enabled);+ }++ #[must_use]+ pub fn state_for(&self, plugin_id: &str, default_enabled: bool) -> bool {+ self.enabled_plugins+ .get(plugin_id)+ .copied()+ .unwrap_or(default_enabled)+ }+}++#[must_use]+pub fn default_config_home() -> PathBuf {+ std::env::var_os("CLAW_CONFIG_HOME")+ .map(PathBuf::from)+ .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".claw")))+ .unwrap_or_else(|| PathBuf::from(".claw"))+}+impl RuntimeHookConfig {#[must_use]- pub fn new(pre_tool_use: Vec<String>, post_tool_use: Vec<String>) -> Self {+ pub fn new(+ pre_tool_use: Vec<String>,+ post_tool_use: Vec<String>,+ post_tool_use_failure: Vec<String>,+ ) -> Self {Self {pre_tool_use,post_tool_use,@@@ -445,16 -394,31 +470,47 @@@&self.post_tool_use}+ #[must_use]+ pub fn merged(&self, other: &Self) -> Self {+ let mut merged = self.clone();+ merged.extend(other);+ merged+ }++ pub fn extend(&mut self, other: &Self) {+ extend_unique(&mut self.pre_tool_use, other.pre_tool_use());+ extend_unique(&mut self.post_tool_use, other.post_tool_use());++ extend_unique(++ &mut self.post_tool_use_failure,++ other.post_tool_use_failure(),++ );++ }+++ #[must_use]+ pub fn post_tool_use_failure(&self) -> &[String] {+ &self.post_tool_use_failure+ }+ }++ impl RuntimePermissionRuleConfig {+ #[must_use]+ pub fn new(allow: Vec<String>, deny: Vec<String>, ask: Vec<String>) -> Self {+ Self { allow, deny, ask }+ }++ #[must_use]+ pub fn allow(&self) -> &[String] {+ &self.allow+ }++ #[must_use]+ pub fn deny(&self) -> &[String] {+ &self.deny+ }++ #[must_use]+ pub fn ask(&self) -> &[String] {+ &self.ask}}@@@ -998,8 -930,8 +1080,8 @@@ mod tests).expect("write project compat config");fs::write(- cwd.join(".claude").join("settings.json"),+ cwd.join(".claw").join("settings.json"),- r#"{"env":{"C":"3"},"hooks":{"PostToolUse":["project"]},"mcpServers":{"project":{"command":"uvx","args":["project"]}}}"#,+ r#"{"env":{"C":"3"},"hooks":{"PostToolUse":["project"],"PostToolUseFailure":["project-failure"]},"permissions":{"ask":["Edit"]},"mcpServers":{"project":{"command":"uvx","args":["project"]}}}"#,).expect("write project settings");fs::write(diff --cc rust/crates/runtime/src/conversation.rsindex da12a8b4,07ac8bca..0e9a5d68--- a/rust/crates/runtime/src/conversation.rs+++ b/rust/crates/runtime/src/conversation.rs@@@ -106,7 -99,8 +108,9 @@@ pub struct ConversationRuntime<C, T>max_iterations: usize,usage_tracker: UsageTracker,hook_runner: HookRunner,+ auto_compaction_input_tokens_threshold: u32,+ hook_abort_signal: HookAbortSignal,+ hook_progress_reporter: Option<Box<dyn HookProgressReporter>>,}impl<C, T> ConversationRuntime<C, T>@@@ -151,7 -146,8 +156,9 @@@ whermax_iterations: usize::MAX,usage_tracker,hook_runner: HookRunner::from_feature_config(&feature_config),+ auto_compaction_input_tokens_threshold: auto_compaction_threshold_from_env(),+ hook_abort_signal: HookAbortSignal::default(),+ hook_progress_reporter: None,}}@@@ -161,12 -157,93 +168,99 @@@self}+ #[must_use]+ pub fn with_auto_compaction_input_tokens_threshold(mut self, threshold: u32) -> Self {+ self.auto_compaction_input_tokens_threshold = threshold;+ self+ }++ #[must_use]+ pub fn with_hook_abort_signal(mut self, hook_abort_signal: HookAbortSignal) -> Self {+ self.hook_abort_signal = hook_abort_signal;+ self+ }++ #[must_use]+ pub fn with_hook_progress_reporter(+ mut self,+ hook_progress_reporter: Box<dyn HookProgressReporter>,+ ) -> Self {+ self.hook_progress_reporter = Some(hook_progress_reporter);+ self+ }++ fn run_pre_tool_use_hook(&mut self, tool_name: &str, input: &str) -> HookRunResult {+ if let Some(reporter) = self.hook_progress_reporter.as_mut() {+ self.hook_runner.run_pre_tool_use_with_context(+ tool_name,+ input,+ Some(&self.hook_abort_signal),+ Some(reporter.as_mut()),+ )+ } else {+ self.hook_runner.run_pre_tool_use_with_context(+ tool_name,+ input,+ Some(&self.hook_abort_signal),+ None,+ )+ }+ }++ fn run_post_tool_use_hook(+ &mut self,+ tool_name: &str,+ input: &str,+ output: &str,+ is_error: bool,+ ) -> HookRunResult {+ if let Some(reporter) = self.hook_progress_reporter.as_mut() {+ self.hook_runner.run_post_tool_use_with_context(+ tool_name,+ input,+ output,+ is_error,+ Some(&self.hook_abort_signal),+ Some(reporter.as_mut()),+ )+ } else {+ self.hook_runner.run_post_tool_use_with_context(+ tool_name,+ input,+ output,+ is_error,+ Some(&self.hook_abort_signal),+ None,+ )+ }+ }++ fn run_post_tool_use_failure_hook(+ &mut self,+ tool_name: &str,+ input: &str,+ output: &str,+ ) -> HookRunResult {+ if let Some(reporter) = self.hook_progress_reporter.as_mut() {+ self.hook_runner.run_post_tool_use_failure_with_context(+ tool_name,+ input,+ output,+ Some(&self.hook_abort_signal),+ Some(reporter.as_mut()),+ )+ } else {+ self.hook_runner.run_post_tool_use_failure_with_context(+ tool_name,+ input,+ output,+ Some(&self.hook_abort_signal),+ None,+ )+ }+ }++ #[allow(clippy::too_many_lines)]pub fn run_turn(&mut self,user_input: impl Into<String>,diff --cc rust/crates/runtime/src/hooks.rsindex 63ef9ff2,4ef5a6cf..739065d6--- a/rust/crates/runtime/src/hooks.rs+++ b/rust/crates/runtime/src/hooks.rs@@@ -195,18 -452,22 +452,24 @@@ impl HookRunner},None => HookCommandOutcome::Warn {message: format!(- "{} hook `{command}` terminated by signal while handling `{tool_name}`",- event.as_str()+ "{} hook `{command}` terminated by signal while handling `{}`",- request.event.as_str(),- request.tool_name++ event.as_str(),++ tool_name),},}}+ Ok(CommandExecution::Cancelled) => HookCommandOutcome::Cancelled {+ message: format!(+ "{} hook `{command}` cancelled while handling `{tool_name}`",+ event.as_str()+ ),+ },Err(error) => HookCommandOutcome::Warn {message: format!(- "{} hook `{command}` failed to start for `{tool_name}`: {error}",- event.as_str()+ "{} hook `{command}` failed to start for `{}`: {error}",- request.event.as_str(),- request.tool_name++ event.as_str(),++ tool_name),},}diff --cc rust/crates/runtime/src/lib.rsindex 68df55fe,f56291a5..1cd720b1--- a/rust/crates/runtime/src/lib.rs+++ b/rust/crates/runtime/src/lib.rs@@@ -28,11 -28,11 +28,12 @@@ pub use config::McpConfigCollection, McpOAuthConfig, McpRemoteServerConfig, McpSdkServerConfig,McpServerConfig, McpStdioServerConfig, McpTransport, McpWebSocketServerConfig, OAuthConfig,ResolvedPermissionMode, RuntimeConfig, RuntimeFeatureConfig, RuntimeHookConfig,- RuntimePluginConfig, ScopedMcpServerConfig, CLAW_SETTINGS_SCHEMA_NAME,- RuntimePermissionRuleConfig, ScopedMcpServerConfig, CLAUDE_CODE_SETTINGS_SCHEMA_NAME,++ RuntimePermissionRuleConfig, RuntimePluginConfig, ScopedMcpServerConfig,++ CLAW_SETTINGS_SCHEMA_NAME,};pub use conversation::{- ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError, StaticToolExecutor,- ToolError, ToolExecutor, TurnSummary,+ auto_compaction_threshold_from_env, ApiClient, ApiRequest, AssistantEvent, AutoCompactionEvent,+ ConversationRuntime, RuntimeError, StaticToolExecutor, ToolError, ToolExecutor, TurnSummary,};pub use file_ops::{edit_file, glob_search, grep_search, read_file, write_file, EditFileOutput, GlobSearchOutput,diff --cc rust/crates/rusty-claude-cli/Cargo.tomlindex 0541c9e6,c1aa0cec..f10a41e1--- a/rust/crates/rusty-claude-cli/Cargo.toml+++ b/rust/crates/rusty-claude-cli/Cargo.toml@@@ -17,10 -17,9 +17,10 @@@ crossterm = "0.28pulldown-cmark = "0.13"rustyline = "15"runtime = { path = "../runtime" }-serde_json = "1"+plugins = { path = "../plugins" }+serde_json.workspace = truesyntect = "5"- tokio = { version = "1", features = ["rt-multi-thread", "time"] }+ tokio = { version = "1", features = ["rt-multi-thread", "signal", "time"] }tools = { path = "../tools" }[lints]diff --cc rust/crates/rusty-claude-cli/src/main.rsindex ce682c66,692fd5db..d12ded8b--- a/rust/crates/rusty-claude-cli/src/main.rs+++ b/rust/crates/rusty-claude-cli/src/main.rs@@@ -10,10 -9,9 +10,10 @@@ use std::io::{self, Read, Write}use std::net::TcpListener;use std::path::{Path, PathBuf};use std::process::Command;- use std::sync::mpsc::{self, RecvTimeoutError};-use std::sync::mpsc::{self, Receiver, Sender};++use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};+use std::sync::{Arc, Mutex};- use std::thread;+ use std::thread::{self, JoinHandle};-use std::time::{SystemTime, UNIX_EPOCH};+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};use api::{resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,@@@ -1136,7 -1096,34 +1191,35 @@@ impl LiveCli)}+ fn prepare_turn_runtime(+ &self,+ emit_output: bool,+ ) -> Result<+ (+ ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,+ HookAbortMonitor,+ ),+ Box<dyn std::error::Error>,+ > {+ let hook_abort_signal = runtime::HookAbortSignal::new();+ let runtime = build_runtime(+ self.runtime.session().clone(),+ self.model.clone(),+ self.system_prompt.clone(),+ true,+ emit_output,+ self.allowed_tools.clone(),+ self.permission_mode,++ None,+ )?+ .with_hook_abort_signal(hook_abort_signal.clone());+ let hook_abort_monitor = HookAbortMonitor::spawn(hook_abort_signal);++ Ok((runtime, hook_abort_monitor))+ }+fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {+ let (mut runtime, hook_abort_monitor) = self.prepare_turn_runtime(true)?;let mut spinner = Spinner::new();let mut stdout = io::stdout();spinner.tick(@@@ -1145,9 -1132,11 +1228,11 @@@&mut stdout,)?;let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);- let result = self.runtime.run_turn(input, Some(&mut permission_prompter));+ let result = runtime.run_turn(input, Some(&mut permission_prompter));+ hook_abort_monitor.stop();+ self.runtime = runtime;match result {- Ok(_) => {+ Ok(summary) => {spinner.finish("✨ Done",TerminalRenderer::new().color_theme(),@@@ -2945,24 -1999,54 +3022,61 @@@ fn build_runtimeemit_output: bool,allowed_tools: Option<AllowedToolSet>,permission_mode: PermissionMode,-) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>-{- let feature_config = build_runtime_feature_config()?;+ progress_reporter: Option<InternalPromptProgressReporter>,+) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>> {+ let (feature_config, tool_registry) = build_runtime_plugin_state()?;- Ok(ConversationRuntime::new_with_features(+ let mut runtime = ConversationRuntime::new_with_features(session,- AnthropicRuntimeClient::new(model, enable_tools, emit_output, allowed_tools.clone())?,- CliToolExecutor::new(allowed_tools, emit_output),- permission_policy(permission_mode, &feature_config),+ AnthropicRuntimeClient::new(+ model,+ enable_tools,+ emit_output,+ allowed_tools.clone(),+ tool_registry.clone(),+ progress_reporter,+ )?,+ CliToolExecutor::new(allowed_tools.clone(), emit_output, tool_registry.clone()),- permission_policy(permission_mode, &tool_registry),++ permission_policy(permission_mode, &feature_config, &tool_registry),system_prompt,feature_config,- ))+ );+ if emit_output {+ runtime = runtime.with_hook_progress_reporter(Box::new(CliHookProgressReporter));+ }+ Ok(runtime)+ }++ struct CliHookProgressReporter;++ impl runtime::HookProgressReporter for CliHookProgressReporter {+ fn on_event(&mut self, event: &runtime::HookProgressEvent) {+ match event {+ runtime::HookProgressEvent::Started {+ event,+ tool_name,+ command,+ } => eprintln!(+ "[hook {event_name}] {tool_name}: {command}",+ event_name = event.as_str()+ ),+ runtime::HookProgressEvent::Completed {+ event,+ tool_name,+ command,+ } => eprintln!(+ "[hook done {event_name}] {tool_name}: {command}",+ event_name = event.as_str()+ ),+ runtime::HookProgressEvent::Cancelled {+ event,+ tool_name,+ command,+ } => eprintln!(+ "[hook cancelled {event_name}] {tool_name}: {command}",+ event_name = event.as_str()+ ),+ }+ }}struct CliPermissionPrompter {@@@ -3817,12 -2794,13 +3934,16 @@@ impl ToolExecutor for CliToolExecutor}}- fn permission_policy(mode: PermissionMode, tool_registry: &GlobalToolRegistry) -> PermissionPolicy {+ fn permission_policy(+ mode: PermissionMode,+ feature_config: &runtime::RuntimeFeatureConfig,++ tool_registry: &GlobalToolRegistry,+ ) -> PermissionPolicy {- tool_permission_specs().into_iter().fold(+ tool_registry.permission_specs(None).into_iter().fold(- PermissionPolicy::new(mode),+ PermissionPolicy::new(mode).with_permission_rules(feature_config.permission_rules()),- |policy, spec| policy.with_tool_requirement(spec.name, spec.required_permission),+ |policy, (name, required_permission)| {+ policy.with_tool_requirement(name, required_permission)+ },)}@@@ -3966,90 -2944,23 +4087,92 @@@ fn print_help()#[cfg(test)]mod tests {use super::{- filter_tool_specs, format_compact_report, format_cost_report, 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, 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, HookAbortMonitor, SlashCommand, StatusUsage, DEFAULT_MODEL,+ 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_branch, parse_git_status_metadata, permission_policy, print_help_to,+ push_output_block, render_config_report, render_diff_report, render_memory_report,+ render_repl_help, resolve_model_alias, response_to_events,+ resume_supported_slash_commands, run_resume_command, status_context, CliAction,- CliOutputFormat, InternalPromptProgressEvent, InternalPromptProgressState, SlashCommand,- StatusUsage, DEFAULT_MODEL,++ CliOutputFormat, HookAbortMonitor, InternalPromptProgressEvent,++ InternalPromptProgressState, SlashCommand, StatusUsage, DEFAULT_MODEL,};use api::{MessageResponse, OutputContentBlock, Usage};+ use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};use runtime::{- AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session,+ AssistantEvent, ContentBlock, ConversationMessage, HookAbortSignal, MessageRole,- PermissionMode,++ PermissionMode, Session,};use serde_json::json;- use std::path::PathBuf;+ use std::fs;+ use std::path::{Path, PathBuf};+ use std::process::Command;+ use std::sync::{Mutex, MutexGuard, OnceLock};+ 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+ }+ use std::sync::mpsc;- use std::time::Duration;#[test]fn defaults_to_repl_when_no_args() {@@@ -5049,56 -3620,42 +5172,95 @@@));}+ #[test]+ fn response_to_events_ignores_thinking_blocks() {+ let mut out = Vec::new();+ let events = response_to_events(+ MessageResponse {+ id: "msg-3".to_string(),+ kind: "message".to_string(),+ model: "claude-opus-4-6".to_string(),+ role: "assistant".to_string(),+ content: vec![+ OutputContentBlock::Thinking {+ thinking: "step 1".to_string(),+ signature: Some("sig_123".to_string()),+ },+ OutputContentBlock::Text {+ text: "Final answer".to_string(),+ },+ ],+ stop_reason: Some("end_turn".to_string()),+ stop_sequence: None,+ usage: Usage {+ input_tokens: 1,+ output_tokens: 1,+ cache_creation_input_tokens: 0,+ cache_read_input_tokens: 0,+ },+ request_id: None,+ },+ &mut out,+ )+ .expect("response conversion should succeed");++ assert!(matches!(+ &events[0],+ AssistantEvent::TextDelta(text) if text == "Final answer"+ ));+ assert!(!String::from_utf8(out).expect("utf8").contains("step 1"));+ }+}++#[cfg(test)]+mod sandbox_report_tests {+ use super::format_sandbox_report;++ #[test]+ fn sandbox_report_renders_expected_fields() {+ let report = format_sandbox_report(&runtime::SandboxStatus::default());+ assert!(report.contains("Sandbox"));+ assert!(report.contains("Enabled"));+ assert!(report.contains("Filesystem mode"));+ assert!(report.contains("Fallback reason"));+ }+++ #[test]+ fn hook_abort_monitor_stops_without_aborting() {+ let abort_signal = HookAbortSignal::new();+ let (ready_tx, ready_rx) = mpsc::channel();+ let monitor = HookAbortMonitor::spawn_with_waiter(+ abort_signal.clone(),+ move |stop_rx, abort_signal| {+ ready_tx.send(()).expect("ready signal");+ let _ = stop_rx.recv();+ assert!(!abort_signal.is_aborted());+ },+ );++ ready_rx.recv().expect("waiter should be ready");+ monitor.stop();++ assert!(!abort_signal.is_aborted());+ }++ #[test]+ fn hook_abort_monitor_propagates_interrupt() {+ let abort_signal = HookAbortSignal::new();+ let (done_tx, done_rx) = mpsc::channel();+ let monitor = HookAbortMonitor::spawn_with_waiter(+ abort_signal.clone(),+ move |_stop_rx, abort_signal| {+ abort_signal.abort();+ done_tx.send(()).expect("done signal");+ },+ );++ done_rx+ .recv_timeout(Duration::from_secs(1))+ .expect("interrupt should complete");+ monitor.stop();++ assert!(abort_signal.is_aborted());+ }}