1 Commits

Author SHA1 Message Date
Yeachan-Heo
2d09bf9961 Make sandbox isolation behavior explicit and inspectable
This adds a small runtime sandbox policy/status layer, threads
sandbox options through the bash tool, and exposes `/sandbox`
status reporting in the CLI. Linux namespace/network isolation
is best-effort and intentionally reported as requested vs active
so the feature does not overclaim guarantees on unsupported
hosts or nested container environments.

Constraint: No new dependencies for isolation support
Constraint: Must keep filesystem restriction claims honest unless hard mount isolation succeeds
Rejected: External sandbox/container wrapper | too heavy for this workspace and request
Rejected: Inline bash-only changes without shared status model | weaker testability and poorer CLI visibility
Confidence: medium
Scope-risk: moderate
Reversibility: clean
Directive: Treat this as observable best-effort isolation, not a hard security boundary, unless stronger mount enforcement is added later
Tested: cargo fmt --all; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo test --workspace
Not-tested: Manual `/sandbox` REPL run on a real nested-container host
2026-04-01 01:14:38 +00:00
15 changed files with 740 additions and 364 deletions

View File

@@ -912,7 +912,6 @@ mod tests {
system: None, system: None,
tools: None, tools: None,
tool_choice: None, tool_choice: None,
thinking: None,
stream: false, stream: false,
}; };

View File

@@ -13,5 +13,5 @@ pub use types::{
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent, ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest, InputContentBlock, InputMessage, MessageDelta, MessageDeltaEvent, MessageRequest,
MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent, MessageResponse, MessageStartEvent, MessageStopEvent, OutputContentBlock, StreamEvent,
ThinkingConfig, ToolChoice, ToolDefinition, ToolResultContentBlock, Usage, ToolChoice, ToolDefinition, ToolResultContentBlock, Usage,
}; };

View File

@@ -12,8 +12,6 @@ pub struct MessageRequest {
pub tools: Option<Vec<ToolDefinition>>, pub tools: Option<Vec<ToolDefinition>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub tool_choice: Option<ToolChoice>, pub tool_choice: Option<ToolChoice>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thinking: Option<ThinkingConfig>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")] #[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub stream: bool, pub stream: bool,
} }
@@ -26,23 +24,6 @@ impl MessageRequest {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ThinkingConfig {
#[serde(rename = "type")]
pub kind: String,
pub budget_tokens: u32,
}
impl ThinkingConfig {
#[must_use]
pub fn enabled(budget_tokens: u32) -> Self {
Self {
kind: "enabled".to_string(),
budget_tokens,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InputMessage { pub struct InputMessage {
pub role: String, pub role: String,
@@ -149,11 +130,6 @@ pub enum OutputContentBlock {
Text { Text {
text: String, text: String,
}, },
Thinking {
thinking: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
signature: Option<String>,
},
ToolUse { ToolUse {
id: String, id: String,
name: String, name: String,
@@ -213,8 +189,6 @@ pub struct ContentBlockDeltaEvent {
#[serde(tag = "type", rename_all = "snake_case")] #[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlockDelta { pub enum ContentBlockDelta {
TextDelta { text: String }, TextDelta { text: String },
ThinkingDelta { thinking: String },
SignatureDelta { signature: String },
InputJsonDelta { partial_json: String }, InputJsonDelta { partial_json: String },
} }

View File

@@ -258,7 +258,6 @@ async fn live_stream_smoke_test() {
system: None, system: None,
tools: None, tools: None,
tool_choice: None, tool_choice: None,
thinking: None,
stream: false, stream: false,
}) })
.await .await
@@ -439,7 +438,6 @@ fn sample_request(stream: bool) -> MessageRequest {
}), }),
}]), }]),
tool_choice: Some(ToolChoice::Auto), tool_choice: Some(ToolChoice::Auto),
thinking: None,
stream, stream,
} }
} }

View File

