Merge pull request #3318 from ultraworkers/pr-3292

fix: harden the agent loop against a self-hosted Anthropic-compatible backend
This commit is contained in:
Bellman authored and GitHub committed 2026-10-13 08:07:04 +09:00
commit 2d920ce915
18 files changed
+1940 -464

No files matched your search

+237 -161
View File
@@ -74,6 +74,22 @@ use tools::{
const DEFAULT_MODEL: &str = "anthropic/claude-opus-4-7";
/// Ceiling on model/tool round trips within one turn.
///
/// `ConversationRuntime` defaults to `usize::MAX`, which for the interactive and `-p` paths means
/// no ceiling at all: a model that keeps re-reading the same file loops until the user kills it.
/// Spawned subagents have always been bounded; this gives the top-level loop the same treatment.
const DEFAULT_MAX_TURN_ITERATIONS: usize = 32;
const MAX_TURN_ITERATIONS_ENV_VAR: &str = "CLAW_MAX_TURN_ITERATIONS";
fn max_turn_iterations_from_env() -> usize {
std::env::var(MAX_TURN_ITERATIONS_ENV_VAR)
.ok()
.and_then(|raw| raw.trim().parse::<usize>().ok())
.filter(|iterations| *iterations > 0)
.unwrap_or(DEFAULT_MAX_TURN_ITERATIONS)
}
/// #148: Model provenance for `claw status` JSON/text output. Records where
/// the resolved model string came from so claws don't have to re-read argv
/// to audit whether their `--model` flag was honored vs falling back to env
@@ -1941,9 +1957,7 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
// Only reject for known top-level subcommands that don't use compact.
let first = rest[0].as_str();
if is_known_top_level_subcommand(first) && first != "prompt" {
return Err(format!(
"invalid_flag_value: --compact is only supported with prompt mode.\nUsage: claw --compact \"<prompt>\" or echo \"<prompt>\" | claw --compact"
));
return Err("invalid_flag_value: --compact is only supported with prompt mode.\nUsage: claw --compact \"<prompt>\" or echo \"<prompt>\" | claw --compact".to_string());
}
}
@@ -3147,10 +3161,11 @@ fn print_model_validation_warning_status(
usage,
permission_mode,
context,
None,
None,
allowed_tools,
Some(&format_selection),
&StatusJsonExtras {
allowed_tools,
format_selection: Some(&format_selection),
..StatusJsonExtras::default()
},
);
let object = value
.as_object_mut()
@@ -3226,9 +3241,7 @@ fn parse_system_prompt_args(
})?;
// #99: validate --date is a plausible date string (no newlines, reasonable length)
if value.contains('\n') || value.contains('\r') {
return Err(format!(
"invalid_flag_value: --date value contains invalid characters.\nUsage: --date <YYYY-MM-DD>"
));
return Err("invalid_flag_value: --date value contains invalid characters.\nUsage: --date <YYYY-MM-DD>".to_string());
}
if value.len() > 20 {
return Err(format!(
@@ -3465,11 +3478,7 @@ impl DiagnosticCheck {
fn json_value(&self) -> Value {
// Derive a stable snake_case id from the check name for machine-readable keying (#704).
let id = self
.name
.to_ascii_lowercase()
.replace(' ', "_")
.replace('-', "_");
let id = self.name.to_ascii_lowercase().replace([' ', '-'], "_");
let mut value = Map::from_iter([
("id".to_string(), Value::String(id.clone())),
(
@@ -6650,10 +6659,8 @@ fn run_resume_command(
},
default_permission_mode().as_str(),
&context,
None, // #148: resumed sessions don't have flag provenance
None,
None,
None,
// #148: resumed sessions don't have flag provenance
&StatusJsonExtras::default(),
)),
})
}
@@ -6834,16 +6841,15 @@ fn run_resume_command(
}
SlashCommand::Plugins { action, target } => {
// Only list is supported in resume mode (no runtime to reload)
match action.as_deref() {
Some(action @ ("install" | "uninstall" | "enable" | "disable" | "update")) => {
// #777: use interactive_only: prefix + \n hint so #776's classify/split
// emits error_kind:interactive_only + non-null hint instead of unknown+null.
// Orchestrators can now detect this and switch to a live REPL instead of retrying.
return Err(format!(
"interactive_only: /plugins {action} requires a live session to reload the plugin runtime.\nStart `claw` and run `/plugins {action}` inside the REPL, or use `claw plugins {action}` as a direct CLI command."
).into());
}
_ => {}
if let Some(action @ ("install" | "uninstall" | "enable" | "disable" | "update")) =
action.as_deref()
{
// #777: use interactive_only: prefix + \n hint so #776's classify/split
// emits error_kind:interactive_only + non-null hint instead of unknown+null.
// Orchestrators can now detect this and switch to a live REPL instead of retrying.
return Err(format!(
"interactive_only: /plugins {action} requires a live session to reload the plugin runtime.\nStart `claw` and run `/plugins {action}` inside the REPL, or use `claw plugins {action}` as a direct CLI command."
).into());
}
let cwd = env::current_dir()?;
let payload = plugins_command_payload_for(
@@ -7907,6 +7913,15 @@ impl LiveCli {
Ok(())
}
Err(error) => {
// Salvage the transcript before the failed runtime is torn down.
//
// `prepare_turn_runtime` handed `run_turn` a CLONE of the session, and the turn
// mutated only that clone — appending the user message, each assistant reply, and
// a tool_result for every tool that actually executed. Dropping the clone throws
// all of that away while the side effects of those tools remain on disk, so the
// retry below would re-issue them against a session that shows no sign they ever
// ran. Adopting the clone keeps the record and the reality in step.
*self.runtime.session_mut() = runtime.session().clone();
runtime.shutdown_plugins()?;
// Same ownership rule as the success arm: `fail` clears the current
// line, so it may only do so when the emitter stopped on a line
@@ -7933,37 +7948,17 @@ impl LiveCli {
// This eliminates the need for users to manually run /compact when they
// hit context limits - the recovery happens automatically.
//
// Detection: We look for "context_window" or "Context window" in the error
// message, which covers error types like:
// - "context_window_blocked"
// - "Context window blocked"
// - "This model's maximum context length is X tokens..."
// Detection: the API layer classified this when it still had the typed error and
// the outgoing request in hand — see `AnthropicRuntimeClient::runtime_error_from_api`.
// It is deliberately NOT re-derived from the rendered message here: compaction
// discards conversation history, and the substrings that used to gate it
// ("error decoding response body", "Failed to parse input at pos") are emitted by
// ordinary transport failures as well as by overflow, so a dropped connection cost
// the session its transcript.
// ============================================================================
let error_str = error.to_string();
// Detect context window overflow. Some providers (e.g. OpenAI-compat backends)
// return 400 with "no parseable body" instead of a proper context_length_exceeded
// error when the request is too large to even parse — treat that as context overflow too.
// Also detect model-specific context error markers (e.g. llama.cpp returns
// "Context size has been exceeded." / "exceed_context_size_error" / "exceeds the available context size").
let is_context_window = error_str.contains("context_window")
|| error_str.contains("Context window")
|| error_str.contains("no parseable body")
|| error_str.contains("exceed_context_size")
|| error_str.contains("exceeds the available context size")
|| error_str
.to_ascii_lowercase()
.contains("context size has been exceeded");
// Also treat "assistant stream produced no content" and reqwest decode failures
// as recoverable errors that may benefit from auto-compaction. Some backends (e.g.
// llama.cpp) return a non-SSE HTTP 500 body when context overflows, causing
// reqwest to fail with "error decoding response body" — treat that as context overflow too.
let is_no_content = error_str.contains("assistant stream produced no content")
|| error_str.contains("Failed to parse input at pos")
|| error_str.contains("error decoding response body");
if is_context_window || is_no_content {
if error.is_context_window_failure() {
// If the error tells us the server's actual context window, adapt our
// auto-compaction threshold so future auto-compact-trigger checks are accurate.
if let Some(window) = extract_context_window_tokens_from_error(&error_str) {
@@ -7983,8 +7978,7 @@ impl LiveCli {
let max_compact_rounds = 4;
let preserve_schedule = [4, 2, 1, 0];
for round in 0..max_compact_rounds {
let preserve = preserve_schedule[round];
for (round, &preserve) in preserve_schedule.iter().enumerate() {
println!(
" Auto-compacting session (round {}/{}, preserving {} recent messages)...",
round + 1,
@@ -8031,7 +8025,11 @@ impl LiveCli {
drop(hook_abort_monitor);
let mut rp = CliPermissionPrompter::new(self.permission_mode);
match new_runtime.run_turn(input, Some(&mut rp)) {
// Resume, do not replay. The salvaged session already carries this turn's
// user message and every tool result that completed before the failure;
// re-running `run_turn(input, ..)` would duplicate the prompt and invite a
// second execution of tools that are not idempotent.
match new_runtime.resume_turn(Some(&mut rp)) {
Ok(summary) => {
self.replace_runtime(new_runtime)?;
if !terminal_tail.at_line_start() {
@@ -8058,20 +8056,7 @@ impl LiveCli {
}
Err(retry_error) => {
let retry_str = retry_error.to_string();
let still_context_window = retry_str.contains("context_window")
|| retry_str.contains("Context window")
|| retry_str.contains("no parseable body")
|| retry_str.contains("exceed_context_size")
|| retry_str.contains("exceeds the available context size")
|| retry_str
.to_ascii_lowercase()
.contains("context size has been exceeded");
let still_no_content = retry_str
.contains("assistant stream produced no content")
|| retry_str.contains("Failed to parse input at pos")
|| retry_str.contains("error decoding response body");
if (still_context_window || still_no_content)
if retry_error.is_context_window_failure()
&& round + 1 < max_compact_rounds
{
// If the retry error reveals the context window, adapt threshold.
@@ -8798,8 +8783,8 @@ impl LiveCli {
let cwd = env::current_dir()?;
// #803: reject flag-shaped tokens in list filter for BOTH text and JSON modes.
// Previously the guard was JSON-only (#793); text mode silently returned empty success.
if action.as_deref() == Some("list") {
if let Some(filter) = target.as_deref() {
if action == Some("list") {
if let Some(filter) = target {
if filter.starts_with('-') {
if matches!(output_format, CliOutputFormat::Json) {
// ROADMAP #817: this is a handled local inventory parse error.
@@ -9794,31 +9779,49 @@ fn print_status_snapshot(
usage,
permission_mode.mode.as_str(),
&context,
Some(&provenance),
Some(&permission_mode),
allowed_tools,
Some(&format_selection),
&StatusJsonExtras {
provenance: Some(&provenance),
permission_provenance: Some(&permission_mode),
allowed_tools,
format_selection: Some(&format_selection),
},
))?
),
}
Ok(())
}
/// Optional provenance and selection inputs for [`status_json_value`].
///
/// Grouped into a struct rather than trailing positional parameters: they are all
/// `Option<&_>` and most callers pass `None` for most of them, which makes a
/// positional tail easy to transpose silently.
///
/// `provenance` (#148) drives the `model_source` field ("flag" | "env" | "config" |
/// "default") and `model_raw` (user input before alias resolution, or null when the
/// source is "default"). Callers without provenance (legacy resume paths) leave it
/// `None`, in which case both fields are omitted.
#[derive(Default)]
struct StatusJsonExtras<'a> {
provenance: Option<&'a ModelProvenance>,
permission_provenance: Option<&'a PermissionModeProvenance>,
allowed_tools: Option<&'a AllowedToolSet>,
format_selection: Option<&'a OutputFormatSelection>,
}
fn status_json_value(
model: Option<&str>,
usage: StatusUsage,
permission_mode: &str,
context: &StatusContext,
// #148: optional provenance for `model` field. Surfaces `model_source`
// ("flag" | "env" | "config" | "default") and `model_raw` (user input
// before alias resolution, or null when source is "default"). Callers
// that don't have provenance (legacy resume paths) pass None, in which
// case both new fields are omitted.
provenance: Option<&ModelProvenance>,
permission_provenance: Option<&PermissionModeProvenance>,
allowed_tools: Option<&AllowedToolSet>,
format_selection: Option<&OutputFormatSelection>,
extras: &StatusJsonExtras<'_>,
) -> serde_json::Value {
let StatusJsonExtras {
provenance,
permission_provenance,
allowed_tools,
format_selection,
} = *extras;
// #143: top-level `status` marker so claws can distinguish
// a clean run from a degraded run (config parse failed but other fields
// are still populated). `config_load_error` carries the parse-error string
@@ -10300,9 +10303,7 @@ fn sandbox_json_value(status: &runtime::SandboxStatus) -> serde_json::Value {
// (#731: "not supported on macOS" is a degraded state, not a hard error;
// filesystem_active:true means partial containment is working)
// error = enabled but unsupported AND no filesystem sandbox either (nothing active)
let top_status = if !status.enabled {
"ok"
} else if status.active {
let top_status = if !status.enabled || status.active {
"ok"
} else if status.supported {
"warn"
@@ -10677,18 +10678,20 @@ fn render_doctor_help_json() -> serde_json::Value {
}
/// #683-#692: extract structured metadata from help prose
fn extract_help_metadata(
topic: LocalHelpTopic,
) -> (
Option<String>, // usage
Option<String>, // purpose
Option<String>, // output description
Option<Vec<String>>, // formats
Option<Vec<String>>, // related
Option<Vec<String>>, // aliases
bool, // local_only
bool, // requires_credentials
) {
/// Parsed fields of a help topic: usage, purpose, output description, formats,
/// related topics, aliases, local-only, requires-credentials.
type HelpMetadata = (
Option<String>,
Option<String>,
Option<String>,
Option<Vec<String>>,
Option<Vec<String>>,
Option<Vec<String>>,
bool,
bool,
);
fn extract_help_metadata(topic: LocalHelpTopic) -> HelpMetadata {
let text = render_help_topic(topic);
let mut usage = None;
let mut purpose = None;
@@ -12732,7 +12735,8 @@ fn build_runtime_with_plugin_state(
policy,
system_prompt,
&feature_config,
);
)
.with_max_iterations(max_turn_iterations_from_env());
if emit_output {
runtime = runtime.with_hook_progress_reporter(Box::new(CliHookProgressReporter));
}
@@ -13146,7 +13150,49 @@ impl ApiClient for AnthropicRuntimeClient {
}
}
/// How full a request must be, as a percentage of the declared context window, before an
/// unreadable failure is taken to mean the window overflowed.
const AMBIGUOUS_FAILURE_WINDOW_PERCENT: u64 = 85;
/// True when a request was close enough to the window that an otherwise unreadable failure is
/// most likely an overflow.
///
/// This is the piece that lets transport errors be classified without matching on their prose.
/// A backend can answer an oversized request with a non-SSE 500 that reqwest reports as
/// "error decoding response body"; the same string also appears when the connection simply
/// dropped. What separates them is not the text, it is whether the request we just sent had any
/// room left. Requires a declared window — with none, every request looks small and this
/// correctly returns false.
fn request_fills_context_window(request: &MessageRequest) -> bool {
let Some(limit) = api::model_token_limit(&request.model) else {
return false;
};
let estimated =
api::estimate_message_request_input_tokens(request).saturating_add(request.max_tokens);
u64::from(estimated) * 100
>= u64::from(limit.context_window_tokens) * AMBIGUOUS_FAILURE_WINDOW_PERCENT
}
impl AnthropicRuntimeClient {
/// Converts an API failure into a runtime error, carrying the overflow verdict with it.
///
/// The verdict is made here, where the error still has its type and the request is still in
/// hand, rather than reconstructed downstream from the rendered message.
fn runtime_error_from_api(
&self,
error: &api::ApiError,
request: &MessageRequest,
) -> RuntimeError {
let message = format_user_visible_api_error(&self.session_id, error);
if error.is_context_window_failure()
|| (error.is_ambiguous_transport_failure() && request_fills_context_window(request))
{
RuntimeError::context_window(message)
} else {
RuntimeError::new(message)
}
}
/// Consume a single streaming response, optionally applying a stall
/// timeout on the first event for post-tool continuations.
#[allow(clippy::too_many_lines)]
@@ -13159,9 +13205,7 @@ impl AnthropicRuntimeClient {
.client
.stream_message(message_request)
.await
.map_err(|error| {
RuntimeError::new(format_user_visible_api_error(&self.session_id, &error))
})?;
.map_err(|error| self.runtime_error_from_api(&error, message_request))?;
let mut stdout = io::stdout();
let mut sink = io::sink();
let mut tracked = TailTrackingWriter::new(&mut stdout, self.terminal_tail.clone());
@@ -13183,9 +13227,8 @@ impl AnthropicRuntimeClient {
loop {
let next = if apply_stall_timeout && !received_any_event {
match tokio::time::timeout(POST_TOOL_STALL_TIMEOUT, stream.next_event()).await {
Ok(inner) => inner.map_err(|error| {
RuntimeError::new(format_user_visible_api_error(&self.session_id, &error))
})?,
Ok(inner) => inner
.map_err(|error| self.runtime_error_from_api(&error, message_request))?,
Err(_elapsed) => {
return Err(RuntimeError::new(
"post-tool stall: model did not respond within timeout",
@@ -13193,9 +13236,10 @@ impl AnthropicRuntimeClient {
}
}
} else {
stream.next_event().await.map_err(|error| {
RuntimeError::new(format_user_visible_api_error(&self.session_id, &error))
})?
stream
.next_event()
.await
.map_err(|error| self.runtime_error_from_api(&error, message_request))?
};
let Some(event) = next else {
@@ -13335,9 +13379,7 @@ impl AnthropicRuntimeClient {
..message_request.clone()
})
.await
.map_err(|error| {
RuntimeError::new(format_user_visible_api_error(&self.session_id, &error))
})?;
.map_err(|error| self.runtime_error_from_api(&error, message_request))?;
let mut events = response_to_events(response, out)?;
push_prompt_cache_record(&self.client, &mut events);
Ok(events)
@@ -13461,8 +13503,8 @@ fn format_context_window_blocked_error(session_id: &str, error: &api::ApiError)
));
lines.push(format!(" Context window {context_window_tokens} tokens"));
}
api::ApiError::Api { message, body, .. } => {
let detail = message.as_deref().unwrap_or(body).trim();
api::ApiError::Api(details) => {
let detail = details.message.as_deref().unwrap_or(&details.body).trim();
if !detail.is_empty() {
lines.push(format!(
" Detail {}",
@@ -13472,7 +13514,7 @@ fn format_context_window_blocked_error(session_id: &str, error: &api::ApiError)
}
api::ApiError::RetriesExhausted { last_error, .. } => {
let detail = match last_error.as_ref() {
api::ApiError::Api { message, body, .. } => message.as_deref().unwrap_or(body),
api::ApiError::Api(details) => details.message.as_deref().unwrap_or(&details.body),
other => return format_context_window_blocked_error(session_id, other),
}
.trim();
@@ -14490,39 +14532,37 @@ fn convert_messages(messages: &[ConversationMessage]) -> Vec<InputMessage> {
let content = message
.blocks
.iter()
.filter_map(|block| match block {
ContentBlock::Text { text } => {
Some(InputContentBlock::Text { text: text.clone() })
}
.map(|block| match block {
ContentBlock::Text { text } => InputContentBlock::Text { text: text.clone() },
ContentBlock::Thinking {
thinking,
signature,
} => {
// 保留 Thinking 块:OpenAI 兼容协议会把它转成 reasoning_content 字段
// 回传给 DeepSeek V4(避免 400 "reasoning_content must be passed back" 错误)
Some(InputContentBlock::Thinking {
InputContentBlock::Thinking {
thinking: thinking.clone(),
signature: signature.clone(),
})
}
}
ContentBlock::ToolUse { id, name, input } => Some(InputContentBlock::ToolUse {
ContentBlock::ToolUse { id, name, input } => InputContentBlock::ToolUse {
id: id.clone(),
name: name.clone(),
input: serde_json::from_str(input)
.unwrap_or_else(|_| serde_json::json!({ "raw": input })),
}),
},
ContentBlock::ToolResult {
tool_use_id,
output,
is_error,
..
} => Some(InputContentBlock::ToolResult {
} => InputContentBlock::ToolResult {
tool_use_id: tool_use_id.clone(),
content: vec![ToolResultContentBlock::Text {
text: output.clone(),
}],
is_error: *is_error,
}),
},
})
.collect::<Vec<_>>();
(!content.is_empty()).then(|| InputMessage {
@@ -14775,7 +14815,7 @@ mod tests {
SessionLifecycleSummary, SlashCommand, StatusUsage, TerminalTail, TmuxPaneSnapshot,
DEFAULT_MODEL, LATEST_SESSION_REFERENCE, STUB_COMMANDS,
};
use api::{ApiError, MessageResponse, OutputContentBlock, Usage};
use api::{ApiError, ApiErrorDetails, MessageResponse, OutputContentBlock, Usage};
use plugins::{
PluginManager, PluginManagerConfig, PluginTool, PluginToolDefinition, PluginToolPermission,
};
@@ -14820,7 +14860,7 @@ mod tests {
#[test]
fn opaque_provider_wrapper_surfaces_failure_class_session_and_trace() {
let error = ApiError::Api {
let error = ApiError::Api(Box::new(ApiErrorDetails {
status: "500".parse().expect("status"),
error_type: Some("api_error".to_string()),
message: Some(
@@ -14832,7 +14872,7 @@ mod tests {
retryable: true,
suggested_action: None,
retry_after: None,
};
}));
let rendered = format_user_visible_api_error("session-issue-22", &error);
assert!(rendered.contains("provider_internal"));
@@ -14844,7 +14884,7 @@ mod tests {
fn retry_exhaustion_uses_retry_failure_class_for_generic_provider_wrapper() {
let error = ApiError::RetriesExhausted {
attempts: 3,
last_error: Box::new(ApiError::Api {
last_error: Box::new(ApiError::Api(Box::new(ApiErrorDetails {
status: "502".parse().expect("status"),
error_type: Some("api_error".to_string()),
message: Some(
@@ -14856,7 +14896,7 @@ mod tests {
retryable: true,
suggested_action: None,
retry_after: None,
}),
}))),
};
let rendered = format_user_visible_api_error("session-issue-22", &error);
@@ -14909,7 +14949,7 @@ mod tests {
#[test]
fn provider_context_window_errors_are_reframed_with_same_guidance() {
let error = ApiError::Api {
let error = ApiError::Api(Box::new(ApiErrorDetails {
status: "400".parse().expect("status"),
error_type: Some("invalid_request_error".to_string()),
message: Some(
@@ -14921,7 +14961,7 @@ mod tests {
retryable: false,
suggested_action: None,
retry_after: None,
};
}));
let rendered = format_user_visible_api_error("session-issue-32", &error);
assert!(rendered.contains("context_window_blocked"), "{rendered}");
@@ -14943,7 +14983,7 @@ mod tests {
#[test]
fn openai_configured_limit_errors_are_rendered_as_context_window_guidance() {
let error = ApiError::Api {
let error = ApiError::Api(Box::new(ApiErrorDetails {
status: "400".parse().expect("status"),
error_type: Some("invalid_request_error".to_string()),
message: Some(
@@ -14955,7 +14995,7 @@ mod tests {
retryable: false,
suggested_action: None,
retry_after: None,
};
}));
let rendered = format_user_visible_api_error("session-issue-32", &error);
assert!(rendered.contains("Context window blocked"), "{rendered}");
@@ -14981,7 +15021,7 @@ mod tests {
fn retry_wrapped_context_window_errors_keep_recovery_guidance() {
let error = ApiError::RetriesExhausted {
attempts: 2,
last_error: Box::new(ApiError::Api {
last_error: Box::new(ApiError::Api(Box::new(ApiErrorDetails {
status: "413".parse().expect("status"),
error_type: Some("invalid_request_error".to_string()),
message: Some("Request is too large for this model's context window.".to_string()),
@@ -14990,7 +15030,7 @@ mod tests {
retryable: false,
suggested_action: None,
retry_after: None,
}),
}))),
};
let rendered = format_user_visible_api_error("session-issue-32", &error);
@@ -15037,11 +15077,54 @@ mod tests {
);
}
fn env_lock() -> MutexGuard<'static, ()> {
/// Serialises tests that mutate process-global state, and isolates them from the
/// developer's real `~/.claw`.
///
/// `parse_args` resolves defaults — notably `permissions.defaultMode` — through the
/// user-scope config, which `default_config_home()` reads from `CLAW_CONFIG_HOME`,
/// falling back to `$HOME/.claw`. Without an override, these tests therefore assert
/// against whatever the machine running them happens to have configured: a
/// `defaultMode` of `dontAsk` there resolves to `DangerFullAccess` and turns a dozen
/// `WorkspaceWrite` assertions red. Point the config home at a fresh empty directory
/// so "no user config" is the state under test, and restore the caller's value on drop.
///
/// Tests that need a *populated* config home can still set `CLAW_CONFIG_HOME`
/// themselves after taking this guard; the guard restores the real value afterwards.
struct EnvGuard {
_lock: MutexGuard<'static, ()>,
config_home: PathBuf,
previous_config_home: Option<std::ffi::OsString>,
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match self.previous_config_home.take() {
Some(previous) => std::env::set_var("CLAW_CONFIG_HOME", previous),
None => std::env::remove_var("CLAW_CONFIG_HOME"),
}
// Best effort: a leftover temp dir must never fail a test.
let _ = std::fs::remove_dir_all(&self.config_home);
}
}
fn env_lock() -> EnvGuard {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
let lock = LOCK
.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.unwrap_or_else(std::sync::PoisonError::into_inner);
// Deliberately empty: the point is that no user settings.json is discoverable.
let config_home = temp_dir();
std::fs::create_dir_all(&config_home).expect("isolated config home should be creatable");
let previous_config_home = std::env::var_os("CLAW_CONFIG_HOME");
std::env::set_var("CLAW_CONFIG_HOME", &config_home);
EnvGuard {
_lock: lock,
config_home,
previous_config_home,
}
}
fn with_current_dir<T>(cwd: &Path, f: impl FnOnce() -> T) -> T {
@@ -15768,6 +15851,8 @@ mod tests {
#[test]
fn removed_login_and_logout_subcommands_error_helpfully() {
// Asserts a `Default`-sourced permission mode, so it must not see a user config.
let _guard = env_lock();
let login = parse_args(&["login".to_string()]).expect_err("login should be removed");
assert!(login.contains("ANTHROPIC_API_KEY"));
let logout = parse_args(&["logout".to_string()]).expect_err("logout should be removed");
@@ -16395,10 +16480,7 @@ mod tests {
usage,
"workspace-write",
&context,
None,
None,
None,
None,
&super::StatusJsonExtras::default(),
);
assert_eq!(
json.get("status").and_then(|v| v.as_str()),
@@ -16470,10 +16552,10 @@ mod tests {
usage,
"workspace-write",
&context,
None,
None,
Some(&allowed),
None,
&super::StatusJsonExtras {
allowed_tools: Some(&allowed),
..super::StatusJsonExtras::default()
},
);
assert_eq!(
restricted_json
@@ -16503,10 +16585,7 @@ mod tests {
usage,
"workspace-write",
&clean_context,
None,
None,
None,
None,
&super::StatusJsonExtras::default(),
);
assert_eq!(
clean_json.get("status").and_then(|v| v.as_str()),
@@ -17454,7 +17533,7 @@ mod tests {
for action in ["remove", "uninstall", "delete"] {
assert_eq!(
parse_args(&["skills".to_string(), action.to_string()])
.expect(&format!("skills {action} should parse")),
.unwrap_or_else(|_| panic!("skills {action} should parse")),
CliAction::Skills {
args: Some(action.to_string()),
output_format: CliOutputFormat::Text,
@@ -18408,10 +18487,7 @@ mod tests {
},
"workspace-write",
&context,
None,
None,
None,
None,
&super::StatusJsonExtras::default(),
);
assert_eq!(
@@ -2,8 +2,6 @@ use std::io::{self, IsTerminal, Write};
use runtime::{save_user_provider_settings, ConfigLoader, RuntimeProviderConfig};
use serde_json;
const PROVIDERS: &[(&str, &str, &str)] = &[
("1", "Anthropic", "anthropic"),
("2", "xAI / Grok", "xai"),
@@ -451,11 +451,16 @@ fn direct_resume_safe_slash_commands_route_to_local_json_actions_831() {
.output()
.expect("git init should launch");
for (command, expected_kind, expected_status) in [
("/version", "version", "ok"),
("/sandbox", "sandbox", "warn"),
("/diff", "diff", "ok"),
("/status", "status", "ok"),
// `/sandbox`'s status reflects the host's real sandbox capability, so it is the one
// entry with more than one legitimate value: "ok" where namespace isolation works,
// "warn" where it is unsupported and only the filesystem sandbox is active (#731).
// This test is about #831 routing — that these commands produce a local JSON action
// instead of `interactive_only` — not about the kernel the suite happens to run on.
for (command, expected_kind, expected_statuses) in [
("/version", "version", &["ok"][..]),
("/sandbox", "sandbox", &["ok", "warn"][..]),
("/diff", "diff", &["ok"][..]),
("/status", "status", &["ok"][..]),
] {
let output = run_claw(&root, &["--output-format", "json", command], &[]);
assert!(
@@ -470,9 +475,9 @@ fn direct_resume_safe_slash_commands_route_to_local_json_actions_831() {
.unwrap_or_else(|_| panic!("{command} must emit JSON (#831), got: {stdout:?}"));
assert_eq!(parsed["kind"], expected_kind, "{command} kind: {parsed}");
assert_eq!(
parsed["status"], expected_status,
"{command} status: {parsed}"
assert!(
expected_statuses.contains(&parsed["status"].as_str().unwrap_or_default()),
"{command} status should be one of {expected_statuses:?}: {parsed}"
);
assert_ne!(
parsed["error_kind"], "interactive_only",
@@ -1007,13 +1012,13 @@ fn inventory_commands_emit_structured_json_when_requested() {
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("reload_runtime")),
.is_some_and(|o| o.contains_key("reload_runtime")),
"plugins list should not include reload_runtime"
);
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("target")),
.is_some_and(|o| o.contains_key("target")),
"plugins list should not include target"
);
// #703: structured summary replaces prose message
@@ -1707,13 +1712,13 @@ fn resumed_inventory_commands_emit_structured_json_when_requested() {
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("reload_runtime")),
.is_some_and(|o| o.contains_key("reload_runtime")),
"plugins list should not include reload_runtime"
);
assert!(
!plugins
.as_object()
.map_or(false, |o| o.contains_key("target")),
.is_some_and(|o| o.contains_key("target")),
"plugins list should not include target"
);
assert!(
@@ -2946,7 +2951,7 @@ fn prompt_empty_arg_json_stdout_missing_prompt_823() {
"claw prompt empty arg must retain abort action (#823); got: {parsed}"
);
assert!(
parsed["hint"].as_str().map_or(false, |h| !h.is_empty()),
parsed["hint"].as_str().is_some_and(|h| !h.is_empty()),
"claw prompt empty arg missing_prompt hint must be non-empty (#823)"
);
}
@@ -2984,9 +2989,9 @@ fn flag_value_errors_have_error_kind_and_hint_756() {
"invalid --reasoning-effort must be invalid_flag_value (#756): {parsed}"
);
assert!(
parsed["hint"].as_str().map_or(false, |h| h.contains("low")
|| h.contains("medium")
|| h.contains("high")),
parsed["hint"]
.as_str()
.is_some_and(|h| h.contains("low") || h.contains("medium") || h.contains("high")),
"hint must mention valid values (#756): {parsed}"
);
@@ -3012,7 +3017,7 @@ fn flag_value_errors_have_error_kind_and_hint_756() {
"missing --model value must be missing_flag_value (#756): {parsed2}"
);
assert!(
parsed2["hint"].as_str().map_or(false, |h| !h.is_empty()),
parsed2["hint"].as_str().is_some_and(|h| !h.is_empty()),
"missing --model hint must be non-empty (#756): {parsed2}"
);
}
@@ -3256,7 +3261,7 @@ fn short_p_flag_swallows_no_flags_755() {
"flag-like token after -p must be rejected as missing_prompt (#755): {parsed2}"
);
assert!(
parsed2["hint"].as_str().map_or(false, |h| !h.is_empty()),
parsed2["hint"].as_str().is_some_and(|h| !h.is_empty()),
"missing_prompt hint must be non-empty (#755)"
);
}
@@ -3398,7 +3403,7 @@ fn config_unsupported_section_json_hint_741() {
assert!(
parsed["supported_sections"]
.as_array()
.map_or(false, |a| !a.is_empty()),
.is_some_and(|a| !a.is_empty()),
"config {section} JSON must include supported_sections (#741)"
);
}
@@ -3455,7 +3460,7 @@ fn export_json_has_kind_702() {
// On success stdout has kind:export; on failure stderr has type:error.
// Either way, both envelopes must be valid JSON.
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr)
let _stderr = String::from_utf8_lossy(&output.stderr)
.lines()
.filter(|l| l.starts_with('{'))
.collect::<Vec<_>>()
@@ -3547,8 +3552,8 @@ fn config_parse_error_has_typed_error_kind_and_hint_764() {
!output.status.success(),
"malformed settings.json should cause non-zero exit"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -3582,8 +3587,8 @@ fn login_logout_removed_subcommands_have_error_kind_and_hint_765() {
!output.status.success(),
"claw {subcmd} should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -3722,8 +3727,8 @@ fn resume_non_slash_trailing_arg_has_typed_error_kind_and_hint_768() {
!output.status.success(),
"claw --resume latest compact should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -3762,8 +3767,8 @@ fn session_with_unknown_subcommand_returns_interactive_only_not_credentials_767(
!output.status.success(),
"claw session {sub} should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -3816,7 +3821,7 @@ fn slash_only_verbs_with_args_return_interactive_only_not_credentials_770() {
"claw {} should exit non-zero",
args.join(" ")
);
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -3858,8 +3863,8 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
{
let output = run_claw(&root, &["--output-format", "json", "agents", "bogus"], &[]);
assert!(!output.status.success(), "agents bogus should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -3882,8 +3887,8 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
{
let output = run_claw(&root, &["--output-format", "json", "plugins", "bogus"], &[]);
assert!(!output.status.success(), "plugins bogus should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -3902,7 +3907,7 @@ fn agents_plugins_mcp_unknown_subcommand_have_hint_774() {
{
let output = run_claw(&root, &["--output-format", "json", "mcp", "bogus"], &[]);
assert!(!output.status.success(), "mcp bogus should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_str = if stdout.trim().starts_with('{') {
@@ -4017,7 +4022,7 @@ fn interactive_only_guard_batch_769_to_771() {
"claw {} should exit non-zero",
args.join(" ")
);
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -4081,7 +4086,7 @@ fn resume_plugin_mutations_are_typed_interactive_only_777() {
!output.status.success(),
"/plugins {mutation} in resume mode should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -4138,7 +4143,7 @@ fn resume_skills_invocation_is_typed_interactive_only_779() {
!output.status.success(),
"/skills <skill> in resume mode should exit non-zero"
);
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
@@ -4179,8 +4184,8 @@ fn acp_unsupported_invocation_has_hint_782() {
let output = run_claw(&root, &["--output-format", "json", "acp", "start"], &[]);
assert!(!output.status.success(), "acp start should fail");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stdout = String::from_utf8_lossy(&output.stdout);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let json_line = stdout
.lines()
@@ -4217,7 +4222,7 @@ fn init_json_envelope_has_hint_and_already_initialized_783() {
// Fresh init — already_initialized should be false, hint should mention CLAUDE.md
let output = run_claw(&root, &["--output-format", "json", "init"], &[]);
assert!(output.status.success(), "init should succeed");
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let raw = if stdout.trim_start().starts_with('{') {
@@ -4286,7 +4291,7 @@ fn init_json_envelope_has_hint_and_already_initialized_783() {
// Idempotent re-init — already_initialized should be true
let output2 = run_claw(&root, &["--output-format", "json", "init"], &[]);
assert!(output2.status.success(), "re-init should succeed");
let stdout2 = String::from_utf8_lossy(&output2.stdout);
let _stdout2 = String::from_utf8_lossy(&output2.stdout);
let stderr2 = String::from_utf8_lossy(&output2.stderr);
let stdout2 = String::from_utf8_lossy(&output2.stdout);
let raw2 = if stdout2.trim_start().starts_with('{') {
@@ -4367,7 +4372,7 @@ fn export_arg_errors_have_typed_kind_and_hint_784() {
&[],
);
assert!(!out1.status.success(), "--output with no value should fail");
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let _stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4394,7 +4399,7 @@ fn export_arg_errors_have_typed_kind_and_hint_784() {
&[],
);
assert!(!out2.status.success(), "extra positional should fail");
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let _stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -4431,7 +4436,7 @@ fn unknown_subcommand_returns_typed_kind_785() {
// "dump" is close enough to "dump-manifests" to trigger the typo suggestion path
let output = run_claw(&root, &["--output-format", "json", "dump"], &[]);
assert!(!output.status.success(), "unknown subcommand should fail");
let stderr = String::from_utf8_lossy(&output.stderr);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -4479,7 +4484,7 @@ fn dump_manifests_missing_dir_has_typed_kind_and_hint_786() {
&[],
);
assert!(!out1.status.success());
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let _stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4511,7 +4516,7 @@ fn dump_manifests_missing_dir_has_typed_kind_and_hint_786() {
&[],
);
assert!(!out2.status.success());
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let _stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -4561,7 +4566,7 @@ fn resume_directory_path_returns_typed_kind_and_hint_787() {
!output.status.success(),
"resume with directory should fail"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -4611,7 +4616,7 @@ fn skills_show_not_found_emits_single_json_object_788() {
assert!(!output.status.success(), "skills show unknown should fail");
// Skills handler emits JSON to stdout; the duplicate was on stderr from the main error path.
// After fix: stdout has 1 JSON object, stderr has none (no duplicate).
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -4773,7 +4778,7 @@ fn system_prompt_unknown_option_returns_typed_kind_790() {
&[],
);
assert!(!out1.status.success());
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let _stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4800,7 +4805,7 @@ fn system_prompt_unknown_option_returns_typed_kind_790() {
&[],
);
assert!(!out2.status.success());
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let _stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -4838,7 +4843,7 @@ fn config_extra_args_have_non_null_hint_791() {
&[],
);
assert!(!out1.status.success());
let stderr1 = String::from_utf8_lossy(&out1.stderr);
let _stderr1 = String::from_utf8_lossy(&out1.stderr);
let stdout1 = String::from_utf8_lossy(&out1.stdout);
let j1: serde_json::Value = stdout1
.lines()
@@ -4872,7 +4877,7 @@ fn config_extra_args_have_non_null_hint_791() {
&[],
);
assert!(!out2.status.success());
let stderr2 = String::from_utf8_lossy(&out2.stderr);
let _stderr2 = String::from_utf8_lossy(&out2.stderr);
let stdout2 = String::from_utf8_lossy(&out2.stdout);
let j2: serde_json::Value = stdout2
.lines()
@@ -5058,7 +5063,7 @@ fn plugins_uninstall_not_found_has_hint_793() {
"plugins uninstall not-found must exit non-zero (#793)"
);
// Error envelope goes to stderr (propagated via ? to main error handler)
let stderr = String::from_utf8_lossy(&output.stderr);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -5103,7 +5108,7 @@ fn plugins_install_not_found_path_returns_typed_kind_794() {
!output.status.success(),
"plugins install not-found-path must exit non-zero (#794)"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -5367,7 +5372,7 @@ fn agents_create_scaffolds_toml_and_lists_locally_431() {
.iter()
.any(|agent| {
agent["name"] == "my-agent"
&& PathBuf::from(agent["path"].as_str().expect("listed agent path"))
&& Path::new(agent["path"].as_str().expect("listed agent path"))
== fs::canonicalize(&agent_path).expect("canonical listed agent path")
}));
}
@@ -5492,7 +5497,7 @@ fn plugins_extra_args_have_non_null_hint_797() {
!output.status.success(),
"plugins show with extra arg must exit non-zero (#797)"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()
@@ -5558,7 +5563,7 @@ fn plugins_list_trailing_dash_text_error_stays_on_stderr_817() {
String::from_utf8_lossy(&output.stdout)
);
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let _stdout = String::from_utf8_lossy(&output.stdout);
assert!(stderr.contains("[error-kind: cli_parse]"), "{stderr}");
assert!(
stderr.contains("unknown option for `claw plugins list`: --"),
@@ -5583,7 +5588,7 @@ fn empty_prompt_has_non_null_hint_798() {
!output.status.success(),
"empty prompt must exit non-zero (#798)"
);
let stderr = String::from_utf8_lossy(&output.stderr);
let _stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
let j: serde_json::Value = stdout
.lines()