1 Commits

Author SHA1 Message Date
Yeachan-Heo
3ba60be514 Expose session cost and budget state in the Rust CLI
The CLI already tracked token usage, but it did not translate that usage into model-aware cost reporting or offer a spend guardrail. This change adds a max-cost flag, integrates estimated USD totals into /status and /cost, emits near-budget warnings, and blocks new turns once the configured budget has been exhausted.

The workspace verification request also surfaced stale runtime test fixtures that still referenced removed permission enum variants, so those test-only call sites were updated to current permission modes to keep full clippy and workspace test coverage green.

Constraint: Reuse existing runtime usage/pricing helpers instead of adding a new billing layer
Constraint: Keep the feature centered in existing CLI/status surfaces with no new dependencies
Rejected: Move budget enforcement into runtime usage/session abstractions | broader refactor than needed for this CLI-scoped feature
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: If resumed sessions later need historically accurate per-turn pricing across model switches, persist model metadata before changing the cost math
Tested: cargo fmt --all --check; cargo clippy --workspace --all-targets -- -D warnings; cargo test --workspace
Not-tested: Live network-backed prompt/REPL budget behavior against real Anthropic responses
2026-04-01 00:57:54 +00:00
8 changed files with 248 additions and 750 deletions

View File

@@ -51,12 +51,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
argument_hint: None,
resume_supported: true,
},
SlashCommandSpec {
name: "sandbox",
summary: "Show sandbox isolation status",
argument_hint: None,
resume_supported: true,
},
SlashCommandSpec {
name: "compact",
summary: "Compact local session history",
@@ -141,7 +135,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
pub enum SlashCommand {
Help,
Status,
Sandbox,
Compact,
Model {
model: Option<String>,
@@ -186,7 +179,6 @@ impl SlashCommand {
Some(match command {
"help" => Self::Help,
"status" => Self::Status,
"sandbox" => Self::Sandbox,
"compact" => Self::Compact,
"model" => Self::Model {
model: parts.next().map(ToOwned::to_owned),
@@ -287,7 +279,6 @@ pub fn handle_slash_command(
session: session.clone(),
}),
SlashCommand::Status
| SlashCommand::Sandbox
| SlashCommand::Model { .. }
| SlashCommand::Permissions { .. }
| SlashCommand::Clear { .. }
@@ -316,7 +307,6 @@ mod tests {
fn parses_supported_slash_commands() {
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
assert_eq!(SlashCommand::parse("/sandbox"), Some(SlashCommand::Sandbox));
assert_eq!(
SlashCommand::parse("/model claude-opus"),
Some(SlashCommand::Model {
@@ -383,7 +373,6 @@ mod tests {
assert!(help.contains("works with --resume SESSION.json"));
assert!(help.contains("/help"));
assert!(help.contains("/status"));
assert!(help.contains("/sandbox"));
assert!(help.contains("/compact"));
assert!(help.contains("/model [model]"));
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
@@ -397,8 +386,8 @@ mod tests {
assert!(help.contains("/version"));
assert!(help.contains("/export [file]"));
assert!(help.contains("/session [list|switch <session-id>]"));
assert_eq!(slash_command_specs().len(), 16);
assert_eq!(resume_supported_slash_commands().len(), 12);
assert_eq!(slash_command_specs().len(), 15);
assert_eq!(resume_supported_slash_commands().len(), 11);
}
#[test]
@@ -445,7 +434,6 @@ mod tests {
let session = Session::new();
assert!(handle_slash_command("/unknown", &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!(
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
);

View File

@@ -1,4 +1,3 @@
use std::env;
use std::io;
use std::process::{Command, Stdio};
use std::time::Duration;
@@ -8,12 +7,6 @@ use tokio::process::Command as TokioCommand;
use tokio::runtime::Builder;
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)]
pub struct BashCommandInput {
pub command: String,
@@ -23,14 +16,6 @@ pub struct BashCommandInput {
pub run_in_background: Option<bool>,
#[serde(rename = "dangerouslyDisableSandbox")]
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)]
@@ -60,17 +45,13 @@ pub struct BashCommandOutput {
pub persisted_output_path: Option<String>,
#[serde(rename = "persistedOutputSize")]
pub persisted_output_size: Option<u64>,
#[serde(rename = "sandboxStatus")]
pub sandbox_status: Option<SandboxStatus>,
}
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) {
let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
let child = child
let child = Command::new("sh")
.arg("-lc")
.arg(&input.command)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -91,20 +72,16 @@ pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
structured_content: None,
persisted_output_path: None,
persisted_output_size: None,
sandbox_status: Some(sandbox_status),
});
}
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(
input: BashCommandInput,
sandbox_status: SandboxStatus,
cwd: std::path::PathBuf,
) -> io::Result<BashCommandOutput> {
let mut command = prepare_tokio_command(&input.command, &cwd, &sandbox_status, true);
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> {
let mut command = TokioCommand::new("sh");
command.arg("-lc").arg(&input.command);
let output_result = if let Some(timeout_ms) = input.timeout {
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
@@ -125,7 +102,6 @@ async fn execute_bash_async(
structured_content: None,
persisted_output_path: None,
persisted_output_size: None,
sandbox_status: Some(sandbox_status),
});
}
}
@@ -160,88 +136,12 @@ async fn execute_bash_async(
structured_content: None,
persisted_output_path: 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)]
mod tests {
use super::{execute_bash, BashCommandInput};
use crate::sandbox::FilesystemIsolationMode;
#[test]
fn executes_simple_command() {
@@ -251,33 +151,10 @@ mod tests {
description: None,
run_in_background: 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");
assert_eq!(output.stdout, "hello");
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

@@ -4,7 +4,6 @@ use std::fs;
use std::path::{Path, PathBuf};
use crate::json::JsonValue;
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
@@ -41,7 +40,6 @@ pub struct RuntimeFeatureConfig {
oauth: Option<OAuthConfig>,
model: Option<String>,
permission_mode: Option<ResolvedPermissionMode>,
sandbox: SandboxConfig,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
@@ -227,7 +225,6 @@ impl ConfigLoader {
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
model: parse_optional_model(&merged_value),
permission_mode: parse_optional_permission_mode(&merged_value)?,
sandbox: parse_optional_sandbox_config(&merged_value)?,
};
Ok(RuntimeConfig {
@@ -292,11 +289,6 @@ impl RuntimeConfig {
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
self.feature_config.permission_mode
}
#[must_use]
pub fn sandbox(&self) -> &SandboxConfig {
&self.feature_config.sandbox
}
}
impl RuntimeFeatureConfig {
@@ -319,11 +311,6 @@ impl RuntimeFeatureConfig {
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
self.permission_mode
}
#[must_use]
pub fn sandbox(&self) -> &SandboxConfig {
&self.sandbox
}
}
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(
root: &JsonValue,
context: &str,
@@ -737,7 +688,6 @@ mod tests {
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
};
use crate::json::JsonValue;
use crate::sandbox::FilesystemIsolationMode;
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -842,44 +792,6 @@ mod tests {
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]
fn parses_typed_mcp_and_oauth_config() {
let root = temp_dir();

View File

@@ -12,7 +12,6 @@ mod oauth;
mod permissions;
mod prompt;
mod remote;
mod sandbox;
mod session;
mod usage;
@@ -74,12 +73,6 @@ pub use remote::{
RemoteSessionContext, UpstreamProxyBootstrap, UpstreamProxyState, DEFAULT_REMOTE_BASE_URL,
DEFAULT_SESSION_TOKEN_PATH, DEFAULT_SYSTEM_CA_BUNDLE, NO_PROXY_HOSTS, UPSTREAM_PROXY_ENV_KEYS,
};
pub use sandbox::{
build_linux_sandbox_command, detect_container_environment, detect_container_environment_from,
resolve_sandbox_status, resolve_sandbox_status_for_request, ContainerEnvironment,
FilesystemIsolationMode, LinuxSandboxCommand, SandboxConfig, SandboxDetectionInputs,
SandboxRequest, SandboxStatus,
};
pub use session::{ContentBlock, ConversationMessage, MessageRole, Session, SessionError};
pub use usage::{
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,

View File

@@ -5,8 +5,6 @@ pub enum PermissionMode {
ReadOnly,
WorkspaceWrite,
DangerFullAccess,
Prompt,
Allow,
}
impl PermissionMode {
@@ -16,8 +14,6 @@ impl PermissionMode {
Self::ReadOnly => "read-only",
Self::WorkspaceWrite => "workspace-write",
Self::DangerFullAccess => "danger-full-access",
Self::Prompt => "prompt",
Self::Allow => "allow",
}
}
}
@@ -94,7 +90,7 @@ impl PermissionPolicy {
) -> PermissionOutcome {
let current_mode = self.active_mode();
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;
}
@@ -105,9 +101,8 @@ impl PermissionPolicy {
required_mode,
};
if current_mode == PermissionMode::Prompt
|| (current_mode == PermissionMode::WorkspaceWrite
&& required_mode == PermissionMode::DangerFullAccess)
if current_mode == PermissionMode::WorkspaceWrite
&& required_mode == PermissionMode::DangerFullAccess
{
return match prompter.as_mut() {
Some(prompter) => match prompter.decide(&request) {

View File

@@ -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);
}
}
}

View File

@@ -22,8 +22,8 @@ use commands::{
use compat_harness::{extract_manifest, UpstreamPaths};
use render::{Spinner, TerminalRenderer};
use runtime::{
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
clear_oauth_credentials, format_usd, generate_pkce_pair, generate_state, load_system_prompt,
parse_oauth_callback_request_target, pricing_for_model, save_oauth_credentials, ApiClient,
ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
@@ -36,6 +36,7 @@ const DEFAULT_MODEL: &str = "claude-sonnet-4-20250514";
const DEFAULT_MAX_TOKENS: u32 = 32;
const DEFAULT_DATE: &str = "2026-03-31";
const DEFAULT_OAUTH_CALLBACK_PORT: u16 = 4545;
const COST_WARNING_FRACTION: f64 = 0.8;
const VERSION: &str = env!("CARGO_PKG_VERSION");
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
@@ -70,7 +71,8 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
output_format,
allowed_tools,
permission_mode,
} => LiveCli::new(model, false, allowed_tools, permission_mode)?
max_cost_usd,
} => LiveCli::new(model, false, allowed_tools, permission_mode, max_cost_usd)?
.run_turn_with_output(&prompt, output_format)?,
CliAction::Login => run_login()?,
CliAction::Logout => run_logout()?,
@@ -78,13 +80,14 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
model,
allowed_tools,
permission_mode,
} => run_repl(model, allowed_tools, permission_mode)?,
max_cost_usd,
} => run_repl(model, allowed_tools, permission_mode, max_cost_usd)?,
CliAction::Help => print_help(),
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq)]
enum CliAction {
DumpManifests,
BootstrapPlan,
@@ -103,6 +106,7 @@ enum CliAction {
output_format: CliOutputFormat,
allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode,
max_cost_usd: Option<f64>,
},
Login,
Logout,
@@ -110,6 +114,7 @@ enum CliAction {
model: String,
allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode,
max_cost_usd: Option<f64>,
},
// prompt-mode formatting is only supported for non-interactive runs
Help,
@@ -139,6 +144,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
let mut output_format = CliOutputFormat::Text;
let mut permission_mode = default_permission_mode();
let mut wants_version = false;
let mut max_cost_usd: Option<f64> = None;
let mut allowed_tool_values = Vec::new();
let mut rest = Vec::new();
let mut index = 0;
@@ -174,6 +180,13 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
permission_mode = parse_permission_mode_arg(value)?;
index += 2;
}
"--max-cost" => {
let value = args
.get(index + 1)
.ok_or_else(|| "missing value for --max-cost".to_string())?;
max_cost_usd = Some(parse_max_cost_arg(value)?);
index += 2;
}
flag if flag.starts_with("--output-format=") => {
output_format = CliOutputFormat::parse(&flag[16..])?;
index += 1;
@@ -182,6 +195,10 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
permission_mode = parse_permission_mode_arg(&flag[18..])?;
index += 1;
}
flag if flag.starts_with("--max-cost=") => {
max_cost_usd = Some(parse_max_cost_arg(&flag[11..])?);
index += 1;
}
"--allowedTools" | "--allowed-tools" => {
let value = args
.get(index + 1)
@@ -215,6 +232,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
model,
allowed_tools,
permission_mode,
max_cost_usd,
});
}
if matches!(rest.first().map(String::as_str), Some("--help" | "-h")) {
@@ -241,6 +259,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
output_format,
allowed_tools,
permission_mode,
max_cost_usd,
})
}
other if !other.starts_with('/') => Ok(CliAction::Prompt {
@@ -249,6 +268,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
output_format,
allowed_tools,
permission_mode,
max_cost_usd,
}),
other => Err(format!("unknown subcommand: {other}")),
}
@@ -312,6 +332,18 @@ fn parse_permission_mode_arg(value: &str) -> Result<PermissionMode, String> {
.map(permission_mode_from_label)
}
fn parse_max_cost_arg(value: &str) -> Result<f64, String> {
let parsed = value
.parse::<f64>()
.map_err(|_| format!("invalid value for --max-cost: {value}"))?;
if !parsed.is_finite() || parsed <= 0.0 {
return Err(format!(
"--max-cost must be a positive finite USD amount: {value}"
));
}
Ok(parsed)
}
fn permission_mode_from_label(mode: &str) -> PermissionMode {
match mode {
"read-only" => PermissionMode::ReadOnly,
@@ -591,7 +623,6 @@ struct StatusContext {
memory_file_count: usize,
project_root: Option<PathBuf>,
git_branch: Option<String>,
sandbox_status: runtime::SandboxStatus,
}
#[derive(Debug, Clone, Copy)]
@@ -679,22 +710,78 @@ fn format_permissions_switch_report(previous: &str, next: &str) -> String {
)
}
fn format_cost_report(usage: TokenUsage) -> String {
fn format_cost_report(model: &str, usage: TokenUsage, max_cost_usd: Option<f64>) -> String {
let estimate = usage_cost_estimate(model, usage);
format!(
"Cost
Model {model}
Input tokens {}
Output tokens {}
Cache create {}
Cache read {}
Total tokens {}",
Total tokens {}
Input cost {}
Output cost {}
Cache create usd {}
Cache read usd {}
Estimated cost {}
Budget {}",
usage.input_tokens,
usage.output_tokens,
usage.cache_creation_input_tokens,
usage.cache_read_input_tokens,
usage.total_tokens(),
format_usd(estimate.input_cost_usd),
format_usd(estimate.output_cost_usd),
format_usd(estimate.cache_creation_cost_usd),
format_usd(estimate.cache_read_cost_usd),
format_usd(estimate.total_cost_usd()),
format_budget_line(estimate.total_cost_usd(), max_cost_usd),
)
}
fn usage_cost_estimate(model: &str, usage: TokenUsage) -> runtime::UsageCostEstimate {
pricing_for_model(model).map_or_else(
|| usage.estimate_cost_usd(),
|pricing| usage.estimate_cost_usd_with_pricing(pricing),
)
}
fn usage_cost_total(model: &str, usage: TokenUsage) -> f64 {
usage_cost_estimate(model, usage).total_cost_usd()
}
fn format_budget_line(cost_usd: f64, max_cost_usd: Option<f64>) -> String {
match max_cost_usd {
Some(limit) => format!("{} / {}", format_usd(cost_usd), format_usd(limit)),
None => format!("{} (unlimited)", format_usd(cost_usd)),
}
}
fn budget_notice_message(
model: &str,
usage: TokenUsage,
max_cost_usd: Option<f64>,
) -> Option<String> {
let limit = max_cost_usd?;
let cost = usage_cost_total(model, usage);
if cost >= limit {
Some(format!(
"cost budget exceeded: cumulative={} budget={}",
format_usd(cost),
format_usd(limit)
))
} else if cost >= limit * COST_WARNING_FRACTION {
Some(format!(
"approaching cost budget: cumulative={} budget={}",
format_usd(cost),
format_usd(limit)
))
} else {
None
}
}
fn format_resume_report(session_path: &str, message_count: usize, turns: u32) -> String {
format!(
"Session resumed
@@ -838,26 +925,15 @@ fn run_resume_command(
},
default_permission_mode().as_str(),
&status_context(Some(session_path))?,
None,
)),
})
}
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 => {
let usage = UsageTracker::from_session(session).cumulative_usage();
Ok(ResumeCommandOutcome {
session: session.clone(),
message: Some(format_cost_report(usage)),
message: Some(format_cost_report("restored-session", usage, None)),
})
}
SlashCommand::Config { section } => Ok(ResumeCommandOutcome {
@@ -904,8 +980,9 @@ fn run_repl(
model: String,
allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode,
max_cost_usd: Option<f64>,
) -> Result<(), Box<dyn std::error::Error>> {
let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode)?;
let mut cli = LiveCli::new(model, true, allowed_tools, permission_mode, max_cost_usd)?;
let mut editor = input::LineEditor::new(" ", slash_command_completion_candidates());
println!("{}", cli.startup_banner());
@@ -958,6 +1035,7 @@ struct LiveCli {
model: String,
allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode,
max_cost_usd: Option<f64>,
system_prompt: Vec<String>,
runtime: ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
session: SessionHandle,
@@ -969,6 +1047,7 @@ impl LiveCli {
enable_tools: bool,
allowed_tools: Option<AllowedToolSet>,
permission_mode: PermissionMode,
max_cost_usd: Option<f64>,
) -> Result<Self, Box<dyn std::error::Error>> {
let system_prompt = build_system_prompt()?;
let session = create_managed_session_handle()?;
@@ -984,6 +1063,7 @@ impl LiveCli {
model,
allowed_tools,
permission_mode,
max_cost_usd,
system_prompt,
runtime,
session,
@@ -994,9 +1074,10 @@ impl LiveCli {
fn startup_banner(&self) -> String {
format!(
"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.",
"Rusty Claude CLI\n Model {}\n Permission mode {}\n Cost budget {}\n Working directory {}\n Session {}\n\nType /help for commands. Shift+Enter or Ctrl+J inserts a newline.",
self.model,
self.permission_mode.as_str(),
self.max_cost_usd.map_or_else(|| "none".to_string(), format_usd),
env::current_dir().map_or_else(
|_| "<unknown>".to_string(),
|path| path.display().to_string(),
@@ -1006,6 +1087,7 @@ impl LiveCli {
}
fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
self.enforce_budget_before_turn()?;
let mut spinner = Spinner::new();
let mut stdout = io::stdout();
spinner.tick(
@@ -1016,13 +1098,14 @@ impl LiveCli {
let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
let result = self.runtime.run_turn(input, Some(&mut permission_prompter));
match result {
Ok(_) => {
Ok(summary) => {
spinner.finish(
"Claude response complete",
TerminalRenderer::new().color_theme(),
&mut stdout,
)?;
println!();
self.print_budget_notice(summary.usage);
self.persist_session()?;
Ok(())
}
@@ -1049,6 +1132,7 @@ impl LiveCli {
}
fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
self.enforce_budget_before_turn()?;
let client = AnthropicClient::from_auth(resolve_cli_auth_source()?);
let request = MessageRequest {
model: self.model.clone(),
@@ -1075,17 +1159,27 @@ impl LiveCli {
})
.collect::<Vec<_>>()
.join("");
let usage = TokenUsage {
input_tokens: response.usage.input_tokens,
output_tokens: response.usage.output_tokens,
cache_creation_input_tokens: response.usage.cache_creation_input_tokens,
cache_read_input_tokens: response.usage.cache_read_input_tokens,
};
println!(
"{}",
json!({
"message": text,
"model": self.model,
"usage": {
"input_tokens": response.usage.input_tokens,
"output_tokens": response.usage.output_tokens,
"cache_creation_input_tokens": response.usage.cache_creation_input_tokens,
"cache_read_input_tokens": response.usage.cache_read_input_tokens,
}
"input_tokens": usage.input_tokens,
"output_tokens": usage.output_tokens,
"cache_creation_input_tokens": usage.cache_creation_input_tokens,
"cache_read_input_tokens": usage.cache_read_input_tokens,
},
"cost_usd": usage_cost_total(&self.model, usage),
"cumulative_cost_usd": usage_cost_total(&self.model, usage),
"max_cost_usd": self.max_cost_usd,
"budget_warning": budget_notice_message(&self.model, usage, self.max_cost_usd),
})
);
Ok(())
@@ -1104,10 +1198,6 @@ impl LiveCli {
self.print_status();
false
}
SlashCommand::Sandbox => {
Self::print_sandbox_status();
false
}
SlashCommand::Compact => {
self.compact()?;
false
@@ -1159,6 +1249,28 @@ impl LiveCli {
Ok(())
}
fn enforce_budget_before_turn(&self) -> Result<(), Box<dyn std::error::Error>> {
let Some(limit) = self.max_cost_usd else {
return Ok(());
};
let cost = usage_cost_total(&self.model, self.runtime.usage().cumulative_usage());
if cost >= limit {
return Err(format!(
"cost budget exceeded before starting turn: cumulative={} budget={}",
format_usd(cost),
format_usd(limit)
)
.into());
}
Ok(())
}
fn print_budget_notice(&self, usage: TokenUsage) {
if let Some(message) = budget_notice_message(&self.model, usage, self.max_cost_usd) {
eprintln!("warning: {message}");
}
}
fn print_status(&self) {
let cumulative = self.runtime.usage().cumulative_usage();
let latest = self.runtime.usage().current_turn_usage();
@@ -1175,22 +1287,11 @@ impl LiveCli {
},
self.permission_mode.as_str(),
&status_context(Some(&self.session.path)).expect("status context should load"),
self.max_cost_usd,
)
);
}
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>> {
let Some(model) = model else {
println!(
@@ -1304,7 +1405,10 @@ impl LiveCli {
fn print_cost(&self) {
let cumulative = self.runtime.usage().cumulative_usage();
println!("{}", format_cost_report(cumulative));
println!(
"{}",
format_cost_report(&self.model, cumulative, self.max_cost_usd)
);
}
fn resume_session(
@@ -1566,7 +1670,6 @@ fn status_context(
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
let (project_root, git_branch) =
parse_git_status_metadata(project_context.git_status.as_deref());
let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
Ok(StatusContext {
cwd,
session_path: session_path.map(Path::to_path_buf),
@@ -1575,7 +1678,6 @@ fn status_context(
memory_file_count: project_context.instruction_files.len(),
project_root,
git_branch,
sandbox_status,
})
}
@@ -1584,7 +1686,10 @@ fn format_status_report(
usage: StatusUsage,
permission_mode: &str,
context: &StatusContext,
max_cost_usd: Option<f64>,
) -> String {
let latest_cost = usage_cost_total(model, usage.latest);
let cumulative_cost = usage_cost_total(model, usage.cumulative);
[
format!(
"Status
@@ -1592,19 +1697,27 @@ fn format_status_report(
Permission mode {permission_mode}
Messages {}
Turns {}
Estimated tokens {}",
usage.message_count, usage.turns, usage.estimated_tokens,
Estimated tokens {}
Cost budget {}",
usage.message_count,
usage.turns,
usage.estimated_tokens,
format_budget_line(cumulative_cost, max_cost_usd),
),
format!(
"Usage
Latest total {}
Latest cost {}
Cumulative input {}
Cumulative output {}
Cumulative total {}",
Cumulative total {}
Cumulative cost {}",
usage.latest.total_tokens(),
format_usd(latest_cost),
usage.cumulative.input_tokens,
usage.cumulative.output_tokens,
usage.cumulative.total_tokens(),
format_usd(cumulative_cost),
),
format!(
"Workspace
@@ -1628,7 +1741,6 @@ fn format_status_report(
context.discovered_config_files,
context.memory_file_count,
),
format_sandbox_report(&context.sandbox_status),
]
.join(
"
@@ -1637,49 +1749,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>> {
let cwd = env::current_dir()?;
let loader = ConfigLoader::default_for(&cwd);
@@ -2420,9 +2489,9 @@ fn print_help() {
println!("rusty-claude-cli v{VERSION}");
println!();
println!("Usage:");
println!(" rusty-claude-cli [--model MODEL] [--allowedTools TOOL[,TOOL...]]");
println!(" rusty-claude-cli [--model MODEL] [--max-cost USD] [--allowedTools TOOL[,TOOL...]]");
println!(" Start the interactive REPL");
println!(" rusty-claude-cli [--model MODEL] [--output-format text|json] prompt TEXT");
println!(" rusty-claude-cli [--model MODEL] [--max-cost USD] [--output-format text|json] prompt TEXT");
println!(" Send one prompt and exit");
println!(" rusty-claude-cli [--model MODEL] [--output-format text|json] TEXT");
println!(" Shorthand non-interactive prompt mode");
@@ -2438,6 +2507,7 @@ fn print_help() {
println!(" --model MODEL Override the active model");
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!(" --max-cost USD Warn at 80% of budget and stop at/exceeding the budget");
println!(" --allowedTools TOOLS Restrict enabled tools (repeatable; comma-separated aliases supported)");
println!(" --version, -V Print version and build information locally");
println!();
@@ -2464,13 +2534,14 @@ fn print_help() {
#[cfg(test)]
mod tests {
use super::{
filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
format_model_report, format_model_switch_report, format_permissions_report,
format_permissions_switch_report, format_resume_report, format_status_report,
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
parse_git_status_metadata, render_config_report, render_init_claude_md,
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
budget_notice_message, filter_tool_specs, format_compact_report, format_cost_report,
format_init_report, format_model_report, format_model_switch_report,
format_permissions_report, format_permissions_switch_report, format_resume_report,
format_status_report, format_tool_call_start, format_tool_result,
normalize_permission_mode, parse_args, parse_git_status_metadata, render_config_report,
render_init_claude_md, render_memory_report, render_repl_help,
resume_supported_slash_commands, status_context, CliAction, CliOutputFormat, SlashCommand,
StatusUsage, DEFAULT_MODEL,
};
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
use std::path::{Path, PathBuf};
@@ -2483,6 +2554,7 @@ mod tests {
model: DEFAULT_MODEL.to_string(),
allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite,
max_cost_usd: None,
}
);
}
@@ -2502,6 +2574,7 @@ mod tests {
output_format: CliOutputFormat::Text,
allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite,
max_cost_usd: None,
}
);
}
@@ -2523,6 +2596,7 @@ mod tests {
output_format: CliOutputFormat::Json,
allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite,
max_cost_usd: None,
}
);
}
@@ -2548,10 +2622,32 @@ mod tests {
model: DEFAULT_MODEL.to_string(),
allowed_tools: None,
permission_mode: PermissionMode::ReadOnly,
max_cost_usd: None,
}
);
}
#[test]
fn parses_max_cost_flag() {
let args = vec!["--max-cost=1.25".to_string()];
assert_eq!(
parse_args(&args).expect("args should parse"),
CliAction::Repl {
model: DEFAULT_MODEL.to_string(),
allowed_tools: None,
permission_mode: PermissionMode::WorkspaceWrite,
max_cost_usd: Some(1.25),
}
);
}
#[test]
fn rejects_invalid_max_cost_flag() {
let error = parse_args(&["--max-cost".to_string(), "0".to_string()])
.expect_err("zero max cost should be rejected");
assert!(error.contains("--max-cost must be a positive finite USD amount"));
}
#[test]
fn parses_allowed_tools_flags_with_aliases_and_lists() {
let args = vec![
@@ -2570,6 +2666,7 @@ mod tests {
.collect()
),
permission_mode: PermissionMode::WorkspaceWrite,
max_cost_usd: None,
}
);
}
@@ -2676,7 +2773,6 @@ mod tests {
assert!(help.contains("REPL"));
assert!(help.contains("/help"));
assert!(help.contains("/status"));
assert!(help.contains("/sandbox"));
assert!(help.contains("/model [model]"));
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
assert!(help.contains("/clear [--confirm]"));
@@ -2701,8 +2797,8 @@ mod tests {
assert_eq!(
names,
vec![
"help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
"init", "diff", "version", "export",
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
"version", "export",
]
);
}
@@ -2728,18 +2824,24 @@ mod tests {
#[test]
fn cost_report_uses_sectioned_layout() {
let report = format_cost_report(runtime::TokenUsage {
input_tokens: 20,
output_tokens: 8,
cache_creation_input_tokens: 3,
cache_read_input_tokens: 1,
});
let report = format_cost_report(
"claude-sonnet",
runtime::TokenUsage {
input_tokens: 20,
output_tokens: 8,
cache_creation_input_tokens: 3,
cache_read_input_tokens: 1,
},
None,
);
assert!(report.contains("Cost"));
assert!(report.contains("Input tokens 20"));
assert!(report.contains("Output tokens 8"));
assert!(report.contains("Cache create 3"));
assert!(report.contains("Cache read 1"));
assert!(report.contains("Total tokens 32"));
assert!(report.contains("Estimated cost"));
assert!(report.contains("Budget $0.0010 (unlimited)"));
}
#[test]
@@ -2820,8 +2922,8 @@ mod tests {
memory_file_count: 4,
project_root: Some(PathBuf::from("/tmp")),
git_branch: Some("main".to_string()),
sandbox_status: runtime::SandboxStatus::default(),
},
Some(1.0),
);
assert!(status.contains("Status"));
assert!(status.contains("Model claude-sonnet"));
@@ -2829,6 +2931,7 @@ mod tests {
assert!(status.contains("Messages 7"));
assert!(status.contains("Latest total 10"));
assert!(status.contains("Cumulative total 31"));
assert!(status.contains("Cost budget $0.0009 / $1.0000"));
assert!(status.contains("Cwd /tmp/project"));
assert!(status.contains("Project root /tmp"));
assert!(status.contains("Git branch main"));
@@ -2837,6 +2940,22 @@ mod tests {
assert!(status.contains("Memory files 4"));
}
#[test]
fn budget_notice_warns_near_limit() {
let message = budget_notice_message(
"claude-sonnet",
runtime::TokenUsage {
input_tokens: 60_000,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
},
Some(1.0),
)
.expect("budget warning expected");
assert!(message.contains("approaching cost budget"));
}
#[test]
fn config_report_supports_section_views() {
let report = render_config_report(Some("env")).expect("config report should render");
@@ -2874,8 +2993,8 @@ mod tests {
fn status_context_reads_real_workspace_metadata() {
let context = status_context(None).expect("status context should load");
assert!(context.cwd.is_absolute());
assert_eq!(context.discovered_config_files, 5);
assert!(context.loaded_config_files <= context.discovered_config_files);
assert!(context.discovered_config_files >= context.loaded_config_files);
assert!(context.discovered_config_files >= 1);
}
#[test]
@@ -2982,17 +3101,3 @@ mod tests {
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,11 +62,7 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
"timeout": { "type": "integer", "minimum": 1 },
"description": { "type": "string" },
"run_in_background": { "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" } }
"dangerouslyDisableSandbox": { "type": "boolean" }
},
"required": ["command"],
"additionalProperties": false
@@ -2218,7 +2214,6 @@ fn execute_shell_command(
structured_content: None,
persisted_output_path: None,
persisted_output_size: None,
sandbox_status: None,
});
}
@@ -2256,7 +2251,6 @@ fn execute_shell_command(
structured_content: None,
persisted_output_path: None,
persisted_output_size: None,
sandbox_status: None,
});
}
if started.elapsed() >= Duration::from_millis(timeout_ms) {
@@ -2287,7 +2281,6 @@ Command exceeded timeout of {timeout_ms} ms",
structured_content: None,
persisted_output_path: None,
persisted_output_size: None,
sandbox_status: None,
});
}
std::thread::sleep(Duration::from_millis(10));
@@ -2314,7 +2307,6 @@ Command exceeded timeout of {timeout_ms} ms",
structured_content: None,
persisted_output_path: None,
persisted_output_size: None,
sandbox_status: None,
})
}