@@ -52,16 +52,16 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
resume_supported: true, resume_supported: true,
}, },
SlashCommandSpec { SlashCommandSpec {
name: "compact", name: "sandbox",
summary: "Compact local session history", summary: "Show sandbox isolation status",
argument_hint: None, argument_hint: None,
resume_supported: true, resume_supported: true,
}, },
SlashCommandSpec { SlashCommandSpec {
name: "thinking", name: "compact",
summary: "Show or toggle extended thinking", summary: "Compact local session history",
argument_hint: Some("[on|off]"), argument_hint: None,
resume_supported: false, resume_supported: true,
}, },
SlashCommandSpec { SlashCommandSpec {
name: "model", name: "model",
@@ -141,10 +141,8 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
pub enum SlashCommand { pub enum SlashCommand {
Help, Help,
Status, Status,
Sandbox,
Compact, Compact,
Thinking {
enabled: Option<bool>,
},
Model { Model {
model: Option<String>, model: Option<String>,
}, },
@@ -188,14 +186,8 @@ 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,
"thinking" => Self::Thinking {
enabled: match parts.next() {
Some("on") => Some(true),
Some("off") => Some(false),
Some(_) | None => None,
},
},
"model" => Self::Model { "model" => Self::Model {
model: parts.next().map(ToOwned::to_owned), model: parts.next().map(ToOwned::to_owned),
}, },
@@ -295,7 +287,7 @@ pub fn handle_slash_command(
session: session.clone(), session: session.clone(),
}), }),
SlashCommand::Status SlashCommand::Status
| SlashCommand::Thinking { .. } | SlashCommand::Sandbox
| SlashCommand::Model { .. } | SlashCommand::Model { .. }
| SlashCommand::Permissions { .. } | SlashCommand::Permissions { .. }
| SlashCommand::Clear { .. } | SlashCommand::Clear { .. }
@@ -324,22 +316,7 @@ 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!( assert_eq!(SlashCommand::parse("/sandbox"), Some(SlashCommand::Sandbox));
SlashCommand::parse("/thinking on"),
Some(SlashCommand::Thinking {
enabled: Some(true),
})
);
assert_eq!(
SlashCommand::parse("/thinking off"),
Some(SlashCommand::Thinking {
enabled: Some(false),
})
);
assert_eq!(
SlashCommand::parse("/thinking"),
Some(SlashCommand::Thinking { enabled: None })
);
assert_eq!( assert_eq!(
SlashCommand::parse("/model claude-opus"), SlashCommand::parse("/model claude-opus"),
Some(SlashCommand::Model { Some(SlashCommand::Model {
@@ -406,8 +383,8 @@ 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("/thinking [on|off]"));
assert!(help.contains("/model [model]")); assert!(help.contains("/model [model]"));
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]")); assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
assert!(help.contains("/clear [--confirm]")); assert!(help.contains("/clear [--confirm]"));
@@ -421,7 +398,7 @@ mod tests {
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(), 16);
assert_eq!(resume_supported_slash_commands().len(), 11); assert_eq!(resume_supported_slash_commands().len(), 12);
} }
#[test] #[test]
@@ -468,9 +445,7 @@ 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!( assert!(handle_slash_command("/sandbox", &session, CompactionConfig::default()).is_none());
handle_slash_command("/thinking on", &session, CompactionConfig::default()).is_none()
);
assert!( assert!(
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none() handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
); );

View File

@@ -1,3 +1,4 @@
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;
@@ -7,6 +8,12 @@ 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,
@@ -16,6 +23,14 @@ 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)]
@@ -45,13 +60,17 @@ 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 child = Command::new("sh") let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
.arg("-lc") let child = child
.arg(&input.command)
.stdin(Stdio::null()) .stdin(Stdio::null())
.stdout(Stdio::null()) .stdout(Stdio::null())
.stderr(Stdio::null()) .stderr(Stdio::null())
@@ -72,16 +91,20 @@ 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)) runtime.block_on(execute_bash_async(input, sandbox_status, cwd))
} }
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> { async fn execute_bash_async(
let mut command = TokioCommand::new("sh"); input: BashCommandInput,
command.arg("-lc").arg(&input.command); sandbox_status: SandboxStatus,
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 {
@@ -102,6 +125,7 @@ async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOu
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),
}); });
} }
} }
@@ -136,12 +160,88 @@ async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOu
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() {
@@ -151,10 +251,33 @@ 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);
} }
} }

View File

