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/jsonl-session' into integration/dori-cleanroom

YeonGyu-Kim9ce259451cb0
diff --cc rust/crates/commands/src/lib.rs
index f4fdc2d0,6a3d2341..0e46c56b
--- a/rust/crates/commands/src/lib.rs
+++ b/rust/crates/commands/src/lib.rs
@@@ -202,34 -125,10 +202,34 @@@ const SLASH_COMMAND_SPECS: &[SlashComma
},
SlashCommandSpec {
name: "session",
+ aliases: &[],
- summary: "List or switch managed local sessions",
- argument_hint: Some("[list|switch <session-id>]"),
+ summary: "List, switch, or fork managed local sessions",
+ argument_hint: Some("[list|switch <session-id>|fork [branch-name]]"),
resume_supported: false,
},
+ SlashCommandSpec {
+ name: "plugin",
+ aliases: &["plugins", "marketplace"],
+ summary: "Manage Claw Code plugins",
+ argument_hint: Some(
+ "[list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]",
+ ),
+ resume_supported: false,
+ },
+ SlashCommandSpec {
+ name: "agents",
+ aliases: &[],
+ summary: "List configured agents",
+ argument_hint: None,
+ resume_supported: true,
+ },
+ SlashCommandSpec {
+ name: "skills",
+ aliases: &[],
+ summary: "List available skills",
+ argument_hint: None,
+ resume_supported: true,
+ },
];
#[derive(Debug, Clone, PartialEq, Eq)]
@@@ -1426,51 -365,22 +1426,58 @@@ mod tests
target: Some("abc123".to_string())
})
);
+ assert_eq!(
+ SlashCommand::parse("/plugins install demo"),
+ Some(SlashCommand::Plugins {
+ action: Some("install".to_string()),
+ target: Some("demo".to_string())
+ })
+ );
+ assert_eq!(
+ SlashCommand::parse("/plugins list"),
+ Some(SlashCommand::Plugins {
+ action: Some("list".to_string()),
+ target: None
+ })
+ );
+ assert_eq!(
+ SlashCommand::parse("/plugins enable demo"),
+ Some(SlashCommand::Plugins {
+ action: Some("enable".to_string()),
+ target: Some("demo".to_string())
+ })
+ );
+ assert_eq!(
+ SlashCommand::parse("/plugins disable demo"),
+ Some(SlashCommand::Plugins {
+ action: Some("disable".to_string()),
+ target: Some("demo".to_string())
+ })
+ );
+ assert_eq!(
+ SlashCommand::parse("/session fork incident-review"),
+ Some(SlashCommand::Session {
+ action: Some("fork".to_string()),
+ target: Some("incident-review".to_string())
+ })
+ );
}
#[test]
fn renders_help_from_shared_specs() {
let help = render_slash_command_help();
- assert!(help.contains("works with --resume SESSION.json"));
+ assert!(help.contains("works with --resume SESSION.jsonl"));
assert!(help.contains("/help"));
assert!(help.contains("/status"));
+ assert!(help.contains("/sandbox"));
assert!(help.contains("/compact"));
+ assert!(help.contains("/bughunter [scope]"));
+ assert!(help.contains("/commit"));
+ assert!(help.contains("/pr [context]"));
+ assert!(help.contains("/issue [context]"));
+ assert!(help.contains("/ultraplan [task]"));
+ assert!(help.contains("/teleport <symbol-or-path>"));
+ assert!(help.contains("/debug-tool-call"));
assert!(help.contains("/model [model]"));
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
assert!(help.contains("/clear [--confirm]"));
@@@ -1482,16 -392,9 +1489,16 @@@
assert!(help.contains("/diff"));
assert!(help.contains("/version"));
assert!(help.contains("/export [file]"));
- assert!(help.contains("/session [list|switch <session-id>]"));
+ assert!(help.contains("/session [list|switch <session-id>|fork [branch-name]]"));
- assert_eq!(slash_command_specs().len(), 15);
- assert_eq!(resume_supported_slash_commands().len(), 11);
+ assert!(help.contains("/sandbox"));
+ assert!(help.contains(
+ "/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
+ ));
+ assert!(help.contains("aliases: /plugins, /marketplace"));
+ assert!(help.contains("/agents"));
+ assert!(help.contains("/skills"));
+ assert_eq!(slash_command_specs().len(), 26);
+ assert_eq!(resume_supported_slash_commands().len(), 14);
}
#[test]
diff --cc rust/crates/runtime/src/conversation.rs
index 0e9a5d68,789a23d5..15f32626
--- a/rust/crates/runtime/src/conversation.rs
+++ b/rust/crates/runtime/src/conversation.rs
@@@ -351,46 -210,50 +353,48 @@@ wher
let result_message = match permission_outcome {
PermissionOutcome::Allow => {
- let pre_hook_result = self.hook_runner.run_pre_tool_use(&tool_name, &input);
- if pre_hook_result.is_denied() {
- let deny_message = format!("PreToolUse hook denied tool `{tool_name}`");
- ConversationMessage::tool_result(
- tool_use_id,
- tool_name,
- format_hook_message(&pre_hook_result, &deny_message),
- true,
+ let (mut output, mut is_error) =
+ match self.tool_executor.execute(&tool_name, &effective_input) {
+ Ok(output) => (output, false),
+ Err(error) => (error.to_string(), true),
+ };
+ output = merge_hook_feedback(pre_hook_result.messages(), output, false);
+
+ let post_hook_result = if is_error {
+ self.run_post_tool_use_failure_hook(
+ &tool_name,
+ &effective_input,
+ &output,
)
} else {
- let (mut output, mut is_error) =
- match self.tool_executor.execute(&tool_name, &input) {
- Ok(output) => (output, false),
- Err(error) => (error.to_string(), true),
- };
- output = merge_hook_feedback(pre_hook_result.messages(), output, false);
-
- let post_hook_result = self
- .hook_runner
- .run_post_tool_use(&tool_name, &input, &output, is_error);
- if post_hook_result.is_denied() {
- is_error = true;
- }
- output = merge_hook_feedback(
- post_hook_result.messages(),
- output,
- post_hook_result.is_denied(),
- );
-
- ConversationMessage::tool_result(
- tool_use_id,
- tool_name,
- output,
- is_error,
+ self.run_post_tool_use_hook(
+ &tool_name,
+ &effective_input,
+ &output,
+ false,
)
+ };
+ if post_hook_result.is_denied() || post_hook_result.is_cancelled() {
+ is_error = true;
}
+ output = merge_hook_feedback(
+ post_hook_result.messages(),
+ output,
+ post_hook_result.is_denied() || post_hook_result.is_cancelled(),
+ );
+
+ ConversationMessage::tool_result(tool_use_id, tool_name, output, is_error)
}
- PermissionOutcome::Deny { reason } => {
- ConversationMessage::tool_result(tool_use_id, tool_name, reason, true)
- }
+ PermissionOutcome::Deny { reason } => ConversationMessage::tool_result(
+ tool_use_id,
+ tool_name,
+ merge_hook_feedback(pre_hook_result.messages(), reason, true),
+ true,
+ ),
};
- self.session.messages.push(result_message.clone());
+ self.session
+ .push_message(result_message.clone())
+ .map_err(|error| RuntimeError::new(error.to_string()))?;
tool_results.push(result_message);
}
}
diff --cc rust/crates/runtime/src/lib.rs
index 1cd720b1,28e7e41a..63e6a3fd
--- a/rust/crates/runtime/src/lib.rs
+++ b/rust/crates/runtime/src/lib.rs
@@@ -79,13 -76,10 +79,16 @@@ pub use remote::
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
};
+pub use sandbox::{
+ build_linux_sandbox_command, detect_container_environment, detect_container_environment_from,
+ resolve_sandbox_status, resolve_sandbox_status_for_request, ContainerEnvironment,
+ FilesystemIsolationMode, LinuxSandboxCommand, SandboxConfig, SandboxDetectionInputs,
+ SandboxRequest, SandboxStatus,
+};
- pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError};
+ pub use session::{
+ ContentBlock, ConversationMessage, MessageRole, Session, SessionCompaction, SessionError,
+ SessionFork,
+ };
pub use usage::{
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
};
diff --cc rust/crates/rusty-claude-cli/src/main.rs
index d12ded8b,60120281..e6d24ca4
--- a/rust/crates/rusty-claude-cli/src/main.rs
+++ b/rust/crates/rusty-claude-cli/src/main.rs
@@@ -10,10 -9,7 +10,10 @@@ use std::io::{self, Read, Write}
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::process::Command;
-use std::time::UNIX_EPOCH;
+use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
+use std::sync::{Arc, Mutex};
+use std::thread::{self, JoinHandle};
- use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
++use std::time::{Duration, Instant, UNIX_EPOCH};
use api::{
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
@@@ -54,7 -47,8 +54,9 @@@ const DEFAULT_OAUTH_CALLBACK_PORT: u16
const VERSION: &str = env!("CARGO_PKG_VERSION");
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
+const INTERNAL_PROGRESS_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(3);
+ const PRIMARY_SESSION_EXTENSION: &str = "jsonl";
+ const LEGACY_SESSION_EXTENSION: &str = "json";
type AllowedToolSet = BTreeSet<String>;
@@@ -1584,9 -1360,11 +1603,12 @@@ impl LiveCli
true,
self.allowed_tools.clone(),
self.permission_mode,
+ None,
)?;
- self.session = handle;
+ self.session = SessionHandle {
+ id: session_id,
+ path: handle.path,
+ };
println!(
"{}",
format_resume_report(
@@@ -1669,9 -1436,11 +1692,12 @@@
true,
self.allowed_tools.clone(),
self.permission_mode,
+ None,
)?;
- self.session = handle;
+ self.session = SessionHandle {
+ id: session_id,
+ path: handle.path,
+ };
println!(
"Session switched\n Active session {}\n File {}\n Messages {}",
self.session.id,
@@@ -1680,8 -1449,41 +1706,42 @@@
);
Ok(true)
}
+ Some("fork") => {
+ let forked = self.runtime.fork_session(target.map(ToOwned::to_owned));
+ let parent_session_id = self.session.id.clone();
+ let handle = create_managed_session_handle(&forked.session_id)?;
+ let branch_name = forked
+ .fork
+ .as_ref()
+ .and_then(|fork| fork.branch_name.clone());
+ let forked = forked.with_persistence_path(handle.path.clone());
+ let message_count = forked.messages.len();
+ forked.save_to_path(&handle.path)?;
+ self.runtime = build_runtime(
+ forked,
+ self.model.clone(),
+ self.system_prompt.clone(),
+ true,
+ true,
+ self.allowed_tools.clone(),
+ self.permission_mode,
++ None,
+ )?;
+ self.session = handle;
+ println!(
+ "Session forked\n Parent session {}\n Active session {}\n Branch {}\n File {}\n Messages {}",
+ parent_session_id,
+ self.session.id,
+ branch_name.as_deref().unwrap_or("(unnamed)"),
+ self.session.path.display(),
+ message_count,
+ );
+ Ok(true)
+ }
Some(other) => {
- println!("Unknown /session action '{other}'. Use /session list or /session switch <session-id>.");
+ println!(
+ "Unknown /session action '{other}'. Use /session list, /session switch <session-id>, or /session fork [branch-name]."
+ );
Ok(false)
}
}
@@@ -4071,10 -2917,8 +4182,10 @@@ fn print_help_to(out: &mut impl Write)
)?;
writeln!(
out,
- " claw --resume session.json /status /diff /export notes.txt"
+ " claw --resume session.jsonl /status /diff /export notes.txt"
)?;
+ writeln!(out, " claw agents")?;
+ writeln!(out, " claw /skills")?;
writeln!(out, " claw login")?;
writeln!(out, " claw init")?;
Ok(())
@@@ -4087,92 -2931,23 +4198,93 @@@ fn print_help()
#[cfg(test)]
mod tests {
use super::{
- create_managed_session_handle, 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, resolve_session_reference, response_to_events,
- resume_supported_slash_commands, status_context, CliAction, CliOutputFormat, 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, HookAbortMonitor, InternalPromptProgressEvent,
+ InternalPromptProgressState, SlashCommand, StatusUsage, DEFAULT_MODEL,
++ create_managed_session_handle, resolve_session_reference,
};
use api::{MessageResponse, OutputContentBlock, Usage};
+ use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};
use runtime::{
- AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session,
+ AssistantEvent, ContentBlock, ConversationMessage, HookAbortSignal, MessageRole,
+ PermissionMode, Session,
};
use serde_json::json;
- use std::path::PathBuf;
- use std::sync::{Mutex, OnceLock};
+ 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;
#[test]
fn defaults_to_repl_when_no_args() {
@@@ -4474,13 -3193,7 +4586,13 @@@
assert!(help.contains("/diff"));
assert!(help.contains("/version"));
assert!(help.contains("/export [file]"));
- assert!(help.contains("/session [list|switch <session-id>]"));
+ assert!(help.contains("/session [list|switch <session-id>|fork [branch-name]]"));
+ assert!(help.contains(
+ "/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
+ ));
+ assert!(help.contains("aliases: /plugins, /marketplace"));
+ assert!(help.contains("/agents"));
+ assert!(help.contains("/skills"));
assert!(help.contains("/exit"));
}