mirror of
https://github.com/instructkr/claw-code.git
synced 2026-04-04 02:44:49 +08:00
Compare commits
3 Commits
rcc/sandbo
...
rcc/runtim
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccebabe605 | ||
|
|
146260083c | ||
|
|
cd01d0e387 |
@@ -133,6 +133,7 @@ Inside the REPL, useful commands include:
|
|||||||
/diff
|
/diff
|
||||||
/version
|
/version
|
||||||
/export notes.txt
|
/export notes.txt
|
||||||
|
/sessions
|
||||||
/session list
|
/session list
|
||||||
/exit
|
/exit
|
||||||
```
|
```
|
||||||
@@ -143,14 +144,14 @@ Inspect or maintain a saved session file without entering the REPL:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd rust
|
cd rust
|
||||||
cargo run -p rusty-claude-cli -- --resume session.json /status /compact /cost
|
cargo run -p rusty-claude-cli -- --resume session-123456 /status /compact /cost
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also inspect memory/config state for a restored session:
|
You can also inspect memory/config state for a restored session:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd rust
|
cd rust
|
||||||
cargo run -p rusty-claude-cli -- --resume session.json /memory /config
|
cargo run -p rusty-claude-cli -- --resume ~/.claude/sessions/session-123456.json /memory /config
|
||||||
```
|
```
|
||||||
|
|
||||||
## Available commands
|
## Available commands
|
||||||
@@ -158,7 +159,7 @@ cargo run -p rusty-claude-cli -- --resume session.json /memory /config
|
|||||||
### Top-level CLI commands
|
### Top-level CLI commands
|
||||||
|
|
||||||
- `prompt <text...>` — run one prompt non-interactively
|
- `prompt <text...>` — run one prompt non-interactively
|
||||||
- `--resume <session.json> [/commands...]` — inspect or maintain a saved session
|
- `--resume <session-id-or-path> [/commands...]` — inspect or maintain a saved session stored under `~/.claude/sessions/`
|
||||||
- `dump-manifests` — print extracted upstream manifest counts
|
- `dump-manifests` — print extracted upstream manifest counts
|
||||||
- `bootstrap-plan` — print the current bootstrap skeleton
|
- `bootstrap-plan` — print the current bootstrap skeleton
|
||||||
- `system-prompt [--cwd PATH] [--date YYYY-MM-DD]` — render the synthesized system prompt
|
- `system-prompt [--cwd PATH] [--date YYYY-MM-DD]` — render the synthesized system prompt
|
||||||
@@ -176,13 +177,14 @@ cargo run -p rusty-claude-cli -- --resume session.json /memory /config
|
|||||||
- `/permissions [read-only|workspace-write|danger-full-access]` — inspect or switch permissions
|
- `/permissions [read-only|workspace-write|danger-full-access]` — inspect or switch permissions
|
||||||
- `/clear [--confirm]` — clear the current local session
|
- `/clear [--confirm]` — clear the current local session
|
||||||
- `/cost` — show token usage totals
|
- `/cost` — show token usage totals
|
||||||
- `/resume <session-path>` — load a saved session into the REPL
|
- `/resume <session-id-or-path>` — load a saved session into the REPL
|
||||||
- `/config [env|hooks|model]` — inspect discovered Claude config
|
- `/config [env|hooks|model]` — inspect discovered Claude config
|
||||||
- `/memory` — inspect loaded instruction memory files
|
- `/memory` — inspect loaded instruction memory files
|
||||||
- `/init` — create a starter `CLAUDE.md`
|
- `/init` — create a starter `CLAUDE.md`
|
||||||
- `/diff` — show the current git diff for the workspace
|
- `/diff` — show the current git diff for the workspace
|
||||||
- `/version` — print version and build metadata locally
|
- `/version` — print version and build metadata locally
|
||||||
- `/export [file]` — export the current conversation transcript
|
- `/export [file]` — export the current conversation transcript
|
||||||
|
- `/sessions` — list recent managed local sessions from `~/.claude/sessions/`
|
||||||
- `/session [list|switch <session-id>]` — inspect or switch managed local sessions
|
- `/session [list|switch <session-id>]` — inspect or switch managed local sessions
|
||||||
- `/exit` — leave the REPL
|
- `/exit` — leave the REPL
|
||||||
|
|
||||||
|
|||||||
@@ -51,12 +51,6 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: true,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
SlashCommandSpec {
|
|
||||||
name: "sandbox",
|
|
||||||
summary: "Show sandbox isolation status",
|
|
||||||
argument_hint: None,
|
|
||||||
resume_supported: true,
|
|
||||||
},
|
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "compact",
|
name: "compact",
|
||||||
summary: "Compact local session history",
|
summary: "Compact local session history",
|
||||||
@@ -90,7 +84,7 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "resume",
|
name: "resume",
|
||||||
summary: "Load a saved session into the REPL",
|
summary: "Load a saved session into the REPL",
|
||||||
argument_hint: Some("<session-path>"),
|
argument_hint: Some("<session-id-or-path>"),
|
||||||
resume_supported: false,
|
resume_supported: false,
|
||||||
},
|
},
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
@@ -135,13 +129,18 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
argument_hint: Some("[list|switch <session-id>]"),
|
argument_hint: Some("[list|switch <session-id>]"),
|
||||||
resume_supported: false,
|
resume_supported: false,
|
||||||
},
|
},
|
||||||
|
SlashCommandSpec {
|
||||||
|
name: "sessions",
|
||||||
|
summary: "List recent managed local sessions",
|
||||||
|
argument_hint: None,
|
||||||
|
resume_supported: false,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum SlashCommand {
|
pub enum SlashCommand {
|
||||||
Help,
|
Help,
|
||||||
Status,
|
Status,
|
||||||
Sandbox,
|
|
||||||
Compact,
|
Compact,
|
||||||
Model {
|
Model {
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
@@ -170,6 +169,7 @@ pub enum SlashCommand {
|
|||||||
action: Option<String>,
|
action: Option<String>,
|
||||||
target: Option<String>,
|
target: Option<String>,
|
||||||
},
|
},
|
||||||
|
Sessions,
|
||||||
Unknown(String),
|
Unknown(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -186,7 +186,6 @@ impl SlashCommand {
|
|||||||
Some(match command {
|
Some(match command {
|
||||||
"help" => Self::Help,
|
"help" => Self::Help,
|
||||||
"status" => Self::Status,
|
"status" => Self::Status,
|
||||||
"sandbox" => Self::Sandbox,
|
|
||||||
"compact" => Self::Compact,
|
"compact" => Self::Compact,
|
||||||
"model" => Self::Model {
|
"model" => Self::Model {
|
||||||
model: parts.next().map(ToOwned::to_owned),
|
model: parts.next().map(ToOwned::to_owned),
|
||||||
@@ -215,6 +214,7 @@ impl SlashCommand {
|
|||||||
action: parts.next().map(ToOwned::to_owned),
|
action: parts.next().map(ToOwned::to_owned),
|
||||||
target: parts.next().map(ToOwned::to_owned),
|
target: parts.next().map(ToOwned::to_owned),
|
||||||
},
|
},
|
||||||
|
"sessions" => Self::Sessions,
|
||||||
other => Self::Unknown(other.to_string()),
|
other => Self::Unknown(other.to_string()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -287,7 +287,6 @@ pub fn handle_slash_command(
|
|||||||
session: session.clone(),
|
session: session.clone(),
|
||||||
}),
|
}),
|
||||||
SlashCommand::Status
|
SlashCommand::Status
|
||||||
| SlashCommand::Sandbox
|
|
||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Clear { .. }
|
| SlashCommand::Clear { .. }
|
||||||
@@ -300,6 +299,7 @@ pub fn handle_slash_command(
|
|||||||
| SlashCommand::Version
|
| SlashCommand::Version
|
||||||
| SlashCommand::Export { .. }
|
| SlashCommand::Export { .. }
|
||||||
| SlashCommand::Session { .. }
|
| SlashCommand::Session { .. }
|
||||||
|
| SlashCommand::Sessions
|
||||||
| SlashCommand::Unknown(_) => None,
|
| SlashCommand::Unknown(_) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -316,7 +316,6 @@ mod tests {
|
|||||||
fn parses_supported_slash_commands() {
|
fn parses_supported_slash_commands() {
|
||||||
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
|
||||||
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
|
||||||
assert_eq!(SlashCommand::parse("/sandbox"), Some(SlashCommand::Sandbox));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
SlashCommand::parse("/model claude-opus"),
|
SlashCommand::parse("/model claude-opus"),
|
||||||
Some(SlashCommand::Model {
|
Some(SlashCommand::Model {
|
||||||
@@ -375,6 +374,10 @@ mod tests {
|
|||||||
target: Some("abc123".to_string())
|
target: Some("abc123".to_string())
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
SlashCommand::parse("/sessions"),
|
||||||
|
Some(SlashCommand::Sessions)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -383,13 +386,12 @@ mod tests {
|
|||||||
assert!(help.contains("works with --resume SESSION.json"));
|
assert!(help.contains("works with --resume SESSION.json"));
|
||||||
assert!(help.contains("/help"));
|
assert!(help.contains("/help"));
|
||||||
assert!(help.contains("/status"));
|
assert!(help.contains("/status"));
|
||||||
assert!(help.contains("/sandbox"));
|
|
||||||
assert!(help.contains("/compact"));
|
assert!(help.contains("/compact"));
|
||||||
assert!(help.contains("/model [model]"));
|
assert!(help.contains("/model [model]"));
|
||||||
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
|
||||||
assert!(help.contains("/clear [--confirm]"));
|
assert!(help.contains("/clear [--confirm]"));
|
||||||
assert!(help.contains("/cost"));
|
assert!(help.contains("/cost"));
|
||||||
assert!(help.contains("/resume <session-path>"));
|
assert!(help.contains("/resume <session-id-or-path>"));
|
||||||
assert!(help.contains("/config [env|hooks|model]"));
|
assert!(help.contains("/config [env|hooks|model]"));
|
||||||
assert!(help.contains("/memory"));
|
assert!(help.contains("/memory"));
|
||||||
assert!(help.contains("/init"));
|
assert!(help.contains("/init"));
|
||||||
@@ -397,8 +399,9 @@ mod tests {
|
|||||||
assert!(help.contains("/version"));
|
assert!(help.contains("/version"));
|
||||||
assert!(help.contains("/export [file]"));
|
assert!(help.contains("/export [file]"));
|
||||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||||
|
assert!(help.contains("/sessions"));
|
||||||
assert_eq!(slash_command_specs().len(), 16);
|
assert_eq!(slash_command_specs().len(), 16);
|
||||||
assert_eq!(resume_supported_slash_commands().len(), 12);
|
assert_eq!(resume_supported_slash_commands().len(), 11);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -415,6 +418,7 @@ mod tests {
|
|||||||
text: "recent".to_string(),
|
text: "recent".to_string(),
|
||||||
}]),
|
}]),
|
||||||
],
|
],
|
||||||
|
metadata: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = handle_slash_command(
|
let result = handle_slash_command(
|
||||||
@@ -445,7 +449,6 @@ mod tests {
|
|||||||
let session = Session::new();
|
let session = Session::new();
|
||||||
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
|
||||||
assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
|
assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
|
||||||
assert!(handle_slash_command("/sandbox", &session, CompactionConfig::default()).is_none());
|
|
||||||
assert!(
|
assert!(
|
||||||
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
|
||||||
);
|
);
|
||||||
@@ -480,5 +483,6 @@ mod tests {
|
|||||||
assert!(
|
assert!(
|
||||||
handle_slash_command("/session list", &session, CompactionConfig::default()).is_none()
|
handle_slash_command("/session list", &session, CompactionConfig::default()).is_none()
|
||||||
);
|
);
|
||||||
|
assert!(handle_slash_command("/sessions", &session, CompactionConfig::default()).is_none());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
use std::env;
|
|
||||||
use std::io;
|
use std::io;
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -8,12 +7,6 @@ use tokio::process::Command as TokioCommand;
|
|||||||
use tokio::runtime::Builder;
|
use tokio::runtime::Builder;
|
||||||
use tokio::time::timeout;
|
use tokio::time::timeout;
|
||||||
|
|
||||||
use crate::sandbox::{
|
|
||||||
build_linux_sandbox_command, resolve_sandbox_status_for_request, FilesystemIsolationMode,
|
|
||||||
SandboxConfig, SandboxStatus,
|
|
||||||
};
|
|
||||||
use crate::ConfigLoader;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
pub struct BashCommandInput {
|
pub struct BashCommandInput {
|
||||||
pub command: String,
|
pub command: String,
|
||||||
@@ -23,14 +16,6 @@ pub struct BashCommandInput {
|
|||||||
pub run_in_background: Option<bool>,
|
pub run_in_background: Option<bool>,
|
||||||
#[serde(rename = "dangerouslyDisableSandbox")]
|
#[serde(rename = "dangerouslyDisableSandbox")]
|
||||||
pub dangerously_disable_sandbox: Option<bool>,
|
pub dangerously_disable_sandbox: Option<bool>,
|
||||||
#[serde(rename = "namespaceRestrictions")]
|
|
||||||
pub namespace_restrictions: Option<bool>,
|
|
||||||
#[serde(rename = "isolateNetwork")]
|
|
||||||
pub isolate_network: Option<bool>,
|
|
||||||
#[serde(rename = "filesystemMode")]
|
|
||||||
pub filesystem_mode: Option<FilesystemIsolationMode>,
|
|
||||||
#[serde(rename = "allowedMounts")]
|
|
||||||
pub allowed_mounts: Option<Vec<String>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
@@ -60,17 +45,13 @@ pub struct BashCommandOutput {
|
|||||||
pub persisted_output_path: Option<String>,
|
pub persisted_output_path: Option<String>,
|
||||||
#[serde(rename = "persistedOutputSize")]
|
#[serde(rename = "persistedOutputSize")]
|
||||||
pub persisted_output_size: Option<u64>,
|
pub persisted_output_size: Option<u64>,
|
||||||
#[serde(rename = "sandboxStatus")]
|
|
||||||
pub sandbox_status: Option<SandboxStatus>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||||
let cwd = env::current_dir()?;
|
|
||||||
let sandbox_status = sandbox_status_for_input(&input, &cwd);
|
|
||||||
|
|
||||||
if input.run_in_background.unwrap_or(false) {
|
if input.run_in_background.unwrap_or(false) {
|
||||||
let mut child = prepare_command(&input.command, &cwd, &sandbox_status, false);
|
let child = Command::new("sh")
|
||||||
let child = child
|
.arg("-lc")
|
||||||
|
.arg(&input.command)
|
||||||
.stdin(Stdio::null())
|
.stdin(Stdio::null())
|
||||||
.stdout(Stdio::null())
|
.stdout(Stdio::null())
|
||||||
.stderr(Stdio::null())
|
.stderr(Stdio::null())
|
||||||
@@ -91,20 +72,16 @@ pub fn execute_bash(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: Some(sandbox_status),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let runtime = Builder::new_current_thread().enable_all().build()?;
|
let runtime = Builder::new_current_thread().enable_all().build()?;
|
||||||
runtime.block_on(execute_bash_async(input, sandbox_status, cwd))
|
runtime.block_on(execute_bash_async(input))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_bash_async(
|
async fn execute_bash_async(input: BashCommandInput) -> io::Result<BashCommandOutput> {
|
||||||
input: BashCommandInput,
|
let mut command = TokioCommand::new("sh");
|
||||||
sandbox_status: SandboxStatus,
|
command.arg("-lc").arg(&input.command);
|
||||||
cwd: std::path::PathBuf,
|
|
||||||
) -> io::Result<BashCommandOutput> {
|
|
||||||
let mut command = prepare_tokio_command(&input.command, &cwd, &sandbox_status, true);
|
|
||||||
|
|
||||||
let output_result = if let Some(timeout_ms) = input.timeout {
|
let output_result = if let Some(timeout_ms) = input.timeout {
|
||||||
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
match timeout(Duration::from_millis(timeout_ms), command.output()).await {
|
||||||
@@ -125,7 +102,6 @@ async fn execute_bash_async(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: Some(sandbox_status),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -160,88 +136,12 @@ async fn execute_bash_async(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: Some(sandbox_status),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sandbox_status_for_input(input: &BashCommandInput, cwd: &std::path::Path) -> SandboxStatus {
|
|
||||||
let config = ConfigLoader::default_for(cwd).load().map_or_else(
|
|
||||||
|_| SandboxConfig::default(),
|
|
||||||
|runtime_config| runtime_config.sandbox().clone(),
|
|
||||||
);
|
|
||||||
let request = config.resolve_request(
|
|
||||||
input.dangerously_disable_sandbox.map(|disabled| !disabled),
|
|
||||||
input.namespace_restrictions,
|
|
||||||
input.isolate_network,
|
|
||||||
input.filesystem_mode,
|
|
||||||
input.allowed_mounts.clone(),
|
|
||||||
);
|
|
||||||
resolve_sandbox_status_for_request(&request, cwd)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_command(
|
|
||||||
command: &str,
|
|
||||||
cwd: &std::path::Path,
|
|
||||||
sandbox_status: &SandboxStatus,
|
|
||||||
create_dirs: bool,
|
|
||||||
) -> Command {
|
|
||||||
if create_dirs {
|
|
||||||
prepare_sandbox_dirs(cwd);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
|
||||||
let mut prepared = Command::new(launcher.program);
|
|
||||||
prepared.args(launcher.args);
|
|
||||||
prepared.current_dir(cwd);
|
|
||||||
prepared.envs(launcher.env);
|
|
||||||
return prepared;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut prepared = Command::new("sh");
|
|
||||||
prepared.arg("-lc").arg(command).current_dir(cwd);
|
|
||||||
if sandbox_status.filesystem_active {
|
|
||||||
prepared.env("HOME", cwd.join(".sandbox-home"));
|
|
||||||
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
|
||||||
}
|
|
||||||
prepared
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_tokio_command(
|
|
||||||
command: &str,
|
|
||||||
cwd: &std::path::Path,
|
|
||||||
sandbox_status: &SandboxStatus,
|
|
||||||
create_dirs: bool,
|
|
||||||
) -> TokioCommand {
|
|
||||||
if create_dirs {
|
|
||||||
prepare_sandbox_dirs(cwd);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(launcher) = build_linux_sandbox_command(command, cwd, sandbox_status) {
|
|
||||||
let mut prepared = TokioCommand::new(launcher.program);
|
|
||||||
prepared.args(launcher.args);
|
|
||||||
prepared.current_dir(cwd);
|
|
||||||
prepared.envs(launcher.env);
|
|
||||||
return prepared;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut prepared = TokioCommand::new("sh");
|
|
||||||
prepared.arg("-lc").arg(command).current_dir(cwd);
|
|
||||||
if sandbox_status.filesystem_active {
|
|
||||||
prepared.env("HOME", cwd.join(".sandbox-home"));
|
|
||||||
prepared.env("TMPDIR", cwd.join(".sandbox-tmp"));
|
|
||||||
}
|
|
||||||
prepared
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare_sandbox_dirs(cwd: &std::path::Path) {
|
|
||||||
let _ = std::fs::create_dir_all(cwd.join(".sandbox-home"));
|
|
||||||
let _ = std::fs::create_dir_all(cwd.join(".sandbox-tmp"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{execute_bash, BashCommandInput};
|
use super::{execute_bash, BashCommandInput};
|
||||||
use crate::sandbox::FilesystemIsolationMode;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn executes_simple_command() {
|
fn executes_simple_command() {
|
||||||
@@ -251,33 +151,10 @@ mod tests {
|
|||||||
description: None,
|
description: None,
|
||||||
run_in_background: Some(false),
|
run_in_background: Some(false),
|
||||||
dangerously_disable_sandbox: Some(false),
|
dangerously_disable_sandbox: Some(false),
|
||||||
namespace_restrictions: Some(false),
|
|
||||||
isolate_network: Some(false),
|
|
||||||
filesystem_mode: Some(FilesystemIsolationMode::WorkspaceOnly),
|
|
||||||
allowed_mounts: None,
|
|
||||||
})
|
})
|
||||||
.expect("bash command should execute");
|
.expect("bash command should execute");
|
||||||
|
|
||||||
assert_eq!(output.stdout, "hello");
|
assert_eq!(output.stdout, "hello");
|
||||||
assert!(!output.interrupted);
|
assert!(!output.interrupted);
|
||||||
assert!(output.sandbox_status.is_some());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn disables_sandbox_when_requested() {
|
|
||||||
let output = execute_bash(BashCommandInput {
|
|
||||||
command: String::from("printf 'hello'"),
|
|
||||||
timeout: Some(1_000),
|
|
||||||
description: None,
|
|
||||||
run_in_background: Some(false),
|
|
||||||
dangerously_disable_sandbox: Some(true),
|
|
||||||
namespace_restrictions: None,
|
|
||||||
isolate_network: None,
|
|
||||||
filesystem_mode: None,
|
|
||||||
allowed_mounts: None,
|
|
||||||
})
|
|
||||||
.expect("bash command should execute");
|
|
||||||
|
|
||||||
assert!(!output.sandbox_status.expect("sandbox status").enabled);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ pub fn compact_session(session: &Session, config: CompactionConfig) -> Compactio
|
|||||||
compacted_session: Session {
|
compacted_session: Session {
|
||||||
version: session.version,
|
version: session.version,
|
||||||
messages: compacted_messages,
|
messages: compacted_messages,
|
||||||
|
metadata: session.metadata.clone(),
|
||||||
},
|
},
|
||||||
removed_message_count: removed.len(),
|
removed_message_count: removed.len(),
|
||||||
}
|
}
|
||||||
@@ -393,6 +394,7 @@ mod tests {
|
|||||||
let session = Session {
|
let session = Session {
|
||||||
version: 1,
|
version: 1,
|
||||||
messages: vec![ConversationMessage::user_text("hello")],
|
messages: vec![ConversationMessage::user_text("hello")],
|
||||||
|
metadata: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = compact_session(&session, CompactionConfig::default());
|
let result = compact_session(&session, CompactionConfig::default());
|
||||||
@@ -420,6 +422,7 @@ mod tests {
|
|||||||
usage: None,
|
usage: None,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
metadata: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = compact_session(
|
let result = compact_session(
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ use std::fs;
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
|
||||||
|
|
||||||
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
||||||
|
|
||||||
@@ -41,7 +40,6 @@ pub struct RuntimeFeatureConfig {
|
|||||||
oauth: Option<OAuthConfig>,
|
oauth: Option<OAuthConfig>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
permission_mode: Option<ResolvedPermissionMode>,
|
permission_mode: Option<ResolvedPermissionMode>,
|
||||||
sandbox: SandboxConfig,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@@ -227,7 +225,6 @@ impl ConfigLoader {
|
|||||||
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
oauth: parse_optional_oauth_config(&merged_value, "merged settings.oauth")?,
|
||||||
model: parse_optional_model(&merged_value),
|
model: parse_optional_model(&merged_value),
|
||||||
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
permission_mode: parse_optional_permission_mode(&merged_value)?,
|
||||||
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(RuntimeConfig {
|
Ok(RuntimeConfig {
|
||||||
@@ -292,11 +289,6 @@ impl RuntimeConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.feature_config.permission_mode
|
self.feature_config.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn sandbox(&self) -> &SandboxConfig {
|
|
||||||
&self.feature_config.sandbox
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeFeatureConfig {
|
impl RuntimeFeatureConfig {
|
||||||
@@ -319,11 +311,6 @@ impl RuntimeFeatureConfig {
|
|||||||
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
pub fn permission_mode(&self) -> Option<ResolvedPermissionMode> {
|
||||||
self.permission_mode
|
self.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn sandbox(&self) -> &SandboxConfig {
|
|
||||||
&self.sandbox
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl McpConfigCollection {
|
impl McpConfigCollection {
|
||||||
@@ -458,42 +445,6 @@ fn parse_permission_mode_label(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_optional_sandbox_config(root: &JsonValue) -> Result<SandboxConfig, ConfigError> {
|
|
||||||
let Some(object) = root.as_object() else {
|
|
||||||
return Ok(SandboxConfig::default());
|
|
||||||
};
|
|
||||||
let Some(sandbox_value) = object.get("sandbox") else {
|
|
||||||
return Ok(SandboxConfig::default());
|
|
||||||
};
|
|
||||||
let sandbox = expect_object(sandbox_value, "merged settings.sandbox")?;
|
|
||||||
let filesystem_mode = optional_string(sandbox, "filesystemMode", "merged settings.sandbox")?
|
|
||||||
.map(parse_filesystem_mode_label)
|
|
||||||
.transpose()?;
|
|
||||||
Ok(SandboxConfig {
|
|
||||||
enabled: optional_bool(sandbox, "enabled", "merged settings.sandbox")?,
|
|
||||||
namespace_restrictions: optional_bool(
|
|
||||||
sandbox,
|
|
||||||
"namespaceRestrictions",
|
|
||||||
"merged settings.sandbox",
|
|
||||||
)?,
|
|
||||||
network_isolation: optional_bool(sandbox, "networkIsolation", "merged settings.sandbox")?,
|
|
||||||
filesystem_mode,
|
|
||||||
allowed_mounts: optional_string_array(sandbox, "allowedMounts", "merged settings.sandbox")?
|
|
||||||
.unwrap_or_default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_filesystem_mode_label(value: &str) -> Result<FilesystemIsolationMode, ConfigError> {
|
|
||||||
match value {
|
|
||||||
"off" => Ok(FilesystemIsolationMode::Off),
|
|
||||||
"workspace-only" => Ok(FilesystemIsolationMode::WorkspaceOnly),
|
|
||||||
"allow-list" => Ok(FilesystemIsolationMode::AllowList),
|
|
||||||
other => Err(ConfigError::Parse(format!(
|
|
||||||
"merged settings.sandbox.filesystemMode: unsupported filesystem mode {other}"
|
|
||||||
))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_optional_oauth_config(
|
fn parse_optional_oauth_config(
|
||||||
root: &JsonValue,
|
root: &JsonValue,
|
||||||
context: &str,
|
context: &str,
|
||||||
@@ -737,7 +688,6 @@ mod tests {
|
|||||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
||||||
};
|
};
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
use crate::sandbox::FilesystemIsolationMode;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
@@ -842,44 +792,6 @@ mod tests {
|
|||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
fs::remove_dir_all(root).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_sandbox_config() {
|
|
||||||
let root = temp_dir();
|
|
||||||
let cwd = root.join("project");
|
|
||||||
let home = root.join("home").join(".claude");
|
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
|
||||||
|
|
||||||
fs::write(
|
|
||||||
cwd.join(".claude").join("settings.local.json"),
|
|
||||||
r#"{
|
|
||||||
"sandbox": {
|
|
||||||
"enabled": true,
|
|
||||||
"namespaceRestrictions": false,
|
|
||||||
"networkIsolation": true,
|
|
||||||
"filesystemMode": "allow-list",
|
|
||||||
"allowedMounts": ["logs", "tmp/cache"]
|
|
||||||
}
|
|
||||||
}"#,
|
|
||||||
)
|
|
||||||
.expect("write local settings");
|
|
||||||
|
|
||||||
let loaded = ConfigLoader::new(&cwd, &home)
|
|
||||||
.load()
|
|
||||||
.expect("config should load");
|
|
||||||
|
|
||||||
assert_eq!(loaded.sandbox().enabled, Some(true));
|
|
||||||
assert_eq!(loaded.sandbox().namespace_restrictions, Some(false));
|
|
||||||
assert_eq!(loaded.sandbox().network_isolation, Some(true));
|
|
||||||
assert_eq!(
|
|
||||||
loaded.sandbox().filesystem_mode,
|
|
||||||
Some(FilesystemIsolationMode::AllowList)
|
|
||||||
);
|
|
||||||
assert_eq!(loaded.sandbox().allowed_mounts, vec!["logs", "tmp/cache"]);
|
|
||||||
|
|
||||||
fs::remove_dir_all(root).expect("cleanup temp dir");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_typed_mcp_and_oauth_config() {
|
fn parses_typed_mcp_and_oauth_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ mod oauth;
|
|||||||
mod permissions;
|
mod permissions;
|
||||||
mod prompt;
|
mod prompt;
|
||||||
mod remote;
|
mod remote;
|
||||||
mod sandbox;
|
|
||||||
mod session;
|
mod session;
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
@@ -74,13 +73,9 @@ 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::{
|
pub use session::{
|
||||||
build_linux_sandbox_command, detect_container_environment, detect_container_environment_from,
|
ContentBlock, ConversationMessage, MessageRole, Session, SessionError, SessionMetadata,
|
||||||
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::{
|
pub use usage::{
|
||||||
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
format_usd, pricing_for_model, ModelPricing, TokenUsage, UsageCostEstimate, UsageTracker,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ pub enum PermissionMode {
|
|||||||
ReadOnly,
|
ReadOnly,
|
||||||
WorkspaceWrite,
|
WorkspaceWrite,
|
||||||
DangerFullAccess,
|
DangerFullAccess,
|
||||||
Prompt,
|
|
||||||
Allow,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PermissionMode {
|
impl PermissionMode {
|
||||||
@@ -16,8 +14,6 @@ impl PermissionMode {
|
|||||||
Self::ReadOnly => "read-only",
|
Self::ReadOnly => "read-only",
|
||||||
Self::WorkspaceWrite => "workspace-write",
|
Self::WorkspaceWrite => "workspace-write",
|
||||||
Self::DangerFullAccess => "danger-full-access",
|
Self::DangerFullAccess => "danger-full-access",
|
||||||
Self::Prompt => "prompt",
|
|
||||||
Self::Allow => "allow",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,7 +90,7 @@ impl PermissionPolicy {
|
|||||||
) -> PermissionOutcome {
|
) -> PermissionOutcome {
|
||||||
let current_mode = self.active_mode();
|
let current_mode = self.active_mode();
|
||||||
let required_mode = self.required_mode_for(tool_name);
|
let required_mode = self.required_mode_for(tool_name);
|
||||||
if current_mode == PermissionMode::Allow || current_mode >= required_mode {
|
if current_mode >= required_mode {
|
||||||
return PermissionOutcome::Allow;
|
return PermissionOutcome::Allow;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,9 +101,8 @@ impl PermissionPolicy {
|
|||||||
required_mode,
|
required_mode,
|
||||||
};
|
};
|
||||||
|
|
||||||
if current_mode == PermissionMode::Prompt
|
if current_mode == PermissionMode::WorkspaceWrite
|
||||||
|| (current_mode == PermissionMode::WorkspaceWrite
|
&& required_mode == PermissionMode::DangerFullAccess
|
||||||
&& required_mode == PermissionMode::DangerFullAccess)
|
|
||||||
{
|
{
|
||||||
return match prompter.as_mut() {
|
return match prompter.as_mut() {
|
||||||
Some(prompter) => match prompter.decide(&request) {
|
Some(prompter) => match prompter.decide(&request) {
|
||||||
|
|||||||
@@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -39,10 +39,19 @@ pub struct ConversationMessage {
|
|||||||
pub usage: Option<TokenUsage>,
|
pub usage: Option<TokenUsage>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SessionMetadata {
|
||||||
|
pub started_at: String,
|
||||||
|
pub model: String,
|
||||||
|
pub message_count: u32,
|
||||||
|
pub last_prompt: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Session {
|
pub struct Session {
|
||||||
pub version: u32,
|
pub version: u32,
|
||||||
pub messages: Vec<ConversationMessage>,
|
pub messages: Vec<ConversationMessage>,
|
||||||
|
pub metadata: Option<SessionMetadata>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -82,6 +91,7 @@ impl Session {
|
|||||||
Self {
|
Self {
|
||||||
version: 1,
|
version: 1,
|
||||||
messages: Vec::new(),
|
messages: Vec::new(),
|
||||||
|
metadata: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,6 +121,9 @@ impl Session {
|
|||||||
.collect(),
|
.collect(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
if let Some(metadata) = &self.metadata {
|
||||||
|
object.insert("metadata".to_string(), metadata.to_json());
|
||||||
|
}
|
||||||
JsonValue::Object(object)
|
JsonValue::Object(object)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,7 +144,15 @@ impl Session {
|
|||||||
.iter()
|
.iter()
|
||||||
.map(ConversationMessage::from_json)
|
.map(ConversationMessage::from_json)
|
||||||
.collect::<Result<Vec<_>, _>>()?;
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
Ok(Self { version, messages })
|
let metadata = object
|
||||||
|
.get("metadata")
|
||||||
|
.map(SessionMetadata::from_json)
|
||||||
|
.transpose()?;
|
||||||
|
Ok(Self {
|
||||||
|
version,
|
||||||
|
messages,
|
||||||
|
metadata,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,6 +162,41 @@ impl Default for Session {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl SessionMetadata {
|
||||||
|
#[must_use]
|
||||||
|
pub fn to_json(&self) -> JsonValue {
|
||||||
|
let mut object = BTreeMap::new();
|
||||||
|
object.insert(
|
||||||
|
"started_at".to_string(),
|
||||||
|
JsonValue::String(self.started_at.clone()),
|
||||||
|
);
|
||||||
|
object.insert("model".to_string(), JsonValue::String(self.model.clone()));
|
||||||
|
object.insert(
|
||||||
|
"message_count".to_string(),
|
||||||
|
JsonValue::Number(i64::from(self.message_count)),
|
||||||
|
);
|
||||||
|
if let Some(last_prompt) = &self.last_prompt {
|
||||||
|
object.insert(
|
||||||
|
"last_prompt".to_string(),
|
||||||
|
JsonValue::String(last_prompt.clone()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
JsonValue::Object(object)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_json(value: &JsonValue) -> Result<Self, SessionError> {
|
||||||
|
let object = value.as_object().ok_or_else(|| {
|
||||||
|
SessionError::Format("session metadata must be an object".to_string())
|
||||||
|
})?;
|
||||||
|
Ok(Self {
|
||||||
|
started_at: required_string(object, "started_at")?,
|
||||||
|
model: required_string(object, "model")?,
|
||||||
|
message_count: required_u32(object, "message_count")?,
|
||||||
|
last_prompt: optional_string(object, "last_prompt"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl ConversationMessage {
|
impl ConversationMessage {
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn user_text(text: impl Into<String>) -> Self {
|
pub fn user_text(text: impl Into<String>) -> Self {
|
||||||
@@ -368,6 +424,13 @@ fn required_string(
|
|||||||
.ok_or_else(|| SessionError::Format(format!("missing {key}")))
|
.ok_or_else(|| SessionError::Format(format!("missing {key}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn optional_string(object: &BTreeMap<String, JsonValue>, key: &str) -> Option<String> {
|
||||||
|
object
|
||||||
|
.get(key)
|
||||||
|
.and_then(JsonValue::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
}
|
||||||
|
|
||||||
fn required_u32(object: &BTreeMap<String, JsonValue>, key: &str) -> Result<u32, SessionError> {
|
fn required_u32(object: &BTreeMap<String, JsonValue>, key: &str) -> Result<u32, SessionError> {
|
||||||
let value = object
|
let value = object
|
||||||
.get(key)
|
.get(key)
|
||||||
@@ -378,7 +441,8 @@ fn required_u32(object: &BTreeMap<String, JsonValue>, key: &str) -> Result<u32,
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{ContentBlock, ConversationMessage, MessageRole, Session};
|
use super::{ContentBlock, ConversationMessage, MessageRole, Session, SessionMetadata};
|
||||||
|
use crate::json::JsonValue;
|
||||||
use crate::usage::TokenUsage;
|
use crate::usage::TokenUsage;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
@@ -386,6 +450,12 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn persists_and_restores_session_json() {
|
fn persists_and_restores_session_json() {
|
||||||
let mut session = Session::new();
|
let mut session = Session::new();
|
||||||
|
session.metadata = Some(SessionMetadata {
|
||||||
|
started_at: "2026-04-01T00:00:00Z".to_string(),
|
||||||
|
model: "claude-sonnet".to_string(),
|
||||||
|
message_count: 3,
|
||||||
|
last_prompt: Some("hello".to_string()),
|
||||||
|
});
|
||||||
session
|
session
|
||||||
.messages
|
.messages
|
||||||
.push(ConversationMessage::user_text("hello"));
|
.push(ConversationMessage::user_text("hello"));
|
||||||
@@ -428,5 +498,23 @@ mod tests {
|
|||||||
restored.messages[1].usage.expect("usage").total_tokens(),
|
restored.messages[1].usage.expect("usage").total_tokens(),
|
||||||
17
|
17
|
||||||
);
|
);
|
||||||
|
assert_eq!(restored.metadata, session.metadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn loads_legacy_session_without_metadata() {
|
||||||
|
let legacy = r#"{
|
||||||
|
"version": 1,
|
||||||
|
"messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"blocks": [{"type": "text", "text": "hello"}]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
let restored = Session::from_json(&JsonValue::parse(legacy).expect("legacy json"))
|
||||||
|
.expect("legacy session should parse");
|
||||||
|
assert_eq!(restored.messages.len(), 1);
|
||||||
|
assert!(restored.metadata.is_none());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -300,6 +300,7 @@ mod tests {
|
|||||||
cache_read_input_tokens: 0,
|
cache_read_input_tokens: 0,
|
||||||
}),
|
}),
|
||||||
}],
|
}],
|
||||||
|
metadata: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let tracker = UsageTracker::from_session(&session);
|
let tracker = UsageTracker::from_session(&session);
|
||||||
|
|||||||
@@ -23,11 +23,11 @@ use compat_harness::{extract_manifest, UpstreamPaths};
|
|||||||
use render::{Spinner, TerminalRenderer};
|
use render::{Spinner, TerminalRenderer};
|
||||||
use runtime::{
|
use runtime::{
|
||||||
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
clear_oauth_credentials, generate_pkce_pair, generate_state, load_system_prompt,
|
||||||
parse_oauth_callback_request_target, resolve_sandbox_status, save_oauth_credentials, ApiClient,
|
parse_oauth_callback_request_target, save_oauth_credentials, ApiClient, ApiRequest,
|
||||||
ApiRequest, AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
AssistantEvent, CompactionConfig, ConfigLoader, ConfigSource, ContentBlock,
|
||||||
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
ConversationMessage, ConversationRuntime, MessageRole, OAuthAuthorizationRequest,
|
||||||
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
OAuthTokenExchangeRequest, PermissionMode, PermissionPolicy, ProjectContext, RuntimeError,
|
||||||
Session, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
Session, SessionMetadata, TokenUsage, ToolError, ToolExecutor, UsageTracker,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
use tools::{execute_tool, mvp_tool_specs, ToolSpec};
|
||||||
@@ -37,6 +37,7 @@ const DEFAULT_MAX_TOKENS: u32 = 32;
|
|||||||
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");
|
||||||
|
const OLD_SESSION_COMPACTION_AGE_SECS: u64 = 60 * 60 * 24;
|
||||||
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
|
const BUILD_TARGET: Option<&str> = option_env!("TARGET");
|
||||||
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
|
const GIT_SHA: Option<&str> = option_env!("GIT_SHA");
|
||||||
|
|
||||||
@@ -535,7 +536,14 @@ fn print_version() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn resume_session(session_path: &Path, commands: &[String]) {
|
fn resume_session(session_path: &Path, commands: &[String]) {
|
||||||
let session = match Session::load_from_path(session_path) {
|
let handle = match resolve_session_reference(&session_path.display().to_string()) {
|
||||||
|
Ok(handle) => handle,
|
||||||
|
Err(error) => {
|
||||||
|
eprintln!("failed to resolve session: {error}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let session = match Session::load_from_path(&handle.path) {
|
||||||
Ok(session) => session,
|
Ok(session) => session,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
eprintln!("failed to restore session: {error}");
|
eprintln!("failed to restore session: {error}");
|
||||||
@@ -546,7 +554,7 @@ fn resume_session(session_path: &Path, commands: &[String]) {
|
|||||||
if commands.is_empty() {
|
if commands.is_empty() {
|
||||||
println!(
|
println!(
|
||||||
"Restored session from {} ({} messages).",
|
"Restored session from {} ({} messages).",
|
||||||
session_path.display(),
|
handle.path.display(),
|
||||||
session.messages.len()
|
session.messages.len()
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
@@ -558,7 +566,7 @@ fn resume_session(session_path: &Path, commands: &[String]) {
|
|||||||
eprintln!("unsupported resumed command: {raw_command}");
|
eprintln!("unsupported resumed command: {raw_command}");
|
||||||
std::process::exit(2);
|
std::process::exit(2);
|
||||||
};
|
};
|
||||||
match run_resume_command(session_path, &session, &command) {
|
match run_resume_command(&handle.path, &session, &command) {
|
||||||
Ok(ResumeCommandOutcome {
|
Ok(ResumeCommandOutcome {
|
||||||
session: next_session,
|
session: next_session,
|
||||||
message,
|
message,
|
||||||
@@ -591,7 +599,6 @@ struct StatusContext {
|
|||||||
memory_file_count: usize,
|
memory_file_count: usize,
|
||||||
project_root: Option<PathBuf>,
|
project_root: Option<PathBuf>,
|
||||||
git_branch: Option<String>,
|
git_branch: Option<String>,
|
||||||
sandbox_status: runtime::SandboxStatus,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
@@ -841,18 +848,6 @@ fn run_resume_command(
|
|||||||
)),
|
)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
SlashCommand::Sandbox => {
|
|
||||||
let cwd = env::current_dir()?;
|
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
|
||||||
let runtime_config = loader.load()?;
|
|
||||||
Ok(ResumeCommandOutcome {
|
|
||||||
session: session.clone(),
|
|
||||||
message: Some(format_sandbox_report(&resolve_sandbox_status(
|
|
||||||
runtime_config.sandbox(),
|
|
||||||
&cwd,
|
|
||||||
))),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
SlashCommand::Cost => {
|
SlashCommand::Cost => {
|
||||||
let usage = UsageTracker::from_session(session).cumulative_usage();
|
let usage = UsageTracker::from_session(session).cumulative_usage();
|
||||||
Ok(ResumeCommandOutcome {
|
Ok(ResumeCommandOutcome {
|
||||||
@@ -896,6 +891,7 @@ fn run_resume_command(
|
|||||||
| SlashCommand::Model { .. }
|
| SlashCommand::Model { .. }
|
||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Session { .. }
|
| SlashCommand::Session { .. }
|
||||||
|
| SlashCommand::Sessions
|
||||||
| SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
|
| SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -952,6 +948,9 @@ struct ManagedSessionSummary {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
modified_epoch_secs: u64,
|
modified_epoch_secs: u64,
|
||||||
message_count: usize,
|
message_count: usize,
|
||||||
|
model: Option<String>,
|
||||||
|
started_at: Option<String>,
|
||||||
|
last_prompt: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct LiveCli {
|
struct LiveCli {
|
||||||
@@ -972,6 +971,7 @@ impl LiveCli {
|
|||||||
) -> 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()?;
|
||||||
|
auto_compact_inactive_sessions(&session.id)?;
|
||||||
let runtime = build_runtime(
|
let runtime = build_runtime(
|
||||||
Session::new(),
|
Session::new(),
|
||||||
model.clone(),
|
model.clone(),
|
||||||
@@ -1104,10 +1104,6 @@ impl LiveCli {
|
|||||||
self.print_status();
|
self.print_status();
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Sandbox => {
|
|
||||||
Self::print_sandbox_status();
|
|
||||||
false
|
|
||||||
}
|
|
||||||
SlashCommand::Compact => {
|
SlashCommand::Compact => {
|
||||||
self.compact()?;
|
self.compact()?;
|
||||||
false
|
false
|
||||||
@@ -1147,6 +1143,10 @@ impl LiveCli {
|
|||||||
SlashCommand::Session { action, target } => {
|
SlashCommand::Session { action, target } => {
|
||||||
self.handle_session_command(action.as_deref(), target.as_deref())?
|
self.handle_session_command(action.as_deref(), target.as_deref())?
|
||||||
}
|
}
|
||||||
|
SlashCommand::Sessions => {
|
||||||
|
println!("{}", render_session_list(&self.session.id)?);
|
||||||
|
false
|
||||||
|
}
|
||||||
SlashCommand::Unknown(name) => {
|
SlashCommand::Unknown(name) => {
|
||||||
eprintln!("unknown slash command: /{name}");
|
eprintln!("unknown slash command: /{name}");
|
||||||
false
|
false
|
||||||
@@ -1155,7 +1155,10 @@ impl LiveCli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn persist_session(&self) -> Result<(), Box<dyn std::error::Error>> {
|
fn persist_session(&self) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
self.runtime.session().save_to_path(&self.session.path)?;
|
let mut session = self.runtime.session().clone();
|
||||||
|
session.metadata = Some(derive_session_metadata(&session, &self.model));
|
||||||
|
session.save_to_path(&self.session.path)?;
|
||||||
|
auto_compact_inactive_sessions(&self.session.id)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1179,18 +1182,6 @@ impl LiveCli {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn print_sandbox_status() {
|
|
||||||
let cwd = env::current_dir().expect("current dir");
|
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
|
||||||
let runtime_config = loader
|
|
||||||
.load()
|
|
||||||
.unwrap_or_else(|_| runtime::RuntimeConfig::empty());
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
format_sandbox_report(&resolve_sandbox_status(runtime_config.sandbox(), &cwd))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
|
fn set_model(&mut self, model: Option<String>) -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
let Some(model) = model else {
|
let Some(model) = model else {
|
||||||
println!(
|
println!(
|
||||||
@@ -1312,13 +1303,20 @@ impl LiveCli {
|
|||||||
session_path: Option<String>,
|
session_path: Option<String>,
|
||||||
) -> Result<bool, Box<dyn std::error::Error>> {
|
) -> Result<bool, Box<dyn std::error::Error>> {
|
||||||
let Some(session_ref) = session_path else {
|
let Some(session_ref) = session_path else {
|
||||||
println!("Usage: /resume <session-path>");
|
println!("Usage: /resume <session-id-or-path>");
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
let handle = resolve_session_reference(&session_ref)?;
|
let handle = resolve_session_reference(&session_ref)?;
|
||||||
let session = Session::load_from_path(&handle.path)?;
|
let session = Session::load_from_path(&handle.path)?;
|
||||||
let message_count = session.messages.len();
|
let message_count = session.messages.len();
|
||||||
|
if let Some(model) = session
|
||||||
|
.metadata
|
||||||
|
.as_ref()
|
||||||
|
.map(|metadata| metadata.model.clone())
|
||||||
|
{
|
||||||
|
self.model = model;
|
||||||
|
}
|
||||||
self.runtime = build_runtime(
|
self.runtime = build_runtime(
|
||||||
session,
|
session,
|
||||||
self.model.clone(),
|
self.model.clone(),
|
||||||
@@ -1395,6 +1393,13 @@ impl LiveCli {
|
|||||||
let handle = resolve_session_reference(target)?;
|
let handle = resolve_session_reference(target)?;
|
||||||
let session = Session::load_from_path(&handle.path)?;
|
let session = Session::load_from_path(&handle.path)?;
|
||||||
let message_count = session.messages.len();
|
let message_count = session.messages.len();
|
||||||
|
if let Some(model) = session
|
||||||
|
.metadata
|
||||||
|
.as_ref()
|
||||||
|
.map(|metadata| metadata.model.clone())
|
||||||
|
{
|
||||||
|
self.model = model;
|
||||||
|
}
|
||||||
self.runtime = build_runtime(
|
self.runtime = build_runtime(
|
||||||
session,
|
session,
|
||||||
self.model.clone(),
|
self.model.clone(),
|
||||||
@@ -1439,8 +1444,10 @@ impl LiveCli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sessions_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
fn sessions_dir() -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||||
let cwd = env::current_dir()?;
|
let home = env::var_os("HOME")
|
||||||
let path = cwd.join(".claude").join("sessions");
|
.map(PathBuf::from)
|
||||||
|
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "HOME is not set"))?;
|
||||||
|
let path = home.join(".claude").join("sessions");
|
||||||
fs::create_dir_all(&path)?;
|
fs::create_dir_all(&path)?;
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
@@ -1461,8 +1468,19 @@ fn generate_session_id() -> String {
|
|||||||
|
|
||||||
fn resolve_session_reference(reference: &str) -> Result<SessionHandle, Box<dyn std::error::Error>> {
|
fn resolve_session_reference(reference: &str) -> Result<SessionHandle, Box<dyn std::error::Error>> {
|
||||||
let direct = PathBuf::from(reference);
|
let direct = PathBuf::from(reference);
|
||||||
|
let expanded = if let Some(stripped) = reference.strip_prefix("~/") {
|
||||||
|
sessions_dir()?
|
||||||
|
.parent()
|
||||||
|
.and_then(|claude| claude.parent())
|
||||||
|
.map(|home| home.join(stripped))
|
||||||
|
.unwrap_or(direct.clone())
|
||||||
|
} else {
|
||||||
|
direct.clone()
|
||||||
|
};
|
||||||
let path = if direct.exists() {
|
let path = if direct.exists() {
|
||||||
direct
|
direct
|
||||||
|
} else if expanded.exists() {
|
||||||
|
expanded
|
||||||
} else {
|
} else {
|
||||||
sessions_dir()?.join(format!("{reference}.json"))
|
sessions_dir()?.join(format!("{reference}.json"))
|
||||||
};
|
};
|
||||||
@@ -1492,9 +1510,11 @@ fn list_managed_sessions() -> Result<Vec<ManagedSessionSummary>, Box<dyn std::er
|
|||||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||||
.map(|duration| duration.as_secs())
|
.map(|duration| duration.as_secs())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let message_count = Session::load_from_path(&path)
|
let session = Session::load_from_path(&path).ok();
|
||||||
.map(|session| session.messages.len())
|
let derived_message_count = session.as_ref().map_or(0, |session| session.messages.len());
|
||||||
.unwrap_or_default();
|
let stored = session
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|session| session.metadata.as_ref());
|
||||||
let id = path
|
let id = path
|
||||||
.file_stem()
|
.file_stem()
|
||||||
.and_then(|value| value.to_str())
|
.and_then(|value| value.to_str())
|
||||||
@@ -1504,7 +1524,12 @@ fn list_managed_sessions() -> Result<Vec<ManagedSessionSummary>, Box<dyn std::er
|
|||||||
id,
|
id,
|
||||||
path,
|
path,
|
||||||
modified_epoch_secs,
|
modified_epoch_secs,
|
||||||
message_count,
|
message_count: stored.map_or(derived_message_count, |metadata| {
|
||||||
|
metadata.message_count as usize
|
||||||
|
}),
|
||||||
|
model: stored.map(|metadata| metadata.model.clone()),
|
||||||
|
started_at: stored.map(|metadata| metadata.started_at.clone()),
|
||||||
|
last_prompt: stored.and_then(|metadata| metadata.last_prompt.clone()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
sessions.sort_by(|left, right| right.modified_epoch_secs.cmp(&left.modified_epoch_secs));
|
sessions.sort_by(|left, right| right.modified_epoch_secs.cmp(&left.modified_epoch_secs));
|
||||||
@@ -1527,17 +1552,99 @@ fn render_session_list(active_session_id: &str) -> Result<String, Box<dyn std::e
|
|||||||
} else {
|
} else {
|
||||||
"○ saved"
|
"○ saved"
|
||||||
};
|
};
|
||||||
|
let model = session.model.as_deref().unwrap_or("unknown");
|
||||||
|
let started = session.started_at.as_deref().unwrap_or("unknown");
|
||||||
|
let last_prompt = session.last_prompt.as_deref().map_or_else(
|
||||||
|
|| "-".to_string(),
|
||||||
|
|prompt| truncate_for_summary(prompt, 36),
|
||||||
|
);
|
||||||
lines.push(format!(
|
lines.push(format!(
|
||||||
" {id:<20} {marker:<10} msgs={msgs:<4} modified={modified} path={path}",
|
" {id:<20} {marker:<10} msgs={msgs:<4} model={model:<24} started={started} modified={modified} last={last_prompt} path={path}",
|
||||||
id = session.id,
|
id = session.id,
|
||||||
msgs = session.message_count,
|
msgs = session.message_count,
|
||||||
|
model = model,
|
||||||
|
started = started,
|
||||||
modified = session.modified_epoch_secs,
|
modified = session.modified_epoch_secs,
|
||||||
|
last_prompt = last_prompt,
|
||||||
path = session.path.display(),
|
path = session.path.display(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Ok(lines.join("\n"))
|
Ok(lines.join("\n"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn current_epoch_secs() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|duration| duration.as_secs())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_timestamp_rfc3339ish() -> String {
|
||||||
|
format!("{}Z", current_epoch_secs())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn last_prompt_from_session(session: &Session) -> Option<String> {
|
||||||
|
session
|
||||||
|
.messages
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|message| message.role == MessageRole::User)
|
||||||
|
.and_then(|message| {
|
||||||
|
message.blocks.iter().find_map(|block| match block {
|
||||||
|
ContentBlock::Text { text } => Some(text.trim().to_string()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.filter(|text| !text.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn derive_session_metadata(session: &Session, model: &str) -> SessionMetadata {
|
||||||
|
let started_at = session
|
||||||
|
.metadata
|
||||||
|
.as_ref()
|
||||||
|
.map_or_else(current_timestamp_rfc3339ish, |metadata| {
|
||||||
|
metadata.started_at.clone()
|
||||||
|
});
|
||||||
|
SessionMetadata {
|
||||||
|
started_at,
|
||||||
|
model: model.to_string(),
|
||||||
|
message_count: session.messages.len().try_into().unwrap_or(u32::MAX),
|
||||||
|
last_prompt: last_prompt_from_session(session),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_age_secs(modified_epoch_secs: u64) -> u64 {
|
||||||
|
current_epoch_secs().saturating_sub(modified_epoch_secs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auto_compact_inactive_sessions(
|
||||||
|
active_session_id: &str,
|
||||||
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
for summary in list_managed_sessions()? {
|
||||||
|
if summary.id == active_session_id
|
||||||
|
|| session_age_secs(summary.modified_epoch_secs) < OLD_SESSION_COMPACTION_AGE_SECS
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let path = summary.path.clone();
|
||||||
|
let Ok(session) = Session::load_from_path(&path) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if !runtime::should_compact(&session, CompactionConfig::default()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut compacted =
|
||||||
|
runtime::compact_session(&session, CompactionConfig::default()).compacted_session;
|
||||||
|
let model = compacted.metadata.as_ref().map_or_else(
|
||||||
|
|| DEFAULT_MODEL.to_string(),
|
||||||
|
|metadata| metadata.model.clone(),
|
||||||
|
);
|
||||||
|
compacted.metadata = Some(derive_session_metadata(&compacted, &model));
|
||||||
|
compacted.save_to_path(&path)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn render_repl_help() -> String {
|
fn render_repl_help() -> String {
|
||||||
[
|
[
|
||||||
"REPL".to_string(),
|
"REPL".to_string(),
|
||||||
@@ -1566,7 +1673,6 @@ fn status_context(
|
|||||||
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
let project_context = ProjectContext::discover_with_git(&cwd, DEFAULT_DATE)?;
|
||||||
let (project_root, git_branch) =
|
let (project_root, git_branch) =
|
||||||
parse_git_status_metadata(project_context.git_status.as_deref());
|
parse_git_status_metadata(project_context.git_status.as_deref());
|
||||||
let sandbox_status = resolve_sandbox_status(runtime_config.sandbox(), &cwd);
|
|
||||||
Ok(StatusContext {
|
Ok(StatusContext {
|
||||||
cwd,
|
cwd,
|
||||||
session_path: session_path.map(Path::to_path_buf),
|
session_path: session_path.map(Path::to_path_buf),
|
||||||
@@ -1575,7 +1681,6 @@ fn status_context(
|
|||||||
memory_file_count: project_context.instruction_files.len(),
|
memory_file_count: project_context.instruction_files.len(),
|
||||||
project_root,
|
project_root,
|
||||||
git_branch,
|
git_branch,
|
||||||
sandbox_status,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1628,7 +1733,6 @@ fn format_status_report(
|
|||||||
context.discovered_config_files,
|
context.discovered_config_files,
|
||||||
context.memory_file_count,
|
context.memory_file_count,
|
||||||
),
|
),
|
||||||
format_sandbox_report(&context.sandbox_status),
|
|
||||||
]
|
]
|
||||||
.join(
|
.join(
|
||||||
"
|
"
|
||||||
@@ -1637,49 +1741,6 @@ fn format_status_report(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_sandbox_report(status: &runtime::SandboxStatus) -> String {
|
|
||||||
format!(
|
|
||||||
"Sandbox
|
|
||||||
Enabled {}
|
|
||||||
Active {}
|
|
||||||
Supported {}
|
|
||||||
In container {}
|
|
||||||
Requested ns {}
|
|
||||||
Active ns {}
|
|
||||||
Requested net {}
|
|
||||||
Active net {}
|
|
||||||
Filesystem mode {}
|
|
||||||
Filesystem active {}
|
|
||||||
Allowed mounts {}
|
|
||||||
Markers {}
|
|
||||||
Fallback reason {}",
|
|
||||||
status.enabled,
|
|
||||||
status.active,
|
|
||||||
status.supported,
|
|
||||||
status.in_container,
|
|
||||||
status.requested.namespace_restrictions,
|
|
||||||
status.namespace_active,
|
|
||||||
status.requested.network_isolation,
|
|
||||||
status.network_active,
|
|
||||||
status.filesystem_mode.as_str(),
|
|
||||||
status.filesystem_active,
|
|
||||||
if status.allowed_mounts.is_empty() {
|
|
||||||
"<none>".to_string()
|
|
||||||
} else {
|
|
||||||
status.allowed_mounts.join(", ")
|
|
||||||
},
|
|
||||||
if status.container_markers.is_empty() {
|
|
||||||
"<none>".to_string()
|
|
||||||
} else {
|
|
||||||
status.container_markers.join(", ")
|
|
||||||
},
|
|
||||||
status
|
|
||||||
.fallback_reason
|
|
||||||
.clone()
|
|
||||||
.unwrap_or_else(|| "<none>".to_string()),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
|
fn render_config_report(section: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
|
||||||
let cwd = env::current_dir()?;
|
let cwd = env::current_dir()?;
|
||||||
let loader = ConfigLoader::default_for(&cwd);
|
let loader = ConfigLoader::default_for(&cwd);
|
||||||
@@ -2464,17 +2525,73 @@ fn print_help() {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
filter_tool_specs, format_compact_report, format_cost_report, format_init_report,
|
derive_session_metadata, filter_tool_specs, format_compact_report, format_cost_report,
|
||||||
format_model_report, format_model_switch_report, format_permissions_report,
|
format_init_report, format_model_report, format_model_switch_report,
|
||||||
format_permissions_switch_report, format_resume_report, format_status_report,
|
format_permissions_report, format_permissions_switch_report, format_resume_report,
|
||||||
format_tool_call_start, format_tool_result, normalize_permission_mode, parse_args,
|
format_status_report, format_tool_call_start, format_tool_result, list_managed_sessions,
|
||||||
parse_git_status_metadata, render_config_report, render_init_claude_md,
|
normalize_permission_mode, parse_args, parse_git_status_metadata, render_config_report,
|
||||||
render_memory_report, render_repl_help, resume_supported_slash_commands, status_context,
|
render_init_claude_md, render_memory_report, render_repl_help,
|
||||||
CliAction, CliOutputFormat, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
resume_supported_slash_commands, sessions_dir, status_context, CliAction, CliOutputFormat,
|
||||||
|
SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||||
};
|
};
|
||||||
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
use runtime::{ContentBlock, ConversationMessage, MessageRole, PermissionMode, Session};
|
||||||
|
use std::fs;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn derive_session_metadata_recomputes_prompt_and_count() {
|
||||||
|
let mut session = Session::new();
|
||||||
|
session
|
||||||
|
.messages
|
||||||
|
.push(ConversationMessage::user_text("first prompt"));
|
||||||
|
session
|
||||||
|
.messages
|
||||||
|
.push(ConversationMessage::assistant(vec![ContentBlock::Text {
|
||||||
|
text: "reply".to_string(),
|
||||||
|
}]));
|
||||||
|
let metadata = derive_session_metadata(&session, "claude-test");
|
||||||
|
assert_eq!(metadata.model, "claude-test");
|
||||||
|
assert_eq!(metadata.message_count, 2);
|
||||||
|
assert_eq!(metadata.last_prompt.as_deref(), Some("first prompt"));
|
||||||
|
assert!(metadata.started_at.ends_with('Z'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn managed_sessions_use_home_directory_and_list_metadata() {
|
||||||
|
let temp =
|
||||||
|
std::env::temp_dir().join(format!("rusty-claude-cli-home-{}", std::process::id()));
|
||||||
|
let _ = fs::remove_dir_all(&temp);
|
||||||
|
fs::create_dir_all(&temp).expect("temp home should exist");
|
||||||
|
let previous_home = std::env::var_os("HOME");
|
||||||
|
std::env::set_var("HOME", &temp);
|
||||||
|
|
||||||
|
let dir = sessions_dir().expect("sessions dir");
|
||||||
|
assert_eq!(dir, temp.join(".claude").join("sessions"));
|
||||||
|
|
||||||
|
let mut session = Session::new();
|
||||||
|
session
|
||||||
|
.messages
|
||||||
|
.push(ConversationMessage::user_text("persist me"));
|
||||||
|
session.metadata = Some(derive_session_metadata(&session, "claude-home"));
|
||||||
|
let file = dir.join("session-test.json");
|
||||||
|
session.save_to_path(&file).expect("session save");
|
||||||
|
|
||||||
|
let listed = list_managed_sessions().expect("session list");
|
||||||
|
let found = listed
|
||||||
|
.into_iter()
|
||||||
|
.find(|entry| entry.id == "session-test")
|
||||||
|
.expect("saved session should be listed");
|
||||||
|
assert_eq!(found.message_count, 1);
|
||||||
|
assert_eq!(found.model.as_deref(), Some("claude-home"));
|
||||||
|
assert_eq!(found.last_prompt.as_deref(), Some("persist me"));
|
||||||
|
|
||||||
|
fs::remove_file(file).ok();
|
||||||
|
if let Some(previous_home) = previous_home {
|
||||||
|
std::env::set_var("HOME", previous_home);
|
||||||
|
}
|
||||||
|
fs::remove_dir_all(temp).ok();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn defaults_to_repl_when_no_args() {
|
fn defaults_to_repl_when_no_args() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -2676,12 +2793,12 @@ 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]"));
|
||||||
assert!(help.contains("/cost"));
|
assert!(help.contains("/cost"));
|
||||||
assert!(help.contains("/resume <session-path>"));
|
assert!(help.contains("/resume <session-id-or-path>"));
|
||||||
|
assert!(help.contains("/sessions"));
|
||||||
assert!(help.contains("/config [env|hooks|model]"));
|
assert!(help.contains("/config [env|hooks|model]"));
|
||||||
assert!(help.contains("/memory"));
|
assert!(help.contains("/memory"));
|
||||||
assert!(help.contains("/init"));
|
assert!(help.contains("/init"));
|
||||||
@@ -2701,8 +2818,8 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
names,
|
names,
|
||||||
vec![
|
vec![
|
||||||
"help", "status", "sandbox", "compact", "clear", "cost", "config", "memory",
|
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
|
||||||
"init", "diff", "version", "export",
|
"version", "export",
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2820,7 +2937,6 @@ mod tests {
|
|||||||
memory_file_count: 4,
|
memory_file_count: 4,
|
||||||
project_root: Some(PathBuf::from("/tmp")),
|
project_root: Some(PathBuf::from("/tmp")),
|
||||||
git_branch: Some("main".to_string()),
|
git_branch: Some("main".to_string()),
|
||||||
sandbox_status: runtime::SandboxStatus::default(),
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
assert!(status.contains("Status"));
|
assert!(status.contains("Status"));
|
||||||
@@ -2874,7 +2990,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_eq!(context.discovered_config_files, 5);
|
assert!(context.discovered_config_files >= 3);
|
||||||
assert!(context.loaded_config_files <= context.discovered_config_files);
|
assert!(context.loaded_config_files <= context.discovered_config_files);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2982,17 +3098,3 @@ mod tests {
|
|||||||
assert!(done.contains("contents"));
|
assert!(done.contains("contents"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod sandbox_report_tests {
|
|
||||||
use super::format_sandbox_report;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sandbox_report_renders_expected_fields() {
|
|
||||||
let report = format_sandbox_report(&runtime::SandboxStatus::default());
|
|
||||||
assert!(report.contains("Sandbox"));
|
|
||||||
assert!(report.contains("Enabled"));
|
|
||||||
assert!(report.contains("Filesystem mode"));
|
|
||||||
assert!(report.contains("Fallback reason"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -62,11 +62,7 @@ pub fn mvp_tool_specs() -> Vec<ToolSpec> {
|
|||||||
"timeout": { "type": "integer", "minimum": 1 },
|
"timeout": { "type": "integer", "minimum": 1 },
|
||||||
"description": { "type": "string" },
|
"description": { "type": "string" },
|
||||||
"run_in_background": { "type": "boolean" },
|
"run_in_background": { "type": "boolean" },
|
||||||
"dangerouslyDisableSandbox": { "type": "boolean" },
|
"dangerouslyDisableSandbox": { "type": "boolean" }
|
||||||
"namespaceRestrictions": { "type": "boolean" },
|
|
||||||
"isolateNetwork": { "type": "boolean" },
|
|
||||||
"filesystemMode": { "type": "string", "enum": ["off", "workspace-only", "allow-list"] },
|
|
||||||
"allowedMounts": { "type": "array", "items": { "type": "string" } }
|
|
||||||
},
|
},
|
||||||
"required": ["command"],
|
"required": ["command"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@@ -2218,7 +2214,6 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2256,7 +2251,6 @@ fn execute_shell_command(
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
if started.elapsed() >= Duration::from_millis(timeout_ms) {
|
||||||
@@ -2287,7 +2281,6 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
std::thread::sleep(Duration::from_millis(10));
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
@@ -2314,7 +2307,6 @@ Command exceeded timeout of {timeout_ms} ms",
|
|||||||
structured_content: None,
|
structured_content: None,
|
||||||
persisted_output_path: None,
|
persisted_output_path: None,
|
||||||
persisted_output_size: None,
|
persisted_output_size: None,
|
||||||
sandbox_status: None,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user