@@ -130,7 +130,7 @@ fn summarize_messages(messages: &[ConversationMessage]) -> String {
.filter_map(|block| match block { .filter_map(|block| match block {
ContentBlock::ToolUse { name, .. } => Some(name.as_str()), ContentBlock::ToolUse { name, .. } => Some(name.as_str()),
ContentBlock::ToolResult { tool_name, .. } => Some(tool_name.as_str()), ContentBlock::ToolResult { tool_name, .. } => Some(tool_name.as_str()),
ContentBlock::Text { .. } | ContentBlock::Thinking { .. } => None, ContentBlock::Text { .. } => None,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
tool_names.sort_unstable(); tool_names.sort_unstable();
@@ -200,7 +200,6 @@ fn summarize_messages(messages: &[ConversationMessage]) -> String {
fn summarize_block(block: &ContentBlock) -> String { fn summarize_block(block: &ContentBlock) -> String {
let raw = match block { let raw = match block {
ContentBlock::Text { text } => text.clone(), ContentBlock::Text { text } => text.clone(),
ContentBlock::Thinking { text, .. } => format!("thinking: {text}"),
ContentBlock::ToolUse { name, input, .. } => format!("tool_use {name}({input})"), ContentBlock::ToolUse { name, input, .. } => format!("tool_use {name}({input})"),
ContentBlock::ToolResult { ContentBlock::ToolResult {
tool_name, tool_name,
@@ -259,7 +258,7 @@ fn collect_key_files(messages: &[ConversationMessage]) -> Vec<String> {
.iter() .iter()
.flat_map(|message| message.blocks.iter()) .flat_map(|message| message.blocks.iter())
.map(|block| match block { .map(|block| match block {
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } => text.as_str(), ContentBlock::Text { text } => text.as_str(),
ContentBlock::ToolUse { input, .. } => input.as_str(), ContentBlock::ToolUse { input, .. } => input.as_str(),
ContentBlock::ToolResult { output, .. } => output.as_str(), ContentBlock::ToolResult { output, .. } => output.as_str(),
}) })
@@ -281,15 +280,10 @@ fn infer_current_work(messages: &[ConversationMessage]) -> Option<String> {
fn first_text_block(message: &ConversationMessage) -> Option<&str> { fn first_text_block(message: &ConversationMessage) -> Option<&str> {
message.blocks.iter().find_map(|block| match block { message.blocks.iter().find_map(|block| match block {
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } ContentBlock::Text { text } if !text.trim().is_empty() => Some(text.as_str()),
if !text.trim().is_empty() =>
{
Some(text.as_str())
}
ContentBlock::ToolUse { .. } ContentBlock::ToolUse { .. }
| ContentBlock::ToolResult { .. } | ContentBlock::ToolResult { .. }
| ContentBlock::Text { .. } | ContentBlock::Text { .. } => None,
| ContentBlock::Thinking { .. } => None,
}) })
} }
@@ -334,7 +328,7 @@ fn estimate_message_tokens(message: &ConversationMessage) -> usize {
.blocks .blocks
.iter() .iter()
.map(|block| match block { .map(|block| match block {
ContentBlock::Text { text } | ContentBlock::Thinking { text, .. } => text.len() / 4 + 1, ContentBlock::Text { text } => text.len() / 4 + 1,
ContentBlock::ToolUse { name, input, .. } => (name.len() + input.len()) / 4 + 1, ContentBlock::ToolUse { name, input, .. } => (name.len() + input.len()) / 4 + 1,
ContentBlock::ToolResult { ContentBlock::ToolResult {
tool_name, output, .. tool_name, output, ..

View File

@@ -4,6 +4,7 @@ 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";
@@ -40,6 +41,7 @@ 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)]
@@ -225,6 +227,7 @@ 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 {
@@ -289,6 +292,11 @@ 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 {
@@ -311,6 +319,11 @@ 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 {
@@ -445,6 +458,42 @@ 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,
@@ -688,6 +737,7 @@ 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};
@@ -792,6 +842,44 @@ 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();

View File

@@ -17,8 +17,6 @@ pub struct ApiRequest {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub enum AssistantEvent { pub enum AssistantEvent {
TextDelta(String), TextDelta(String),
ThinkingDelta(String),
ThinkingSignature(String),
ToolUse { ToolUse {
id: String, id: String,
name: String, name: String,
@@ -249,26 +247,15 @@ fn build_assistant_message(
events: Vec<AssistantEvent>, events: Vec<AssistantEvent>,
) -> Result<(ConversationMessage, Option<TokenUsage>), RuntimeError> { ) -> Result<(ConversationMessage, Option<TokenUsage>), RuntimeError> {
let mut text = String::new(); let mut text = String::new();
let mut thinking = String::new();
let mut thinking_signature: Option<String> = None;
let mut blocks = Vec::new(); let mut blocks = Vec::new();
let mut finished = false; let mut finished = false;
let mut usage = None; let mut usage = None;
for event in events { for event in events {
match event { match event {
AssistantEvent::TextDelta(delta) => { AssistantEvent::TextDelta(delta) => text.push_str(&delta),
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
text.push_str(&delta);
}
AssistantEvent::ThinkingDelta(delta) => {
flush_text_block(&mut text, &mut blocks);
thinking.push_str(&delta);
}
AssistantEvent::ThinkingSignature(signature) => thinking_signature = Some(signature),
AssistantEvent::ToolUse { id, name, input } => { AssistantEvent::ToolUse { id, name, input } => {
flush_text_block(&mut text, &mut blocks); flush_text_block(&mut text, &mut blocks);
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
blocks.push(ContentBlock::ToolUse { id, name, input }); blocks.push(ContentBlock::ToolUse { id, name, input });
} }
AssistantEvent::Usage(value) => usage = Some(value), AssistantEvent::Usage(value) => usage = Some(value),
@@ -279,7 +266,6 @@ fn build_assistant_message(
} }
flush_text_block(&mut text, &mut blocks); flush_text_block(&mut text, &mut blocks);
flush_thinking_block(&mut thinking, &mut thinking_signature, &mut blocks);
if !finished { if !finished {
return Err(RuntimeError::new( return Err(RuntimeError::new(
@@ -304,19 +290,6 @@ fn flush_text_block(text: &mut String, blocks: &mut Vec<ContentBlock>) {
} }
} }
fn flush_thinking_block(
thinking: &mut String,
signature: &mut Option<String>,
blocks: &mut Vec<ContentBlock>,
) {
if !thinking.is_empty() || signature.is_some() {
blocks.push(ContentBlock::Thinking {
text: std::mem::take(thinking),
signature: signature.take(),
});
}
}
type ToolHandler = Box<dyn FnMut(&str) -> Result<String, ToolError>>; type ToolHandler = Box<dyn FnMut(&str) -> Result<String, ToolError>>;
#[derive(Default)] #[derive(Default)]
@@ -352,8 +325,8 @@ impl ToolExecutor for StaticToolExecutor {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{ use super::{
build_assistant_message, ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError,
RuntimeError, StaticToolExecutor, StaticToolExecutor,
}; };
use crate::compact::CompactionConfig; use crate::compact::CompactionConfig;
use crate::permissions::{ use crate::permissions::{
@@ -529,29 +502,6 @@ mod tests {
)); ));
} }
#[test]
fn thinking_blocks_are_preserved_separately_from_text() {
let (message, usage) = build_assistant_message(vec![
AssistantEvent::ThinkingDelta("first ".to_string()),
AssistantEvent::ThinkingDelta("second".to_string()),
AssistantEvent::ThinkingSignature("sig-1".to_string()),
AssistantEvent::TextDelta("final".to_string()),
AssistantEvent::MessageStop,
])
.expect("assistant message should build");
assert_eq!(usage, None);
assert!(matches!(
&message.blocks[0],
ContentBlock::Thinking { text, signature }
if text == "first second" && signature.as_deref() == Some("sig-1")
));
assert!(matches!(
&message.blocks[1],
ContentBlock::Text { text } if text == "final"
));
}
#[test] #[test]
fn reconstructs_usage_tracker_from_restored_session() { fn reconstructs_usage_tracker_from_restored_session() {
struct SimpleApi; struct SimpleApi;

View File

@@ -12,6 +12,7 @@ mod oauth;
mod permissions; mod permissions;
mod prompt; mod prompt;
mod remote; mod remote;
mod sandbox;
mod session; mod session;
mod usage; mod usage;
@@ -73,6 +74,12 @@ 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,

View File

@@ -5,6 +5,8 @@ pub enum PermissionMode {
ReadOnly, ReadOnly,
WorkspaceWrite, WorkspaceWrite,
DangerFullAccess, DangerFullAccess,
Prompt,
Allow,
} }
impl PermissionMode { impl PermissionMode {
@@ -14,6 +16,8 @@ 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",
} }
} }
} }
@@ -90,7 +94,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 >= required_mode { if current_mode == PermissionMode::Allow || current_mode >= required_mode {
return PermissionOutcome::Allow; return PermissionOutcome::Allow;
} }
@@ -101,8 +105,9 @@ impl PermissionPolicy {
required_mode, required_mode,
}; };
if current_mode == PermissionMode::WorkspaceWrite if current_mode == PermissionMode::Prompt
&& required_mode == PermissionMode::DangerFullAccess || (current_mode == PermissionMode::WorkspaceWrite
&& 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) {

View File

@@ -0,0 +1,364 @@
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);
}
}
}

View File

@@ -19,10 +19,6 @@ pub enum ContentBlock {
Text { Text {
text: String, text: String,
}, },
Thinking {
text: String,
signature: Option<String>,
},
ToolUse { ToolUse {
id: String, id: String,
name: String, name: String,
@@ -261,19 +257,6 @@ impl ContentBlock {
object.insert("type".to_string(), JsonValue::String("text".to_string())); object.insert("type".to_string(), JsonValue::String("text".to_string()));
object.insert("text".to_string(), JsonValue::String(text.clone())); object.insert("text".to_string(), JsonValue::String(text.clone()));
} }
Self::Thinking { text, signature } => {
object.insert(
"type".to_string(),
JsonValue::String("thinking".to_string()),
);
object.insert("text".to_string(), JsonValue::String(text.clone()));
if let Some(signature) = signature {
object.insert(
"signature".to_string(),
JsonValue::String(signature.clone()),
);
}
}
Self::ToolUse { id, name, input } => { Self::ToolUse { id, name, input } => {
object.insert( object.insert(
"type".to_string(), "type".to_string(),
@@ -320,13 +303,6 @@ impl ContentBlock {
"text" => Ok(Self::Text { "text" => Ok(Self::Text {
text: required_string(object, "text")?, text: required_string(object, "text")?,
}), }),
"thinking" => Ok(Self::Thinking {
text: required_string(object, "text")?,
signature: object
.get("signature")
.and_then(JsonValue::as_str)
.map(ToOwned::to_owned),
}),
"tool_use" => Ok(Self::ToolUse { "tool_use" => Ok(Self::ToolUse {
id: required_string(object, "id")?, id: required_string(object, "id")?,
name: required_string(object, "name")?, name: required_string(object, "name")?,

View File

@@ -13,8 +13,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use api::{ use api::{
resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock, resolve_startup_auth_source, AnthropicClient, AuthSource, ContentBlockDelta, InputContentBlock,
InputMessage, MessageRequest, MessageResponse, OutputContentBlock, InputMessage, MessageRequest, MessageResponse, OutputContentBlock,
StreamEvent as ApiStreamEvent, ThinkingConfig, ToolChoice, ToolDefinition, StreamEvent as ApiStreamEvent, ToolChoice, ToolDefinition, ToolResultContentBlock,
ToolResultContentBlock,
}; };
use commands::{ use commands::{
@@ -24,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, save_oauth_credentials, ApiClient, ApiRequest, parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock, ApiRequest, 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,
@@ -35,7 +34,6 @@ use tools::{execute_tool, mvp_tool_specs, ToolSpec};
const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514"; const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
const DEFAULT_MAX_TOKENS: u32 = 32; const DEFAULT_MAX_TOKENS: u32 = 32;
const DEFAULT_THINKING_BUDGET_TOKENS: u32 = 2_048;
const DEFAULT_DATE: &str = "2026-03-31"; const DEFAULT_DATE: &str = "2026-03-31";
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545; const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
const VERSION: &str = env!("CARGO_PKG_VERSION"); const VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -72,8 +70,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
output_format, output_format,
allowed_tools, allowed_tools,
permission_mode, permission_mode,
thinking, } => LiveCli::new(model, false, allowed_tools, permission_mode)?
} => LiveCli::new(model, false, allowed_tools, permission_mode, thinking)?
.run_turn_with_output(&prompt, output_format)?, .run_turn_with_output(&prompt, output_format)?,
CliAction::Login => run_login()?, CliAction::Login => run_login()?,
CliAction::Logout => run_logout()?, CliAction::Logout => run_logout()?,
@@ -81,8 +78,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
model, model,
allowed_tools, allowed_tools,
permission_mode, permission_mode,
thinking, } => run_repl(model, allowed_tools, permission_mode)?,
} => run_repl(model, allowed_tools, permission_mode, thinking)?,
CliAction::Help => print_help(), CliAction::Help => print_help(),
} }
Ok(()) Ok(())
@@ -107,7 +103,6 @@ enum CliAction {
output_format: CliOutputFormat, output_format: CliOutputFormat,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode, permission_mode: PermissionMode,
thinking: bool,
}, },
Login, Login,
Logout, Logout,
@@ -115,7 +110,6 @@ enum CliAction {
model: String, model: String,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode, permission_mode: PermissionMode,
thinking: bool,
}, },
// prompt-mode formatting is only supported for non-interactive runs // prompt-mode formatting is only supported for non-interactive runs
Help, Help,
@@ -145,7 +139,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
let mut output_format = CliOutputFormat::Text; let mut output_format = CliOutputFormat::Text;
let mut permission_mode = default_permission_mode(); let mut permission_mode = default_permission_mode();
let mut wants_version = false; let mut wants_version = false;
let mut thinking = false;
let mut allowed_tool_values = Vec::new(); let mut allowed_tool_values = Vec::new();
let mut rest = Vec::new(); let mut rest = Vec::new();
let mut index = 0; let mut index = 0;
@@ -156,10 +149,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
wants_version = true; wants_version = true;
index += 1; index += 1;
} }
"--thinking" => {
thinking = true;
index += 1;
}
"--model" => { "--model" => {
let value = args let value = args
.get(index + 1) .get(index + 1)
@@ -226,7 +215,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
model, model,
allowed_tools, allowed_tools,
permission_mode, permission_mode,
thinking,
}); });
} }
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) { if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
@@ -253,7 +241,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
output_format, output_format,
allowed_tools, allowed_tools,
permission_mode, permission_mode,
thinking,
}) })
} }
other if !other.starts_with('/') => Ok(CliAction::Prompt { other if !other.starts_with('/') => Ok(CliAction::Prompt {
@@ -262,7 +249,6 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
output_format, output_format,
allowed_tools, allowed_tools,
permission_mode, permission_mode,
thinking,
}), }),
other => Err(format!("unknown subcommand: {other}")), other => Err(format!("unknown subcommand: {other}")),
} }
@@ -605,6 +591,7 @@ 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)]
@@ -614,7 +601,6 @@ struct StatusUsage {
latest: TokenUsage, latest: TokenUsage,
cumulative: TokenUsage, cumulative: TokenUsage,
estimated_tokens: usize, estimated_tokens: usize,
thinking_enabled: bool,
} }
fn format_model_report(model: &str, message_count: usize, turns: u32) -> String { fn format_model_report(model: &str, message_count: usize, turns: u32) -> String {
@@ -682,39 +668,6 @@ Usage
) )
} }
fn format_thinking_report(enabled: bool) -> String {
let state = if enabled { "on" } else { "off" };
let budget = if enabled {
DEFAULT_THINKING_BUDGET_TOKENS.to_string()
} else {
"disabled".to_string()
};
format!(
"Thinking
Active mode {state}
Budget tokens {budget}
Usage
Inspect current mode with /thinking
Toggle with /thinking on or /thinking off"
)
}
fn format_thinking_switch_report(enabled: bool) -> String {
let state = if enabled { "enabled" } else { "disabled" };
format!(
"Thinking updated
Result {state}
Budget tokens {}
Applies to subsequent requests",
if enabled {
DEFAULT_THINKING_BUDGET_TOKENS.to_string()
} else {
"disabled".to_string()
}
)
}
fn format_permissions_switch_report(previous: &str, next: &str) -> String { fn format_permissions_switch_report(previous: &str, next: &str) -> String {
format!( format!(
"Permissions updated "Permissions updated
@@ -882,13 +835,24 @@ fn run_resume_command(
latest: tracker.current_turn_usage(), latest: tracker.current_turn_usage(),
cumulative: usage, cumulative: usage,
estimated_tokens: 0, estimated_tokens: 0,
thinking_enabled: false,
}, },
default_permission_mode().as_str(), default_permission_mode().as_str(),
&status_context(Some(session_path))?, &status_context(Some(session_path))?,
)), )),
}) })
} }
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 {
@@ -929,7 +893,6 @@ fn run_resume_command(
}) })
} }
SlashCommand::Resume { .. } SlashCommand::Resume { .. }
| SlashCommand::Thinking { .. }
| SlashCommand::Model { .. } | SlashCommand::Model { .. }
| SlashCommand::Permissions { .. } | SlashCommand::Permissions { .. }
| SlashCommand::Session { .. } | SlashCommand::Session { .. }
@@ -941,15 +904,8 @@ fn run_repl(
model: String, model: String,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode, permission_mode: PermissionMode,
thinking_enabled: bool,
) -> Result<(), Box<dyn std::error::Error>> { ) -> Result<(), Box<dyn std::error::Error>> {
let mut cli = LiveCli::new( let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
model,
true,
allowed_tools,
permission_mode,
thinking_enabled,
)?;
let mut editor = input::LineEditor::new(" ", slash_command_completion_candidates()); let mut editor = input::LineEditor::new(" ", slash_command_completion_candidates());
println!("{}", cli.startup_banner()); println!("{}", cli.startup_banner());
@@ -1002,7 +958,6 @@ struct LiveCli {
model: String, model: String,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode, permission_mode: PermissionMode,
thinking_enabled: bool,
system_prompt: Vec<String>, system_prompt: Vec<String>,
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
session: SessionHandle, session: SessionHandle,
@@ -1014,7 +969,6 @@ impl LiveCli {
enable_tools: bool, enable_tools: bool,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode, permission_mode: PermissionMode,
thinking_enabled: bool,
) -> Result<Self, Box<dyn std::error::Error>> { ) -> Result<Self, Box<dyn std::error::Error>> {
let system_prompt = build_system_prompt()?; let system_prompt = build_system_prompt()?;
let session = create_managed_session_handle()?; let session = create_managed_session_handle()?;
@@ -1025,13 +979,11 @@ impl LiveCli {
enable_tools, enable_tools,
allowed_tools.clone(), allowed_tools.clone(),
permission_mode, permission_mode,
thinking_enabled,
)?; )?;
let cli = Self { let cli = Self {
model, model,
allowed_tools, allowed_tools,
permission_mode, permission_mode,
thinking_enabled,
system_prompt, system_prompt,
runtime, runtime,
session, session,
@@ -1042,10 +994,9 @@ impl LiveCli {
fn startup_banner(&self) -> String { fn startup_banner(&self) -> String {
format!( format!(
"Rusty Claude CLI\n Model {}\n Permission mode {}\n Thinking {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.", "Rusty Claude CLI\n Model {}\n Permission mode {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.",
self.model, self.model,
self.permission_mode.as_str(), self.permission_mode.as_str(),
if self.thinking_enabled { "on" } else { "off" },
env::current_dir().map_or_else( env::current_dir().map_or_else(
|_| "<unknown>".to_string(), |_| "<unknown>".to_string(),
|path| path.display().to_string(), |path| path.display().to_string(),
@@ -1111,9 +1062,6 @@ impl LiveCli {
system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")), system: (!self.system_prompt.is_empty()).then(|| self.system_prompt.join("\n\n")),
tools: None, tools: None,
tool_choice: None, tool_choice: None,
thinking: self
.thinking_enabled
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
stream: false, stream: false,
}; };
let runtime = tokio::runtime::Runtime::new()?; let runtime = tokio::runtime::Runtime::new()?;
@@ -1123,7 +1071,7 @@ impl LiveCli {
.iter() .iter()
.filter_map(|block| match block { .filter_map(|block| match block {
OutputContentBlock::Text { text } => Some(text.as_str()), OutputContentBlock::Text { text } => Some(text.as_str()),
OutputContentBlock::Thinking { .. } | OutputContentBlock::ToolUse { .. } => None, OutputContentBlock::ToolUse { .. } => None,
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(""); .join("");
@@ -1156,11 +1104,14 @@ 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
} }
SlashCommand::Thinking { enabled } => self.set_thinking(enabled)?,
SlashCommand::Model { model } => self.set_model(model)?, SlashCommand::Model { model } => self.set_model(model)?,
SlashCommand::Permissions { mode } => self.set_permissions(mode)?, SlashCommand::Permissions { mode } => self.set_permissions(mode)?,
SlashCommand::Clear { confirm } => self.clear_session(confirm)?, SlashCommand::Clear { confirm } => self.clear_session(confirm)?,
@@ -1221,7 +1172,6 @@ impl LiveCli {
latest, latest,
cumulative, cumulative,
estimated_tokens: self.runtime.estimated_tokens(), estimated_tokens: self.runtime.estimated_tokens(),
thinking_enabled: self.thinking_enabled,
}, },
self.permission_mode.as_str(), self.permission_mode.as_str(),
&status_context(Some(&self.session.path)).expect("status context should load"), &status_context(Some(&self.session.path)).expect("status context should load"),
@@ -1229,6 +1179,18 @@ 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!(
@@ -1264,7 +1226,6 @@ impl LiveCli {
true, true,
self.allowed_tools.clone(), self.allowed_tools.clone(),
self.permission_mode, self.permission_mode,
self.thinking_enabled,
)?; )?;
self.model.clone_from(&model); self.model.clone_from(&model);
println!( println!(
@@ -1274,32 +1235,6 @@ impl LiveCli {
Ok(true) Ok(true)
} }
fn set_thinking(&mut self, enabled: Option<bool>) -> Result<bool, Box<dyn std::error::Error>> {
let Some(enabled) = enabled else {
println!("{}", format_thinking_report(self.thinking_enabled));
return Ok(false);
};
if enabled == self.thinking_enabled {
println!("{}", format_thinking_report(self.thinking_enabled));
return Ok(false);
}
let session = self.runtime.session().clone();
self.thinking_enabled = enabled;
self.runtime = build_runtime(
session,
self.model.clone(),
self.system_prompt.clone(),
true,
self.allowed_tools.clone(),
self.permission_mode,
self.thinking_enabled,
)?;
println!("{}", format_thinking_switch_report(self.thinking_enabled));
Ok(true)
}
fn set_permissions( fn set_permissions(
&mut self, &mut self,
mode: Option<String>, mode: Option<String>,
@@ -1333,7 +1268,6 @@ impl LiveCli {
true, true,
self.allowed_tools.clone(), self.allowed_tools.clone(),
self.permission_mode, self.permission_mode,
self.thinking_enabled,
)?; )?;
println!( println!(
"{}", "{}",
@@ -1358,7 +1292,6 @@ impl LiveCli {
true, true,
self.allowed_tools.clone(), self.allowed_tools.clone(),
self.permission_mode, self.permission_mode,
self.thinking_enabled,
)?; )?;
println!( println!(
"Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}", "Session cleared\n Mode fresh session\n Preserved model {}\n Permission mode {}\n Session {}",
@@ -1393,7 +1326,6 @@ impl LiveCli {
true, true,
self.allowed_tools.clone(), self.allowed_tools.clone(),
self.permission_mode, self.permission_mode,
self.thinking_enabled,
)?; )?;
self.session = handle; self.session = handle;
println!( println!(
@@ -1470,7 +1402,6 @@ impl LiveCli {
true, true,
self.allowed_tools.clone(), self.allowed_tools.clone(),
self.permission_mode, self.permission_mode,
self.thinking_enabled,
)?; )?;
self.session = handle; self.session = handle;
println!( println!(
@@ -1500,7 +1431,6 @@ impl LiveCli {
true, true,
self.allowed_tools.clone(), self.allowed_tools.clone(),
self.permission_mode, self.permission_mode,
self.thinking_enabled,
)?; )?;
self.persist_session()?; self.persist_session()?;
println!("{}", format_compact_report(removed, kept, skipped)); println!("{}", format_compact_report(removed, kept, skipped));
@@ -1612,7 +1542,6 @@ fn render_repl_help() -> String {
[ [
"REPL".to_string(), "REPL".to_string(),
" /exit Quit the REPL".to_string(), " /exit Quit the REPL".to_string(),
" /thinking [on|off] Show or toggle extended thinking".to_string(),
" /quit Quit the REPL".to_string(), " /quit Quit the REPL".to_string(),
" Up/Down Navigate prompt history".to_string(), " Up/Down Navigate prompt history".to_string(),
" Tab Complete slash commands".to_string(), " Tab Complete slash commands".to_string(),
@@ -1637,6 +1566,7 @@ 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),
@@ -1645,6 +1575,7 @@ 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,
}) })
} }
@@ -1659,14 +1590,10 @@ fn format_status_report(
"Status "Status
Model {model} Model {model}
Permission mode {permission_mode} Permission mode {permission_mode}
Thinking {}
Messages {} Messages {}
Turns {} Turns {}
Estimated tokens {}", Estimated tokens {}",
if usage.thinking_enabled { "on" } else { "off" }, usage.message_count, usage.turns, usage.estimated_tokens,
usage.message_count,
usage.turns,
usage.estimated_tokens,
), ),
format!( format!(
"Usage "Usage
@@ -1701,6 +1628,7 @@ 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(
" "
@@ -1709,6 +1637,49 @@ 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);
@@ -1938,15 +1909,6 @@ fn render_export_text(session: &Session) -> String {
for block in &message.blocks { for block in &message.blocks {
match block { match block {
ContentBlock::Text { text } => lines.push(text.clone()), ContentBlock::Text { text } => lines.push(text.clone()),
ContentBlock::Thinking { text, signature } => {
lines.push(format!(
"[thinking{}] {}",
signature
.as_ref()
.map_or(String::new(), |value| format!(" signature={value}")),
text
));
}
ContentBlock::ToolUse { id, name, input } => { ContentBlock::ToolUse { id, name, input } => {
lines.push(format!("[tool_use id={id} name={name}] {input}")); lines.push(format!("[tool_use id={id} name={name}] {input}"));
} }
@@ -2037,12 +1999,11 @@ fn build_runtime(
enable_tools: bool, enable_tools: bool,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode, permission_mode: PermissionMode,
thinking_enabled: bool,
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>> ) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
{ {
Ok(ConversationRuntime::new( Ok(ConversationRuntime::new(
session, session,
AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone(), thinking_enabled)?, AnthropicRuntimeClient::new(model, enable_tools, allowed_tools.clone())?,
CliToolExecutor::new(allowed_tools), CliToolExecutor::new(allowed_tools),
permission_policy(permission_mode), permission_policy(permission_mode),
system_prompt, system_prompt,
@@ -2101,7 +2062,6 @@ struct AnthropicRuntimeClient {
model: String, model: String,
enable_tools: bool, enable_tools: bool,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
thinking_enabled: bool,
} }
impl AnthropicRuntimeClient { impl AnthropicRuntimeClient {
@@ -2109,7 +2069,6 @@ impl AnthropicRuntimeClient {
model: String, model: String,
enable_tools: bool, enable_tools: bool,
allowed_tools: Option<AllowedToolSet>, allowed_tools: Option<AllowedToolSet>,
thinking_enabled: bool,
) -> Result<Self, Box<dyn std::error::Error>> { ) -> Result<Self, Box<dyn std::error::Error>> {
Ok(Self { Ok(Self {
runtime: tokio::runtime::Runtime::new()?, runtime: tokio::runtime::Runtime::new()?,
@@ -2117,7 +2076,6 @@ impl AnthropicRuntimeClient {
model, model,
enable_tools, enable_tools,
allowed_tools, allowed_tools,
thinking_enabled,
}) })
} }
} }
@@ -2151,9 +2109,6 @@ impl ApiClient for AnthropicRuntimeClient {
.collect() .collect()
}), }),
tool_choice: self.enable_tools.then_some(ToolChoice::Auto), tool_choice: self.enable_tools.then_some(ToolChoice::Auto),
thinking: self
.thinking_enabled
.then_some(ThinkingConfig::enabled(DEFAULT_THINKING_BUDGET_TOKENS)),
stream: true, stream: true,
}; };
@@ -2166,7 +2121,6 @@ impl ApiClient for AnthropicRuntimeClient {
let mut stdout = io::stdout(); let mut stdout = io::stdout();
let mut events = Vec::new(); let mut events = Vec::new();
let mut pending_tool: Option<(String, String, String)> = None; let mut pending_tool: Option<(String, String, String)> = None;
let mut pending_thinking_signature: Option<String> = None;
let mut saw_stop = false; let mut saw_stop = false;
while let Some(event) = stream while let Some(event) = stream
@@ -2177,13 +2131,7 @@ impl ApiClient for AnthropicRuntimeClient {
match event { match event {
ApiStreamEvent::MessageStart(start) => { ApiStreamEvent::MessageStart(start) => {
for block in start.message.content { for block in start.message.content {
push_output_block( push_output_block(block, &mut stdout, &mut events, &mut pending_tool)?;
block,
&mut stdout,
&mut events,
&mut pending_tool,
&mut pending_thinking_signature,
)?;
} }
} }
ApiStreamEvent::ContentBlockStart(start) => { ApiStreamEvent::ContentBlockStart(start) => {
@@ -2192,7 +2140,6 @@ impl ApiClient for AnthropicRuntimeClient {
&mut stdout, &mut stdout,
&mut events, &mut events,
&mut pending_tool, &mut pending_tool,
&mut pending_thinking_signature,
)?; )?;
} }
ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta { ApiStreamEvent::ContentBlockDelta(delta) => match delta.delta {
@@ -2204,14 +2151,6 @@ impl ApiClient for AnthropicRuntimeClient {
events.push(AssistantEvent::TextDelta(text)); events.push(AssistantEvent::TextDelta(text));
} }
} }
ContentBlockDelta::ThinkingDelta { thinking } => {
if !thinking.is_empty() {
events.push(AssistantEvent::ThinkingDelta(thinking));
}
}
ContentBlockDelta::SignatureDelta { signature } => {
events.push(AssistantEvent::ThinkingSignature(signature));
}
ContentBlockDelta::InputJsonDelta { partial_json } => { ContentBlockDelta::InputJsonDelta { partial_json } => {
if let Some((_, _, input)) = &mut pending_tool { if let Some((_, _, input)) = &mut pending_tool {
input.push_str(&partial_json); input.push_str(&partial_json);
@@ -2241,8 +2180,6 @@ impl ApiClient for AnthropicRuntimeClient {
if !saw_stop if !saw_stop
&& events.iter().any(|event| { && events.iter().any(|event| {
matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty()) matches!(event, AssistantEvent::TextDelta(text) if !text.is_empty())
|| matches!(event, AssistantEvent::ThinkingDelta(text) if !text.is_empty())
|| matches!(event, AssistantEvent::ThinkingSignature(_))
|| matches!(event, AssistantEvent::ToolUse { .. }) || matches!(event, AssistantEvent::ToolUse { .. })
}) })
{ {
@@ -2326,19 +2263,11 @@ fn truncate_for_summary(value: &str, limit: usize) -> String {
} }
} }
fn render_thinking_block_summary(text: &str, out: &mut impl Write) -> Result<(), RuntimeError> {
let summary = format!("▶ Thinking ({} chars hidden)", text.chars().count());
writeln!(out, "\n{summary}")
.and_then(|()| out.flush())
.map_err(|error| RuntimeError::new(error.to_string()))
}
fn push_output_block( fn push_output_block(
block: OutputContentBlock, block: OutputContentBlock,
out: &mut impl Write, out: &mut impl Write,
events: &mut Vec<AssistantEvent>, events: &mut Vec<AssistantEvent>,
pending_tool: &mut Option<(String, String, String)>, pending_tool: &mut Option<(String, String, String)>,
pending_thinking_signature: &mut Option<String>,
) -> Result<(), RuntimeError> { ) -> Result<(), RuntimeError> {
match block { match block {
OutputContentBlock::Text { text } => { OutputContentBlock::Text { text } => {
@@ -2349,19 +2278,6 @@ fn push_output_block(
events.push(AssistantEvent::TextDelta(text)); events.push(AssistantEvent::TextDelta(text));
} }
} }
OutputContentBlock::Thinking {
thinking,
signature,
} => {
render_thinking_block_summary(&thinking, out)?;
if !thinking.is_empty() {
events.push(AssistantEvent::ThinkingDelta(thinking));
}
if let Some(signature) = signature {
*pending_thinking_signature = Some(signature.clone());
events.push(AssistantEvent::ThinkingSignature(signature));
}
}
OutputContentBlock::ToolUse { id, name, input } => { OutputContentBlock::ToolUse { id, name, input } => {
writeln!( writeln!(
out, out,
@@ -2383,16 +2299,9 @@ fn response_to_events(
) -> Result<Vec<AssistantEvent>, RuntimeError> { ) -> Result<Vec<AssistantEvent>, RuntimeError> {
let mut events = Vec::new(); let mut events = Vec::new();
let mut pending_tool = None; let mut pending_tool = None;
let mut pending_thinking_signature = None;
for block in response.content { for block in response.content {
push_output_block( push_output_block(block, out, &mut events, &mut pending_tool)?;
block,
out,
&mut events,
&mut pending_tool,
&mut pending_thinking_signature,
)?;
if let Some((id, name, input)) = pending_tool.take() { if let Some((id, name, input)) = pending_tool.take() {
events.push(AssistantEvent::ToolUse { id, name, input }); events.push(AssistantEvent::ToolUse { id, name, input });
} }
@@ -2477,29 +2386,26 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
let content = message let content = message
.blocks .blocks
.iter() .iter()
.filter_map(|block| match block { .map(|block| match block {
ContentBlock::Text { text } => { ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
Some(InputContentBlock::Text { text: text.clone() }) ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
}
ContentBlock::Thinking { .. } => None,
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
id: id.clone(), id: id.clone(),
name: name.clone(), name: name.clone(),
input: serde_json::from_str(input) input: serde_json::from_str(input)
.unwrap_or_else(|_| serde_json::json!({ "raw": input })), .unwrap_or_else(|_| serde_json::json!({ "raw": input })),
}), },
ContentBlock::ToolResult { ContentBlock::ToolResult {
tool_use_id, tool_use_id,
output, output,
is_error, is_error,
.. ..
} => Some(InputContentBlock::ToolResult { } => InputContentBlock::ToolResult {
tool_use_id: tool_use_id.clone(), tool_use_id: tool_use_id.clone(),
content: vec![ToolResultContentBlock::Text { content: vec![ToolResultContentBlock::Text {
text: output.clone(), text: output.clone(),
}], }],
is_error: *is_error, is_error: *is_error,
}), },
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
(!content.is_empty()).then(|| InputMessage { (!content.is_empty()).then(|| InputMessage {
@@ -2532,7 +2438,6 @@ fn print_help() {
println!(" --model MODEL Override the active model"); println!(" --model MODEL Override the active model");
println!(" --output-format FORMAT Non-interactive output format: text or json"); println!(" --output-format FORMAT Non-interactive output format: text or json");
println!(" --permission-mode MODE Set read-only, workspace-write, or danger-full-access"); println!(" --permission-mode MODE Set read-only, workspace-write, or danger-full-access");
println!(" --thinking Enable extended thinking with the default budget");
println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)"); println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
println!(" --version, -V Print version and build information locally"); println!(" --version, -V Print version and build information locally");
println!(); println!();
@@ -2578,7 +2483,6 @@ mod tests {
model: DEFAULT_MODEL.to_string(), model: DEFAULT_MODEL.to_string(),
allowed_tools: None, allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite, permission_mode: PermissionMode::WorkspaceWrite,
thinking: false,
} }
); );
} }
@@ -2598,7 +2502,6 @@ mod tests {
output_format: CliOutputFormat::Text, output_format: CliOutputFormat::Text,
allowed_tools: None, allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite, permission_mode: PermissionMode::WorkspaceWrite,
thinking: false,
} }
); );
} }
@@ -2620,7 +2523,6 @@ mod tests {
output_format: CliOutputFormat::Json, output_format: CliOutputFormat::Json,
allowed_tools: None, allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite, permission_mode: PermissionMode::WorkspaceWrite,
thinking: false,
} }
); );
} }
@@ -2646,7 +2548,6 @@ mod tests {
model: DEFAULT_MODEL.to_string(), model: DEFAULT_MODEL.to_string(),
allowed_tools: None, allowed_tools: None,
permission_mode: PermissionMode::ReadOnly, permission_mode: PermissionMode::ReadOnly,
thinking: false,
} }
); );
} }
@@ -2669,7 +2570,6 @@ mod tests {
.collect() .collect()
), ),
permission_mode: PermissionMode::WorkspaceWrite, permission_mode: PermissionMode::WorkspaceWrite,
thinking: false,
} }
); );
} }
@@ -2776,6 +2676,7 @@ 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]"));
@@ -2800,8 +2701,8 @@ mod tests {
assert_eq!( assert_eq!(
names, names,
vec![ vec![
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff", "help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
"version", "export", "init", "diff", "version", "export",
] ]
); );
} }
@@ -2909,7 +2810,6 @@ mod tests {
cache_read_input_tokens: 1, cache_read_input_tokens: 1,
}, },
estimated_tokens: 128, estimated_tokens: 128,
thinking_enabled: true,
}, },
"workspace-write", "workspace-write",
&super::StatusContext { &super::StatusContext {
@@ -2920,6 +2820,7 @@ 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"));
@@ -2973,7 +2874,7 @@ mod tests {
fn status_context_reads_real_workspace_metadata() { fn status_context_reads_real_workspace_metadata() {
let context = status_context(None).expect("status context should load"); let context = status_context(None).expect("status context should load");
assert!(context.cwd.is_absolute()); assert!(context.cwd.is_absolute());
assert!(context.discovered_config_files >= context.loaded_config_files); assert_eq!(context.discovered_config_files, 5);
assert!(context.loaded_config_files <= context.discovered_config_files); assert!(context.loaded_config_files <= context.discovered_config_files);
} }
@@ -3081,3 +2982,17 @@ 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"));
}
}

View File

@@ -62,7 +62,11 @@ 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
@@ -2214,6 +2218,7 @@ 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,
}); });
} }
@@ -2251,6 +2256,7 @@ 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) {
@@ -2281,6 +2287,7 @@ 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));
@@ -2307,6 +2314,7 @@ 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,
}) })
} }