mirror of
https://github.com/instructkr/claw-code.git
synced 2026-04-04 05:04:48 +08:00
Compare commits
1 Commits
rcc/sandbo
...
rcc/git
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82018e8184 |
@@ -51,12 +51,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: true,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
SlashCommandSpec {
|
|
||||||
name: "sandbox",
|
|
||||||
summary: "Show sandbox isolation status",
|
|
||||||
argument_hint: None,
|
|
||||||
resume_supported: true,
|
|
||||||
},
|
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "compact",
|
name: "compact",
|
||||||
summary: "Compact local session history",
|
summary: "Compact local session history",
|
||||||
@@ -141,7 +135,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
pub enum SlashCommand {
|
pub enum SlashCommand {
|
||||||
Help,
|
Help,
|
||||||
Status,
|
Status,
|
||||||
Sandbox,
|
|
||||||
Compact,
|
Compact,
|
||||||
Model {
|
Model {
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
@@ -186,7 +179,6 @@ impl SlashCommand {
|
|||||||
Some(match command {
|
Some(match command {
|
||||||
"help" => Self::Help,
|
"help" => Self::Help,
|
||||||
"status" => Self::Status,
|
"status" => Self::Status,
|
||||||
"sandbox" => Self::Sandbox,
|
|
||||||
"compact" => Self::Compact,
|
"compact" => Self::Compact,
|
||||||
"model" => Self::Model {
|
"model" => Self::Model {
|
||||||
model: parts.next().map(ToOwned::to_owned),
|
model: parts.next().map(ToOwned::to_owned),
|
||||||
@@ -287,7 +279,6 @@ pub fn handle_slash_command(
|
|||||||
session: session.clone(),
|
session: session.clone(),
|
||||||
}),
|
}),
|
||||||
SlashCommand::Status
|
SlashCommand::Status
|
||||||
| SlashCommand::Sandbox
|
|
||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Clear { .. }
|
| SlashCommand::Clear { .. }
|
||||||
@@ -316,7 +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("/sandbox"), Some(SlashCommand::Sandbox));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
SlashCommand::parse("/model claude-opus"),
|
SlashCommand::parse("/model claude-opus"),
|
||||||
Some(SlashCommand::Model {
|
Some(SlashCommand::Model {
|
||||||
@@ -383,7 +373,6 @@ mod tests {
|
|||||||
assert!(help.contains("works with --resume SESSION.json"));
|
assert!(help.contains("works with --resume SESSION.json"));
|
||||||
assert!(help.contains("/help"));
|
assert!(help.contains("/help"));
|
||||||
assert!(help.contains("/status"));
|
assert!(help.contains("/status"));
|
||||||
assert!(help.contains("/sandbox"));
|
|
||||||
assert!(help.contains("/compact"));
|
assert!(help.contains("/compact"));
|
||||||
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]"));
|
||||||
@@ -397,8 +386,8 @@ 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(), 12);
|
assert_eq!(resume_supported_slash_commands().len(), 11);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -445,7 +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("/sandbox", &session, CompactionConfig::default()).is_none());
|
|
||||||
assert!(
|
assert!(
|
||||||
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use std::env;
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -8,12 +7,6 @@ use tokio::process::Command as TokioCommand;
|
|||||||
use tokio::runtime::Builder;
|
use tokio::runtime::Builder;
|
||||||
use tokio::time::timeout;
|
use tokio::time::timeout;
|
||||||
|
|
||||||
use crate::sandbox::{
|
|
||||||
build_linux_sandbox_command, resolve_sandbox_status_for_request, FilesystemIsolationMode,
|
|
||||||
SandboxConfig, SandboxStatus,
|
|
||||||
};
|
|
||||||
use crate::ConfigLoader;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
pub struct BashCommandInput {
|
pub struct BashCommandInput {
|
||||||
pub command: String,
|
pub command: String,
|
||||||
@@ -23,14 +16,6 @@ pub struct BashCommandInput {
|
|||||||
pub run_in_background: Option<bool>,
|
pub run_in_background: Option<bool>,
|
||||||
#[serde(rename = "dangerouslyDisableSandbox")]
|
#[serde(rename = "dangerouslyDisableSandbox")]
|
||||||
pub dangerously_disable_sandbox: Option<bool>,
|
pub dangerously_disable_sandbox: Option<bool>,
|
||||||
#[serde(rename = "namespaceRestrictions")]
|
|
||||||
pub namespace_restrictions: Option<bool>,
|
|
||||||
#[serde(rename = "isolateNetwork")]
|
|
||||||
pub isolate_network: Option<bool>,
|
|
||||||
#[serde(rename = "filesystemMode")]
|
|
||||||
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
|
||||||
#[serde(rename = "allowedMounts")]
|
|
||||||
pub allowed_mounts: Option<Vec<String>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
@@ -60,17 +45,13 @@ pub struct BashCommandOutput {
|
|||||||
pub persisted_output_path: Option<String>,
|
pub persisted_output_path: Option<String>,
|
||||||
#[serde(rename = "persistedOutputSize")]
|
#[serde(rename = "persistedOutputSize")]
|
||||||
pub persisted_output_size: Option<u64>,
|
pub persisted_output_size: Option<u64>,
|
||||||
#[serde(rename = "sandboxStatus")]
|
|
||||||
pub sandbox_status: Option<SandboxStatus>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||||
let cwd = env::current_dir()?;
|
|
||||||
let sandbox_status = sandbox_status_for_input(&input, &cwd);
|
|
||||||
|
|
||||||
if input.run_in_background.unwrap_or(false) {
|
if input.run_in_background.unwrap_or(false) {
|
||||||
let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
|
let child = Command::new("sh")
|
||||||
let child = child
|
.arg("-lc")
|
||||||
|
.arg(&input.command)
|
||||||
.stdin(Stdio::null())
|
.stdin(Stdio::null())
|
||||||
.stdout(Stdio::null())
|
.stdout(Stdio::null())
|
||||||
.stderr(Stdio::null())
|
.stderr(Stdio::null())
|
||||||
@@ -91,20 +72,16 @@ pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: Some(sandbox_status),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let runtime = Builder::new_current_thread().enable_all().build()?;
|
let runtime = Builder::new_current_thread().enable_all().build()?;
|
||||||
runtime.block_on(execute_bash_async(input, sandbox_status, cwd))
|
runtime.block_on(execute_bash_async(input))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_bash_async(
|
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||||
input: BashCommandInput,
|
let mut command = TokioCommand::new("sh");
|
||||||
sandbox_status: SandboxStatus,
|
command.arg("-lc").arg(&input.command);
|
||||||
cwd: std::path::PathBuf,
|
|
||||||
) -> io::Result<BashCommandOutput> {
|
|
||||||
let mut command = prepare_tokio_command(&input.command, &cwd, &sandbox_status, true);
|
|
||||||
|
|
||||||
let output_result = if let Some(timeout_ms) = input.timeout {
|
let output_result = if let Some(timeout_ms) = input.timeout {
|
||||||
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
||||||
@@ -125,7 +102,6 @@ async fn execute_bash_async(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: Some(sandbox_status),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,88 +136,12 @@ async fn execute_bash_async(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: Some(sandbox_status),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sandbox_status_for_input(input: &BashCommandInput, cwd: &std::path::Path) -> SandboxStatus {
|
|
||||||
let config = ConfigLoader::default_for(cwd).load().map_or_else(
|
|
||||||
|_| SandboxConfig::default(),
|
|
||||||
|runtime_config| runtime_config.sandbox().clone(),
|
|
||||||
);
|
|
||||||
let request = config.resolve_request(
|
|
||||||
input.dangerously_disable_sandbox.map(|disabled| !disabled),
|
|
||||||
input.namespace_restrictions,
|
|
||||||
input.isolate_network,
|
|
||||||
input.filesystem_mode,
|
|
||||||
input.allowed_mounts.clone(),
|
|
||||||
);
|
|
||||||
resolve_sandbox_status_for_request(&request, cwd)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_command(
|
|
||||||
command: &str,
|
|
||||||
cwd: &std::path::Path,
|
|
||||||
sandbox_status: &SandboxStatus,
|
|
||||||
create_dirs: bool,
|
|
||||||
) -> Command {
|
|
||||||
if create_dirs {
|
|
||||||
prepare_sandbox_dirs(cwd);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
|
||||||
let mut prepared = Command::new(launcher.program);
|
|
||||||
prepared.args(launcher.args);
|
|
||||||
prepared.current_dir(cwd);
|
|
||||||
prepared.envs(launcher.env);
|
|
||||||
return prepared;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut prepared = Command::new("sh");
|
|
||||||
prepared.arg("-lc").arg(command).current_dir(cwd);
|
|
||||||
if sandbox_status.filesystem_active {
|
|
||||||
prepared.env("HOME", cwd.join(".sandbox-home"));
|
|
||||||
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
|
||||||
}
|
|
||||||
prepared
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_tokio_command(
|
|
||||||
command: &str,
|
|
||||||
cwd: &std::path::Path,
|
|
||||||
sandbox_status: &SandboxStatus,
|
|
||||||
create_dirs: bool,
|
|
||||||
) -> TokioCommand {
|
|
||||||
if create_dirs {
|
|
||||||
prepare_sandbox_dirs(cwd);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
|
||||||
let mut prepared = TokioCommand::new(launcher.program);
|
|
||||||
prepared.args(launcher.args);
|
|
||||||
prepared.current_dir(cwd);
|
|
||||||
prepared.envs(launcher.env);
|
|
||||||
return prepared;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut prepared = TokioCommand::new("sh");
|
|
||||||
prepared.arg("-lc").arg(command).current_dir(cwd);
|
|
||||||
if sandbox_status.filesystem_active {
|
|
||||||
prepared.env("HOME", cwd.join(".sandbox-home"));
|
|
||||||
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
|
||||||
}
|
|
||||||
prepared
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_sandbox_dirs(cwd: &std::path::Path) {
|
|
||||||
let _ = std::fs::create_dir_all(cwd.join(".sandbox-home"));
|
|
||||||
let _ = std::fs::create_dir_all(cwd.join(".sandbox-tmp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{execute_bash, BashCommandInput};
|
use super::{execute_bash, BashCommandInput};
|
||||||
use crate::sandbox::FilesystemIsolationMode;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn executes_simple_command() {
|
fn executes_simple_command() {
|
||||||
@@ -251,33 +151,10 @@ mod tests {
|
|||||||
description: None,
|
description: None,
|
||||||
run_in_background: Some(false),
|
run_in_background: Some(false),
|
||||||
dangerously_disable_sandbox: Some(false),
|
dangerously_disable_sandbox: Some(false),
|
||||||
namespace_restrictions: Some(false),
|
|
||||||
isolate_network: Some(false),
|
|
||||||
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
|
||||||
allowed_mounts: None,
|
|
||||||
})
|
})
|
||||||
.expect("bash command should execute");
|
.expect("bash command should execute");
|
||||||
|
|
||||||
assert_eq!(output.stdout, "hello");
|
assert_eq!(output.stdout, "hello");
|
||||||
assert!(!output.interrupted);
|
assert!(!output.interrupted);
|
||||||
assert!(output.sandbox_status.is_some());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn disables_sandbox_when_requested() {
|
|
||||||
let output = execute_bash(BashCommandInput {
|
|
||||||
command: String::from("printf 'hello'"),
|
|
||||||
timeout: Some(1_000),
|
|
||||||
description: None,
|
|
||||||
run_in_background: Some(false),
|
|
||||||
dangerously_disable_sandbox: Some(true),
|
|
||||||
namespace_restrictions: None,
|
|
||||||
isolate_network: None,
|
|
||||||
filesystem_mode: None,
|
|
||||||
allowed_mounts: None,
|
|
||||||
})
|
|
||||||
.expect("bash command should execute");
|
|
||||||
|
|
||||||
assert!(!output.sandbox_status.expect("sandbox status").enabled);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ use std::fs;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
|
||||||
|
|
||||||
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
||||||
|
|
||||||
@@ -41,7 +40,6 @@ pub struct RuntimeFeatureConfig {
|
|||||||
oauth: Option<OAuthConfig>,
|
oauth: Option<OAuthConfig>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
permission_mode: Option<ResolvedPermissionMode>,
|
permission_mode: Option<ResolvedPermissionMode>,
|
||||||
sandbox: SandboxConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@@ -227,7 +225,6 @@ impl ConfigLoader {
|
|||||||
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
||||||
model: parse_optional_model(&merged_value),
|
model: parse_optional_model(&merged_value),
|
||||||
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
||||||
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(RuntimeConfig {
|
Ok(RuntimeConfig {
|
||||||
@@ -292,11 +289,6 @@ impl RuntimeConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.feature_config.permission_mode
|
self.feature_config.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn sandbox(&self) -> &SandboxConfig {
|
|
||||||
&self.feature_config.sandbox
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeFeatureConfig {
|
impl RuntimeFeatureConfig {
|
||||||
@@ -319,11 +311,6 @@ impl RuntimeFeatureConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.permission_mode
|
self.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn sandbox(&self) -> &SandboxConfig {
|
|
||||||
&self.sandbox
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl McpConfigCollection {
|
impl McpConfigCollection {
|
||||||
@@ -458,42 +445,6 @@ fn parse_permission_mode_label(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_optional_sandbox_config(root: &JsonValue) -> Result<SandboxConfig, ConfigError> {
|
|
||||||
let Some(object) = root.as_object() else {
|
|
||||||
return Ok(SandboxConfig::default());
|
|
||||||
};
|
|
||||||
let Some(sandbox_value) = object.get("sandbox") else {
|
|
||||||
return Ok(SandboxConfig::default());
|
|
||||||
};
|
|
||||||
let sandbox = expect_object(sandbox_value, "merged settings.sandbox")?;
|
|
||||||
let filesystem_mode = optional_string(sandbox, "filesystemMode", "merged settings.sandbox")?
|
|
||||||
.map(parse_filesystem_mode_label)
|
|
||||||
.transpose()?;
|
|
||||||
Ok(SandboxConfig {
|
|
||||||
enabled: optional_bool(sandbox, "enabled", "merged settings.sandbox")?,
|
|
||||||
namespace_restrictions: optional_bool(
|
|
||||||
sandbox,
|
|
||||||
"namespaceRestrictions",
|
|
||||||
"merged settings.sandbox",
|
|
||||||
)?,
|
|
||||||
network_isolation: optional_bool(sandbox, "networkIsolation", "merged settings.sandbox")?,
|
|
||||||
filesystem_mode,
|
|
||||||
allowed_mounts: optional_string_array(sandbox, "allowedMounts", "merged settings.sandbox")?
|
|
||||||
.unwrap_or_default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_filesystem_mode_label(value: &str) -> Result<FilesystemIsolationMode, ConfigError> {
|
|
||||||
match value {
|
|
||||||
"off" => Ok(FilesystemIsolationMode::Off),
|
|
||||||
"workspace-only" => Ok(FilesystemIsolationMode::WorkspaceOnly),
|
|
||||||
"allow-list" => Ok(FilesystemIsolationMode::AllowList),
|
|
||||||
other => Err(ConfigError::Parse(format!(
|
|
||||||
"merged settings.sandbox.filesystemMode: unsupported filesystem mode {other}"
|
|
||||||
))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_optional_oauth_config(
|
fn parse_optional_oauth_config(
|
||||||
root: &JsonValue,
|
root: &JsonValue,
|
||||||
context: &str,
|
context: &str,
|
||||||
@@ -737,7 +688,6 @@ mod tests {
|
|||||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
||||||
};
|
};
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
use crate::sandbox::FilesystemIsolationMode;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
@@ -842,44 +792,6 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_sandbox_config() {
|
|
||||||
let root = temp_dir();
|
|
||||||
let cwd = root.join("project");
|
|
||||||
let home = root.join("home").join(".claude");
|
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
|
||||||
|
|
||||||
fs::write(
|
|
||||||
cwd.join(".claude").join("settings.local.json"),
|
|
||||||
r#"{
|
|
||||||
"sandbox": {
|
|
||||||
"enabled": true,
|
|
||||||
"namespaceRestrictions": false,
|
|
||||||
"networkIsolation": true,
|
|
||||||
"filesystemMode": "allow-list",
|
|
||||||
"allowedMounts": ["logs", "tmp/cache"]
|
|
||||||
}
|
|
||||||
}"#,
|
|
||||||
)
|
|
||||||
.expect("write local settings");
|
|
||||||
|
|
||||||
let loaded = ConfigLoader::new(&cwd, &home)
|
|
||||||
.load()
|
|
||||||
.expect("config should load");
|
|
||||||
|
|
||||||
assert_eq!(loaded.sandbox().enabled, Some(true));
|
|
||||||
assert_eq!(loaded.sandbox().namespace_restrictions, Some(false));
|
|
||||||
assert_eq!(loaded.sandbox().network_isolation, Some(true));
|
|
||||||
assert_eq!(
|
|
||||||
loaded.sandbox().filesystem_mode,
|
|
||||||
Some(FilesystemIsolationMode::AllowList)
|
|
||||||
);
|
|
||||||
assert_eq!(loaded.sandbox().allowed_mounts, vec!["logs", "tmp/cache"]);
|
|
||||||
|
|
||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_typed_mcp_and_oauth_config() {
|
fn parses_typed_mcp_and_oauth_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
|
|||||||
@@ -414,6 +414,7 @@ mod tests {
|
|||||||
cwd: PathBuf::from("/tmp/project"),
|
cwd: PathBuf::from("/tmp/project"),
|
||||||
current_date: "2026-03-31".to_string(),
|
current_date: "2026-03-31".to_string(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
|
git_diff: None,
|
||||||
instruction_files: Vec::new(),
|
instruction_files: Vec::new(),
|
||||||
})
|
})
|
||||||
.with_os("linux", "6.8")
|
.with_os("linux", "6.8")
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ mod oauth;
|
|||||||
mod permissions;
|
mod permissions;
|
||||||
mod prompt;
|
mod prompt;
|
||||||
mod remote;
|
mod remote;
|
||||||
mod sandbox;
|
|
||||||
mod session;
|
mod session;
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
@@ -74,12 +73,6 @@ pub use remote::{
|
|||||||
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
|
||||||
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
|
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
|
||||||
};
|
};
|
||||||
pub use 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, SessionError};
|
||||||
pub use usage::{
|
pub use usage::{
|
||||||
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ pub enum PermissionMode {
|
|||||||
ReadOnly,
|
ReadOnly,
|
||||||
WorkspaceWrite,
|
WorkspaceWrite,
|
||||||
DangerFullAccess,
|
DangerFullAccess,
|
||||||
Prompt,
|
|
||||||
Allow,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PermissionMode {
|
impl PermissionMode {
|
||||||
@@ -16,8 +14,6 @@ impl PermissionMode {
|
|||||||
Self::ReadOnly => "read-only",
|
Self::ReadOnly => "read-only",
|
||||||
Self::WorkspaceWrite => "workspace-write",
|
Self::WorkspaceWrite => "workspace-write",
|
||||||
Self::DangerFullAccess => "danger-full-access",
|
Self::DangerFullAccess => "danger-full-access",
|
||||||
Self::Prompt => "prompt",
|
|
||||||
Self::Allow => "allow",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,7 +90,7 @@ impl PermissionPolicy {
|
|||||||
) -> PermissionOutcome {
|
) -> PermissionOutcome {
|
||||||
let current_mode = self.active_mode();
|
let current_mode = self.active_mode();
|
||||||
let required_mode = self.required_mode_for(tool_name);
|
let required_mode = self.required_mode_for(tool_name);
|
||||||
if current_mode == PermissionMode::Allow || current_mode >= required_mode {
|
if current_mode >= required_mode {
|
||||||
return PermissionOutcome::Allow;
|
return PermissionOutcome::Allow;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,9 +101,8 @@ impl PermissionPolicy {
|
|||||||
required_mode,
|
required_mode,
|
||||||
};
|
};
|
||||||
|
|
||||||
if current_mode == PermissionMode::Prompt
|
if current_mode == PermissionMode::WorkspaceWrite
|
||||||
|| (current_mode == PermissionMode::WorkspaceWrite
|
&& required_mode == PermissionMode::DangerFullAccess
|
||||||
&& required_mode == PermissionMode::DangerFullAccess)
|
|
||||||
{
|
{
|
||||||
return match prompter.as_mut() {
|
return match prompter.as_mut() {
|
||||||
Some(prompter) => match prompter.decide(&request) {
|
Some(prompter) => match prompter.decide(&request) {
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ pub struct ProjectContext {
|
|||||||
pub cwd: PathBuf,
|
pub cwd: PathBuf,
|
||||||
pub current_date: String,
|
pub current_date: String,
|
||||||
pub git_status: Option<String>,
|
pub git_status: Option<String>,
|
||||||
|
pub git_diff: Option<String>,
|
||||||
pub instruction_files: Vec<ContextFile>,
|
pub instruction_files: Vec<ContextFile>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,6 +65,7 @@ impl ProjectContext {
|
|||||||
cwd,
|
cwd,
|
||||||
current_date: current_date.into(),
|
current_date: current_date.into(),
|
||||||
git_status: None,
|
git_status: None,
|
||||||
|
git_diff: None,
|
||||||
instruction_files,
|
instruction_files,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -74,6 +76,7 @@ impl ProjectContext {
|
|||||||
) -> std::io::Result<Self> {
|
) -> std::io::Result<Self> {
|
||||||
let mut context = Self::discover(cwd, current_date)?;
|
let mut context = Self::discover(cwd, current_date)?;
|
||||||
context.git_status = read_git_status(&context.cwd);
|
context.git_status = read_git_status(&context.cwd);
|
||||||
|
context.git_diff = read_git_diff(&context.cwd);
|
||||||
Ok(context)
|
Ok(context)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -239,6 +242,38 @@ fn read_git_status(cwd: &Path) -> Option<String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn read_git_diff(cwd: &Path) -> Option<String> {
|
||||||
|
let mut sections = Vec::new();
|
||||||
|
|
||||||
|
let staged = read_git_output(cwd, &["diff", "--cached"])?;
|
||||||
|
if !staged.trim().is_empty() {
|
||||||
|
sections.push(format!("Staged changes:\n{}", staged.trim_end()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let unstaged = read_git_output(cwd, &["diff"])?;
|
||||||
|
if !unstaged.trim().is_empty() {
|
||||||
|
sections.push(format!("Unstaged changes:\n{}", unstaged.trim_end()));
|
||||||
|
}
|
||||||
|
|
||||||
|
if sections.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(sections.join("\n\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_git_output(cwd: &Path, args: &[&str]) -> Option<String> {
|
||||||
|
let output = Command::new("git")
|
||||||
|
.args(args)
|
||||||
|
.current_dir(cwd)
|
||||||
|
.output()
|
||||||
|
.ok()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
String::from_utf8(output.stdout).ok()
|
||||||
|
}
|
||||||
|
|
||||||
fn render_project_context(project_context: &ProjectContext) -> String {
|
fn render_project_context(project_context: &ProjectContext) -> String {
|
||||||
let mut lines = vec!["# Project context".to_string()];
|
let mut lines = vec!["# Project context".to_string()];
|
||||||
let mut bullets = vec![
|
let mut bullets = vec![
|
||||||
@@ -257,6 +292,11 @@ fn render_project_context(project_context: &ProjectContext) -> String {
|
|||||||
lines.push("Git status snapshot:".to_string());
|
lines.push("Git status snapshot:".to_string());
|
||||||
lines.push(status.clone());
|
lines.push(status.clone());
|
||||||
}
|
}
|
||||||
|
if let Some(diff) = &project_context.git_diff {
|
||||||
|
lines.push(String::new());
|
||||||
|
lines.push("Git diff snapshot:".to_string());
|
||||||
|
lines.push(diff.clone());
|
||||||
|
}
|
||||||
lines.join("\n")
|
lines.join("\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -577,6 +617,49 @@ mod tests {
|
|||||||
assert!(status.contains("## No commits yet on") || status.contains("## "));
|
assert!(status.contains("## No commits yet on") || status.contains("## "));
|
||||||
assert!(status.contains("?? CLAUDE.md"));
|
assert!(status.contains("?? CLAUDE.md"));
|
||||||
assert!(status.contains("?? tracked.txt"));
|
assert!(status.contains("?? tracked.txt"));
|
||||||
|
assert!(context.git_diff.is_none());
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn discover_with_git_includes_diff_snapshot_for_tracked_changes() {
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
|
std::process::Command::new("git")
|
||||||
|
.args(["init", "--quiet"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.status()
|
||||||
|
.expect("git init should run");
|
||||||
|
std::process::Command::new("git")
|
||||||
|
.args(["config", "user.email", "tests@example.com"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.status()
|
||||||
|
.expect("git config email should run");
|
||||||
|
std::process::Command::new("git")
|
||||||
|
.args(["config", "user.name", "Runtime Prompt Tests"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.status()
|
||||||
|
.expect("git config name should run");
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked file");
|
||||||
|
std::process::Command::new("git")
|
||||||
|
.args(["add", "tracked.txt"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.status()
|
||||||
|
.expect("git add should run");
|
||||||
|
std::process::Command::new("git")
|
||||||
|
.args(["commit", "-m", "init", "--quiet"])
|
||||||
|
.current_dir(&root)
|
||||||
|
.status()
|
||||||
|
.expect("git commit should run");
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("rewrite tracked file");
|
||||||
|
|
||||||
|
let context =
|
||||||
|
ProjectContext::discover_with_git(&root, "2026-03-31").expect("context should load");
|
||||||
|
|
||||||
|
let diff = context.git_diff.expect("git diff should be present");
|
||||||
|
assert!(diff.contains("Unstaged changes:"));
|
||||||
|
assert!(diff.contains("tracked.txt"));
|
||||||
|
|
||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,364 +0,0 @@
|
|||||||
use std::env;
|
|
||||||
use std::fs;
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
|
||||||
#[serde(rename_all = "kebab-case")]
|
|
||||||
pub enum FilesystemIsolationMode {
|
|
||||||
Off,
|
|
||||||
#[default]
|
|
||||||
WorkspaceOnly,
|
|
||||||
AllowList,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FilesystemIsolationMode {
|
|
||||||
#[must_use]
|
|
||||||
pub fn as_str(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Self::Off => "off",
|
|
||||||
Self::WorkspaceOnly => "workspace-only",
|
|
||||||
Self::AllowList => "allow-list",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
|
||||||
pub struct SandboxConfig {
|
|
||||||
pub enabled: Option<bool>,
|
|
||||||
pub namespace_restrictions: Option<bool>,
|
|
||||||
pub network_isolation: Option<bool>,
|
|
||||||
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
|
||||||
pub allowed_mounts: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
|
||||||
pub struct SandboxRequest {
|
|
||||||
pub enabled: bool,
|
|
||||||
pub namespace_restrictions: bool,
|
|
||||||
pub network_isolation: bool,
|
|
||||||
pub filesystem_mode: FilesystemIsolationMode,
|
|
||||||
pub allowed_mounts: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
|
||||||
pub struct ContainerEnvironment {
|
|
||||||
pub in_container: bool,
|
|
||||||
pub markers: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::struct_excessive_bools)]
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
|
||||||
pub struct SandboxStatus {
|
|
||||||
pub enabled: bool,
|
|
||||||
pub requested: SandboxRequest,
|
|
||||||
pub supported: bool,
|
|
||||||
pub active: bool,
|
|
||||||
pub namespace_supported: bool,
|
|
||||||
pub namespace_active: bool,
|
|
||||||
pub network_supported: bool,
|
|
||||||
pub network_active: bool,
|
|
||||||
pub filesystem_mode: FilesystemIsolationMode,
|
|
||||||
pub filesystem_active: bool,
|
|
||||||
pub allowed_mounts: Vec<String>,
|
|
||||||
pub in_container: bool,
|
|
||||||
pub container_markers: Vec<String>,
|
|
||||||
pub fallback_reason: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct SandboxDetectionInputs<'a> {
|
|
||||||
pub env_pairs: Vec<(String, String)>,
|
|
||||||
pub dockerenv_exists: bool,
|
|
||||||
pub containerenv_exists: bool,
|
|
||||||
pub proc_1_cgroup: Option<&'a str>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct LinuxSandboxCommand {
|
|
||||||
pub program: String,
|
|
||||||
pub args: Vec<String>,
|
|
||||||
pub env: Vec<(String, String)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SandboxConfig {
|
|
||||||
#[must_use]
|
|
||||||
pub fn resolve_request(
|
|
||||||
&self,
|
|
||||||
enabled_override: Option<bool>,
|
|
||||||
namespace_override: Option<bool>,
|
|
||||||
network_override: Option<bool>,
|
|
||||||
filesystem_mode_override: Option<FilesystemIsolationMode>,
|
|
||||||
allowed_mounts_override: Option<Vec<String>>,
|
|
||||||
) -> SandboxRequest {
|
|
||||||
SandboxRequest {
|
|
||||||
enabled: enabled_override.unwrap_or(self.enabled.unwrap_or(true)),
|
|
||||||
namespace_restrictions: namespace_override
|
|
||||||
.unwrap_or(self.namespace_restrictions.unwrap_or(true)),
|
|
||||||
network_isolation: network_override.unwrap_or(self.network_isolation.unwrap_or(false)),
|
|
||||||
filesystem_mode: filesystem_mode_override
|
|
||||||
.or(self.filesystem_mode)
|
|
||||||
.unwrap_or_default(),
|
|
||||||
allowed_mounts: allowed_mounts_override.unwrap_or_else(|| self.allowed_mounts.clone()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn detect_container_environment() -> ContainerEnvironment {
|
|
||||||
let proc_1_cgroup = fs::read_to_string("/proc/1/cgroup").ok();
|
|
||||||
detect_container_environment_from(SandboxDetectionInputs {
|
|
||||||
env_pairs: env::vars().collect(),
|
|
||||||
dockerenv_exists: Path::new("/.dockerenv").exists(),
|
|
||||||
containerenv_exists: Path::new("/run/.containerenv").exists(),
|
|
||||||
proc_1_cgroup: proc_1_cgroup.as_deref(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn detect_container_environment_from(
|
|
||||||
inputs: SandboxDetectionInputs<'_>,
|
|
||||||
) -> ContainerEnvironment {
|
|
||||||
let mut markers = Vec::new();
|
|
||||||
if inputs.dockerenv_exists {
|
|
||||||
markers.push("/.dockerenv".to_string());
|
|
||||||
}
|
|
||||||
if inputs.containerenv_exists {
|
|
||||||
markers.push("/run/.containerenv".to_string());
|
|
||||||
}
|
|
||||||
for (key, value) in inputs.env_pairs {
|
|
||||||
let normalized = key.to_ascii_lowercase();
|
|
||||||
if matches!(
|
|
||||||
normalized.as_str(),
|
|
||||||
"container" | "docker" | "podman" | "kubernetes_service_host"
|
|
||||||
) && !value.is_empty()
|
|
||||||
{
|
|
||||||
markers.push(format!("env:{key}={value}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(cgroup) = inputs.proc_1_cgroup {
|
|
||||||
for needle in ["docker", "containerd", "kubepods", "podman", "libpod"] {
|
|
||||||
if cgroup.contains(needle) {
|
|
||||||
markers.push(format!("/proc/1/cgroup:{needle}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
markers.sort();
|
|
||||||
markers.dedup();
|
|
||||||
ContainerEnvironment {
|
|
||||||
in_container: !markers.is_empty(),
|
|
||||||
markers,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn resolve_sandbox_status(config: &SandboxConfig, cwd: &Path) -> SandboxStatus {
|
|
||||||
let request = config.resolve_request(None, None, None, None, None);
|
|
||||||
resolve_sandbox_status_for_request(&request, cwd)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn resolve_sandbox_status_for_request(request: &SandboxRequest, cwd: &Path) -> SandboxStatus {
|
|
||||||
let container = detect_container_environment();
|
|
||||||
let namespace_supported = cfg!(target_os = "linux") && command_exists("unshare");
|
|
||||||
let network_supported = namespace_supported;
|
|
||||||
let filesystem_active =
|
|
||||||
request.enabled && request.filesystem_mode != FilesystemIsolationMode::Off;
|
|
||||||
let mut fallback_reasons = Vec::new();
|
|
||||||
|
|
||||||
if request.enabled && request.namespace_restrictions && !namespace_supported {
|
|
||||||
fallback_reasons
|
|
||||||
.push("namespace isolation unavailable (requires Linux with `unshare`)".to_string());
|
|
||||||
}
|
|
||||||
if request.enabled && request.network_isolation && !network_supported {
|
|
||||||
fallback_reasons
|
|
||||||
.push("network isolation unavailable (requires Linux with `unshare`)".to_string());
|
|
||||||
}
|
|
||||||
if request.enabled
|
|
||||||
&& request.filesystem_mode == FilesystemIsolationMode::AllowList
|
|
||||||
&& request.allowed_mounts.is_empty()
|
|
||||||
{
|
|
||||||
fallback_reasons
|
|
||||||
.push("filesystem allow-list requested without configured mounts".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
let active = request.enabled
|
|
||||||
&& (!request.namespace_restrictions || namespace_supported)
|
|
||||||
&& (!request.network_isolation || network_supported);
|
|
||||||
|
|
||||||
let allowed_mounts = normalize_mounts(&request.allowed_mounts, cwd);
|
|
||||||
|
|
||||||
SandboxStatus {
|
|
||||||
enabled: request.enabled,
|
|
||||||
requested: request.clone(),
|
|
||||||
supported: namespace_supported,
|
|
||||||
active,
|
|
||||||
namespace_supported,
|
|
||||||
namespace_active: request.enabled && request.namespace_restrictions && namespace_supported,
|
|
||||||
network_supported,
|
|
||||||
network_active: request.enabled && request.network_isolation && network_supported,
|
|
||||||
filesystem_mode: request.filesystem_mode,
|
|
||||||
filesystem_active,
|
|
||||||
allowed_mounts,
|
|
||||||
in_container: container.in_container,
|
|
||||||
container_markers: container.markers,
|
|
||||||
fallback_reason: (!fallback_reasons.is_empty()).then(|| fallback_reasons.join("; ")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn build_linux_sandbox_command(
|
|
||||||
command: &str,
|
|
||||||
cwd: &Path,
|
|
||||||
status: &SandboxStatus,
|
|
||||||
) -> Option<LinuxSandboxCommand> {
|
|
||||||
if !cfg!(target_os = "linux")
|
|
||||||
|| !status.enabled
|
|
||||||
|| (!status.namespace_active && !status.network_active)
|
|
||||||
{
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut args = vec![
|
|
||||||
"--user".to_string(),
|
|
||||||
"--map-root-user".to_string(),
|
|
||||||
"--mount".to_string(),
|
|
||||||
"--ipc".to_string(),
|
|
||||||
"--pid".to_string(),
|
|
||||||
"--uts".to_string(),
|
|
||||||
"--fork".to_string(),
|
|
||||||
];
|
|
||||||
if status.network_active {
|
|
||||||
args.push("--net".to_string());
|
|
||||||
}
|
|
||||||
args.push("sh".to_string());
|
|
||||||
args.push("-lc".to_string());
|
|
||||||
args.push(command.to_string());
|
|
||||||
|
|
||||||
let sandbox_home = cwd.join(".sandbox-home");
|
|
||||||
let sandbox_tmp = cwd.join(".sandbox-tmp");
|
|
||||||
let mut env = vec![
|
|
||||||
("HOME".to_string(), sandbox_home.display().to_string()),
|
|
||||||
("TMPDIR".to_string(), sandbox_tmp.display().to_string()),
|
|
||||||
(
|
|
||||||
"CLAWD_SANDBOX_FILESYSTEM_MODE".to_string(),
|
|
||||||
status.filesystem_mode.as_str().to_string(),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"CLAWD_SANDBOX_ALLOWED_MOUNTS".to_string(),
|
|
||||||
status.allowed_mounts.join(":"),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
if let Ok(path) = env::var("PATH") {
|
|
||||||
env.push(("PATH".to_string(), path));
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(LinuxSandboxCommand {
|
|
||||||
program: "unshare".to_string(),
|
|
||||||
args,
|
|
||||||
env,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn normalize_mounts(mounts: &[String], cwd: &Path) -> Vec<String> {
|
|
||||||
let cwd = cwd.to_path_buf();
|
|
||||||
mounts
|
|
||||||
.iter()
|
|
||||||
.map(|mount| {
|
|
||||||
let path = PathBuf::from(mount);
|
|
||||||
if path.is_absolute() {
|
|
||||||
path
|
|
||||||
} else {
|
|
||||||
cwd.join(path)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.map(|path| path.display().to_string())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn command_exists(command: &str) -> bool {
|
|
||||||
env::var_os("PATH")
|
|
||||||
.is_some_and(|paths| env::split_paths(&paths).any(|path| path.join(command).exists()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::{
|
|
||||||
build_linux_sandbox_command, detect_container_environment_from, FilesystemIsolationMode,
|
|
||||||
SandboxConfig, SandboxDetectionInputs,
|
|
||||||
};
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn detects_container_markers_from_multiple_sources() {
|
|
||||||
let detected = detect_container_environment_from(SandboxDetectionInputs {
|
|
||||||
env_pairs: vec![("container".to_string(), "docker".to_string())],
|
|
||||||
dockerenv_exists: true,
|
|
||||||
containerenv_exists: false,
|
|
||||||
proc_1_cgroup: Some("12:memory:/docker/abc"),
|
|
||||||
});
|
|
||||||
|
|
||||||
assert!(detected.in_container);
|
|
||||||
assert!(detected
|
|
||||||
.markers
|
|
||||||
.iter()
|
|
||||||
.any(|marker| marker == "/.dockerenv"));
|
|
||||||
assert!(detected
|
|
||||||
.markers
|
|
||||||
.iter()
|
|
||||||
.any(|marker| marker == "env:container=docker"));
|
|
||||||
assert!(detected
|
|
||||||
.markers
|
|
||||||
.iter()
|
|
||||||
.any(|marker| marker == "/proc/1/cgroup:docker"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn resolves_request_with_overrides() {
|
|
||||||
let config = SandboxConfig {
|
|
||||||
enabled: Some(true),
|
|
||||||
namespace_restrictions: Some(true),
|
|
||||||
network_isolation: Some(false),
|
|
||||||
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
|
||||||
allowed_mounts: vec!["logs".to_string()],
|
|
||||||
};
|
|
||||||
|
|
||||||
let request = config.resolve_request(
|
|
||||||
Some(true),
|
|
||||||
Some(false),
|
|
||||||
Some(true),
|
|
||||||
Some(FilesystemIsolationMode::AllowList),
|
|
||||||
Some(vec!["tmp".to_string()]),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(request.enabled);
|
|
||||||
assert!(!request.namespace_restrictions);
|
|
||||||
assert!(request.network_isolation);
|
|
||||||
assert_eq!(request.filesystem_mode, FilesystemIsolationMode::AllowList);
|
|
||||||
assert_eq!(request.allowed_mounts, vec!["tmp"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn builds_linux_launcher_with_network_flag_when_requested() {
|
|
||||||
let config = SandboxConfig::default();
|
|
||||||
let status = super::resolve_sandbox_status_for_request(
|
|
||||||
&config.resolve_request(
|
|
||||||
Some(true),
|
|
||||||
Some(true),
|
|
||||||
Some(true),
|
|
||||||
Some(FilesystemIsolationMode::WorkspaceOnly),
|
|
||||||
None,
|
|
||||||
),
|
|
||||||
Path::new("/workspace"),
|
|
||||||
);
|
|
||||||
|
|
||||||
if let Some(launcher) =
|
|
||||||
build_linux_sandbox_command("printf hi", Path::new("/workspace"), &status)
|
|
||||||
{
|
|
||||||
assert_eq!(launcher.program, "unshare");
|
|
||||||
assert!(launcher.args.iter().any(|arg| arg == "--mount"));
|
|
||||||
assert!(launcher.args.iter().any(|arg| arg == "--net") == status.network_active);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,8 +23,8 @@ use compat_harness::{extract_manifest, UpstreamPaths};
|
|||||||
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,
|
||||||
parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
|
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
||||||
ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
||||||
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
||||||
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
||||||
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
||||||
@@ -591,7 +591,6 @@ struct StatusContext {
|
|||||||
memory_file_count: usize,
|
memory_file_count: usize,
|
||||||
project_root: Option<PathBuf>,
|
project_root: Option<PathBuf>,
|
||||||
git_branch: Option<String>,
|
git_branch: Option<String>,
|
||||||
sandbox_status: runtime::SandboxStatus,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
@@ -743,27 +742,61 @@ fn format_compact_report(removed: usize, resulting_messages: usize, skipped: boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
|
fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
|
||||||
let Some(status) = status else {
|
parse_git_status_metadata_for(
|
||||||
return (None, None);
|
&env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
|
||||||
};
|
status,
|
||||||
let branch = status.lines().next().and_then(|line| {
|
)
|
||||||
line.strip_prefix("## ")
|
|
||||||
.map(|line| {
|
|
||||||
line.split(['.', ' '])
|
|
||||||
.next()
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_string()
|
|
||||||
})
|
|
||||||
.filter(|value| !value.is_empty())
|
|
||||||
});
|
|
||||||
let project_root = find_git_root().ok();
|
|
||||||
(project_root, branch)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_git_root() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
fn parse_git_status_branch(status: Option<&str>) -> Option<String> {
|
||||||
|
let status = status?;
|
||||||
|
let first_line = status.lines().next()?;
|
||||||
|
let line = first_line.strip_prefix("## ")?;
|
||||||
|
if line.starts_with("HEAD") {
|
||||||
|
return Some("detached HEAD".to_string());
|
||||||
|
}
|
||||||
|
let branch = line.split(['.', ' ']).next().unwrap_or_default().trim();
|
||||||
|
if branch.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(branch.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_git_branch_for(cwd: &Path) -> Option<String> {
|
||||||
|
let branch = run_git_capture_in(cwd, &["branch", "--show-current"])?;
|
||||||
|
let branch = branch.trim();
|
||||||
|
if !branch.is_empty() {
|
||||||
|
return Some(branch.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let fallback = run_git_capture_in(cwd, &["rev-parse", "--abbrev-ref", "HEAD"])?;
|
||||||
|
let fallback = fallback.trim();
|
||||||
|
if fallback.is_empty() {
|
||||||
|
None
|
||||||
|
} else if fallback == "HEAD" {
|
||||||
|
Some("detached HEAD".to_string())
|
||||||
|
} else {
|
||||||
|
Some(fallback.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_git_capture_in(cwd: &Path, args: &[&str]) -> Option<String> {
|
||||||
|
let output = std::process::Command::new("git")
|
||||||
|
.args(args)
|
||||||
|
.current_dir(cwd)
|
||||||
|
.output()
|
||||||
|
.ok()?;
|
||||||
|
if !output.status.success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
String::from_utf8(output.stdout).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_git_root_in(cwd: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||||
let output = std::process::Command::new("git")
|
let output = std::process::Command::new("git")
|
||||||
.args(["rev-parse", "--show-toplevel"])
|
.args(["rev-parse", "--show-toplevel"])
|
||||||
.current_dir(env::current_dir()?)
|
.current_dir(cwd)
|
||||||
.output()?;
|
.output()?;
|
||||||
if !output.status.success() {
|
if !output.status.success() {
|
||||||
return Err("not a git repository".into());
|
return Err("not a git repository".into());
|
||||||
@@ -775,6 +808,15 @@ fn find_git_root() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
|||||||
Ok(PathBuf::from(path))
|
Ok(PathBuf::from(path))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn parse_git_status_metadata_for(
|
||||||
|
cwd: &Path,
|
||||||
|
status: Option<&str>,
|
||||||
|
) -> (Option<PathBuf>, Option<String>) {
|
||||||
|
let branch = resolve_git_branch_for(cwd).or_else(|| parse_git_status_branch(status));
|
||||||
|
let project_root = find_git_root_in(cwd).ok();
|
||||||
|
(project_root, branch)
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
#[allow(clippy::too_many_lines)]
|
||||||
fn run_resume_command(
|
fn run_resume_command(
|
||||||
session_path: &Path,
|
session_path: &Path,
|
||||||
@@ -841,18 +883,6 @@ fn run_resume_command(
|
|||||||
)),
|
)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
SlashCommand::Sandbox => {
|
|
||||||
let cwd = env::current_dir()?;
|
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
|
||||||
let runtime_config = loader.load()?;
|
|
||||||
Ok(ResumeCommandOutcome {
|
|
||||||
session: session.clone(),
|
|
||||||
message: Some(format_sandbox_report(&resolve_sandbox_status(
|
|
||||||
runtime_config.sandbox(),
|
|
||||||
&cwd,
|
|
||||||
))),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
SlashCommand::Cost => {
|
SlashCommand::Cost => {
|
||||||
let usage = UsageTracker::from_session(session).cumulative_usage();
|
let usage = UsageTracker::from_session(session).cumulative_usage();
|
||||||
Ok(ResumeCommandOutcome {
|
Ok(ResumeCommandOutcome {
|
||||||
@@ -874,7 +904,9 @@ fn run_resume_command(
|
|||||||
}),
|
}),
|
||||||
SlashCommand::Diff => Ok(ResumeCommandOutcome {
|
SlashCommand::Diff => Ok(ResumeCommandOutcome {
|
||||||
session: session.clone(),
|
session: session.clone(),
|
||||||
message: Some(render_diff_report()?),
|
message: Some(render_diff_report_for(
|
||||||
|
session_path.parent().unwrap_or_else(|| Path::new(".")),
|
||||||
|
)?),
|
||||||
}),
|
}),
|
||||||
SlashCommand::Version => Ok(ResumeCommandOutcome {
|
SlashCommand::Version => Ok(ResumeCommandOutcome {
|
||||||
session: session.clone(),
|
session: session.clone(),
|
||||||
@@ -1104,10 +1136,6 @@ impl LiveCli {
|
|||||||
self.print_status();
|
self.print_status();
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Sandbox => {
|
|
||||||
Self::print_sandbox_status();
|
|
||||||
false
|
|
||||||
}
|
|
||||||
SlashCommand::Compact => {
|
SlashCommand::Compact => {
|
||||||
self.compact()?;
|
self.compact()?;
|
||||||
false
|
false
|
||||||
@@ -1179,18 +1207,6 @@ impl LiveCli {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_sandbox_status() {
|
|
||||||
let cwd = env::current_dir().expect("current dir");
|
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
|
||||||
let runtime_config = loader
|
|
||||||
.load()
|
|
||||||
.unwrap_or_else(|_| runtime::RuntimeConfig::empty());
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
format_sandbox_report(&resolve_sandbox_status(runtime_config.sandbox(), &cwd))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
|
fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
let Some(model) = model else {
|
let Some(model) = model else {
|
||||||
println!(
|
println!(
|
||||||
@@ -1566,7 +1582,6 @@ fn status_context(
|
|||||||
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
||||||
let (project_root, git_branch) =
|
let (project_root, git_branch) =
|
||||||
parse_git_status_metadata(project_context.git_status.as_deref());
|
parse_git_status_metadata(project_context.git_status.as_deref());
|
||||||
let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
|
|
||||||
Ok(StatusContext {
|
Ok(StatusContext {
|
||||||
cwd,
|
cwd,
|
||||||
session_path: session_path.map(Path::to_path_buf),
|
session_path: session_path.map(Path::to_path_buf),
|
||||||
@@ -1575,7 +1590,6 @@ fn status_context(
|
|||||||
memory_file_count: project_context.instruction_files.len(),
|
memory_file_count: project_context.instruction_files.len(),
|
||||||
project_root,
|
project_root,
|
||||||
git_branch,
|
git_branch,
|
||||||
sandbox_status,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1628,7 +1642,6 @@ fn format_status_report(
|
|||||||
context.discovered_config_files,
|
context.discovered_config_files,
|
||||||
context.memory_file_count,
|
context.memory_file_count,
|
||||||
),
|
),
|
||||||
format_sandbox_report(&context.sandbox_status),
|
|
||||||
]
|
]
|
||||||
.join(
|
.join(
|
||||||
"
|
"
|
||||||
@@ -1637,49 +1650,6 @@ fn format_status_report(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_sandbox_report(status: &runtime::SandboxStatus) -> String {
|
|
||||||
format!(
|
|
||||||
"Sandbox
|
|
||||||
Enabled {}
|
|
||||||
Active {}
|
|
||||||
Supported {}
|
|
||||||
In container {}
|
|
||||||
Requested ns {}
|
|
||||||
Active ns {}
|
|
||||||
Requested net {}
|
|
||||||
Active net {}
|
|
||||||
Filesystem mode {}
|
|
||||||
Filesystem active {}
|
|
||||||
Allowed mounts {}
|
|
||||||
Markers {}
|
|
||||||
Fallback reason {}",
|
|
||||||
status.enabled,
|
|
||||||
status.active,
|
|
||||||
status.supported,
|
|
||||||
status.in_container,
|
|
||||||
status.requested.namespace_restrictions,
|
|
||||||
status.namespace_active,
|
|
||||||
status.requested.network_isolation,
|
|
||||||
status.network_active,
|
|
||||||
status.filesystem_mode.as_str(),
|
|
||||||
status.filesystem_active,
|
|
||||||
if status.allowed_mounts.is_empty() {
|
|
||||||
"<none>".to_string()
|
|
||||||
} else {
|
|
||||||
status.allowed_mounts.join(", ")
|
|
||||||
},
|
|
||||||
if status.container_markers.is_empty() {
|
|
||||||
"<none>".to_string()
|
|
||||||
} else {
|
|
||||||
status.container_markers.join(", ")
|
|
||||||
},
|
|
||||||
status
|
|
||||||
.fallback_reason
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| "<none>".to_string()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
|
fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let cwd = env::current_dir()?;
|
let cwd = env::current_dir()?;
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
let loader = ConfigLoader::default_for(&cwd);
|
||||||
@@ -1870,22 +1840,43 @@ fn normalize_permission_mode(mode: &str) -> Option<&'static str> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn render_diff_report() -> Result<String, Box<dyn std::error::Error>> {
|
fn render_diff_report() -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let output = std::process::Command::new("git")
|
render_diff_report_for(&env::current_dir()?)
|
||||||
.args(["diff", "--", ":(exclude).omx"])
|
|
||||||
.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 diff failed: {stderr}").into());
|
|
||||||
}
|
}
|
||||||
let diff = String::from_utf8(output.stdout)?;
|
|
||||||
if diff.trim().is_empty() {
|
fn render_diff_report_for(cwd: &Path) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
|
let staged = run_git_diff_command_in(cwd, &["diff", "--cached"])?;
|
||||||
|
let unstaged = run_git_diff_command_in(cwd, &["diff"])?;
|
||||||
|
if staged.trim().is_empty() && unstaged.trim().is_empty() {
|
||||||
return Ok(
|
return Ok(
|
||||||
"Diff\n Result clean working tree\n Detail no current changes"
|
"Diff\n Result clean working tree\n Detail no current changes"
|
||||||
.to_string(),
|
.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 {
|
fn render_version_report() -> String {
|
||||||
@@ -2468,12 +2459,53 @@ mod tests {
|
|||||||
format_model_report, format_model_switch_report, format_permissions_report,
|
format_model_report, format_model_switch_report, format_permissions_report,
|
||||||
format_permissions_switch_report, format_resume_report, format_status_report,
|
format_permissions_switch_report, format_resume_report, format_status_report,
|
||||||
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
|
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
|
||||||
parse_git_status_metadata, render_config_report, render_init_claude_md,
|
parse_git_status_branch, parse_git_status_metadata, render_config_report,
|
||||||
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
|
render_diff_report, render_init_claude_md, render_memory_report, render_repl_help,
|
||||||
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
resume_supported_slash_commands, run_resume_command, status_context, CliAction,
|
||||||
|
CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||||
};
|
};
|
||||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session};
|
||||||
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
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]
|
#[test]
|
||||||
fn defaults_to_repl_when_no_args() {
|
fn defaults_to_repl_when_no_args() {
|
||||||
@@ -2676,7 +2708,6 @@ mod tests {
|
|||||||
assert!(help.contains("REPL"));
|
assert!(help.contains("REPL"));
|
||||||
assert!(help.contains("/help"));
|
assert!(help.contains("/help"));
|
||||||
assert!(help.contains("/status"));
|
assert!(help.contains("/status"));
|
||||||
assert!(help.contains("/sandbox"));
|
|
||||||
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]"));
|
||||||
@@ -2701,8 +2732,8 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
names,
|
names,
|
||||||
vec![
|
vec![
|
||||||
"help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
|
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
|
||||||
"init", "diff", "version", "export",
|
"version", "export",
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2820,7 +2851,6 @@ mod tests {
|
|||||||
memory_file_count: 4,
|
memory_file_count: 4,
|
||||||
project_root: Some(PathBuf::from("/tmp")),
|
project_root: Some(PathBuf::from("/tmp")),
|
||||||
git_branch: Some("main".to_string()),
|
git_branch: Some("main".to_string()),
|
||||||
sandbox_status: runtime::SandboxStatus::default(),
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
assert!(status.contains("Status"));
|
assert!(status.contains("Status"));
|
||||||
@@ -2862,19 +2892,140 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_git_status_metadata() {
|
fn parses_git_status_metadata() {
|
||||||
let (root, branch) = parse_git_status_metadata(Some(
|
let _guard = env_lock();
|
||||||
|
let temp_root = temp_dir();
|
||||||
|
fs::create_dir_all(&temp_root).expect("root dir");
|
||||||
|
let (project_root, branch) = with_current_dir(&temp_root, || {
|
||||||
|
parse_git_status_metadata(Some(
|
||||||
"## rcc/cli...origin/rcc/cli
|
"## rcc/cli...origin/rcc/cli
|
||||||
M src/main.rs",
|
M src/main.rs",
|
||||||
));
|
))
|
||||||
|
});
|
||||||
assert_eq!(branch.as_deref(), Some("rcc/cli"));
|
assert_eq!(branch.as_deref(), Some("rcc/cli"));
|
||||||
let _ = root;
|
assert!(project_root.is_none());
|
||||||
|
fs::remove_dir_all(temp_root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_detached_head_from_status_snapshot() {
|
||||||
|
let _guard = env_lock();
|
||||||
|
assert_eq!(
|
||||||
|
parse_git_status_branch(Some(
|
||||||
|
"## HEAD (no branch)
|
||||||
|
M src/main.rs"
|
||||||
|
)),
|
||||||
|
Some("detached HEAD".to_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_diff_report_shows_clean_tree_for_committed_repo() {
|
||||||
|
let _guard = env_lock();
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
|
git(&["init", "--quiet"], &root);
|
||||||
|
git(&["config", "user.email", "tests@example.com"], &root);
|
||||||
|
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
|
||||||
|
git(&["add", "tracked.txt"], &root);
|
||||||
|
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||||
|
|
||||||
|
let report = with_current_dir(&root, || {
|
||||||
|
render_diff_report().expect("diff report should render")
|
||||||
|
});
|
||||||
|
assert!(report.contains("clean working tree"));
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_diff_report_includes_staged_and_unstaged_sections() {
|
||||||
|
let _guard = env_lock();
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
|
git(&["init", "--quiet"], &root);
|
||||||
|
git(&["config", "user.email", "tests@example.com"], &root);
|
||||||
|
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\n").expect("write file");
|
||||||
|
git(&["add", "tracked.txt"], &root);
|
||||||
|
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||||
|
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\nstaged\n").expect("update file");
|
||||||
|
git(&["add", "tracked.txt"], &root);
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\nstaged\nunstaged\n")
|
||||||
|
.expect("update file twice");
|
||||||
|
|
||||||
|
let report = with_current_dir(&root, || {
|
||||||
|
render_diff_report().expect("diff report should render")
|
||||||
|
});
|
||||||
|
assert!(report.contains("Staged changes:"));
|
||||||
|
assert!(report.contains("Unstaged changes:"));
|
||||||
|
assert!(report.contains("tracked.txt"));
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn render_diff_report_omits_ignored_files() {
|
||||||
|
let _guard = env_lock();
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
|
git(&["init", "--quiet"], &root);
|
||||||
|
git(&["config", "user.email", "tests@example.com"], &root);
|
||||||
|
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||||
|
fs::write(root.join(".gitignore"), ".omx/\nignored.txt\n").expect("write gitignore");
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
|
||||||
|
git(&["add", ".gitignore", "tracked.txt"], &root);
|
||||||
|
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||||
|
fs::create_dir_all(root.join(".omx")).expect("write omx dir");
|
||||||
|
fs::write(root.join(".omx").join("state.json"), "{}").expect("write ignored omx");
|
||||||
|
fs::write(root.join("ignored.txt"), "secret\n").expect("write ignored file");
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("write tracked change");
|
||||||
|
|
||||||
|
let report = with_current_dir(&root, || {
|
||||||
|
render_diff_report().expect("diff report should render")
|
||||||
|
});
|
||||||
|
assert!(report.contains("tracked.txt"));
|
||||||
|
assert!(!report.contains("+++ b/ignored.txt"));
|
||||||
|
assert!(!report.contains("+++ b/.omx/state.json"));
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resume_diff_command_renders_report_for_saved_session() {
|
||||||
|
let _guard = env_lock();
|
||||||
|
let root = temp_dir();
|
||||||
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
|
git(&["init", "--quiet"], &root);
|
||||||
|
git(&["config", "user.email", "tests@example.com"], &root);
|
||||||
|
git(&["config", "user.name", "Rusty Claude Tests"], &root);
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\n").expect("write tracked");
|
||||||
|
git(&["add", "tracked.txt"], &root);
|
||||||
|
git(&["commit", "-m", "init", "--quiet"], &root);
|
||||||
|
fs::write(root.join("tracked.txt"), "hello\nworld\n").expect("modify tracked");
|
||||||
|
let session_path = root.join("session.json");
|
||||||
|
Session::new()
|
||||||
|
.save_to_path(&session_path)
|
||||||
|
.expect("session should save");
|
||||||
|
|
||||||
|
let session = Session::load_from_path(&session_path).expect("session should load");
|
||||||
|
let outcome = with_current_dir(&root, || {
|
||||||
|
run_resume_command(&session_path, &session, &SlashCommand::Diff)
|
||||||
|
.expect("resume diff should work")
|
||||||
|
});
|
||||||
|
let message = outcome.message.expect("diff message should exist");
|
||||||
|
assert!(message.contains("Unstaged changes:"));
|
||||||
|
assert!(message.contains("tracked.txt"));
|
||||||
|
|
||||||
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
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_eq!(context.discovered_config_files, 5);
|
assert!(context.discovered_config_files >= context.loaded_config_files);
|
||||||
assert!(context.loaded_config_files <= context.discovered_config_files);
|
assert!(context.loaded_config_files <= context.discovered_config_files);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2982,17 +3133,3 @@ mod tests {
|
|||||||
assert!(done.contains("contents"));
|
assert!(done.contains("contents"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -62,11 +62,7 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
|||||||
"timeout": { "type": "integer", "minimum": 1 },
|
"timeout": { "type": "integer", "minimum": 1 },
|
||||||
"description": { "type": "string" },
|
"description": { "type": "string" },
|
||||||
"run_in_background": { "type": "boolean" },
|
"run_in_background": { "type": "boolean" },
|
||||||
"dangerouslyDisableSandbox": { "type": "boolean" },
|
"dangerouslyDisableSandbox": { "type": "boolean" }
|
||||||
"namespaceRestrictions": { "type": "boolean" },
|
|
||||||
"isolateNetwork": { "type": "boolean" },
|
|
||||||
"filesystemMode": { "type": "string", "enum": ["off", "workspace-only", "allow-list"] },
|
|
||||||
"allowedMounts": { "type": "array", "items": { "type": "string" } }
|
|
||||||
},
|
},
|
||||||
"required": ["command"],
|
"required": ["command"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@@ -2218,7 +2214,6 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2256,7 +2251,6 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
||||||
@@ -2287,7 +2281,6 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
std::thread::sleep(Duration::from_millis(10));
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
@@ -2314,7 +2307,6 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user