mirror of
https://github.com/instructkr/claw-code.git
synced 2026-04-03 18:24:48 +08:00
Compare commits
15 Commits
dev/rust
...
f1765edb51
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1765edb51 | ||
|
|
331c9dbb9d | ||
|
|
8ca53dec0d | ||
|
|
5b997e2de2 | ||
|
|
409073c10c | ||
|
|
bb4d2f364a | ||
|
|
933ad1df4e | ||
|
|
3a6a21ac36 | ||
|
|
ec09efa81a | ||
|
|
b402b1c6b6 | ||
|
|
40008b6513 | ||
|
|
f477dde4a6 | ||
|
|
178934a9a0 | ||
|
|
2a0f4b677a | ||
|
|
cbc0a83059 |
1
rust/Cargo.lock
generated
1
rust/Cargo.lock
generated
@@ -113,6 +113,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"plugins",
|
"plugins",
|
||||||
"runtime",
|
"runtime",
|
||||||
|
"serde_json",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ edition = "2021"
|
|||||||
license = "MIT"
|
license = "MIT"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
|
[workspace.dependencies]
|
||||||
|
serde_json = "1"
|
||||||
|
|
||||||
[workspace.lints.rust]
|
[workspace.lints.rust]
|
||||||
unsafe_code = "forbid"
|
unsafe_code = "forbid"
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ publish.workspace = true
|
|||||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json.workspace = true
|
||||||
tokio = { version = "1", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
|
tokio = { version = "1", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,10 @@ use std::time::Duration;
|
|||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ApiError {
|
pub enum ApiError {
|
||||||
MissingApiKey,
|
MissingCredentials {
|
||||||
|
provider: &'static str,
|
||||||
|
env_vars: &'static [&'static str],
|
||||||
|
},
|
||||||
ExpiredOAuthToken,
|
ExpiredOAuthToken,
|
||||||
Auth(String),
|
Auth(String),
|
||||||
InvalidApiKeyEnv(VarError),
|
InvalidApiKeyEnv(VarError),
|
||||||
@@ -30,13 +33,21 @@ pub enum ApiError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ApiError {
|
impl ApiError {
|
||||||
|
#[must_use]
|
||||||
|
pub const fn missing_credentials(
|
||||||
|
provider: &'static str,
|
||||||
|
env_vars: &'static [&'static str],
|
||||||
|
) -> Self {
|
||||||
|
Self::MissingCredentials { provider, env_vars }
|
||||||
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn is_retryable(&self) -> bool {
|
pub fn is_retryable(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Http(error) => error.is_connect() || error.is_timeout() || error.is_request(),
|
Self::Http(error) => error.is_connect() || error.is_timeout() || error.is_request(),
|
||||||
Self::Api { retryable, .. } => *retryable,
|
Self::Api { retryable, .. } => *retryable,
|
||||||
Self::RetriesExhausted { last_error, .. } => last_error.is_retryable(),
|
Self::RetriesExhausted { last_error, .. } => last_error.is_retryable(),
|
||||||
Self::MissingApiKey
|
Self::MissingCredentials { .. }
|
||||||
| Self::ExpiredOAuthToken
|
| Self::ExpiredOAuthToken
|
||||||
| Self::Auth(_)
|
| Self::Auth(_)
|
||||||
| Self::InvalidApiKeyEnv(_)
|
| Self::InvalidApiKeyEnv(_)
|
||||||
@@ -51,12 +62,11 @@ impl ApiError {
|
|||||||
impl Display for ApiError {
|
impl Display for ApiError {
|
||||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
Self::MissingApiKey => {
|
Self::MissingCredentials { provider, env_vars } => write!(
|
||||||
write!(
|
f,
|
||||||
f,
|
"missing {provider} credentials; export {} before calling the {provider} API",
|
||||||
"ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY is not set; export one before calling the Anthropic API"
|
env_vars.join(" or ")
|
||||||
)
|
),
|
||||||
}
|
|
||||||
Self::ExpiredOAuthToken => {
|
Self::ExpiredOAuthToken => {
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
@@ -65,10 +75,7 @@ impl Display for ApiError {
|
|||||||
}
|
}
|
||||||
Self::Auth(message) => write!(f, "auth error: {message}"),
|
Self::Auth(message) => write!(f, "auth error: {message}"),
|
||||||
Self::InvalidApiKeyEnv(error) => {
|
Self::InvalidApiKeyEnv(error) => {
|
||||||
write!(
|
write!(f, "failed to read credential environment variable: {error}")
|
||||||
f,
|
|
||||||
"failed to read ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY: {error}"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
Self::Http(error) => write!(f, "http error: {error}"),
|
Self::Http(error) => write!(f, "http error: {error}"),
|
||||||
Self::Io(error) => write!(f, "io error: {error}"),
|
Self::Io(error) => write!(f, "io error: {error}"),
|
||||||
@@ -81,20 +88,14 @@ impl Display for ApiError {
|
|||||||
..
|
..
|
||||||
} => match (error_type, message) {
|
} => match (error_type, message) {
|
||||||
(Some(error_type), Some(message)) => {
|
(Some(error_type), Some(message)) => {
|
||||||
write!(
|
write!(f, "api returned {status} ({error_type}): {message}")
|
||||||
f,
|
|
||||||
"anthropic api returned {status} ({error_type}): {message}"
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
_ => write!(f, "anthropic api returned {status}: {body}"),
|
_ => write!(f, "api returned {status}: {body}"),
|
||||||
},
|
},
|
||||||
Self::RetriesExhausted {
|
Self::RetriesExhausted {
|
||||||
attempts,
|
attempts,
|
||||||
last_error,
|
last_error,
|
||||||
} => write!(
|
} => write!(f, "api failed after {attempts} attempts: {last_error}"),
|
||||||
f,
|
|
||||||
"anthropic api failed after {attempts} attempts: {last_error}"
|
|
||||||
),
|
|
||||||
Self::InvalidSseFrame(message) => write!(f, "invalid sse frame: {message}"),
|
Self::InvalidSseFrame(message) => write!(f, "invalid sse frame: {message}"),
|
||||||
Self::BackoffOverflow {
|
Self::BackoffOverflow {
|
||||||
attempt,
|
attempt,
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
mod client;
|
mod client;
|
||||||
mod error;
|
mod error;
|
||||||
|
mod providers;
|
||||||
mod sse;
|
mod sse;
|
||||||
mod types;
|
mod types;
|
||||||
|
|
||||||
pub use client::{
|
pub use client::{
|
||||||
oauth_token_is_expired, read_base_url, resolve_saved_oauth_token, resolve_startup_auth_source,
|
oauth_token_is_expired, read_base_url, read_xai_base_url, resolve_saved_oauth_token,
|
||||||
AnthropicClient, AuthSource, MessageStream, OAuthTokenSet,
|
resolve_startup_auth_source, MessageStream, OAuthTokenSet, ProviderClient,
|
||||||
};
|
};
|
||||||
pub use error::ApiError;
|
pub use error::ApiError;
|
||||||
|
pub use providers::anthropic::{AnthropicClient, AnthropicClient as ApiClient, AuthSource};
|
||||||
|
pub use providers::openai_compat::{OpenAiCompatClient, OpenAiCompatConfig};
|
||||||
|
pub use providers::{
|
||||||
|
detect_provider_kind, max_tokens_for_model, resolve_model_alias, ProviderKind,
|
||||||
|
};
|
||||||
pub use sse::{parse_frame, SseParser};
|
pub use sse::{parse_frame, SseParser};
|
||||||
pub use types::{
|
pub use types::{
|
||||||
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||||
|
|||||||
1046
rust/crates/api/src/providers/anthropic.rs
Normal file
1046
rust/crates/api/src/providers/anthropic.rs
Normal file
File diff suppressed because it is too large
Load Diff
216
rust/crates/api/src/providers/mod.rs
Normal file
216
rust/crates/api/src/providers/mod.rs
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
use std::future::Future;
|
||||||
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
use crate::error::ApiError;
|
||||||
|
use crate::types::{MessageRequest, MessageResponse};
|
||||||
|
|
||||||
|
pub mod anthropic;
|
||||||
|
pub mod openai_compat;
|
||||||
|
|
||||||
|
pub type ProviderFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, ApiError>> + Send + 'a>>;
|
||||||
|
|
||||||
|
pub trait Provider {
|
||||||
|
type Stream;
|
||||||
|
|
||||||
|
fn send_message<'a>(
|
||||||
|
&'a self,
|
||||||
|
request: &'a MessageRequest,
|
||||||
|
) -> ProviderFuture<'a, MessageResponse>;
|
||||||
|
|
||||||
|
fn stream_message<'a>(
|
||||||
|
&'a self,
|
||||||
|
request: &'a MessageRequest,
|
||||||
|
) -> ProviderFuture<'a, Self::Stream>;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ProviderKind {
|
||||||
|
Anthropic,
|
||||||
|
Xai,
|
||||||
|
OpenAi,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ProviderMetadata {
|
||||||
|
pub provider: ProviderKind,
|
||||||
|
pub auth_env: &'static str,
|
||||||
|
pub base_url_env: &'static str,
|
||||||
|
pub default_base_url: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
const MODEL_REGISTRY: &[(&str, ProviderMetadata)] = &[
|
||||||
|
(
|
||||||
|
"opus",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Anthropic,
|
||||||
|
auth_env: "ANTHROPIC_API_KEY",
|
||||||
|
base_url_env: "ANTHROPIC_BASE_URL",
|
||||||
|
default_base_url: anthropic::DEFAULT_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"sonnet",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Anthropic,
|
||||||
|
auth_env: "ANTHROPIC_API_KEY",
|
||||||
|
base_url_env: "ANTHROPIC_BASE_URL",
|
||||||
|
default_base_url: anthropic::DEFAULT_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"haiku",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Anthropic,
|
||||||
|
auth_env: "ANTHROPIC_API_KEY",
|
||||||
|
base_url_env: "ANTHROPIC_BASE_URL",
|
||||||
|
default_base_url: anthropic::DEFAULT_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"grok",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Xai,
|
||||||
|
auth_env: "XAI_API_KEY",
|
||||||
|
base_url_env: "XAI_BASE_URL",
|
||||||
|
default_base_url: openai_compat::DEFAULT_XAI_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"grok-3",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Xai,
|
||||||
|
auth_env: "XAI_API_KEY",
|
||||||
|
base_url_env: "XAI_BASE_URL",
|
||||||
|
default_base_url: openai_compat::DEFAULT_XAI_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"grok-mini",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Xai,
|
||||||
|
auth_env: "XAI_API_KEY",
|
||||||
|
base_url_env: "XAI_BASE_URL",
|
||||||
|
default_base_url: openai_compat::DEFAULT_XAI_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"grok-3-mini",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Xai,
|
||||||
|
auth_env: "XAI_API_KEY",
|
||||||
|
base_url_env: "XAI_BASE_URL",
|
||||||
|
default_base_url: openai_compat::DEFAULT_XAI_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"grok-2",
|
||||||
|
ProviderMetadata {
|
||||||
|
provider: ProviderKind::Xai,
|
||||||
|
auth_env: "XAI_API_KEY",
|
||||||
|
base_url_env: "XAI_BASE_URL",
|
||||||
|
default_base_url: openai_compat::DEFAULT_XAI_BASE_URL,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn resolve_model_alias(model: &str) -> String {
|
||||||
|
let trimmed = model.trim();
|
||||||
|
let lower = trimmed.to_ascii_lowercase();
|
||||||
|
MODEL_REGISTRY
|
||||||
|
.iter()
|
||||||
|
.find_map(|(alias, metadata)| {
|
||||||
|
(*alias == lower).then_some(match metadata.provider {
|
||||||
|
ProviderKind::Anthropic => match *alias {
|
||||||
|
"opus" => "claude-opus-4-6",
|
||||||
|
"sonnet" => "claude-sonnet-4-6",
|
||||||
|
"haiku" => "claude-haiku-4-5-20251213",
|
||||||
|
_ => trimmed,
|
||||||
|
},
|
||||||
|
ProviderKind::Xai => match *alias {
|
||||||
|
"grok" | "grok-3" => "grok-3",
|
||||||
|
"grok-mini" | "grok-3-mini" => "grok-3-mini",
|
||||||
|
"grok-2" => "grok-2",
|
||||||
|
_ => trimmed,
|
||||||
|
},
|
||||||
|
ProviderKind::OpenAi => trimmed,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map_or_else(|| trimmed.to_string(), ToOwned::to_owned)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn metadata_for_model(model: &str) -> Option<ProviderMetadata> {
|
||||||
|
let canonical = resolve_model_alias(model);
|
||||||
|
if canonical.starts_with("claude") {
|
||||||
|
return Some(ProviderMetadata {
|
||||||
|
provider: ProviderKind::Anthropic,
|
||||||
|
auth_env: "ANTHROPIC_API_KEY",
|
||||||
|
base_url_env: "ANTHROPIC_BASE_URL",
|
||||||
|
default_base_url: anthropic::DEFAULT_BASE_URL,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if canonical.starts_with("grok") {
|
||||||
|
return Some(ProviderMetadata {
|
||||||
|
provider: ProviderKind::Xai,
|
||||||
|
auth_env: "XAI_API_KEY",
|
||||||
|
base_url_env: "XAI_BASE_URL",
|
||||||
|
default_base_url: openai_compat::DEFAULT_XAI_BASE_URL,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn detect_provider_kind(model: &str) -> ProviderKind {
|
||||||
|
if let Some(metadata) = metadata_for_model(model) {
|
||||||
|
return metadata.provider;
|
||||||
|
}
|
||||||
|
if anthropic::has_auth_from_env_or_saved().unwrap_or(false) {
|
||||||
|
return ProviderKind::Anthropic;
|
||||||
|
}
|
||||||
|
if openai_compat::has_api_key("OPENAI_API_KEY") {
|
||||||
|
return ProviderKind::OpenAi;
|
||||||
|
}
|
||||||
|
if openai_compat::has_api_key("XAI_API_KEY") {
|
||||||
|
return ProviderKind::Xai;
|
||||||
|
}
|
||||||
|
ProviderKind::Anthropic
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_tokens_for_model(model: &str) -> u32 {
|
||||||
|
let canonical = resolve_model_alias(model);
|
||||||
|
if canonical.contains("opus") {
|
||||||
|
32_000
|
||||||
|
} else {
|
||||||
|
64_000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{detect_provider_kind, max_tokens_for_model, resolve_model_alias, ProviderKind};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_grok_aliases() {
|
||||||
|
assert_eq!(resolve_model_alias("grok"), "grok-3");
|
||||||
|
assert_eq!(resolve_model_alias("grok-mini"), "grok-3-mini");
|
||||||
|
assert_eq!(resolve_model_alias("grok-2"), "grok-2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn detects_provider_from_model_name_first() {
|
||||||
|
assert_eq!(detect_provider_kind("grok"), ProviderKind::Xai);
|
||||||
|
assert_eq!(
|
||||||
|
detect_provider_kind("claude-sonnet-4-6"),
|
||||||
|
ProviderKind::Anthropic
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keeps_existing_max_token_heuristic() {
|
||||||
|
assert_eq!(max_tokens_for_model("opus"), 32_000);
|
||||||
|
assert_eq!(max_tokens_for_model("grok-3"), 64_000);
|
||||||
|
}
|
||||||
|
}
|
||||||
1050
rust/crates/api/src/providers/openai_compat.rs
Normal file
1050
rust/crates/api/src/providers/openai_compat.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -3,9 +3,9 @@ use std::sync::Arc;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use api::{
|
use api::{
|
||||||
AnthropicClient, ApiError, ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent,
|
ApiClient, ApiError, AuthSource, ContentBlockDelta, ContentBlockDeltaEvent,
|
||||||
InputContentBlock, InputMessage, MessageDeltaEvent, MessageRequest, OutputContentBlock,
|
ContentBlockStartEvent, InputContentBlock, InputMessage, MessageDeltaEvent, MessageRequest,
|
||||||
StreamEvent, ToolChoice, ToolDefinition,
|
OutputContentBlock, ProviderClient, StreamEvent, ToolChoice, ToolDefinition,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
@@ -34,7 +34,7 @@ async fn send_message_posts_json_and_parses_response() {
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let client = AnthropicClient::new("test-key")
|
let client = ApiClient::new("test-key")
|
||||||
.with_auth_token(Some("proxy-token".to_string()))
|
.with_auth_token(Some("proxy-token".to_string()))
|
||||||
.with_base_url(server.base_url());
|
.with_base_url(server.base_url());
|
||||||
let response = client
|
let response = client
|
||||||
@@ -75,48 +75,6 @@ async fn send_message_posts_json_and_parses_response() {
|
|||||||
assert_eq!(body["tool_choice"]["type"], json!("auto"));
|
assert_eq!(body["tool_choice"]["type"], json!("auto"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn send_message_parses_response_with_thinking_blocks() {
|
|
||||||
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
|
||||||
let body = concat!(
|
|
||||||
"{",
|
|
||||||
"\"id\":\"msg_thinking\",",
|
|
||||||
"\"type\":\"message\",",
|
|
||||||
"\"role\":\"assistant\",",
|
|
||||||
"\"content\":[",
|
|
||||||
"{\"type\":\"thinking\",\"thinking\":\"step 1\",\"signature\":\"sig_123\"},",
|
|
||||||
"{\"type\":\"text\",\"text\":\"Final answer\"}",
|
|
||||||
"],",
|
|
||||||
"\"model\":\"claude-3-7-sonnet-latest\",",
|
|
||||||
"\"stop_reason\":\"end_turn\",",
|
|
||||||
"\"stop_sequence\":null,",
|
|
||||||
"\"usage\":{\"input_tokens\":12,\"output_tokens\":4}",
|
|
||||||
"}"
|
|
||||||
);
|
|
||||||
let server = spawn_server(
|
|
||||||
state,
|
|
||||||
vec![http_response("200 OK", "application/json", body)],
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let client = AnthropicClient::new("test-key").with_base_url(server.base_url());
|
|
||||||
let response = client
|
|
||||||
.send_message(&sample_request(false))
|
|
||||||
.await
|
|
||||||
.expect("request should succeed");
|
|
||||||
|
|
||||||
assert_eq!(response.content.len(), 2);
|
|
||||||
assert!(matches!(
|
|
||||||
&response.content[0],
|
|
||||||
OutputContentBlock::Thinking { thinking, signature }
|
|
||||||
if thinking == "step 1" && signature.as_deref() == Some("sig_123")
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
&response.content[1],
|
|
||||||
OutputContentBlock::Text { text } if text == "Final answer"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn stream_message_parses_sse_events_with_tool_use() {
|
async fn stream_message_parses_sse_events_with_tool_use() {
|
||||||
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
@@ -146,7 +104,7 @@ async fn stream_message_parses_sse_events_with_tool_use() {
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let client = AnthropicClient::new("test-key")
|
let client = ApiClient::new("test-key")
|
||||||
.with_auth_token(Some("proxy-token".to_string()))
|
.with_auth_token(Some("proxy-token".to_string()))
|
||||||
.with_base_url(server.base_url());
|
.with_base_url(server.base_url());
|
||||||
let mut stream = client
|
let mut stream = client
|
||||||
@@ -204,85 +162,6 @@ async fn stream_message_parses_sse_events_with_tool_use() {
|
|||||||
assert!(request.body.contains("\"stream\":true"));
|
assert!(request.body.contains("\"stream\":true"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn stream_message_parses_sse_events_with_thinking_blocks() {
|
|
||||||
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
|
||||||
let sse = concat!(
|
|
||||||
"event: message_start\n",
|
|
||||||
"data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_stream_thinking\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-3-7-sonnet-latest\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":8,\"output_tokens\":0}}}\n\n",
|
|
||||||
"event: content_block_start\n",
|
|
||||||
"data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\"}}\n\n",
|
|
||||||
"event: content_block_delta\n",
|
|
||||||
"data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"step 1\"}}\n\n",
|
|
||||||
"event: content_block_delta\n",
|
|
||||||
"data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"sig_123\"}}\n\n",
|
|
||||||
"event: content_block_stop\n",
|
|
||||||
"data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
|
|
||||||
"event: content_block_start\n",
|
|
||||||
"data: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"text\",\"text\":\"Final answer\"}}\n\n",
|
|
||||||
"event: content_block_stop\n",
|
|
||||||
"data: {\"type\":\"content_block_stop\",\"index\":1}\n\n",
|
|
||||||
"event: message_delta\n",
|
|
||||||
"data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\",\"stop_sequence\":null},\"usage\":{\"input_tokens\":8,\"output_tokens\":1}}\n\n",
|
|
||||||
"event: message_stop\n",
|
|
||||||
"data: {\"type\":\"message_stop\"}\n\n",
|
|
||||||
"data: [DONE]\n\n"
|
|
||||||
);
|
|
||||||
let server = spawn_server(
|
|
||||||
state,
|
|
||||||
vec![http_response("200 OK", "text/event-stream", sse)],
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let client = AnthropicClient::new("test-key").with_base_url(server.base_url());
|
|
||||||
let mut stream = client
|
|
||||||
.stream_message(&sample_request(false))
|
|
||||||
.await
|
|
||||||
.expect("stream should start");
|
|
||||||
|
|
||||||
let mut events = Vec::new();
|
|
||||||
while let Some(event) = stream
|
|
||||||
.next_event()
|
|
||||||
.await
|
|
||||||
.expect("stream event should parse")
|
|
||||||
{
|
|
||||||
events.push(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
assert_eq!(events.len(), 9);
|
|
||||||
assert!(matches!(
|
|
||||||
&events[1],
|
|
||||||
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
|
|
||||||
content_block: OutputContentBlock::Thinking { thinking, signature },
|
|
||||||
..
|
|
||||||
}) if thinking.is_empty() && signature.is_none()
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
&events[2],
|
|
||||||
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
|
|
||||||
delta: ContentBlockDelta::ThinkingDelta { thinking },
|
|
||||||
..
|
|
||||||
}) if thinking == "step 1"
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
&events[3],
|
|
||||||
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
|
|
||||||
delta: ContentBlockDelta::SignatureDelta { signature },
|
|
||||||
..
|
|
||||||
}) if signature == "sig_123"
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
&events[5],
|
|
||||||
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
|
|
||||||
content_block: OutputContentBlock::Text { text },
|
|
||||||
..
|
|
||||||
}) if text == "Final answer"
|
|
||||||
));
|
|
||||||
assert!(matches!(events[6], StreamEvent::ContentBlockStop(_)));
|
|
||||||
assert!(matches!(events[7], StreamEvent::MessageDelta(_)));
|
|
||||||
assert!(matches!(events[8], StreamEvent::MessageStop(_)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn retries_retryable_failures_before_succeeding() {
|
async fn retries_retryable_failures_before_succeeding() {
|
||||||
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
@@ -303,7 +182,7 @@ async fn retries_retryable_failures_before_succeeding() {
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let client = AnthropicClient::new("test-key")
|
let client = ApiClient::new("test-key")
|
||||||
.with_base_url(server.base_url())
|
.with_base_url(server.base_url())
|
||||||
.with_retry_policy(2, Duration::from_millis(1), Duration::from_millis(2));
|
.with_retry_policy(2, Duration::from_millis(1), Duration::from_millis(2));
|
||||||
|
|
||||||
@@ -316,6 +195,47 @@ async fn retries_retryable_failures_before_succeeding() {
|
|||||||
assert_eq!(state.lock().await.len(), 2);
|
assert_eq!(state.lock().await.len(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn provider_client_dispatches_anthropic_requests() {
|
||||||
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
|
let server = spawn_server(
|
||||||
|
state.clone(),
|
||||||
|
vec![http_response(
|
||||||
|
"200 OK",
|
||||||
|
"application/json",
|
||||||
|
"{\"id\":\"msg_provider\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"Dispatched\"}],\"model\":\"claude-3-7-sonnet-latest\",\"stop_reason\":\"end_turn\",\"stop_sequence\":null,\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}",
|
||||||
|
)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let client = ProviderClient::from_model_with_anthropic_auth(
|
||||||
|
"claude-sonnet-4-6",
|
||||||
|
Some(AuthSource::ApiKey("test-key".to_string())),
|
||||||
|
)
|
||||||
|
.expect("anthropic provider client should be constructed");
|
||||||
|
let client = match client {
|
||||||
|
ProviderClient::Anthropic(client) => {
|
||||||
|
ProviderClient::Anthropic(client.with_base_url(server.base_url()))
|
||||||
|
}
|
||||||
|
other => panic!("expected anthropic provider, got {other:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.send_message(&sample_request(false))
|
||||||
|
.await
|
||||||
|
.expect("provider-dispatched request should succeed");
|
||||||
|
|
||||||
|
assert_eq!(response.total_tokens(), 5);
|
||||||
|
|
||||||
|
let captured = state.lock().await;
|
||||||
|
let request = captured.first().expect("server should capture request");
|
||||||
|
assert_eq!(request.path, "/v1/messages");
|
||||||
|
assert_eq!(
|
||||||
|
request.headers.get("x-api-key").map(String::as_str),
|
||||||
|
Some("test-key")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn surfaces_retry_exhaustion_for_persistent_retryable_errors() {
|
async fn surfaces_retry_exhaustion_for_persistent_retryable_errors() {
|
||||||
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
@@ -336,7 +256,7 @@ async fn surfaces_retry_exhaustion_for_persistent_retryable_errors() {
|
|||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let client = AnthropicClient::new("test-key")
|
let client = ApiClient::new("test-key")
|
||||||
.with_base_url(server.base_url())
|
.with_base_url(server.base_url())
|
||||||
.with_retry_policy(1, Duration::from_millis(1), Duration::from_millis(2));
|
.with_retry_policy(1, Duration::from_millis(1), Duration::from_millis(2));
|
||||||
|
|
||||||
@@ -367,7 +287,7 @@ async fn surfaces_retry_exhaustion_for_persistent_retryable_errors() {
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
#[ignore = "requires ANTHROPIC_API_KEY and network access"]
|
#[ignore = "requires ANTHROPIC_API_KEY and network access"]
|
||||||
async fn live_stream_smoke_test() {
|
async fn live_stream_smoke_test() {
|
||||||
let client = AnthropicClient::from_env().expect("ANTHROPIC_API_KEY must be set");
|
let client = ApiClient::from_env().expect("ANTHROPIC_API_KEY must be set");
|
||||||
let mut stream = client
|
let mut stream = client
|
||||||
.stream_message(&MessageRequest {
|
.stream_message(&MessageRequest {
|
||||||
model: std::env::var("ANTHROPIC_MODEL")
|
model: std::env::var("ANTHROPIC_MODEL")
|
||||||
|
|||||||
415
rust/crates/api/tests/openai_compat_integration.rs
Normal file
415
rust/crates/api/tests/openai_compat_integration.rs
Normal file
@@ -0,0 +1,415 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ffi::OsString;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::{Mutex as StdMutex, OnceLock};
|
||||||
|
|
||||||
|
use api::{
|
||||||
|
ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
|
||||||
|
InputContentBlock, InputMessage, MessageRequest, OpenAiCompatClient, OpenAiCompatConfig,
|
||||||
|
OutputContentBlock, ProviderClient, StreamEvent, ToolChoice, ToolDefinition,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn send_message_uses_openai_compatible_endpoint_and_auth() {
|
||||||
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
|
let body = concat!(
|
||||||
|
"{",
|
||||||
|
"\"id\":\"chatcmpl_test\",",
|
||||||
|
"\"model\":\"grok-3\",",
|
||||||
|
"\"choices\":[{",
|
||||||
|
"\"message\":{\"role\":\"assistant\",\"content\":\"Hello from Grok\",\"tool_calls\":[]},",
|
||||||
|
"\"finish_reason\":\"stop\"",
|
||||||
|
"}],",
|
||||||
|
"\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":5}",
|
||||||
|
"}"
|
||||||
|
);
|
||||||
|
let server = spawn_server(
|
||||||
|
state.clone(),
|
||||||
|
vec![http_response("200 OK", "application/json", body)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let client = OpenAiCompatClient::new("xai-test-key", OpenAiCompatConfig::xai())
|
||||||
|
.with_base_url(server.base_url());
|
||||||
|
let response = client
|
||||||
|
.send_message(&sample_request(false))
|
||||||
|
.await
|
||||||
|
.expect("request should succeed");
|
||||||
|
|
||||||
|
assert_eq!(response.model, "grok-3");
|
||||||
|
assert_eq!(response.total_tokens(), 16);
|
||||||
|
assert_eq!(
|
||||||
|
response.content,
|
||||||
|
vec![OutputContentBlock::Text {
|
||||||
|
text: "Hello from Grok".to_string(),
|
||||||
|
}]
|
||||||
|
);
|
||||||
|
|
||||||
|
let captured = state.lock().await;
|
||||||
|
let request = captured.first().expect("server should capture request");
|
||||||
|
assert_eq!(request.path, "/chat/completions");
|
||||||
|
assert_eq!(
|
||||||
|
request.headers.get("authorization").map(String::as_str),
|
||||||
|
Some("Bearer xai-test-key")
|
||||||
|
);
|
||||||
|
let body: serde_json::Value = serde_json::from_str(&request.body).expect("json body");
|
||||||
|
assert_eq!(body["model"], json!("grok-3"));
|
||||||
|
assert_eq!(body["messages"][0]["role"], json!("system"));
|
||||||
|
assert_eq!(body["tools"][0]["type"], json!("function"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn send_message_accepts_full_chat_completions_endpoint_override() {
|
||||||
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
|
let body = concat!(
|
||||||
|
"{",
|
||||||
|
"\"id\":\"chatcmpl_full_endpoint\",",
|
||||||
|
"\"model\":\"grok-3\",",
|
||||||
|
"\"choices\":[{",
|
||||||
|
"\"message\":{\"role\":\"assistant\",\"content\":\"Endpoint override works\",\"tool_calls\":[]},",
|
||||||
|
"\"finish_reason\":\"stop\"",
|
||||||
|
"}],",
|
||||||
|
"\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}",
|
||||||
|
"}"
|
||||||
|
);
|
||||||
|
let server = spawn_server(
|
||||||
|
state.clone(),
|
||||||
|
vec![http_response("200 OK", "application/json", body)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let endpoint_url = format!("{}/chat/completions", server.base_url());
|
||||||
|
let client = OpenAiCompatClient::new("xai-test-key", OpenAiCompatConfig::xai())
|
||||||
|
.with_base_url(endpoint_url);
|
||||||
|
let response = client
|
||||||
|
.send_message(&sample_request(false))
|
||||||
|
.await
|
||||||
|
.expect("request should succeed");
|
||||||
|
|
||||||
|
assert_eq!(response.total_tokens(), 10);
|
||||||
|
|
||||||
|
let captured = state.lock().await;
|
||||||
|
let request = captured.first().expect("server should capture request");
|
||||||
|
assert_eq!(request.path, "/chat/completions");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn stream_message_normalizes_text_and_multiple_tool_calls() {
|
||||||
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
|
let sse = concat!(
|
||||||
|
"data: {\"id\":\"chatcmpl_stream\",\"model\":\"grok-3\",\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n",
|
||||||
|
"data: {\"id\":\"chatcmpl_stream\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"weather\",\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"}},{\"index\":1,\"id\":\"call_2\",\"function\":{\"name\":\"clock\",\"arguments\":\"{\\\"zone\\\":\\\"UTC\\\"}\"}}]}}]}\n\n",
|
||||||
|
"data: {\"id\":\"chatcmpl_stream\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
|
||||||
|
"data: [DONE]\n\n"
|
||||||
|
);
|
||||||
|
let server = spawn_server(
|
||||||
|
state.clone(),
|
||||||
|
vec![http_response_with_headers(
|
||||||
|
"200 OK",
|
||||||
|
"text/event-stream",
|
||||||
|
sse,
|
||||||
|
&[("x-request-id", "req_grok_stream")],
|
||||||
|
)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let client = OpenAiCompatClient::new("xai-test-key", OpenAiCompatConfig::xai())
|
||||||
|
.with_base_url(server.base_url());
|
||||||
|
let mut stream = client
|
||||||
|
.stream_message(&sample_request(false))
|
||||||
|
.await
|
||||||
|
.expect("stream should start");
|
||||||
|
|
||||||
|
assert_eq!(stream.request_id(), Some("req_grok_stream"));
|
||||||
|
|
||||||
|
let mut events = Vec::new();
|
||||||
|
while let Some(event) = stream.next_event().await.expect("event should parse") {
|
||||||
|
events.push(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(matches!(events[0], StreamEvent::MessageStart(_)));
|
||||||
|
assert!(matches!(
|
||||||
|
events[1],
|
||||||
|
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
|
||||||
|
content_block: OutputContentBlock::Text { .. },
|
||||||
|
..
|
||||||
|
})
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[2],
|
||||||
|
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
|
||||||
|
delta: ContentBlockDelta::TextDelta { .. },
|
||||||
|
..
|
||||||
|
})
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[3],
|
||||||
|
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
|
||||||
|
index: 1,
|
||||||
|
content_block: OutputContentBlock::ToolUse { .. },
|
||||||
|
})
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[4],
|
||||||
|
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
|
||||||
|
index: 1,
|
||||||
|
delta: ContentBlockDelta::InputJsonDelta { .. },
|
||||||
|
})
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[5],
|
||||||
|
StreamEvent::ContentBlockStart(ContentBlockStartEvent {
|
||||||
|
index: 2,
|
||||||
|
content_block: OutputContentBlock::ToolUse { .. },
|
||||||
|
})
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[6],
|
||||||
|
StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
|
||||||
|
index: 2,
|
||||||
|
delta: ContentBlockDelta::InputJsonDelta { .. },
|
||||||
|
})
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[7],
|
||||||
|
StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 1 })
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[8],
|
||||||
|
StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 2 })
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
events[9],
|
||||||
|
StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 0 })
|
||||||
|
));
|
||||||
|
assert!(matches!(events[10], StreamEvent::MessageDelta(_)));
|
||||||
|
assert!(matches!(events[11], StreamEvent::MessageStop(_)));
|
||||||
|
|
||||||
|
let captured = state.lock().await;
|
||||||
|
let request = captured.first().expect("captured request");
|
||||||
|
assert_eq!(request.path, "/chat/completions");
|
||||||
|
assert!(request.body.contains("\"stream\":true"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn provider_client_dispatches_xai_requests_from_env() {
|
||||||
|
let _lock = env_lock();
|
||||||
|
let _api_key = ScopedEnvVar::set("XAI_API_KEY", "xai-test-key");
|
||||||
|
|
||||||
|
let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
|
||||||
|
let server = spawn_server(
|
||||||
|
state.clone(),
|
||||||
|
vec![http_response(
|
||||||
|
"200 OK",
|
||||||
|
"application/json",
|
||||||
|
"{\"id\":\"chatcmpl_provider\",\"model\":\"grok-3\",\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"Through provider client\",\"tool_calls\":[]},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4}}",
|
||||||
|
)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let _base_url = ScopedEnvVar::set("XAI_BASE_URL", server.base_url());
|
||||||
|
|
||||||
|
let client =
|
||||||
|
ProviderClient::from_model("grok").expect("xAI provider client should be constructed");
|
||||||
|
assert!(matches!(client, ProviderClient::Xai(_)));
|
||||||
|
|
||||||
|
let response = client
|
||||||
|
.send_message(&sample_request(false))
|
||||||
|
.await
|
||||||
|
.expect("provider-dispatched request should succeed");
|
||||||
|
|
||||||
|
assert_eq!(response.total_tokens(), 13);
|
||||||
|
|
||||||
|
let captured = state.lock().await;
|
||||||
|
let request = captured.first().expect("captured request");
|
||||||
|
assert_eq!(request.path, "/chat/completions");
|
||||||
|
assert_eq!(
|
||||||
|
request.headers.get("authorization").map(String::as_str),
|
||||||
|
Some("Bearer xai-test-key")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct CapturedRequest {
|
||||||
|
path: String,
|
||||||
|
headers: HashMap<String, String>,
|
||||||
|
body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TestServer {
|
||||||
|
base_url: String,
|
||||||
|
join_handle: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestServer {
|
||||||
|
fn base_url(&self) -> String {
|
||||||
|
self.base_url.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TestServer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.join_handle.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn spawn_server(
|
||||||
|
state: Arc<Mutex<Vec<CapturedRequest>>>,
|
||||||
|
responses: Vec<String>,
|
||||||
|
) -> TestServer {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0")
|
||||||
|
.await
|
||||||
|
.expect("listener should bind");
|
||||||
|
let address = listener.local_addr().expect("listener addr");
|
||||||
|
let join_handle = tokio::spawn(async move {
|
||||||
|
for response in responses {
|
||||||
|
let (mut socket, _) = listener.accept().await.expect("accept");
|
||||||
|
let mut buffer = Vec::new();
|
||||||
|
let mut header_end = None;
|
||||||
|
loop {
|
||||||
|
let mut chunk = [0_u8; 1024];
|
||||||
|
let read = socket.read(&mut chunk).await.expect("read request");
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
buffer.extend_from_slice(&chunk[..read]);
|
||||||
|
if let Some(position) = find_header_end(&buffer) {
|
||||||
|
header_end = Some(position);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let header_end = header_end.expect("headers should exist");
|
||||||
|
let (header_bytes, remaining) = buffer.split_at(header_end);
|
||||||
|
let header_text = String::from_utf8(header_bytes.to_vec()).expect("utf8 headers");
|
||||||
|
let mut lines = header_text.split("\r\n");
|
||||||
|
let request_line = lines.next().expect("request line");
|
||||||
|
let path = request_line
|
||||||
|
.split_whitespace()
|
||||||
|
.nth(1)
|
||||||
|
.expect("path")
|
||||||
|
.to_string();
|
||||||
|
let mut headers = HashMap::new();
|
||||||
|
let mut content_length = 0_usize;
|
||||||
|
for line in lines {
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (name, value) = line.split_once(':').expect("header");
|
||||||
|
let value = value.trim().to_string();
|
||||||
|
if name.eq_ignore_ascii_case("content-length") {
|
||||||
|
content_length = value.parse().expect("content length");
|
||||||
|
}
|
||||||
|
headers.insert(name.to_ascii_lowercase(), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body = remaining[4..].to_vec();
|
||||||
|
while body.len() < content_length {
|
||||||
|
let mut chunk = vec![0_u8; content_length - body.len()];
|
||||||
|
let read = socket.read(&mut chunk).await.expect("read body");
|
||||||
|
if read == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&chunk[..read]);
|
||||||
|
}
|
||||||
|
|
||||||
|
state.lock().await.push(CapturedRequest {
|
||||||
|
path,
|
||||||
|
headers,
|
||||||
|
body: String::from_utf8(body).expect("utf8 body"),
|
||||||
|
});
|
||||||
|
|
||||||
|
socket
|
||||||
|
.write_all(response.as_bytes())
|
||||||
|
.await
|
||||||
|
.expect("write response");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
TestServer {
|
||||||
|
base_url: format!("http://{address}"),
|
||||||
|
join_handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_header_end(bytes: &[u8]) -> Option<usize> {
|
||||||
|
bytes.windows(4).position(|window| window == b"\r\n\r\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn http_response(status: &str, content_type: &str, body: &str) -> String {
|
||||||
|
http_response_with_headers(status, content_type, body, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn http_response_with_headers(
|
||||||
|
status: &str,
|
||||||
|
content_type: &str,
|
||||||
|
body: &str,
|
||||||
|
headers: &[(&str, &str)],
|
||||||
|
) -> String {
|
||||||
|
let mut extra_headers = String::new();
|
||||||
|
for (name, value) in headers {
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
write!(&mut extra_headers, "{name}: {value}\r\n").expect("header write");
|
||||||
|
}
|
||||||
|
format!(
|
||||||
|
"HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\n{extra_headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sample_request(stream: bool) -> MessageRequest {
|
||||||
|
MessageRequest {
|
||||||
|
model: "grok-3".to_string(),
|
||||||
|
max_tokens: 64,
|
||||||
|
messages: vec![InputMessage {
|
||||||
|
role: "user".to_string(),
|
||||||
|
content: vec![InputContentBlock::Text {
|
||||||
|
text: "Say hello".to_string(),
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
system: Some("Use tools when needed".to_string()),
|
||||||
|
tools: Some(vec![ToolDefinition {
|
||||||
|
name: "weather".to_string(),
|
||||||
|
description: Some("Fetches weather".to_string()),
|
||||||
|
input_schema: json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": {"city": {"type": "string"}},
|
||||||
|
"required": ["city"]
|
||||||
|
}),
|
||||||
|
}]),
|
||||||
|
tool_choice: Some(ToolChoice::Auto),
|
||||||
|
stream,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||||
|
static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
|
||||||
|
LOCK.get_or_init(|| StdMutex::new(()))
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ScopedEnvVar {
|
||||||
|
key: &'static str,
|
||||||
|
previous: Option<OsString>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScopedEnvVar {
|
||||||
|
fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
|
||||||
|
let previous = std::env::var_os(key);
|
||||||
|
std::env::set_var(key, value);
|
||||||
|
Self { key, previous }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ScopedEnvVar {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
match &self.previous {
|
||||||
|
Some(value) => std::env::set_var(self.key, value),
|
||||||
|
None => std::env::remove_var(self.key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
86
rust/crates/api/tests/provider_client_integration.rs
Normal file
86
rust/crates/api/tests/provider_client_integration.rs
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
use std::ffi::OsString;
|
||||||
|
use std::sync::{Mutex, OnceLock};
|
||||||
|
|
||||||
|
use api::{read_xai_base_url, ApiError, AuthSource, ProviderClient, ProviderKind};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn provider_client_routes_grok_aliases_through_xai() {
|
||||||
|
let _lock = env_lock();
|
||||||
|
let _xai_api_key = EnvVarGuard::set("XAI_API_KEY", Some("xai-test-key"));
|
||||||
|
|
||||||
|
let client = ProviderClient::from_model("grok-mini").expect("grok alias should resolve");
|
||||||
|
|
||||||
|
assert_eq!(client.provider_kind(), ProviderKind::Xai);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn provider_client_reports_missing_xai_credentials_for_grok_models() {
|
||||||
|
let _lock = env_lock();
|
||||||
|
let _xai_api_key = EnvVarGuard::set("XAI_API_KEY", None);
|
||||||
|
|
||||||
|
let error = ProviderClient::from_model("grok-3")
|
||||||
|
.expect_err("grok requests without XAI_API_KEY should fail fast");
|
||||||
|
|
||||||
|
match error {
|
||||||
|
ApiError::MissingCredentials { provider, env_vars } => {
|
||||||
|
assert_eq!(provider, "xAI");
|
||||||
|
assert_eq!(env_vars, &["XAI_API_KEY"]);
|
||||||
|
}
|
||||||
|
other => panic!("expected missing xAI credentials, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn provider_client_uses_explicit_anthropic_auth_without_env_lookup() {
|
||||||
|
let _lock = env_lock();
|
||||||
|
let _anthropic_api_key = EnvVarGuard::set("ANTHROPIC_API_KEY", None);
|
||||||
|
let _anthropic_auth_token = EnvVarGuard::set("ANTHROPIC_AUTH_TOKEN", None);
|
||||||
|
|
||||||
|
let client = ProviderClient::from_model_with_anthropic_auth(
|
||||||
|
"claude-sonnet-4-6",
|
||||||
|
Some(AuthSource::ApiKey("anthropic-test-key".to_string())),
|
||||||
|
)
|
||||||
|
.expect("explicit anthropic auth should avoid env lookup");
|
||||||
|
|
||||||
|
assert_eq!(client.provider_kind(), ProviderKind::Anthropic);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn read_xai_base_url_prefers_env_override() {
|
||||||
|
let _lock = env_lock();
|
||||||
|
let _xai_base_url = EnvVarGuard::set("XAI_BASE_URL", Some("https://example.xai.test/v1"));
|
||||||
|
|
||||||
|
assert_eq!(read_xai_base_url(), "https://example.xai.test/v1");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||||
|
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||||
|
LOCK.get_or_init(|| Mutex::new(()))
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EnvVarGuard {
|
||||||
|
key: &'static str,
|
||||||
|
original: Option<OsString>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EnvVarGuard {
|
||||||
|
fn set(key: &'static str, value: Option<&str>) -> Self {
|
||||||
|
let original = std::env::var_os(key);
|
||||||
|
match value {
|
||||||
|
Some(value) => std::env::set_var(key, value),
|
||||||
|
None => std::env::remove_var(key),
|
||||||
|
}
|
||||||
|
Self { key, original }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for EnvVarGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
match &self.original {
|
||||||
|
Some(value) => std::env::set_var(self.key, value),
|
||||||
|
None => std::env::remove_var(self.key),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,3 +11,4 @@ workspace = true
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
plugins = { path = "../plugins" }
|
plugins = { path = "../plugins" }
|
||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
|
serde_json.workspace = true
|
||||||
|
|||||||
@@ -201,9 +201,9 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
resume_supported: false,
|
resume_supported: false,
|
||||||
},
|
},
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "plugins",
|
name: "plugin",
|
||||||
aliases: &["plugin", "marketplace"],
|
aliases: &["plugins", "marketplace"],
|
||||||
summary: "Manage Claude Code plugins",
|
summary: "Manage Claw Code plugins",
|
||||||
argument_hint: Some(
|
argument_hint: Some(
|
||||||
"[list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]",
|
"[list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]",
|
||||||
),
|
),
|
||||||
@@ -212,16 +212,16 @@ const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
|
|||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "agents",
|
name: "agents",
|
||||||
aliases: &[],
|
aliases: &[],
|
||||||
summary: "Manage agent configurations",
|
summary: "List configured agents",
|
||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: false,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
SlashCommandSpec {
|
SlashCommandSpec {
|
||||||
name: "skills",
|
name: "skills",
|
||||||
aliases: &[],
|
aliases: &[],
|
||||||
summary: "List available skills",
|
summary: "List available skills",
|
||||||
argument_hint: None,
|
argument_hint: None,
|
||||||
resume_supported: false,
|
resume_supported: true,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -470,6 +470,29 @@ struct SkillSummary {
|
|||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
source: DefinitionSource,
|
source: DefinitionSource,
|
||||||
shadowed_by: Option<DefinitionSource>,
|
shadowed_by: Option<DefinitionSource>,
|
||||||
|
origin: SkillOrigin,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum SkillOrigin {
|
||||||
|
SkillsDir,
|
||||||
|
LegacyCommandsDir,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SkillOrigin {
|
||||||
|
fn detail_label(self) -> Option<&'static str> {
|
||||||
|
match self {
|
||||||
|
Self::SkillsDir => None,
|
||||||
|
Self::LegacyCommandsDir => Some("legacy /commands"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
struct SkillRoot {
|
||||||
|
source: DefinitionSource,
|
||||||
|
path: PathBuf,
|
||||||
|
origin: SkillOrigin,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
#[allow(clippy::too_many_lines)]
|
||||||
@@ -585,23 +608,27 @@ pub fn handle_plugins_slash_command(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_agents_slash_command(args: Option<&str>, cwd: &Path) -> std::io::Result<String> {
|
pub fn handle_agents_slash_command(args: Option<&str>, cwd: &Path) -> std::io::Result<String> {
|
||||||
if let Some(args) = args.filter(|value| !value.trim().is_empty()) {
|
match normalize_optional_args(args) {
|
||||||
return Ok(format!("Usage: /agents\nUnexpected arguments: {args}"));
|
None | Some("list") => {
|
||||||
|
let roots = discover_definition_roots(cwd, "agents");
|
||||||
|
let agents = load_agents_from_roots(&roots)?;
|
||||||
|
Ok(render_agents_report(&agents))
|
||||||
|
}
|
||||||
|
Some("-h" | "--help" | "help") => Ok(render_agents_usage(None)),
|
||||||
|
Some(args) => Ok(render_agents_usage(Some(args))),
|
||||||
}
|
}
|
||||||
|
|
||||||
let roots = discover_definition_roots(cwd, "agents");
|
|
||||||
let agents = load_agents_from_roots(&roots)?;
|
|
||||||
Ok(render_agents_report(&agents))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn handle_skills_slash_command(args: Option<&str>, cwd: &Path) -> std::io::Result<String> {
|
pub fn handle_skills_slash_command(args: Option<&str>, cwd: &Path) -> std::io::Result<String> {
|
||||||
if let Some(args) = args.filter(|value| !value.trim().is_empty()) {
|
match normalize_optional_args(args) {
|
||||||
return Ok(format!("Usage: /skills\nUnexpected arguments: {args}"));
|
None | Some("list") => {
|
||||||
|
let roots = discover_skill_roots(cwd);
|
||||||
|
let skills = load_skills_from_roots(&roots)?;
|
||||||
|
Ok(render_skills_report(&skills))
|
||||||
|
}
|
||||||
|
Some("-h" | "--help" | "help") => Ok(render_skills_usage(None)),
|
||||||
|
Some(args) => Ok(render_skills_usage(Some(args))),
|
||||||
}
|
}
|
||||||
|
|
||||||
let roots = discover_definition_roots(cwd, "skills");
|
|
||||||
let skills = load_skills_from_roots(&roots)?;
|
|
||||||
Ok(render_skills_report(&skills))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
@@ -697,6 +724,83 @@ fn discover_definition_roots(cwd: &Path, leaf: &str) -> Vec<(DefinitionSource, P
|
|||||||
roots
|
roots
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn discover_skill_roots(cwd: &Path) -> Vec<SkillRoot> {
|
||||||
|
let mut roots = Vec::new();
|
||||||
|
|
||||||
|
for ancestor in cwd.ancestors() {
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::ProjectCodex,
|
||||||
|
ancestor.join(".codex").join("skills"),
|
||||||
|
SkillOrigin::SkillsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::ProjectClaude,
|
||||||
|
ancestor.join(".claude").join("skills"),
|
||||||
|
SkillOrigin::SkillsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::ProjectCodex,
|
||||||
|
ancestor.join(".codex").join("commands"),
|
||||||
|
SkillOrigin::LegacyCommandsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::ProjectClaude,
|
||||||
|
ancestor.join(".claude").join("commands"),
|
||||||
|
SkillOrigin::LegacyCommandsDir,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Ok(codex_home) = env::var("CODEX_HOME") {
|
||||||
|
let codex_home = PathBuf::from(codex_home);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::UserCodexHome,
|
||||||
|
codex_home.join("skills"),
|
||||||
|
SkillOrigin::SkillsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::UserCodexHome,
|
||||||
|
codex_home.join("commands"),
|
||||||
|
SkillOrigin::LegacyCommandsDir,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(home) = env::var_os("HOME") {
|
||||||
|
let home = PathBuf::from(home);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::UserCodex,
|
||||||
|
home.join(".codex").join("skills"),
|
||||||
|
SkillOrigin::SkillsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::UserCodex,
|
||||||
|
home.join(".codex").join("commands"),
|
||||||
|
SkillOrigin::LegacyCommandsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::UserClaude,
|
||||||
|
home.join(".claude").join("skills"),
|
||||||
|
SkillOrigin::SkillsDir,
|
||||||
|
);
|
||||||
|
push_unique_skill_root(
|
||||||
|
&mut roots,
|
||||||
|
DefinitionSource::UserClaude,
|
||||||
|
home.join(".claude").join("commands"),
|
||||||
|
SkillOrigin::LegacyCommandsDir,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
roots
|
||||||
|
}
|
||||||
|
|
||||||
fn push_unique_root(
|
fn push_unique_root(
|
||||||
roots: &mut Vec<(DefinitionSource, PathBuf)>,
|
roots: &mut Vec<(DefinitionSource, PathBuf)>,
|
||||||
source: DefinitionSource,
|
source: DefinitionSource,
|
||||||
@@ -707,6 +811,21 @@ fn push_unique_root(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn push_unique_skill_root(
|
||||||
|
roots: &mut Vec<SkillRoot>,
|
||||||
|
source: DefinitionSource,
|
||||||
|
path: PathBuf,
|
||||||
|
origin: SkillOrigin,
|
||||||
|
) {
|
||||||
|
if path.is_dir() && !roots.iter().any(|existing| existing.path == path) {
|
||||||
|
roots.push(SkillRoot {
|
||||||
|
source,
|
||||||
|
path,
|
||||||
|
origin,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn load_agents_from_roots(
|
fn load_agents_from_roots(
|
||||||
roots: &[(DefinitionSource, PathBuf)],
|
roots: &[(DefinitionSource, PathBuf)],
|
||||||
) -> std::io::Result<Vec<AgentSummary>> {
|
) -> std::io::Result<Vec<AgentSummary>> {
|
||||||
@@ -721,11 +840,10 @@ fn load_agents_from_roots(
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let contents = fs::read_to_string(entry.path())?;
|
let contents = fs::read_to_string(entry.path())?;
|
||||||
let fallback_name = entry
|
let fallback_name = entry.path().file_stem().map_or_else(
|
||||||
.path()
|
|| entry.file_name().to_string_lossy().to_string(),
|
||||||
.file_stem()
|
|stem| stem.to_string_lossy().to_string(),
|
||||||
.map(|stem| stem.to_string_lossy().to_string())
|
);
|
||||||
.unwrap_or_else(|| entry.file_name().to_string_lossy().to_string());
|
|
||||||
root_agents.push(AgentSummary {
|
root_agents.push(AgentSummary {
|
||||||
name: parse_toml_string(&contents, "name").unwrap_or(fallback_name),
|
name: parse_toml_string(&contents, "name").unwrap_or(fallback_name),
|
||||||
description: parse_toml_string(&contents, "description"),
|
description: parse_toml_string(&contents, "description"),
|
||||||
@@ -751,31 +869,66 @@ fn load_agents_from_roots(
|
|||||||
Ok(agents)
|
Ok(agents)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn load_skills_from_roots(
|
fn load_skills_from_roots(roots: &[SkillRoot]) -> std::io::Result<Vec<SkillSummary>> {
|
||||||
roots: &[(DefinitionSource, PathBuf)],
|
|
||||||
) -> std::io::Result<Vec<SkillSummary>> {
|
|
||||||
let mut skills = Vec::new();
|
let mut skills = Vec::new();
|
||||||
let mut active_sources = BTreeMap::<String, DefinitionSource>::new();
|
let mut active_sources = BTreeMap::<String, DefinitionSource>::new();
|
||||||
|
|
||||||
for (source, root) in roots {
|
for root in roots {
|
||||||
let mut root_skills = Vec::new();
|
let mut root_skills = Vec::new();
|
||||||
for entry in fs::read_dir(root)? {
|
for entry in fs::read_dir(&root.path)? {
|
||||||
let entry = entry?;
|
let entry = entry?;
|
||||||
if !entry.path().is_dir() {
|
match root.origin {
|
||||||
continue;
|
SkillOrigin::SkillsDir => {
|
||||||
|
if !entry.path().is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let skill_path = entry.path().join("SKILL.md");
|
||||||
|
if !skill_path.is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let contents = fs::read_to_string(skill_path)?;
|
||||||
|
let (name, description) = parse_skill_frontmatter(&contents);
|
||||||
|
root_skills.push(SkillSummary {
|
||||||
|
name: name
|
||||||
|
.unwrap_or_else(|| entry.file_name().to_string_lossy().to_string()),
|
||||||
|
description,
|
||||||
|
source: root.source,
|
||||||
|
shadowed_by: None,
|
||||||
|
origin: root.origin,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
SkillOrigin::LegacyCommandsDir => {
|
||||||
|
let path = entry.path();
|
||||||
|
let markdown_path = if path.is_dir() {
|
||||||
|
let skill_path = path.join("SKILL.md");
|
||||||
|
if !skill_path.is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
skill_path
|
||||||
|
} else if path
|
||||||
|
.extension()
|
||||||
|
.is_some_and(|ext| ext.to_string_lossy().eq_ignore_ascii_case("md"))
|
||||||
|
{
|
||||||
|
path
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let contents = fs::read_to_string(&markdown_path)?;
|
||||||
|
let fallback_name = markdown_path.file_stem().map_or_else(
|
||||||
|
|| entry.file_name().to_string_lossy().to_string(),
|
||||||
|
|stem| stem.to_string_lossy().to_string(),
|
||||||
|
);
|
||||||
|
let (name, description) = parse_skill_frontmatter(&contents);
|
||||||
|
root_skills.push(SkillSummary {
|
||||||
|
name: name.unwrap_or(fallback_name),
|
||||||
|
description,
|
||||||
|
source: root.source,
|
||||||
|
shadowed_by: None,
|
||||||
|
origin: root.origin,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let skill_path = entry.path().join("SKILL.md");
|
|
||||||
if !skill_path.is_file() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let contents = fs::read_to_string(skill_path)?;
|
|
||||||
let (name, description) = parse_skill_frontmatter(&contents);
|
|
||||||
root_skills.push(SkillSummary {
|
|
||||||
name: name.unwrap_or_else(|| entry.file_name().to_string_lossy().to_string()),
|
|
||||||
description,
|
|
||||||
source: *source,
|
|
||||||
shadowed_by: None,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
root_skills.sort_by(|left, right| left.name.cmp(&right.name));
|
root_skills.sort_by(|left, right| left.name.cmp(&right.name));
|
||||||
|
|
||||||
@@ -831,16 +984,16 @@ fn parse_skill_frontmatter(contents: &str) -> (Option<String>, Option<String>) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if let Some(value) = trimmed.strip_prefix("name:") {
|
if let Some(value) = trimmed.strip_prefix("name:") {
|
||||||
let value = value.trim();
|
let value = unquote_frontmatter_value(value.trim());
|
||||||
if !value.is_empty() {
|
if !value.is_empty() {
|
||||||
name = Some(value.to_string());
|
name = Some(value);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Some(value) = trimmed.strip_prefix("description:") {
|
if let Some(value) = trimmed.strip_prefix("description:") {
|
||||||
let value = value.trim();
|
let value = unquote_frontmatter_value(value.trim());
|
||||||
if !value.is_empty() {
|
if !value.is_empty() {
|
||||||
description = Some(value.to_string());
|
description = Some(value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -848,6 +1001,20 @@ fn parse_skill_frontmatter(contents: &str) -> (Option<String>, Option<String>) {
|
|||||||
(name, description)
|
(name, description)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn unquote_frontmatter_value(value: &str) -> String {
|
||||||
|
value
|
||||||
|
.strip_prefix('"')
|
||||||
|
.and_then(|trimmed| trimmed.strip_suffix('"'))
|
||||||
|
.or_else(|| {
|
||||||
|
value
|
||||||
|
.strip_prefix('\'')
|
||||||
|
.and_then(|trimmed| trimmed.strip_suffix('\''))
|
||||||
|
})
|
||||||
|
.unwrap_or(value)
|
||||||
|
.trim()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
fn render_agents_report(agents: &[AgentSummary]) -> String {
|
fn render_agents_report(agents: &[AgentSummary]) -> String {
|
||||||
if agents.is_empty() {
|
if agents.is_empty() {
|
||||||
return "No agents found.".to_string();
|
return "No agents found.".to_string();
|
||||||
@@ -938,10 +1105,14 @@ fn render_skills_report(skills: &[SkillSummary]) -> String {
|
|||||||
|
|
||||||
lines.push(format!("{}:", source.label()));
|
lines.push(format!("{}:", source.label()));
|
||||||
for skill in group {
|
for skill in group {
|
||||||
let detail = match &skill.description {
|
let mut parts = vec![skill.name.clone()];
|
||||||
Some(description) => format!("{} · {}", skill.name, description),
|
if let Some(description) = &skill.description {
|
||||||
None => skill.name.clone(),
|
parts.push(description.clone());
|
||||||
};
|
}
|
||||||
|
if let Some(detail) = skill.origin.detail_label() {
|
||||||
|
parts.push(detail.to_string());
|
||||||
|
}
|
||||||
|
let detail = parts.join(" · ");
|
||||||
match skill.shadowed_by {
|
match skill.shadowed_by {
|
||||||
Some(winner) => lines.push(format!(" (shadowed by {}) {detail}", winner.label())),
|
Some(winner) => lines.push(format!(" (shadowed by {}) {detail}", winner.label())),
|
||||||
None => lines.push(format!(" {detail}")),
|
None => lines.push(format!(" {detail}")),
|
||||||
@@ -953,6 +1124,36 @@ fn render_skills_report(skills: &[SkillSummary]) -> String {
|
|||||||
lines.join("\n").trim_end().to_string()
|
lines.join("\n").trim_end().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn normalize_optional_args(args: Option<&str>) -> Option<&str> {
|
||||||
|
args.map(str::trim).filter(|value| !value.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_agents_usage(unexpected: Option<&str>) -> String {
|
||||||
|
let mut lines = vec![
|
||||||
|
"Agents".to_string(),
|
||||||
|
" Usage /agents".to_string(),
|
||||||
|
" Direct CLI claw agents".to_string(),
|
||||||
|
" Sources .codex/agents, .claude/agents, $CODEX_HOME/agents".to_string(),
|
||||||
|
];
|
||||||
|
if let Some(args) = unexpected {
|
||||||
|
lines.push(format!(" Unexpected {args}"));
|
||||||
|
}
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_skills_usage(unexpected: Option<&str>) -> String {
|
||||||
|
let mut lines = vec![
|
||||||
|
"Skills".to_string(),
|
||||||
|
" Usage /skills".to_string(),
|
||||||
|
" Direct CLI claw skills".to_string(),
|
||||||
|
" Sources .codex/skills, .claude/skills, legacy /commands".to_string(),
|
||||||
|
];
|
||||||
|
if let Some(args) = unexpected {
|
||||||
|
lines.push(format!(" Unexpected {args}"));
|
||||||
|
}
|
||||||
|
lines.join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn handle_slash_command(
|
pub fn handle_slash_command(
|
||||||
input: &str,
|
input: &str,
|
||||||
@@ -1012,7 +1213,7 @@ mod tests {
|
|||||||
handle_plugins_slash_command, handle_slash_command, load_agents_from_roots,
|
handle_plugins_slash_command, handle_slash_command, load_agents_from_roots,
|
||||||
load_skills_from_roots, render_agents_report, render_plugins_report, render_skills_report,
|
load_skills_from_roots, render_agents_report, render_plugins_report, render_skills_report,
|
||||||
render_slash_command_help, resume_supported_slash_commands, slash_command_specs,
|
render_slash_command_help, resume_supported_slash_commands, slash_command_specs,
|
||||||
DefinitionSource, SlashCommand,
|
DefinitionSource, SkillOrigin, SkillRoot, SlashCommand,
|
||||||
};
|
};
|
||||||
use plugins::{PluginKind, PluginManager, PluginManagerConfig, PluginMetadata, PluginSummary};
|
use plugins::{PluginKind, PluginManager, PluginManagerConfig, PluginMetadata, PluginSummary};
|
||||||
use runtime::{CompactionConfig, ContentBlock, ConversationMessage, MessageRole, Session};
|
use runtime::{CompactionConfig, ContentBlock, ConversationMessage, MessageRole, Session};
|
||||||
@@ -1072,6 +1273,15 @@ mod tests {
|
|||||||
.expect("write skill");
|
.expect("write skill");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn write_legacy_command(root: &Path, name: &str, description: &str) {
|
||||||
|
fs::create_dir_all(root).expect("commands root");
|
||||||
|
fs::write(
|
||||||
|
root.join(format!("{name}.md")),
|
||||||
|
format!("---\nname: {name}\ndescription: {description}\n---\n\n# {name}\n"),
|
||||||
|
)
|
||||||
|
.expect("write command");
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
#[allow(clippy::too_many_lines)]
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_supported_slash_commands() {
|
fn parses_supported_slash_commands() {
|
||||||
@@ -1227,10 +1437,13 @@ mod tests {
|
|||||||
assert!(help.contains("/export [file]"));
|
assert!(help.contains("/export [file]"));
|
||||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||||
assert!(help.contains(
|
assert!(help.contains(
|
||||||
"/plugins [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
|
"/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
|
||||||
));
|
));
|
||||||
|
assert!(help.contains("aliases: /plugins, /marketplace"));
|
||||||
|
assert!(help.contains("/agents"));
|
||||||
|
assert!(help.contains("/skills"));
|
||||||
assert_eq!(slash_command_specs().len(), 25);
|
assert_eq!(slash_command_specs().len(), 25);
|
||||||
assert_eq!(resume_supported_slash_commands().len(), 11);
|
assert_eq!(resume_supported_slash_commands().len(), 13);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -1423,24 +1636,41 @@ mod tests {
|
|||||||
fn lists_skills_from_project_and_user_roots() {
|
fn lists_skills_from_project_and_user_roots() {
|
||||||
let workspace = temp_dir("skills-workspace");
|
let workspace = temp_dir("skills-workspace");
|
||||||
let project_skills = workspace.join(".codex").join("skills");
|
let project_skills = workspace.join(".codex").join("skills");
|
||||||
|
let project_commands = workspace.join(".claude").join("commands");
|
||||||
let user_home = temp_dir("skills-home");
|
let user_home = temp_dir("skills-home");
|
||||||
let user_skills = user_home.join(".codex").join("skills");
|
let user_skills = user_home.join(".codex").join("skills");
|
||||||
|
|
||||||
write_skill(&project_skills, "plan", "Project planning guidance");
|
write_skill(&project_skills, "plan", "Project planning guidance");
|
||||||
|
write_legacy_command(&project_commands, "deploy", "Legacy deployment guidance");
|
||||||
write_skill(&user_skills, "plan", "User planning guidance");
|
write_skill(&user_skills, "plan", "User planning guidance");
|
||||||
write_skill(&user_skills, "help", "Help guidance");
|
write_skill(&user_skills, "help", "Help guidance");
|
||||||
|
|
||||||
let roots = vec![
|
let roots = vec![
|
||||||
(DefinitionSource::ProjectCodex, project_skills),
|
SkillRoot {
|
||||||
(DefinitionSource::UserCodex, user_skills),
|
source: DefinitionSource::ProjectCodex,
|
||||||
|
path: project_skills,
|
||||||
|
origin: SkillOrigin::SkillsDir,
|
||||||
|
},
|
||||||
|
SkillRoot {
|
||||||
|
source: DefinitionSource::ProjectClaude,
|
||||||
|
path: project_commands,
|
||||||
|
origin: SkillOrigin::LegacyCommandsDir,
|
||||||
|
},
|
||||||
|
SkillRoot {
|
||||||
|
source: DefinitionSource::UserCodex,
|
||||||
|
path: user_skills,
|
||||||
|
origin: SkillOrigin::SkillsDir,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
let report =
|
let report =
|
||||||
render_skills_report(&load_skills_from_roots(&roots).expect("skill roots should load"));
|
render_skills_report(&load_skills_from_roots(&roots).expect("skill roots should load"));
|
||||||
|
|
||||||
assert!(report.contains("Skills"));
|
assert!(report.contains("Skills"));
|
||||||
assert!(report.contains("2 available skills"));
|
assert!(report.contains("3 available skills"));
|
||||||
assert!(report.contains("Project (.codex):"));
|
assert!(report.contains("Project (.codex):"));
|
||||||
assert!(report.contains("plan · Project planning guidance"));
|
assert!(report.contains("plan · Project planning guidance"));
|
||||||
|
assert!(report.contains("Project (.claude):"));
|
||||||
|
assert!(report.contains("deploy · Legacy deployment guidance · legacy /commands"));
|
||||||
assert!(report.contains("User (~/.codex):"));
|
assert!(report.contains("User (~/.codex):"));
|
||||||
assert!(report.contains("(shadowed by Project (.codex)) plan · User planning guidance"));
|
assert!(report.contains("(shadowed by Project (.codex)) plan · User planning guidance"));
|
||||||
assert!(report.contains("help · Help guidance"));
|
assert!(report.contains("help · Help guidance"));
|
||||||
@@ -1449,6 +1679,39 @@ mod tests {
|
|||||||
let _ = fs::remove_dir_all(user_home);
|
let _ = fs::remove_dir_all(user_home);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn agents_and_skills_usage_support_help_and_unexpected_args() {
|
||||||
|
let cwd = temp_dir("slash-usage");
|
||||||
|
|
||||||
|
let agents_help =
|
||||||
|
super::handle_agents_slash_command(Some("help"), &cwd).expect("agents help");
|
||||||
|
assert!(agents_help.contains("Usage /agents"));
|
||||||
|
assert!(agents_help.contains("Direct CLI claw agents"));
|
||||||
|
|
||||||
|
let agents_unexpected =
|
||||||
|
super::handle_agents_slash_command(Some("show planner"), &cwd).expect("agents usage");
|
||||||
|
assert!(agents_unexpected.contains("Unexpected show planner"));
|
||||||
|
|
||||||
|
let skills_help =
|
||||||
|
super::handle_skills_slash_command(Some("--help"), &cwd).expect("skills help");
|
||||||
|
assert!(skills_help.contains("Usage /skills"));
|
||||||
|
assert!(skills_help.contains("legacy /commands"));
|
||||||
|
|
||||||
|
let skills_unexpected =
|
||||||
|
super::handle_skills_slash_command(Some("show help"), &cwd).expect("skills usage");
|
||||||
|
assert!(skills_unexpected.contains("Unexpected show help"));
|
||||||
|
|
||||||
|
let _ = fs::remove_dir_all(cwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_quoted_skill_frontmatter_values() {
|
||||||
|
let contents = "---\nname: \"hud\"\ndescription: 'Quoted description'\n---\n";
|
||||||
|
let (name, description) = super::parse_skill_frontmatter(contents);
|
||||||
|
assert_eq!(name.as_deref(), Some("hud"));
|
||||||
|
assert_eq!(description.as_deref(), Some("Quoted description"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn installs_plugin_from_path_and_lists_it() {
|
fn installs_plugin_from_path_and_lists_it() {
|
||||||
let config_home = temp_dir("home");
|
let config_home = temp_dir("home");
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ publish.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json.workspace = true
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@@ -1208,6 +1208,8 @@ impl PluginManager {
|
|||||||
let install_path = install_root.join(sanitize_plugin_id(&plugin_id));
|
let install_path = install_root.join(sanitize_plugin_id(&plugin_id));
|
||||||
let now = unix_time_ms();
|
let now = unix_time_ms();
|
||||||
let existing_record = registry.plugins.get(&plugin_id);
|
let existing_record = registry.plugins.get(&plugin_id);
|
||||||
|
let installed_copy_is_valid =
|
||||||
|
install_path.exists() && load_plugin_from_directory(&install_path).is_ok();
|
||||||
let needs_sync = existing_record.is_none_or(|record| {
|
let needs_sync = existing_record.is_none_or(|record| {
|
||||||
record.kind != PluginKind::Bundled
|
record.kind != PluginKind::Bundled
|
||||||
|| record.version != manifest.version
|
|| record.version != manifest.version
|
||||||
@@ -1215,6 +1217,7 @@ impl PluginManager {
|
|||||||
|| record.description != manifest.description
|
|| record.description != manifest.description
|
||||||
|| record.install_path != install_path
|
|| record.install_path != install_path
|
||||||
|| !record.install_path.exists()
|
|| !record.install_path.exists()
|
||||||
|
|| !installed_copy_is_valid
|
||||||
});
|
});
|
||||||
|
|
||||||
if !needs_sync {
|
if !needs_sync {
|
||||||
@@ -1294,6 +1297,7 @@ impl PluginManager {
|
|||||||
fn load_registry(&self) -> Result<InstalledPluginRegistry, PluginError> {
|
fn load_registry(&self) -> Result<InstalledPluginRegistry, PluginError> {
|
||||||
let path = self.registry_path();
|
let path = self.registry_path();
|
||||||
match fs::read_to_string(&path) {
|
match fs::read_to_string(&path) {
|
||||||
|
Ok(contents) if contents.trim().is_empty() => Ok(InstalledPluginRegistry::default()),
|
||||||
Ok(contents) => Ok(serde_json::from_str(&contents)?),
|
Ok(contents) => Ok(serde_json::from_str(&contents)?),
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||||
Ok(InstalledPluginRegistry::default())
|
Ok(InstalledPluginRegistry::default())
|
||||||
@@ -2003,7 +2007,11 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
fn temp_dir(label: &str) -> PathBuf {
|
fn temp_dir(label: &str) -> PathBuf {
|
||||||
std::env::temp_dir().join(format!("plugins-{label}-{}", unix_time_ms()))
|
let nanos = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.expect("time should be after epoch")
|
||||||
|
.as_nanos();
|
||||||
|
std::env::temp_dir().join(format!("plugins-{label}-{nanos}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn write_file(path: &Path, contents: &str) {
|
fn write_file(path: &Path, contents: &str) {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ glob = "0.3"
|
|||||||
plugins = { path = "../plugins" }
|
plugins = { path = "../plugins" }
|
||||||
regex = "1"
|
regex = "1"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json.workspace = true
|
||||||
tokio = { version = "1", features = ["io-util", "macros", "process", "rt", "rt-multi-thread", "time"] }
|
tokio = { version = "1", features = ["io-util", "macros", "process", "rt", "rt-multi-thread", "time"] }
|
||||||
walkdir = "2"
|
walkdir = "2"
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
use crate::sandbox::{FilesystemIsolationMode, SandboxConfig};
|
||||||
|
|
||||||
pub const CLAUDE_CODE_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
pub const CLAW_SETTINGS_SCHEMA_NAME: &str = "SettingsSchema";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum ConfigSource {
|
pub enum ConfigSource {
|
||||||
@@ -52,7 +52,6 @@ pub struct RuntimeFeatureConfig {
|
|||||||
oauth: Option<OAuthConfig>,
|
oauth: Option<OAuthConfig>,
|
||||||
model: Option<String>,
|
model: Option<String>,
|
||||||
permission_mode: Option<ResolvedPermissionMode>,
|
permission_mode: Option<ResolvedPermissionMode>,
|
||||||
permission_rules: RuntimePermissionRuleConfig,
|
|
||||||
sandbox: SandboxConfig,
|
sandbox: SandboxConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,14 +59,6 @@ pub struct RuntimeFeatureConfig {
|
|||||||
pub struct RuntimeHookConfig {
|
pub struct RuntimeHookConfig {
|
||||||
pre_tool_use: Vec<String>,
|
pre_tool_use: Vec<String>,
|
||||||
post_tool_use: Vec<String>,
|
post_tool_use: Vec<String>,
|
||||||
post_tool_use_failure: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
||||||
pub struct RuntimePermissionRuleConfig {
|
|
||||||
allow: Vec<String>,
|
|
||||||
deny: Vec<String>,
|
|
||||||
ask: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@@ -88,7 +79,7 @@ pub enum McpTransport {
|
|||||||
Http,
|
Http,
|
||||||
Ws,
|
Ws,
|
||||||
Sdk,
|
Sdk,
|
||||||
ClaudeAiProxy,
|
ManagedProxy,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -98,7 +89,7 @@ pub enum McpServerConfig {
|
|||||||
Http(McpRemoteServerConfig),
|
Http(McpRemoteServerConfig),
|
||||||
Ws(McpWebSocketServerConfig),
|
Ws(McpWebSocketServerConfig),
|
||||||
Sdk(McpSdkServerConfig),
|
Sdk(McpSdkServerConfig),
|
||||||
ClaudeAiProxy(McpClaudeAiProxyServerConfig),
|
ManagedProxy(McpManagedProxyServerConfig),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -129,7 +120,7 @@ pub struct McpSdkServerConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct McpClaudeAiProxyServerConfig {
|
pub struct McpManagedProxyServerConfig {
|
||||||
pub url: String,
|
pub url: String,
|
||||||
pub id: String,
|
pub id: String,
|
||||||
}
|
}
|
||||||
@@ -205,8 +196,8 @@ impl ConfigLoader {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn discover(&self) -> Vec<ConfigEntry> {
|
pub fn discover(&self) -> Vec<ConfigEntry> {
|
||||||
let user_legacy_path = self.config_home.parent().map_or_else(
|
let user_legacy_path = self.config_home.parent().map_or_else(
|
||||||
|| PathBuf::from(".claude.json"),
|
|| PathBuf::from(".claw.json"),
|
||||||
|parent| parent.join(".claude.json"),
|
|parent| parent.join(".claw.json"),
|
||||||
);
|
);
|
||||||
vec![
|
vec![
|
||||||
ConfigEntry {
|
ConfigEntry {
|
||||||
@@ -219,15 +210,15 @@ impl ConfigLoader {
|
|||||||
},
|
},
|
||||||
ConfigEntry {
|
ConfigEntry {
|
||||||
source: ConfigSource::Project,
|
source: ConfigSource::Project,
|
||||||
path: self.cwd.join(".claude.json"),
|
path: self.cwd.join(".claw.json"),
|
||||||
},
|
},
|
||||||
ConfigEntry {
|
ConfigEntry {
|
||||||
source: ConfigSource::Project,
|
source: ConfigSource::Project,
|
||||||
path: self.cwd.join(".claude").join("settings.json"),
|
path: self.cwd.join(".claw").join("settings.json"),
|
||||||
},
|
},
|
||||||
ConfigEntry {
|
ConfigEntry {
|
||||||
source: ConfigSource::Local,
|
source: ConfigSource::Local,
|
||||||
path: self.cwd.join(".claude").join("settings.local.json"),
|
path: self.cwd.join(".claw").join("settings.local.json"),
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -257,7 +248,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)?,
|
||||||
permission_rules: parse_optional_permission_rules(&merged_value)?,
|
|
||||||
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
sandbox: parse_optional_sandbox_config(&merged_value)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -334,11 +324,6 @@ impl RuntimeConfig {
|
|||||||
self.feature_config.permission_mode
|
self.feature_config.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn permission_rules(&self) -> &RuntimePermissionRuleConfig {
|
|
||||||
&self.feature_config.permission_rules
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn sandbox(&self) -> &SandboxConfig {
|
pub fn sandbox(&self) -> &SandboxConfig {
|
||||||
&self.feature_config.sandbox
|
&self.feature_config.sandbox
|
||||||
@@ -388,11 +373,6 @@ impl RuntimeFeatureConfig {
|
|||||||
self.permission_mode
|
self.permission_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn permission_rules(&self) -> &RuntimePermissionRuleConfig {
|
|
||||||
&self.permission_rules
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn sandbox(&self) -> &SandboxConfig {
|
pub fn sandbox(&self) -> &SandboxConfig {
|
||||||
&self.sandbox
|
&self.sandbox
|
||||||
@@ -440,23 +420,18 @@ impl RuntimePluginConfig {
|
|||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn default_config_home() -> PathBuf {
|
pub fn default_config_home() -> PathBuf {
|
||||||
std::env::var_os("CLAUDE_CONFIG_HOME")
|
std::env::var_os("CLAW_CONFIG_HOME")
|
||||||
.map(PathBuf::from)
|
.map(PathBuf::from)
|
||||||
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".claude")))
|
.or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".claw")))
|
||||||
.unwrap_or_else(|| PathBuf::from(".claude"))
|
.unwrap_or_else(|| PathBuf::from(".claw"))
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeHookConfig {
|
impl RuntimeHookConfig {
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(
|
pub fn new(pre_tool_use: Vec<String>, post_tool_use: Vec<String>) -> Self {
|
||||||
pre_tool_use: Vec<String>,
|
|
||||||
post_tool_use: Vec<String>,
|
|
||||||
post_tool_use_failure: Vec<String>,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
pre_tool_use,
|
pre_tool_use,
|
||||||
post_tool_use,
|
post_tool_use,
|
||||||
post_tool_use_failure,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -470,11 +445,6 @@ impl RuntimeHookConfig {
|
|||||||
&self.post_tool_use
|
&self.post_tool_use
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn post_tool_use_failure(&self) -> &[String] {
|
|
||||||
&self.post_tool_use_failure
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn merged(&self, other: &Self) -> Self {
|
pub fn merged(&self, other: &Self) -> Self {
|
||||||
let mut merged = self.clone();
|
let mut merged = self.clone();
|
||||||
@@ -485,32 +455,6 @@ impl RuntimeHookConfig {
|
|||||||
pub fn extend(&mut self, other: &Self) {
|
pub fn extend(&mut self, other: &Self) {
|
||||||
extend_unique(&mut self.pre_tool_use, other.pre_tool_use());
|
extend_unique(&mut self.pre_tool_use, other.pre_tool_use());
|
||||||
extend_unique(&mut self.post_tool_use, other.post_tool_use());
|
extend_unique(&mut self.post_tool_use, other.post_tool_use());
|
||||||
extend_unique(
|
|
||||||
&mut self.post_tool_use_failure,
|
|
||||||
other.post_tool_use_failure(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RuntimePermissionRuleConfig {
|
|
||||||
#[must_use]
|
|
||||||
pub fn new(allow: Vec<String>, deny: Vec<String>, ask: Vec<String>) -> Self {
|
|
||||||
Self { allow, deny, ask }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn allow(&self) -> &[String] {
|
|
||||||
&self.allow
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn deny(&self) -> &[String] {
|
|
||||||
&self.deny
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn ask(&self) -> &[String] {
|
|
||||||
&self.ask
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -542,7 +486,7 @@ impl McpServerConfig {
|
|||||||
Self::Http(_) => McpTransport::Http,
|
Self::Http(_) => McpTransport::Http,
|
||||||
Self::Ws(_) => McpTransport::Ws,
|
Self::Ws(_) => McpTransport::Ws,
|
||||||
Self::Sdk(_) => McpTransport::Sdk,
|
Self::Sdk(_) => McpTransport::Sdk,
|
||||||
Self::ClaudeAiProxy(_) => McpTransport::ClaudeAiProxy,
|
Self::ManagedProxy(_) => McpTransport::ManagedProxy,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -550,7 +494,7 @@ impl McpServerConfig {
|
|||||||
fn read_optional_json_object(
|
fn read_optional_json_object(
|
||||||
path: &Path,
|
path: &Path,
|
||||||
) -> Result<Option<BTreeMap<String, JsonValue>>, ConfigError> {
|
) -> Result<Option<BTreeMap<String, JsonValue>>, ConfigError> {
|
||||||
let is_legacy_config = path.file_name().and_then(|name| name.to_str()) == Some(".claude.json");
|
let is_legacy_config = path.file_name().and_then(|name| name.to_str()) == Some(".claw.json");
|
||||||
let contents = match fs::read_to_string(path) {
|
let contents = match fs::read_to_string(path) {
|
||||||
Ok(contents) => contents,
|
Ok(contents) => contents,
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
@@ -625,32 +569,6 @@ fn parse_optional_hooks_config(root: &JsonValue) -> Result<RuntimeHookConfig, Co
|
|||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
post_tool_use: optional_string_array(hooks, "PostToolUse", "merged settings.hooks")?
|
post_tool_use: optional_string_array(hooks, "PostToolUse", "merged settings.hooks")?
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
post_tool_use_failure: optional_string_array(
|
|
||||||
hooks,
|
|
||||||
"PostToolUseFailure",
|
|
||||||
"merged settings.hooks",
|
|
||||||
)?
|
|
||||||
.unwrap_or_default(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_optional_permission_rules(
|
|
||||||
root: &JsonValue,
|
|
||||||
) -> Result<RuntimePermissionRuleConfig, ConfigError> {
|
|
||||||
let Some(object) = root.as_object() else {
|
|
||||||
return Ok(RuntimePermissionRuleConfig::default());
|
|
||||||
};
|
|
||||||
let Some(permissions) = object.get("permissions").and_then(JsonValue::as_object) else {
|
|
||||||
return Ok(RuntimePermissionRuleConfig::default());
|
|
||||||
};
|
|
||||||
|
|
||||||
Ok(RuntimePermissionRuleConfig {
|
|
||||||
allow: optional_string_array(permissions, "allow", "merged settings.permissions")?
|
|
||||||
.unwrap_or_default(),
|
|
||||||
deny: optional_string_array(permissions, "deny", "merged settings.permissions")?
|
|
||||||
.unwrap_or_default(),
|
|
||||||
ask: optional_string_array(permissions, "ask", "merged settings.permissions")?
|
|
||||||
.unwrap_or_default(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -806,12 +724,10 @@ fn parse_mcp_server_config(
|
|||||||
"sdk" => Ok(McpServerConfig::Sdk(McpSdkServerConfig {
|
"sdk" => Ok(McpServerConfig::Sdk(McpSdkServerConfig {
|
||||||
name: expect_string(object, "name", context)?.to_string(),
|
name: expect_string(object, "name", context)?.to_string(),
|
||||||
})),
|
})),
|
||||||
"claudeai-proxy" => Ok(McpServerConfig::ClaudeAiProxy(
|
"claudeai-proxy" => Ok(McpServerConfig::ManagedProxy(McpManagedProxyServerConfig {
|
||||||
McpClaudeAiProxyServerConfig {
|
url: expect_string(object, "url", context)?.to_string(),
|
||||||
url: expect_string(object, "url", context)?.to_string(),
|
id: expect_string(object, "id", context)?.to_string(),
|
||||||
id: expect_string(object, "id", context)?.to_string(),
|
})),
|
||||||
},
|
|
||||||
)),
|
|
||||||
other => Err(ConfigError::Parse(format!(
|
other => Err(ConfigError::Parse(format!(
|
||||||
"{context}: unsupported MCP server type for {server_name}: {other}"
|
"{context}: unsupported MCP server type for {server_name}: {other}"
|
||||||
))),
|
))),
|
||||||
@@ -1024,7 +940,7 @@ fn push_unique(target: &mut Vec<String>, value: String) {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
ConfigLoader, ConfigSource, McpServerConfig, McpTransport, ResolvedPermissionMode,
|
ConfigLoader, ConfigSource, McpServerConfig, McpTransport, ResolvedPermissionMode,
|
||||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
CLAW_SETTINGS_SCHEMA_NAME,
|
||||||
};
|
};
|
||||||
use crate::json::JsonValue;
|
use crate::json::JsonValue;
|
||||||
use crate::sandbox::FilesystemIsolationMode;
|
use crate::sandbox::FilesystemIsolationMode;
|
||||||
@@ -1043,7 +959,7 @@ mod tests {
|
|||||||
fn rejects_non_object_settings_files() {
|
fn rejects_non_object_settings_files() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
fs::create_dir_all(&cwd).expect("project dir");
|
fs::create_dir_all(&cwd).expect("project dir");
|
||||||
fs::write(home.join("settings.json"), "[]").expect("write bad settings");
|
fs::write(home.join("settings.json"), "[]").expect("write bad settings");
|
||||||
@@ -1062,32 +978,32 @@ mod tests {
|
|||||||
fn loads_and_merges_claude_code_config_files_by_precedence() {
|
fn loads_and_merges_claude_code_config_files_by_precedence() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
fs::create_dir_all(cwd.join(".claw")).expect("project config dir");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
fs::write(
|
fs::write(
|
||||||
home.parent().expect("home parent").join(".claude.json"),
|
home.parent().expect("home parent").join(".claw.json"),
|
||||||
r#"{"model":"haiku","env":{"A":"1"},"mcpServers":{"home":{"command":"uvx","args":["home"]}}}"#,
|
r#"{"model":"haiku","env":{"A":"1"},"mcpServers":{"home":{"command":"uvx","args":["home"]}}}"#,
|
||||||
)
|
)
|
||||||
.expect("write user compat config");
|
.expect("write user compat config");
|
||||||
fs::write(
|
fs::write(
|
||||||
home.join("settings.json"),
|
home.join("settings.json"),
|
||||||
r#"{"model":"sonnet","env":{"A2":"1"},"hooks":{"PreToolUse":["base"]},"permissions":{"defaultMode":"plan","allow":["Read"],"deny":["Bash(rm -rf)"]}}"#,
|
r#"{"model":"sonnet","env":{"A2":"1"},"hooks":{"PreToolUse":["base"]},"permissions":{"defaultMode":"plan"}}"#,
|
||||||
)
|
)
|
||||||
.expect("write user settings");
|
.expect("write user settings");
|
||||||
fs::write(
|
fs::write(
|
||||||
cwd.join(".claude.json"),
|
cwd.join(".claw.json"),
|
||||||
r#"{"model":"project-compat","env":{"B":"2"}}"#,
|
r#"{"model":"project-compat","env":{"B":"2"}}"#,
|
||||||
)
|
)
|
||||||
.expect("write project compat config");
|
.expect("write project compat config");
|
||||||
fs::write(
|
fs::write(
|
||||||
cwd.join(".claude").join("settings.json"),
|
cwd.join(".claw").join("settings.json"),
|
||||||
r#"{"env":{"C":"3"},"hooks":{"PostToolUse":["project"],"PostToolUseFailure":["project-failure"]},"permissions":{"ask":["Edit"]},"mcpServers":{"project":{"command":"uvx","args":["project"]}}}"#,
|
r#"{"env":{"C":"3"},"hooks":{"PostToolUse":["project"]},"mcpServers":{"project":{"command":"uvx","args":["project"]}}}"#,
|
||||||
)
|
)
|
||||||
.expect("write project settings");
|
.expect("write project settings");
|
||||||
fs::write(
|
fs::write(
|
||||||
cwd.join(".claude").join("settings.local.json"),
|
cwd.join(".claw").join("settings.local.json"),
|
||||||
r#"{"model":"opus","permissionMode":"acceptEdits"}"#,
|
r#"{"model":"opus","permissionMode":"acceptEdits"}"#,
|
||||||
)
|
)
|
||||||
.expect("write local settings");
|
.expect("write local settings");
|
||||||
@@ -1096,7 +1012,7 @@ mod tests {
|
|||||||
.load()
|
.load()
|
||||||
.expect("config should load");
|
.expect("config should load");
|
||||||
|
|
||||||
assert_eq!(CLAUDE_CODE_SETTINGS_SCHEMA_NAME, "SettingsSchema");
|
assert_eq!(CLAW_SETTINGS_SCHEMA_NAME, "SettingsSchema");
|
||||||
assert_eq!(loaded.loaded_entries().len(), 5);
|
assert_eq!(loaded.loaded_entries().len(), 5);
|
||||||
assert_eq!(loaded.loaded_entries()[0].source, ConfigSource::User);
|
assert_eq!(loaded.loaded_entries()[0].source, ConfigSource::User);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1128,16 +1044,6 @@ mod tests {
|
|||||||
.contains_key("PostToolUse"));
|
.contains_key("PostToolUse"));
|
||||||
assert_eq!(loaded.hooks().pre_tool_use(), &["base".to_string()]);
|
assert_eq!(loaded.hooks().pre_tool_use(), &["base".to_string()]);
|
||||||
assert_eq!(loaded.hooks().post_tool_use(), &["project".to_string()]);
|
assert_eq!(loaded.hooks().post_tool_use(), &["project".to_string()]);
|
||||||
assert_eq!(
|
|
||||||
loaded.hooks().post_tool_use_failure(),
|
|
||||||
&["project-failure".to_string()]
|
|
||||||
);
|
|
||||||
assert_eq!(loaded.permission_rules().allow(), &["Read".to_string()]);
|
|
||||||
assert_eq!(
|
|
||||||
loaded.permission_rules().deny(),
|
|
||||||
&["Bash(rm -rf)".to_string()]
|
|
||||||
);
|
|
||||||
assert_eq!(loaded.permission_rules().ask(), &["Edit".to_string()]);
|
|
||||||
assert!(loaded.mcp().get("home").is_some());
|
assert!(loaded.mcp().get("home").is_some());
|
||||||
assert!(loaded.mcp().get("project").is_some());
|
assert!(loaded.mcp().get("project").is_some());
|
||||||
|
|
||||||
@@ -1148,12 +1054,12 @@ mod tests {
|
|||||||
fn parses_sandbox_config() {
|
fn parses_sandbox_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
fs::create_dir_all(cwd.join(".claw")).expect("project config dir");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
fs::write(
|
fs::write(
|
||||||
cwd.join(".claude").join("settings.local.json"),
|
cwd.join(".claw").join("settings.local.json"),
|
||||||
r#"{
|
r#"{
|
||||||
"sandbox": {
|
"sandbox": {
|
||||||
"enabled": true,
|
"enabled": true,
|
||||||
@@ -1186,8 +1092,8 @@ mod tests {
|
|||||||
fn parses_typed_mcp_and_oauth_config() {
|
fn parses_typed_mcp_and_oauth_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
fs::create_dir_all(cwd.join(".claw")).expect("project config dir");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
fs::write(
|
fs::write(
|
||||||
@@ -1224,7 +1130,7 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.expect("write user settings");
|
.expect("write user settings");
|
||||||
fs::write(
|
fs::write(
|
||||||
cwd.join(".claude").join("settings.local.json"),
|
cwd.join(".claw").join("settings.local.json"),
|
||||||
r#"{
|
r#"{
|
||||||
"mcpServers": {
|
"mcpServers": {
|
||||||
"remote-server": {
|
"remote-server": {
|
||||||
@@ -1277,8 +1183,8 @@ mod tests {
|
|||||||
fn parses_plugin_config_from_enabled_plugins() {
|
fn parses_plugin_config_from_enabled_plugins() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
fs::create_dir_all(cwd.join(".claw")).expect("project config dir");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
fs::write(
|
fs::write(
|
||||||
@@ -1315,8 +1221,8 @@ mod tests {
|
|||||||
fn parses_plugin_config() {
|
fn parses_plugin_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(cwd.join(".claude")).expect("project config dir");
|
fs::create_dir_all(cwd.join(".claw")).expect("project config dir");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
|
|
||||||
fs::write(
|
fs::write(
|
||||||
@@ -1367,7 +1273,7 @@ mod tests {
|
|||||||
fn rejects_invalid_mcp_server_shapes() {
|
fn rejects_invalid_mcp_server_shapes() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let cwd = root.join("project");
|
let cwd = root.join("project");
|
||||||
let home = root.join("home").join(".claude");
|
let home = root.join("home").join(".claw");
|
||||||
fs::create_dir_all(&home).expect("home config dir");
|
fs::create_dir_all(&home).expect("home config dir");
|
||||||
fs::create_dir_all(&cwd).expect("project dir");
|
fs::create_dir_all(&cwd).expect("project dir");
|
||||||
fs::write(
|
fs::write(
|
||||||
|
|||||||
@@ -1,22 +1,15 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::fmt::{Display, Formatter};
|
use std::fmt::{Display, Formatter};
|
||||||
|
|
||||||
use plugins::{HookRunner as PluginHookRunner, PluginRegistry};
|
|
||||||
|
|
||||||
use crate::compact::{
|
use crate::compact::{
|
||||||
compact_session, estimate_session_tokens, CompactionConfig, CompactionResult,
|
compact_session, estimate_session_tokens, CompactionConfig, CompactionResult,
|
||||||
};
|
};
|
||||||
use crate::config::RuntimeFeatureConfig;
|
use crate::config::RuntimeFeatureConfig;
|
||||||
use crate::hooks::{HookAbortSignal, HookProgressReporter, HookRunResult, HookRunner};
|
use crate::hooks::{HookRunResult, HookRunner};
|
||||||
use crate::permissions::{
|
use crate::permissions::{PermissionOutcome, PermissionPolicy, PermissionPrompter};
|
||||||
PermissionContext, PermissionOutcome, PermissionPolicy, PermissionPrompter,
|
|
||||||
};
|
|
||||||
use crate::session::{ContentBlock, ConversationMessage, Session};
|
use crate::session::{ContentBlock, ConversationMessage, Session};
|
||||||
use crate::usage::{TokenUsage, UsageTracker};
|
use crate::usage::{TokenUsage, UsageTracker};
|
||||||
|
|
||||||
const DEFAULT_AUTO_COMPACTION_INPUT_TOKENS_THRESHOLD: u32 = 200_000;
|
|
||||||
const AUTO_COMPACTION_THRESHOLD_ENV_VAR: &str = "CLAUDE_CODE_AUTO_COMPACT_INPUT_TOKENS";
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ApiRequest {
|
pub struct ApiRequest {
|
||||||
pub system_prompt: Vec<String>,
|
pub system_prompt: Vec<String>,
|
||||||
@@ -93,12 +86,6 @@ pub struct TurnSummary {
|
|||||||
pub tool_results: Vec<ConversationMessage>,
|
pub tool_results: Vec<ConversationMessage>,
|
||||||
pub iterations: usize,
|
pub iterations: usize,
|
||||||
pub usage: TokenUsage,
|
pub usage: TokenUsage,
|
||||||
pub auto_compaction: Option<AutoCompactionEvent>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct AutoCompactionEvent {
|
|
||||||
pub removed_message_count: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ConversationRuntime<C, T> {
|
pub struct ConversationRuntime<C, T> {
|
||||||
@@ -110,27 +97,6 @@ pub struct ConversationRuntime<C, T> {
|
|||||||
max_iterations: usize,
|
max_iterations: usize,
|
||||||
usage_tracker: UsageTracker,
|
usage_tracker: UsageTracker,
|
||||||
hook_runner: HookRunner,
|
hook_runner: HookRunner,
|
||||||
auto_compaction_input_tokens_threshold: u32,
|
|
||||||
plugin_hook_runner: Option<PluginHookRunner>,
|
|
||||||
plugin_registry: Option<PluginRegistry>,
|
|
||||||
plugins_shutdown: bool,
|
|
||||||
hook_abort_signal: HookAbortSignal,
|
|
||||||
hook_progress_reporter: Option<Box<dyn HookProgressReporter>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C, T> ConversationRuntime<C, T> {
|
|
||||||
fn shutdown_registered_plugins(&mut self) -> Result<(), RuntimeError> {
|
|
||||||
if self.plugins_shutdown {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
if let Some(registry) = &self.plugin_registry {
|
|
||||||
registry
|
|
||||||
.shutdown()
|
|
||||||
.map_err(|error| RuntimeError::new(format!("plugin shutdown failed: {error}")))?;
|
|
||||||
}
|
|
||||||
self.plugins_shutdown = true;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C, T> ConversationRuntime<C, T>
|
impl<C, T> ConversationRuntime<C, T>
|
||||||
@@ -157,7 +123,6 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
#[allow(clippy::needless_pass_by_value)]
|
|
||||||
pub fn new_with_features(
|
pub fn new_with_features(
|
||||||
session: Session,
|
session: Session,
|
||||||
api_client: C,
|
api_client: C,
|
||||||
@@ -176,144 +141,15 @@ where
|
|||||||
max_iterations: usize::MAX,
|
max_iterations: usize::MAX,
|
||||||
usage_tracker,
|
usage_tracker,
|
||||||
hook_runner: HookRunner::from_feature_config(&feature_config),
|
hook_runner: HookRunner::from_feature_config(&feature_config),
|
||||||
auto_compaction_input_tokens_threshold: auto_compaction_threshold_from_env(),
|
|
||||||
plugin_hook_runner: None,
|
|
||||||
plugin_registry: None,
|
|
||||||
plugins_shutdown: false,
|
|
||||||
hook_abort_signal: HookAbortSignal::default(),
|
|
||||||
hook_progress_reporter: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::needless_pass_by_value)]
|
|
||||||
pub fn new_with_plugins(
|
|
||||||
session: Session,
|
|
||||||
api_client: C,
|
|
||||||
tool_executor: T,
|
|
||||||
permission_policy: PermissionPolicy,
|
|
||||||
system_prompt: Vec<String>,
|
|
||||||
feature_config: RuntimeFeatureConfig,
|
|
||||||
plugin_registry: PluginRegistry,
|
|
||||||
) -> Result<Self, RuntimeError> {
|
|
||||||
let plugin_hook_runner =
|
|
||||||
PluginHookRunner::from_registry(&plugin_registry).map_err(|error| {
|
|
||||||
RuntimeError::new(format!("plugin hook registration failed: {error}"))
|
|
||||||
})?;
|
|
||||||
plugin_registry
|
|
||||||
.initialize()
|
|
||||||
.map_err(|error| RuntimeError::new(format!("plugin initialization failed: {error}")))?;
|
|
||||||
let mut runtime = Self::new_with_features(
|
|
||||||
session,
|
|
||||||
api_client,
|
|
||||||
tool_executor,
|
|
||||||
permission_policy,
|
|
||||||
system_prompt,
|
|
||||||
feature_config,
|
|
||||||
);
|
|
||||||
runtime.plugin_hook_runner = Some(plugin_hook_runner);
|
|
||||||
runtime.plugin_registry = Some(plugin_registry);
|
|
||||||
Ok(runtime)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn with_max_iterations(mut self, max_iterations: usize) -> Self {
|
pub fn with_max_iterations(mut self, max_iterations: usize) -> Self {
|
||||||
self.max_iterations = max_iterations;
|
self.max_iterations = max_iterations;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn with_auto_compaction_input_tokens_threshold(mut self, threshold: u32) -> Self {
|
|
||||||
self.auto_compaction_input_tokens_threshold = threshold;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn with_hook_abort_signal(mut self, hook_abort_signal: HookAbortSignal) -> Self {
|
|
||||||
self.hook_abort_signal = hook_abort_signal;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn with_hook_progress_reporter(
|
|
||||||
mut self,
|
|
||||||
hook_progress_reporter: Box<dyn HookProgressReporter>,
|
|
||||||
) -> Self {
|
|
||||||
self.hook_progress_reporter = Some(hook_progress_reporter);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_pre_tool_use_hook(&mut self, tool_name: &str, input: &str) -> HookRunResult {
|
|
||||||
if let Some(reporter) = self.hook_progress_reporter.as_mut() {
|
|
||||||
self.hook_runner.run_pre_tool_use_with_context(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
Some(&self.hook_abort_signal),
|
|
||||||
Some(reporter.as_mut()),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
self.hook_runner.run_pre_tool_use_with_context(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
Some(&self.hook_abort_signal),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_post_tool_use_hook(
|
|
||||||
&mut self,
|
|
||||||
tool_name: &str,
|
|
||||||
input: &str,
|
|
||||||
output: &str,
|
|
||||||
is_error: bool,
|
|
||||||
) -> HookRunResult {
|
|
||||||
if let Some(reporter) = self.hook_progress_reporter.as_mut() {
|
|
||||||
self.hook_runner.run_post_tool_use_with_context(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
is_error,
|
|
||||||
Some(&self.hook_abort_signal),
|
|
||||||
Some(reporter.as_mut()),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
self.hook_runner.run_post_tool_use_with_context(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
is_error,
|
|
||||||
Some(&self.hook_abort_signal),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_post_tool_use_failure_hook(
|
|
||||||
&mut self,
|
|
||||||
tool_name: &str,
|
|
||||||
input: &str,
|
|
||||||
output: &str,
|
|
||||||
) -> HookRunResult {
|
|
||||||
if let Some(reporter) = self.hook_progress_reporter.as_mut() {
|
|
||||||
self.hook_runner.run_post_tool_use_failure_with_context(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
Some(&self.hook_abort_signal),
|
|
||||||
Some(reporter.as_mut()),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
self.hook_runner.run_post_tool_use_failure_with_context(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
output,
|
|
||||||
Some(&self.hook_abort_signal),
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::too_many_lines)]
|
|
||||||
pub fn run_turn(
|
pub fn run_turn(
|
||||||
&mut self,
|
&mut self,
|
||||||
user_input: impl Into<String>,
|
user_input: impl Into<String>,
|
||||||
@@ -326,7 +162,6 @@ where
|
|||||||
let mut assistant_messages = Vec::new();
|
let mut assistant_messages = Vec::new();
|
||||||
let mut tool_results = Vec::new();
|
let mut tool_results = Vec::new();
|
||||||
let mut iterations = 0;
|
let mut iterations = 0;
|
||||||
let mut max_turn_input_tokens = 0;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
iterations += 1;
|
iterations += 1;
|
||||||
@@ -343,7 +178,6 @@ where
|
|||||||
let events = self.api_client.stream(request)?;
|
let events = self.api_client.stream(request)?;
|
||||||
let (assistant_message, usage) = build_assistant_message(events)?;
|
let (assistant_message, usage) = build_assistant_message(events)?;
|
||||||
if let Some(usage) = usage {
|
if let Some(usage) = usage {
|
||||||
max_turn_input_tokens = max_turn_input_tokens.max(usage.input_tokens);
|
|
||||||
self.usage_tracker.record(usage);
|
self.usage_tracker.record(usage);
|
||||||
}
|
}
|
||||||
let pending_tool_uses = assistant_message
|
let pending_tool_uses = assistant_message
|
||||||
@@ -365,108 +199,42 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (tool_use_id, tool_name, input) in pending_tool_uses {
|
for (tool_use_id, tool_name, input) in pending_tool_uses {
|
||||||
let pre_hook_result = self.run_pre_tool_use_hook(&tool_name, &input);
|
let permission_outcome = if let Some(prompt) = prompter.as_mut() {
|
||||||
let effective_input = pre_hook_result
|
self.permission_policy
|
||||||
.updated_input()
|
.authorize(&tool_name, &input, Some(*prompt))
|
||||||
.map_or_else(|| input.clone(), ToOwned::to_owned);
|
|
||||||
let permission_context = PermissionContext::new(
|
|
||||||
pre_hook_result.permission_override(),
|
|
||||||
pre_hook_result.permission_reason().map(ToOwned::to_owned),
|
|
||||||
);
|
|
||||||
|
|
||||||
let permission_outcome = if pre_hook_result.is_cancelled() {
|
|
||||||
PermissionOutcome::Deny {
|
|
||||||
reason: format_hook_message(
|
|
||||||
pre_hook_result.messages(),
|
|
||||||
&format!("PreToolUse hook cancelled tool `{tool_name}`"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
} else if pre_hook_result.is_denied() {
|
|
||||||
PermissionOutcome::Deny {
|
|
||||||
reason: format_hook_message(
|
|
||||||
pre_hook_result.messages(),
|
|
||||||
&format!("PreToolUse hook denied tool `{tool_name}`"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
} else if let Some(prompt) = prompter.as_mut() {
|
|
||||||
self.permission_policy.authorize_with_context(
|
|
||||||
&tool_name,
|
|
||||||
&effective_input,
|
|
||||||
&permission_context,
|
|
||||||
Some(*prompt),
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
self.permission_policy.authorize_with_context(
|
self.permission_policy.authorize(&tool_name, &input, None)
|
||||||
&tool_name,
|
|
||||||
&effective_input,
|
|
||||||
&permission_context,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let result_message = match permission_outcome {
|
let result_message = match permission_outcome {
|
||||||
PermissionOutcome::Allow => {
|
PermissionOutcome::Allow => {
|
||||||
let plugin_pre_hook_result =
|
let pre_hook_result = self.hook_runner.run_pre_tool_use(&tool_name, &input);
|
||||||
self.run_plugin_pre_tool_use(&tool_name, &effective_input);
|
if pre_hook_result.is_denied() {
|
||||||
if plugin_pre_hook_result.is_denied() {
|
|
||||||
let deny_message = format!("PreToolUse hook denied tool `{tool_name}`");
|
let deny_message = format!("PreToolUse hook denied tool `{tool_name}`");
|
||||||
let mut messages = pre_hook_result.messages().to_vec();
|
|
||||||
messages.extend(plugin_pre_hook_result.messages().iter().cloned());
|
|
||||||
ConversationMessage::tool_result(
|
ConversationMessage::tool_result(
|
||||||
tool_use_id,
|
tool_use_id,
|
||||||
tool_name,
|
tool_name,
|
||||||
format_hook_message(&messages, &deny_message),
|
format_hook_message(&pre_hook_result, &deny_message),
|
||||||
true,
|
true,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
let (mut output, mut is_error) =
|
let (mut output, mut is_error) =
|
||||||
match self.tool_executor.execute(&tool_name, &effective_input) {
|
match self.tool_executor.execute(&tool_name, &input) {
|
||||||
Ok(output) => (output, false),
|
Ok(output) => (output, false),
|
||||||
Err(error) => (error.to_string(), true),
|
Err(error) => (error.to_string(), true),
|
||||||
};
|
};
|
||||||
output = merge_hook_feedback(pre_hook_result.messages(), output, false);
|
output = merge_hook_feedback(pre_hook_result.messages(), output, false);
|
||||||
output = merge_hook_feedback(
|
|
||||||
plugin_pre_hook_result.messages(),
|
|
||||||
output,
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
|
|
||||||
let hook_output = output.clone();
|
let post_hook_result = self
|
||||||
let post_hook_result = if is_error {
|
.hook_runner
|
||||||
self.run_post_tool_use_failure_hook(
|
.run_post_tool_use(&tool_name, &input, &output, is_error);
|
||||||
&tool_name,
|
if post_hook_result.is_denied() {
|
||||||
&effective_input,
|
|
||||||
&hook_output,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
self.run_post_tool_use_hook(
|
|
||||||
&tool_name,
|
|
||||||
&effective_input,
|
|
||||||
&hook_output,
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let plugin_post_hook_result = self.run_plugin_post_tool_use(
|
|
||||||
&tool_name,
|
|
||||||
&effective_input,
|
|
||||||
&hook_output,
|
|
||||||
is_error,
|
|
||||||
);
|
|
||||||
if post_hook_result.is_denied()
|
|
||||||
|| post_hook_result.is_cancelled()
|
|
||||||
|| plugin_post_hook_result.is_denied()
|
|
||||||
{
|
|
||||||
is_error = true;
|
is_error = true;
|
||||||
}
|
}
|
||||||
output = merge_hook_feedback(
|
output = merge_hook_feedback(
|
||||||
post_hook_result.messages(),
|
post_hook_result.messages(),
|
||||||
output,
|
output,
|
||||||
post_hook_result.is_denied() || post_hook_result.is_cancelled(),
|
post_hook_result.is_denied(),
|
||||||
);
|
|
||||||
output = merge_hook_feedback(
|
|
||||||
plugin_post_hook_result.messages(),
|
|
||||||
output,
|
|
||||||
plugin_post_hook_result.is_denied(),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
ConversationMessage::tool_result(
|
ConversationMessage::tool_result(
|
||||||
@@ -477,26 +245,20 @@ where
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
PermissionOutcome::Deny { reason } => ConversationMessage::tool_result(
|
PermissionOutcome::Deny { reason } => {
|
||||||
tool_use_id,
|
ConversationMessage::tool_result(tool_use_id, tool_name, reason, true)
|
||||||
tool_name,
|
}
|
||||||
merge_hook_feedback(pre_hook_result.messages(), reason, true),
|
|
||||||
true,
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
self.session.messages.push(result_message.clone());
|
self.session.messages.push(result_message.clone());
|
||||||
tool_results.push(result_message);
|
tool_results.push(result_message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let auto_compaction = self.maybe_auto_compact(max_turn_input_tokens);
|
|
||||||
|
|
||||||
Ok(TurnSummary {
|
Ok(TurnSummary {
|
||||||
assistant_messages,
|
assistant_messages,
|
||||||
tool_results,
|
tool_results,
|
||||||
iterations,
|
iterations,
|
||||||
usage: self.usage_tracker.cumulative_usage(),
|
usage: self.usage_tracker.cumulative_usage(),
|
||||||
auto_compaction,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -521,81 +283,9 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn into_session(mut self) -> Session {
|
pub fn into_session(self) -> Session {
|
||||||
let _ = self.shutdown_registered_plugins();
|
self.session
|
||||||
std::mem::take(&mut self.session)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn shutdown_plugins(&mut self) -> Result<(), RuntimeError> {
|
|
||||||
self.shutdown_registered_plugins()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_plugin_pre_tool_use(&self, tool_name: &str, input: &str) -> plugins::HookRunResult {
|
|
||||||
self.plugin_hook_runner.as_ref().map_or_else(
|
|
||||||
|| plugins::HookRunResult::allow(Vec::new()),
|
|
||||||
|runner| runner.run_pre_tool_use(tool_name, input),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_plugin_post_tool_use(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
input: &str,
|
|
||||||
output: &str,
|
|
||||||
is_error: bool,
|
|
||||||
) -> plugins::HookRunResult {
|
|
||||||
self.plugin_hook_runner.as_ref().map_or_else(
|
|
||||||
|| plugins::HookRunResult::allow(Vec::new()),
|
|
||||||
|runner| runner.run_post_tool_use(tool_name, input, output, is_error),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn maybe_auto_compact(&mut self, turn_input_tokens: u32) -> Option<AutoCompactionEvent> {
|
|
||||||
if turn_input_tokens < self.auto_compaction_input_tokens_threshold {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = compact_session(
|
|
||||||
&self.session,
|
|
||||||
CompactionConfig {
|
|
||||||
max_estimated_tokens: usize::try_from(self.auto_compaction_input_tokens_threshold)
|
|
||||||
.unwrap_or(usize::MAX),
|
|
||||||
..CompactionConfig::default()
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if result.removed_message_count == 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.session = result.compacted_session;
|
|
||||||
Some(AutoCompactionEvent {
|
|
||||||
removed_message_count: result.removed_message_count,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C, T> Drop for ConversationRuntime<C, T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let _ = self.shutdown_registered_plugins();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn auto_compaction_threshold_from_env() -> u32 {
|
|
||||||
parse_auto_compaction_threshold(
|
|
||||||
std::env::var(AUTO_COMPACTION_THRESHOLD_ENV_VAR)
|
|
||||||
.ok()
|
|
||||||
.as_deref(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
fn parse_auto_compaction_threshold(value: Option<&str>) -> u32 {
|
|
||||||
value
|
|
||||||
.and_then(|raw| raw.trim().parse::<u32>().ok())
|
|
||||||
.filter(|threshold| *threshold > 0)
|
|
||||||
.unwrap_or(DEFAULT_AUTO_COMPACTION_INPUT_TOKENS_THRESHOLD)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_assistant_message(
|
fn build_assistant_message(
|
||||||
@@ -645,11 +335,11 @@ fn flush_text_block(text: &mut String, blocks: &mut Vec<ContentBlock>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_hook_message(messages: &[String], fallback: &str) -> String {
|
fn format_hook_message(result: &HookRunResult, fallback: &str) -> String {
|
||||||
if messages.is_empty() {
|
if result.messages().is_empty() {
|
||||||
fallback.to_string()
|
fallback.to_string()
|
||||||
} else {
|
} else {
|
||||||
messages.join("\n")
|
result.messages().join("\n")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -706,9 +396,8 @@ impl ToolExecutor for StaticToolExecutor {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
parse_auto_compaction_threshold, ApiClient, ApiRequest, AssistantEvent,
|
ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError,
|
||||||
AutoCompactionEvent, ConversationRuntime, RuntimeError, StaticToolExecutor,
|
StaticToolExecutor,
|
||||||
DEFAULT_AUTO_COMPACTION_INPUT_TOKENS_THRESHOLD,
|
|
||||||
};
|
};
|
||||||
use crate::compact::CompactionConfig;
|
use crate::compact::CompactionConfig;
|
||||||
use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
|
use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
|
||||||
@@ -719,13 +408,7 @@ mod tests {
|
|||||||
use crate::prompt::{ProjectContext, SystemPromptBuilder};
|
use crate::prompt::{ProjectContext, SystemPromptBuilder};
|
||||||
use crate::session::{ContentBlock, MessageRole, Session};
|
use crate::session::{ContentBlock, MessageRole, Session};
|
||||||
use crate::usage::TokenUsage;
|
use crate::usage::TokenUsage;
|
||||||
use plugins::{PluginManager, PluginManagerConfig};
|
|
||||||
use std::fs;
|
|
||||||
#[cfg(unix)]
|
|
||||||
use std::os::unix::fs::PermissionsExt;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::time::{SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
struct ScriptedApiClient {
|
struct ScriptedApiClient {
|
||||||
call_count: usize,
|
call_count: usize,
|
||||||
@@ -787,68 +470,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn temp_dir(label: &str) -> PathBuf {
|
|
||||||
let nanos = SystemTime::now()
|
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.expect("time should be after epoch")
|
|
||||||
.as_nanos();
|
|
||||||
std::env::temp_dir().join(format!("runtime-plugin-{label}-{nanos}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_lifecycle_plugin(root: &Path, name: &str) -> PathBuf {
|
|
||||||
fs::create_dir_all(root.join(".claude-plugin")).expect("manifest dir");
|
|
||||||
fs::create_dir_all(root.join("lifecycle")).expect("lifecycle dir");
|
|
||||||
let log_path = root.join("lifecycle.log");
|
|
||||||
fs::write(
|
|
||||||
root.join("lifecycle").join("init.sh"),
|
|
||||||
"#!/bin/sh\nprintf 'init\\n' >> lifecycle.log\n",
|
|
||||||
)
|
|
||||||
.expect("write init script");
|
|
||||||
fs::write(
|
|
||||||
root.join("lifecycle").join("shutdown.sh"),
|
|
||||||
"#!/bin/sh\nprintf 'shutdown\\n' >> lifecycle.log\n",
|
|
||||||
)
|
|
||||||
.expect("write shutdown script");
|
|
||||||
fs::write(
|
|
||||||
root.join(".claude-plugin").join("plugin.json"),
|
|
||||||
format!(
|
|
||||||
"{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"runtime lifecycle plugin\",\n \"lifecycle\": {{\n \"Init\": [\"./lifecycle/init.sh\"],\n \"Shutdown\": [\"./lifecycle/shutdown.sh\"]\n }}\n}}"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.expect("write plugin manifest");
|
|
||||||
log_path
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_hook_plugin(root: &Path, name: &str, pre_message: &str, post_message: &str) {
|
|
||||||
fs::create_dir_all(root.join(".claude-plugin")).expect("manifest dir");
|
|
||||||
fs::create_dir_all(root.join("hooks")).expect("hooks dir");
|
|
||||||
fs::write(
|
|
||||||
root.join("hooks").join("pre.sh"),
|
|
||||||
format!("#!/bin/sh\nprintf '%s\\n' '{pre_message}'\n"),
|
|
||||||
)
|
|
||||||
.expect("write pre hook");
|
|
||||||
fs::write(
|
|
||||||
root.join("hooks").join("post.sh"),
|
|
||||||
format!("#!/bin/sh\nprintf '%s\\n' '{post_message}'\n"),
|
|
||||||
)
|
|
||||||
.expect("write post hook");
|
|
||||||
#[cfg(unix)]
|
|
||||||
{
|
|
||||||
let exec_mode = fs::Permissions::from_mode(0o755);
|
|
||||||
fs::set_permissions(root.join("hooks").join("pre.sh"), exec_mode.clone())
|
|
||||||
.expect("chmod pre hook");
|
|
||||||
fs::set_permissions(root.join("hooks").join("post.sh"), exec_mode)
|
|
||||||
.expect("chmod post hook");
|
|
||||||
}
|
|
||||||
fs::write(
|
|
||||||
root.join(".claude-plugin").join("plugin.json"),
|
|
||||||
format!(
|
|
||||||
"{{\n \"name\": \"{name}\",\n \"version\": \"1.0.0\",\n \"description\": \"runtime hook plugin\",\n \"hooks\": {{\n \"PreToolUse\": [\"./hooks/pre.sh\"],\n \"PostToolUse\": [\"./hooks/post.sh\"]\n }}\n}}"
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.expect("write plugin manifest");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn runs_user_to_tool_to_result_loop_end_to_end_and_tracks_usage() {
|
fn runs_user_to_tool_to_result_loop_end_to_end_and_tracks_usage() {
|
||||||
let api_client = ScriptedApiClient { call_count: 0 };
|
let api_client = ScriptedApiClient { call_count: 0 };
|
||||||
@@ -887,7 +508,6 @@ mod tests {
|
|||||||
assert_eq!(summary.tool_results.len(), 1);
|
assert_eq!(summary.tool_results.len(), 1);
|
||||||
assert_eq!(runtime.session().messages.len(), 4);
|
assert_eq!(runtime.session().messages.len(), 4);
|
||||||
assert_eq!(summary.usage.output_tokens, 10);
|
assert_eq!(summary.usage.output_tokens, 10);
|
||||||
assert_eq!(summary.auto_compaction, None);
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
runtime.session().messages[1].blocks[1],
|
runtime.session().messages[1].blocks[1],
|
||||||
ContentBlock::ToolUse { .. }
|
ContentBlock::ToolUse { .. }
|
||||||
@@ -992,7 +612,6 @@ mod tests {
|
|||||||
RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||||
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
|
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
Vec::new(),
|
|
||||||
)),
|
)),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1059,7 +678,6 @@ mod tests {
|
|||||||
RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
RuntimeFeatureConfig::default().with_hooks(RuntimeHookConfig::new(
|
||||||
vec![shell_snippet("printf 'pre hook ran'")],
|
vec![shell_snippet("printf 'pre hook ran'")],
|
||||||
vec![shell_snippet("printf 'post hook ran'")],
|
vec![shell_snippet("printf 'post hook ran'")],
|
||||||
Vec::new(),
|
|
||||||
)),
|
)),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -1092,153 +710,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn initializes_and_shuts_down_plugins_with_runtime_lifecycle() {
|
|
||||||
let config_home = temp_dir("config");
|
|
||||||
let source_root = temp_dir("source");
|
|
||||||
let _ = write_lifecycle_plugin(&source_root, "runtime-lifecycle");
|
|
||||||
|
|
||||||
let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
|
|
||||||
let install = manager
|
|
||||||
.install(source_root.to_str().expect("utf8 path"))
|
|
||||||
.expect("install should succeed");
|
|
||||||
let log_path = install.install_path.join("lifecycle.log");
|
|
||||||
let registry = manager.plugin_registry().expect("registry should load");
|
|
||||||
|
|
||||||
{
|
|
||||||
let runtime = ConversationRuntime::new_with_plugins(
|
|
||||||
Session::new(),
|
|
||||||
ScriptedApiClient { call_count: 0 },
|
|
||||||
StaticToolExecutor::new().register("add", |_input| Ok("4".to_string())),
|
|
||||||
PermissionPolicy::new(PermissionMode::WorkspaceWrite),
|
|
||||||
vec!["system".to_string()],
|
|
||||||
RuntimeFeatureConfig::default(),
|
|
||||||
registry,
|
|
||||||
)
|
|
||||||
.expect("runtime should initialize plugins");
|
|
||||||
|
|
||||||
let log = fs::read_to_string(&log_path).expect("init log should exist");
|
|
||||||
assert_eq!(log, "init\n");
|
|
||||||
drop(runtime);
|
|
||||||
}
|
|
||||||
|
|
||||||
let log = fs::read_to_string(&log_path).expect("shutdown log should exist");
|
|
||||||
assert_eq!(log, "init\nshutdown\n");
|
|
||||||
|
|
||||||
let _ = fs::remove_dir_all(config_home);
|
|
||||||
let _ = fs::remove_dir_all(source_root);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn executes_hooks_from_installed_plugins_during_tool_use() {
|
|
||||||
struct TwoCallApiClient {
|
|
||||||
calls: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApiClient for TwoCallApiClient {
|
|
||||||
fn stream(&mut self, request: ApiRequest) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
self.calls += 1;
|
|
||||||
match self.calls {
|
|
||||||
1 => Ok(vec![
|
|
||||||
AssistantEvent::ToolUse {
|
|
||||||
id: "tool-1".to_string(),
|
|
||||||
name: "add".to_string(),
|
|
||||||
input: r#"{"lhs":2,"rhs":2}"#.to_string(),
|
|
||||||
},
|
|
||||||
AssistantEvent::MessageStop,
|
|
||||||
]),
|
|
||||||
2 => {
|
|
||||||
assert!(request
|
|
||||||
.messages
|
|
||||||
.iter()
|
|
||||||
.any(|message| message.role == MessageRole::Tool));
|
|
||||||
Ok(vec![
|
|
||||||
AssistantEvent::TextDelta("done".to_string()),
|
|
||||||
AssistantEvent::MessageStop,
|
|
||||||
])
|
|
||||||
}
|
|
||||||
_ => Err(RuntimeError::new("unexpected extra API call")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let config_home = temp_dir("hook-config");
|
|
||||||
let first_source_root = temp_dir("hook-source-a");
|
|
||||||
let second_source_root = temp_dir("hook-source-b");
|
|
||||||
write_hook_plugin(
|
|
||||||
&first_source_root,
|
|
||||||
"first",
|
|
||||||
"plugin pre one",
|
|
||||||
"plugin post one",
|
|
||||||
);
|
|
||||||
write_hook_plugin(
|
|
||||||
&second_source_root,
|
|
||||||
"second",
|
|
||||||
"plugin pre two",
|
|
||||||
"plugin post two",
|
|
||||||
);
|
|
||||||
|
|
||||||
let mut manager = PluginManager::new(PluginManagerConfig::new(&config_home));
|
|
||||||
manager
|
|
||||||
.install(first_source_root.to_str().expect("utf8 path"))
|
|
||||||
.expect("first plugin install should succeed");
|
|
||||||
manager
|
|
||||||
.install(second_source_root.to_str().expect("utf8 path"))
|
|
||||||
.expect("second plugin install should succeed");
|
|
||||||
let registry = manager.plugin_registry().expect("registry should load");
|
|
||||||
|
|
||||||
let mut runtime = ConversationRuntime::new_with_plugins(
|
|
||||||
Session::new(),
|
|
||||||
TwoCallApiClient { calls: 0 },
|
|
||||||
StaticToolExecutor::new().register("add", |_input| Ok("4".to_string())),
|
|
||||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
|
||||||
vec!["system".to_string()],
|
|
||||||
RuntimeFeatureConfig::default(),
|
|
||||||
registry,
|
|
||||||
)
|
|
||||||
.expect("runtime should load plugin hooks");
|
|
||||||
|
|
||||||
let summary = runtime
|
|
||||||
.run_turn("use add", None)
|
|
||||||
.expect("tool loop succeeds");
|
|
||||||
|
|
||||||
assert_eq!(summary.tool_results.len(), 1);
|
|
||||||
let ContentBlock::ToolResult {
|
|
||||||
is_error, output, ..
|
|
||||||
} = &summary.tool_results[0].blocks[0]
|
|
||||||
else {
|
|
||||||
panic!("expected tool result block");
|
|
||||||
};
|
|
||||||
assert!(
|
|
||||||
!*is_error,
|
|
||||||
"plugin hooks should not force an error: {output:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
output.contains('4'),
|
|
||||||
"tool output missing value: {output:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
output.contains("plugin pre one"),
|
|
||||||
"tool output missing first pre hook feedback: {output:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
output.contains("plugin pre two"),
|
|
||||||
"tool output missing second pre hook feedback: {output:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
output.contains("plugin post one"),
|
|
||||||
"tool output missing first post hook feedback: {output:?}"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
output.contains("plugin post two"),
|
|
||||||
"tool output missing second post hook feedback: {output:?}"
|
|
||||||
);
|
|
||||||
|
|
||||||
let _ = fs::remove_dir_all(config_home);
|
|
||||||
let _ = fs::remove_dir_all(first_source_root);
|
|
||||||
let _ = fs::remove_dir_all(second_source_root);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn reconstructs_usage_tracker_from_restored_session() {
|
fn reconstructs_usage_tracker_from_restored_session() {
|
||||||
struct SimpleApi;
|
struct SimpleApi;
|
||||||
@@ -1327,177 +798,4 @@ mod tests {
|
|||||||
fn shell_snippet(script: &str) -> String {
|
fn shell_snippet(script: &str) -> String {
|
||||||
script.to_string()
|
script.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn auto_compacts_when_turn_input_threshold_is_crossed() {
|
|
||||||
struct SimpleApi;
|
|
||||||
impl ApiClient for SimpleApi {
|
|
||||||
fn stream(
|
|
||||||
&mut self,
|
|
||||||
_request: ApiRequest,
|
|
||||||
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
Ok(vec![
|
|
||||||
AssistantEvent::TextDelta("done".to_string()),
|
|
||||||
AssistantEvent::Usage(TokenUsage {
|
|
||||||
input_tokens: 120_000,
|
|
||||||
output_tokens: 4,
|
|
||||||
cache_creation_input_tokens: 0,
|
|
||||||
cache_read_input_tokens: 0,
|
|
||||||
}),
|
|
||||||
AssistantEvent::MessageStop,
|
|
||||||
])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let session = Session {
|
|
||||||
version: 1,
|
|
||||||
messages: vec![
|
|
||||||
crate::session::ConversationMessage::user_text("one ".repeat(30_000)),
|
|
||||||
crate::session::ConversationMessage::assistant(vec![ContentBlock::Text {
|
|
||||||
text: "two ".repeat(30_000),
|
|
||||||
}]),
|
|
||||||
crate::session::ConversationMessage::user_text("three ".repeat(30_000)),
|
|
||||||
crate::session::ConversationMessage::assistant(vec![ContentBlock::Text {
|
|
||||||
text: "four ".repeat(30_000),
|
|
||||||
}]),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut runtime = ConversationRuntime::new(
|
|
||||||
session,
|
|
||||||
SimpleApi,
|
|
||||||
StaticToolExecutor::new(),
|
|
||||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
|
||||||
vec!["system".to_string()],
|
|
||||||
)
|
|
||||||
.with_auto_compaction_input_tokens_threshold(100_000);
|
|
||||||
|
|
||||||
let summary = runtime
|
|
||||||
.run_turn("trigger", None)
|
|
||||||
.expect("turn should succeed");
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
summary.auto_compaction,
|
|
||||||
Some(AutoCompactionEvent {
|
|
||||||
removed_message_count: 2,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
assert_eq!(runtime.session().messages[0].role, MessageRole::System);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn auto_compaction_does_not_repeat_after_context_is_already_compacted() {
|
|
||||||
struct SequentialUsageApi {
|
|
||||||
call_count: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ApiClient for SequentialUsageApi {
|
|
||||||
fn stream(
|
|
||||||
&mut self,
|
|
||||||
_request: ApiRequest,
|
|
||||||
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
self.call_count += 1;
|
|
||||||
let input_tokens = if self.call_count == 1 { 120_000 } else { 64 };
|
|
||||||
Ok(vec![
|
|
||||||
AssistantEvent::TextDelta("done".to_string()),
|
|
||||||
AssistantEvent::Usage(TokenUsage {
|
|
||||||
input_tokens,
|
|
||||||
output_tokens: 4,
|
|
||||||
cache_creation_input_tokens: 0,
|
|
||||||
cache_read_input_tokens: 0,
|
|
||||||
}),
|
|
||||||
AssistantEvent::MessageStop,
|
|
||||||
])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let session = Session {
|
|
||||||
version: 1,
|
|
||||||
messages: vec![
|
|
||||||
crate::session::ConversationMessage::user_text("one ".repeat(30_000)),
|
|
||||||
crate::session::ConversationMessage::assistant(vec![ContentBlock::Text {
|
|
||||||
text: "two ".repeat(30_000),
|
|
||||||
}]),
|
|
||||||
crate::session::ConversationMessage::user_text("three ".repeat(30_000)),
|
|
||||||
crate::session::ConversationMessage::assistant(vec![ContentBlock::Text {
|
|
||||||
text: "four ".repeat(30_000),
|
|
||||||
}]),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut runtime = ConversationRuntime::new(
|
|
||||||
session,
|
|
||||||
SequentialUsageApi { call_count: 0 },
|
|
||||||
StaticToolExecutor::new(),
|
|
||||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
|
||||||
vec!["system".to_string()],
|
|
||||||
)
|
|
||||||
.with_auto_compaction_input_tokens_threshold(100_000);
|
|
||||||
|
|
||||||
let first = runtime
|
|
||||||
.run_turn("trigger", None)
|
|
||||||
.expect("first turn should succeed");
|
|
||||||
assert_eq!(
|
|
||||||
first.auto_compaction,
|
|
||||||
Some(AutoCompactionEvent {
|
|
||||||
removed_message_count: 2,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
let second = runtime
|
|
||||||
.run_turn("continue", None)
|
|
||||||
.expect("second turn should succeed");
|
|
||||||
assert_eq!(second.auto_compaction, None);
|
|
||||||
assert_eq!(runtime.session().messages[0].role, MessageRole::System);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn skips_auto_compaction_below_threshold() {
|
|
||||||
struct SimpleApi;
|
|
||||||
impl ApiClient for SimpleApi {
|
|
||||||
fn stream(
|
|
||||||
&mut self,
|
|
||||||
_request: ApiRequest,
|
|
||||||
) -> Result<Vec<AssistantEvent>, RuntimeError> {
|
|
||||||
Ok(vec![
|
|
||||||
AssistantEvent::TextDelta("done".to_string()),
|
|
||||||
AssistantEvent::Usage(TokenUsage {
|
|
||||||
input_tokens: 99_999,
|
|
||||||
output_tokens: 4,
|
|
||||||
cache_creation_input_tokens: 0,
|
|
||||||
cache_read_input_tokens: 0,
|
|
||||||
}),
|
|
||||||
AssistantEvent::MessageStop,
|
|
||||||
])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut runtime = ConversationRuntime::new(
|
|
||||||
Session::new(),
|
|
||||||
SimpleApi,
|
|
||||||
StaticToolExecutor::new(),
|
|
||||||
PermissionPolicy::new(PermissionMode::DangerFullAccess),
|
|
||||||
vec!["system".to_string()],
|
|
||||||
)
|
|
||||||
.with_auto_compaction_input_tokens_threshold(100_000);
|
|
||||||
|
|
||||||
let summary = runtime
|
|
||||||
.run_turn("trigger", None)
|
|
||||||
.expect("turn should succeed");
|
|
||||||
assert_eq!(summary.auto_compaction, None);
|
|
||||||
assert_eq!(runtime.session().messages.len(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn auto_compaction_threshold_defaults_and_parses_values() {
|
|
||||||
assert_eq!(
|
|
||||||
parse_auto_compaction_threshold(None),
|
|
||||||
DEFAULT_AUTO_COMPACTION_INPUT_TOKENS_THRESHOLD
|
|
||||||
);
|
|
||||||
assert_eq!(parse_auto_compaction_threshold(Some("4321")), 4321);
|
|
||||||
assert_eq!(
|
|
||||||
parse_auto_compaction_threshold(Some("not-a-number")),
|
|
||||||
DEFAULT_AUTO_COMPACTION_INPUT_TOKENS_THRESHOLD
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,91 +1,29 @@
|
|||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::io::Write;
|
use std::process::Command;
|
||||||
use std::path::Path;
|
|
||||||
use std::process::{Command, Stdio};
|
|
||||||
use std::sync::{
|
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
Arc,
|
|
||||||
};
|
|
||||||
use std::thread;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use serde_json::{json, Value};
|
use serde_json::json;
|
||||||
|
|
||||||
use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
|
use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
|
||||||
use crate::permissions::PermissionOverride;
|
|
||||||
|
|
||||||
pub type HookPermissionDecision = PermissionOverride;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum HookEvent {
|
pub enum HookEvent {
|
||||||
PreToolUse,
|
PreToolUse,
|
||||||
PostToolUse,
|
PostToolUse,
|
||||||
PostToolUseFailure,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HookEvent {
|
impl HookEvent {
|
||||||
#[must_use]
|
fn as_str(self) -> &'static str {
|
||||||
pub fn as_str(self) -> &'static str {
|
|
||||||
match self {
|
match self {
|
||||||
Self::PreToolUse => "PreToolUse",
|
Self::PreToolUse => "PreToolUse",
|
||||||
Self::PostToolUse => "PostToolUse",
|
Self::PostToolUse => "PostToolUse",
|
||||||
Self::PostToolUseFailure => "PostToolUseFailure",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum HookProgressEvent {
|
|
||||||
Started {
|
|
||||||
event: HookEvent,
|
|
||||||
tool_name: String,
|
|
||||||
command: String,
|
|
||||||
},
|
|
||||||
Completed {
|
|
||||||
event: HookEvent,
|
|
||||||
tool_name: String,
|
|
||||||
command: String,
|
|
||||||
},
|
|
||||||
Cancelled {
|
|
||||||
event: HookEvent,
|
|
||||||
tool_name: String,
|
|
||||||
command: String,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait HookProgressReporter {
|
|
||||||
fn on_event(&mut self, event: &HookProgressEvent);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
|
||||||
pub struct HookAbortSignal {
|
|
||||||
aborted: Arc<AtomicBool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HookAbortSignal {
|
|
||||||
#[must_use]
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn abort(&self) {
|
|
||||||
self.aborted.store(true, Ordering::SeqCst);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn is_aborted(&self) -> bool {
|
|
||||||
self.aborted.load(Ordering::SeqCst)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct HookRunResult {
|
pub struct HookRunResult {
|
||||||
denied: bool,
|
denied: bool,
|
||||||
cancelled: bool,
|
|
||||||
messages: Vec<String>,
|
messages: Vec<String>,
|
||||||
permission_override: Option<PermissionOverride>,
|
|
||||||
permission_reason: Option<String>,
|
|
||||||
updated_input: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HookRunResult {
|
impl HookRunResult {
|
||||||
@@ -93,11 +31,7 @@ impl HookRunResult {
|
|||||||
pub fn allow(messages: Vec<String>) -> Self {
|
pub fn allow(messages: Vec<String>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
denied: false,
|
denied: false,
|
||||||
cancelled: false,
|
|
||||||
messages,
|
messages,
|
||||||
permission_override: None,
|
|
||||||
permission_reason: None,
|
|
||||||
updated_input: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,40 +40,10 @@ impl HookRunResult {
|
|||||||
self.denied
|
self.denied
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn is_cancelled(&self) -> bool {
|
|
||||||
self.cancelled
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn messages(&self) -> &[String] {
|
pub fn messages(&self) -> &[String] {
|
||||||
&self.messages
|
&self.messages
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn permission_override(&self) -> Option<PermissionOverride> {
|
|
||||||
self.permission_override
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn permission_decision(&self) -> Option<HookPermissionDecision> {
|
|
||||||
self.permission_override
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn permission_reason(&self) -> Option<&str> {
|
|
||||||
self.permission_reason.as_deref()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn updated_input(&self) -> Option<&str> {
|
|
||||||
self.updated_input.as_deref()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn updated_input_json(&self) -> Option<&str> {
|
|
||||||
self.updated_input()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
@@ -147,6 +51,16 @@ pub struct HookRunner {
|
|||||||
config: RuntimeHookConfig,
|
config: RuntimeHookConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
struct HookCommandRequest<'a> {
|
||||||
|
event: HookEvent,
|
||||||
|
tool_name: &'a str,
|
||||||
|
tool_input: &'a str,
|
||||||
|
tool_output: Option<&'a str>,
|
||||||
|
is_error: bool,
|
||||||
|
payload: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
impl HookRunner {
|
impl HookRunner {
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(config: RuntimeHookConfig) -> Self {
|
pub fn new(config: RuntimeHookConfig) -> Self {
|
||||||
@@ -160,39 +74,16 @@ impl HookRunner {
|
|||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn run_pre_tool_use(&self, tool_name: &str, tool_input: &str) -> HookRunResult {
|
pub fn run_pre_tool_use(&self, tool_name: &str, tool_input: &str) -> HookRunResult {
|
||||||
self.run_pre_tool_use_with_context(tool_name, tool_input, None, None)
|
self.run_commands(
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_pre_tool_use_with_context(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
reporter: Option<&mut dyn HookProgressReporter>,
|
|
||||||
) -> HookRunResult {
|
|
||||||
Self::run_commands(
|
|
||||||
HookEvent::PreToolUse,
|
HookEvent::PreToolUse,
|
||||||
self.config.pre_tool_use(),
|
self.config.pre_tool_use(),
|
||||||
tool_name,
|
tool_name,
|
||||||
tool_input,
|
tool_input,
|
||||||
None,
|
None,
|
||||||
false,
|
false,
|
||||||
abort_signal,
|
|
||||||
reporter,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_pre_tool_use_with_signal(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
) -> HookRunResult {
|
|
||||||
self.run_pre_tool_use_with_context(tool_name, tool_input, abort_signal, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn run_post_tool_use(
|
pub fn run_post_tool_use(
|
||||||
&self,
|
&self,
|
||||||
@@ -201,274 +92,121 @@ impl HookRunner {
|
|||||||
tool_output: &str,
|
tool_output: &str,
|
||||||
is_error: bool,
|
is_error: bool,
|
||||||
) -> HookRunResult {
|
) -> HookRunResult {
|
||||||
self.run_post_tool_use_with_context(
|
self.run_commands(
|
||||||
tool_name,
|
|
||||||
tool_input,
|
|
||||||
tool_output,
|
|
||||||
is_error,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_post_tool_use_with_context(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_output: &str,
|
|
||||||
is_error: bool,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
reporter: Option<&mut dyn HookProgressReporter>,
|
|
||||||
) -> HookRunResult {
|
|
||||||
Self::run_commands(
|
|
||||||
HookEvent::PostToolUse,
|
HookEvent::PostToolUse,
|
||||||
self.config.post_tool_use(),
|
self.config.post_tool_use(),
|
||||||
tool_name,
|
tool_name,
|
||||||
tool_input,
|
tool_input,
|
||||||
Some(tool_output),
|
Some(tool_output),
|
||||||
is_error,
|
is_error,
|
||||||
abort_signal,
|
|
||||||
reporter,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_post_tool_use_with_signal(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_output: &str,
|
|
||||||
is_error: bool,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
) -> HookRunResult {
|
|
||||||
self.run_post_tool_use_with_context(
|
|
||||||
tool_name,
|
|
||||||
tool_input,
|
|
||||||
tool_output,
|
|
||||||
is_error,
|
|
||||||
abort_signal,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_post_tool_use_failure(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_error: &str,
|
|
||||||
) -> HookRunResult {
|
|
||||||
self.run_post_tool_use_failure_with_context(tool_name, tool_input, tool_error, None, None)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_post_tool_use_failure_with_context(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_error: &str,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
reporter: Option<&mut dyn HookProgressReporter>,
|
|
||||||
) -> HookRunResult {
|
|
||||||
Self::run_commands(
|
|
||||||
HookEvent::PostToolUseFailure,
|
|
||||||
self.config.post_tool_use_failure(),
|
|
||||||
tool_name,
|
|
||||||
tool_input,
|
|
||||||
Some(tool_error),
|
|
||||||
true,
|
|
||||||
abort_signal,
|
|
||||||
reporter,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn run_post_tool_use_failure_with_signal(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_error: &str,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
) -> HookRunResult {
|
|
||||||
self.run_post_tool_use_failure_with_context(
|
|
||||||
tool_name,
|
|
||||||
tool_input,
|
|
||||||
tool_error,
|
|
||||||
abort_signal,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
fn run_commands(
|
fn run_commands(
|
||||||
|
&self,
|
||||||
event: HookEvent,
|
event: HookEvent,
|
||||||
commands: &[String],
|
commands: &[String],
|
||||||
tool_name: &str,
|
tool_name: &str,
|
||||||
tool_input: &str,
|
tool_input: &str,
|
||||||
tool_output: Option<&str>,
|
tool_output: Option<&str>,
|
||||||
is_error: bool,
|
is_error: bool,
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
mut reporter: Option<&mut dyn HookProgressReporter>,
|
|
||||||
) -> HookRunResult {
|
) -> HookRunResult {
|
||||||
if commands.is_empty() {
|
if commands.is_empty() {
|
||||||
return HookRunResult::allow(Vec::new());
|
return HookRunResult::allow(Vec::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
if abort_signal.is_some_and(HookAbortSignal::is_aborted) {
|
let payload = json!({
|
||||||
return HookRunResult {
|
"hook_event_name": event.as_str(),
|
||||||
denied: false,
|
"tool_name": tool_name,
|
||||||
cancelled: true,
|
"tool_input": parse_tool_input(tool_input),
|
||||||
messages: vec![format!(
|
"tool_input_json": tool_input,
|
||||||
"{} hook cancelled before execution",
|
"tool_output": tool_output,
|
||||||
event.as_str()
|
"tool_result_is_error": is_error,
|
||||||
)],
|
})
|
||||||
permission_override: None,
|
.to_string();
|
||||||
permission_reason: None,
|
|
||||||
updated_input: None,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
let payload = hook_payload(event, tool_name, tool_input, tool_output, is_error).to_string();
|
let mut messages = Vec::new();
|
||||||
let mut result = HookRunResult::allow(Vec::new());
|
|
||||||
|
|
||||||
for command in commands {
|
for command in commands {
|
||||||
if let Some(reporter) = reporter.as_deref_mut() {
|
|
||||||
reporter.on_event(&HookProgressEvent::Started {
|
|
||||||
event,
|
|
||||||
tool_name: tool_name.to_string(),
|
|
||||||
command: command.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
match Self::run_command(
|
match Self::run_command(
|
||||||
command,
|
command,
|
||||||
event,
|
HookCommandRequest {
|
||||||
tool_name,
|
event,
|
||||||
tool_input,
|
tool_name,
|
||||||
tool_output,
|
tool_input,
|
||||||
is_error,
|
tool_output,
|
||||||
&payload,
|
is_error,
|
||||||
abort_signal,
|
payload: &payload,
|
||||||
|
},
|
||||||
) {
|
) {
|
||||||
HookCommandOutcome::Allow { parsed } => {
|
HookCommandOutcome::Allow { message } => {
|
||||||
if let Some(reporter) = reporter.as_deref_mut() {
|
if let Some(message) = message {
|
||||||
reporter.on_event(&HookProgressEvent::Completed {
|
messages.push(message);
|
||||||
event,
|
|
||||||
tool_name: tool_name.to_string(),
|
|
||||||
command: command.clone(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
merge_parsed_hook_output(&mut result, parsed);
|
|
||||||
}
|
}
|
||||||
HookCommandOutcome::Deny { parsed } => {
|
HookCommandOutcome::Deny { message } => {
|
||||||
if let Some(reporter) = reporter.as_deref_mut() {
|
let message = message.unwrap_or_else(|| {
|
||||||
reporter.on_event(&HookProgressEvent::Completed {
|
format!("{} hook denied tool `{tool_name}`", event.as_str())
|
||||||
event,
|
});
|
||||||
tool_name: tool_name.to_string(),
|
messages.push(message);
|
||||||
command: command.clone(),
|
return HookRunResult {
|
||||||
});
|
denied: true,
|
||||||
}
|
messages,
|
||||||
merge_parsed_hook_output(&mut result, parsed);
|
};
|
||||||
result.denied = true;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
HookCommandOutcome::Warn { message } => {
|
|
||||||
if let Some(reporter) = reporter.as_deref_mut() {
|
|
||||||
reporter.on_event(&HookProgressEvent::Completed {
|
|
||||||
event,
|
|
||||||
tool_name: tool_name.to_string(),
|
|
||||||
command: command.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
result.messages.push(message);
|
|
||||||
}
|
|
||||||
HookCommandOutcome::Cancelled { message } => {
|
|
||||||
if let Some(reporter) = reporter.as_deref_mut() {
|
|
||||||
reporter.on_event(&HookProgressEvent::Cancelled {
|
|
||||||
event,
|
|
||||||
tool_name: tool_name.to_string(),
|
|
||||||
command: command.clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
result.cancelled = true;
|
|
||||||
result.messages.push(message);
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
HookCommandOutcome::Warn { message } => messages.push(message),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
HookRunResult::allow(messages)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
fn run_command(command: &str, request: HookCommandRequest<'_>) -> HookCommandOutcome {
|
||||||
fn run_command(
|
|
||||||
command: &str,
|
|
||||||
event: HookEvent,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_output: Option<&str>,
|
|
||||||
is_error: bool,
|
|
||||||
payload: &str,
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
) -> HookCommandOutcome {
|
|
||||||
let mut child = shell_command(command);
|
let mut child = shell_command(command);
|
||||||
child.stdin(Stdio::piped());
|
child.stdin(std::process::Stdio::piped());
|
||||||
child.stdout(Stdio::piped());
|
child.stdout(std::process::Stdio::piped());
|
||||||
child.stderr(Stdio::piped());
|
child.stderr(std::process::Stdio::piped());
|
||||||
child.env("HOOK_EVENT", event.as_str());
|
child.env("HOOK_EVENT", request.event.as_str());
|
||||||
child.env("HOOK_TOOL_NAME", tool_name);
|
child.env("HOOK_TOOL_NAME", request.tool_name);
|
||||||
child.env("HOOK_TOOL_INPUT", tool_input);
|
child.env("HOOK_TOOL_INPUT", request.tool_input);
|
||||||
child.env("HOOK_TOOL_IS_ERROR", if is_error { "1" } else { "0" });
|
child.env(
|
||||||
if let Some(tool_output) = tool_output {
|
"HOOK_TOOL_IS_ERROR",
|
||||||
|
if request.is_error { "1" } else { "0" },
|
||||||
|
);
|
||||||
|
if let Some(tool_output) = request.tool_output {
|
||||||
child.env("HOOK_TOOL_OUTPUT", tool_output);
|
child.env("HOOK_TOOL_OUTPUT", tool_output);
|
||||||
}
|
}
|
||||||
|
|
||||||
match child.output_with_stdin(payload.as_bytes(), abort_signal) {
|
match child.output_with_stdin(request.payload.as_bytes()) {
|
||||||
Ok(CommandExecution::Finished(output)) => {
|
Ok(output) => {
|
||||||
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
|
||||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||||
let parsed = parse_hook_output(&stdout);
|
let message = (!stdout.is_empty()).then_some(stdout);
|
||||||
match output.status.code() {
|
match output.status.code() {
|
||||||
Some(0) => {
|
Some(0) => HookCommandOutcome::Allow { message },
|
||||||
if parsed.deny {
|
Some(2) => HookCommandOutcome::Deny { message },
|
||||||
HookCommandOutcome::Deny { parsed }
|
|
||||||
} else {
|
|
||||||
HookCommandOutcome::Allow { parsed }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some(2) => HookCommandOutcome::Deny {
|
|
||||||
parsed: parsed.with_fallback_message(format!(
|
|
||||||
"{} hook denied tool `{tool_name}`",
|
|
||||||
event.as_str()
|
|
||||||
)),
|
|
||||||
},
|
|
||||||
Some(code) => HookCommandOutcome::Warn {
|
Some(code) => HookCommandOutcome::Warn {
|
||||||
message: format_hook_warning(
|
message: format_hook_warning(
|
||||||
command,
|
command,
|
||||||
code,
|
code,
|
||||||
parsed.primary_message(),
|
message.as_deref(),
|
||||||
stderr.as_str(),
|
stderr.as_str(),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
None => HookCommandOutcome::Warn {
|
None => HookCommandOutcome::Warn {
|
||||||
message: format!(
|
message: format!(
|
||||||
"{} hook `{command}` terminated by signal while handling `{tool_name}`",
|
"{} hook `{command}` terminated by signal while handling `{}`",
|
||||||
event.as_str()
|
request.event.as_str(),
|
||||||
|
request.tool_name
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(CommandExecution::Cancelled) => HookCommandOutcome::Cancelled {
|
|
||||||
message: format!(
|
|
||||||
"{} hook `{command}` cancelled while handling `{tool_name}`",
|
|
||||||
event.as_str()
|
|
||||||
),
|
|
||||||
},
|
|
||||||
Err(error) => HookCommandOutcome::Warn {
|
Err(error) => HookCommandOutcome::Warn {
|
||||||
message: format!(
|
message: format!(
|
||||||
"{} hook `{command}` failed to start for `{tool_name}`: {error}",
|
"{} hook `{command}` failed to start for `{}`: {error}",
|
||||||
event.as_str()
|
request.event.as_str(),
|
||||||
|
request.tool_name
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -476,131 +214,12 @@ impl HookRunner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
enum HookCommandOutcome {
|
enum HookCommandOutcome {
|
||||||
Allow { parsed: ParsedHookOutput },
|
Allow { message: Option<String> },
|
||||||
Deny { parsed: ParsedHookOutput },
|
Deny { message: Option<String> },
|
||||||
Warn { message: String },
|
Warn { message: String },
|
||||||
Cancelled { message: String },
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
fn parse_tool_input(tool_input: &str) -> serde_json::Value {
|
||||||
struct ParsedHookOutput {
|
|
||||||
messages: Vec<String>,
|
|
||||||
deny: bool,
|
|
||||||
permission_override: Option<PermissionOverride>,
|
|
||||||
permission_reason: Option<String>,
|
|
||||||
updated_input: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ParsedHookOutput {
|
|
||||||
fn with_fallback_message(mut self, fallback: String) -> Self {
|
|
||||||
if self.messages.is_empty() {
|
|
||||||
self.messages.push(fallback);
|
|
||||||
}
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn primary_message(&self) -> Option<&str> {
|
|
||||||
self.messages.first().map(String::as_str)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn merge_parsed_hook_output(target: &mut HookRunResult, parsed: ParsedHookOutput) {
|
|
||||||
target.messages.extend(parsed.messages);
|
|
||||||
if parsed.permission_override.is_some() {
|
|
||||||
target.permission_override = parsed.permission_override;
|
|
||||||
}
|
|
||||||
if parsed.permission_reason.is_some() {
|
|
||||||
target.permission_reason = parsed.permission_reason;
|
|
||||||
}
|
|
||||||
if parsed.updated_input.is_some() {
|
|
||||||
target.updated_input = parsed.updated_input;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_hook_output(stdout: &str) -> ParsedHookOutput {
|
|
||||||
if stdout.is_empty() {
|
|
||||||
return ParsedHookOutput::default();
|
|
||||||
}
|
|
||||||
|
|
||||||
let Ok(Value::Object(root)) = serde_json::from_str::<Value>(stdout) else {
|
|
||||||
return ParsedHookOutput {
|
|
||||||
messages: vec![stdout.to_string()],
|
|
||||||
..ParsedHookOutput::default()
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut parsed = ParsedHookOutput::default();
|
|
||||||
|
|
||||||
if let Some(message) = root.get("systemMessage").and_then(Value::as_str) {
|
|
||||||
parsed.messages.push(message.to_string());
|
|
||||||
}
|
|
||||||
if let Some(message) = root.get("reason").and_then(Value::as_str) {
|
|
||||||
parsed.messages.push(message.to_string());
|
|
||||||
}
|
|
||||||
if root.get("continue").and_then(Value::as_bool) == Some(false)
|
|
||||||
|| root.get("decision").and_then(Value::as_str) == Some("block")
|
|
||||||
{
|
|
||||||
parsed.deny = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(Value::Object(specific)) = root.get("hookSpecificOutput") {
|
|
||||||
if let Some(Value::String(additional_context)) = specific.get("additionalContext") {
|
|
||||||
parsed.messages.push(additional_context.clone());
|
|
||||||
}
|
|
||||||
if let Some(decision) = specific.get("permissionDecision").and_then(Value::as_str) {
|
|
||||||
parsed.permission_override = match decision {
|
|
||||||
"allow" => Some(PermissionOverride::Allow),
|
|
||||||
"deny" => Some(PermissionOverride::Deny),
|
|
||||||
"ask" => Some(PermissionOverride::Ask),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
if let Some(reason) = specific
|
|
||||||
.get("permissionDecisionReason")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
{
|
|
||||||
parsed.permission_reason = Some(reason.to_string());
|
|
||||||
}
|
|
||||||
if let Some(updated_input) = specific.get("updatedInput") {
|
|
||||||
parsed.updated_input = serde_json::to_string(updated_input).ok();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if parsed.messages.is_empty() {
|
|
||||||
parsed.messages.push(stdout.to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
parsed
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hook_payload(
|
|
||||||
event: HookEvent,
|
|
||||||
tool_name: &str,
|
|
||||||
tool_input: &str,
|
|
||||||
tool_output: Option<&str>,
|
|
||||||
is_error: bool,
|
|
||||||
) -> Value {
|
|
||||||
match event {
|
|
||||||
HookEvent::PostToolUseFailure => json!({
|
|
||||||
"hook_event_name": event.as_str(),
|
|
||||||
"tool_name": tool_name,
|
|
||||||
"tool_input": parse_tool_input(tool_input),
|
|
||||||
"tool_input_json": tool_input,
|
|
||||||
"tool_error": tool_output,
|
|
||||||
"tool_result_is_error": true,
|
|
||||||
}),
|
|
||||||
_ => json!({
|
|
||||||
"hook_event_name": event.as_str(),
|
|
||||||
"tool_name": tool_name,
|
|
||||||
"tool_input": parse_tool_input(tool_input),
|
|
||||||
"tool_input_json": tool_input,
|
|
||||||
"tool_output": tool_output,
|
|
||||||
"tool_result_is_error": is_error,
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_tool_input(tool_input: &str) -> Value {
|
|
||||||
serde_json::from_str(tool_input).unwrap_or_else(|_| json!({ "raw": tool_input }))
|
serde_json::from_str(tool_input).unwrap_or_else(|_| json!({ "raw": tool_input }))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -626,11 +245,7 @@ fn shell_command(command: &str) -> CommandWithStdin {
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
let command_builder = if Path::new(command).exists() {
|
let command_builder = {
|
||||||
let mut command_builder = Command::new("sh");
|
|
||||||
command_builder.arg(command);
|
|
||||||
CommandWithStdin::new(command_builder)
|
|
||||||
} else {
|
|
||||||
let mut command_builder = Command::new("sh");
|
let mut command_builder = Command::new("sh");
|
||||||
command_builder.arg("-lc").arg(command);
|
command_builder.arg("-lc").arg(command);
|
||||||
CommandWithStdin::new(command_builder)
|
CommandWithStdin::new(command_builder)
|
||||||
@@ -648,17 +263,17 @@ impl CommandWithStdin {
|
|||||||
Self { command }
|
Self { command }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stdin(&mut self, cfg: Stdio) -> &mut Self {
|
fn stdin(&mut self, cfg: std::process::Stdio) -> &mut Self {
|
||||||
self.command.stdin(cfg);
|
self.command.stdin(cfg);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stdout(&mut self, cfg: Stdio) -> &mut Self {
|
fn stdout(&mut self, cfg: std::process::Stdio) -> &mut Self {
|
||||||
self.command.stdout(cfg);
|
self.command.stdout(cfg);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stderr(&mut self, cfg: Stdio) -> &mut Self {
|
fn stderr(&mut self, cfg: std::process::Stdio) -> &mut Self {
|
||||||
self.command.stderr(cfg);
|
self.command.stderr(cfg);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@@ -672,64 +287,26 @@ impl CommandWithStdin {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn output_with_stdin(
|
fn output_with_stdin(&mut self, stdin: &[u8]) -> std::io::Result<std::process::Output> {
|
||||||
&mut self,
|
|
||||||
stdin: &[u8],
|
|
||||||
abort_signal: Option<&HookAbortSignal>,
|
|
||||||
) -> std::io::Result<CommandExecution> {
|
|
||||||
let mut child = self.command.spawn()?;
|
let mut child = self.command.spawn()?;
|
||||||
if let Some(mut child_stdin) = child.stdin.take() {
|
if let Some(mut child_stdin) = child.stdin.take() {
|
||||||
|
use std::io::Write;
|
||||||
child_stdin.write_all(stdin)?;
|
child_stdin.write_all(stdin)?;
|
||||||
}
|
}
|
||||||
|
child.wait_with_output()
|
||||||
loop {
|
|
||||||
if abort_signal.is_some_and(HookAbortSignal::is_aborted) {
|
|
||||||
let _ = child.kill();
|
|
||||||
let _ = child.wait_with_output();
|
|
||||||
return Ok(CommandExecution::Cancelled);
|
|
||||||
}
|
|
||||||
|
|
||||||
match child.try_wait()? {
|
|
||||||
Some(_) => return child.wait_with_output().map(CommandExecution::Finished),
|
|
||||||
None => thread::sleep(Duration::from_millis(20)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
enum CommandExecution {
|
|
||||||
Finished(std::process::Output),
|
|
||||||
Cancelled,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use std::thread;
|
use super::{HookRunResult, HookRunner};
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use super::{
|
|
||||||
HookAbortSignal, HookEvent, HookProgressEvent, HookProgressReporter, HookRunResult,
|
|
||||||
HookRunner,
|
|
||||||
};
|
|
||||||
use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
|
use crate::config::{RuntimeFeatureConfig, RuntimeHookConfig};
|
||||||
use crate::permissions::PermissionOverride;
|
|
||||||
|
|
||||||
struct RecordingReporter {
|
|
||||||
events: Vec<HookProgressEvent>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HookProgressReporter for RecordingReporter {
|
|
||||||
fn on_event(&mut self, event: &HookProgressEvent) {
|
|
||||||
self.events.push(event.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn allows_exit_code_zero_and_captures_stdout() {
|
fn allows_exit_code_zero_and_captures_stdout() {
|
||||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||||
vec![shell_snippet("printf 'pre ok'")],
|
vec![shell_snippet("printf 'pre ok'")],
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
Vec::new(),
|
|
||||||
));
|
));
|
||||||
|
|
||||||
let result = runner.run_pre_tool_use("Read", r#"{"path":"README.md"}"#);
|
let result = runner.run_pre_tool_use("Read", r#"{"path":"README.md"}"#);
|
||||||
@@ -742,7 +319,6 @@ mod tests {
|
|||||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
let runner = HookRunner::new(RuntimeHookConfig::new(
|
||||||
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
|
vec![shell_snippet("printf 'blocked by hook'; exit 2")],
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
Vec::new(),
|
|
||||||
));
|
));
|
||||||
|
|
||||||
let result = runner.run_pre_tool_use("Bash", r#"{"command":"pwd"}"#);
|
let result = runner.run_pre_tool_use("Bash", r#"{"command":"pwd"}"#);
|
||||||
@@ -757,7 +333,6 @@ mod tests {
|
|||||||
RuntimeHookConfig::new(
|
RuntimeHookConfig::new(
|
||||||
vec![shell_snippet("printf 'warning hook'; exit 1")],
|
vec![shell_snippet("printf 'warning hook'; exit 1")],
|
||||||
Vec::new(),
|
Vec::new(),
|
||||||
Vec::new(),
|
|
||||||
),
|
),
|
||||||
));
|
));
|
||||||
|
|
||||||
@@ -770,82 +345,6 @@ mod tests {
|
|||||||
.any(|message| message.contains("allowing tool execution to continue")));
|
.any(|message| message.contains("allowing tool execution to continue")));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn parses_pre_hook_permission_override_and_updated_input() {
|
|
||||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
|
||||||
vec![shell_snippet(
|
|
||||||
r#"printf '%s' '{"systemMessage":"updated","hookSpecificOutput":{"permissionDecision":"allow","permissionDecisionReason":"hook ok","updatedInput":{"command":"git status"}}}'"#,
|
|
||||||
)],
|
|
||||||
Vec::new(),
|
|
||||||
Vec::new(),
|
|
||||||
));
|
|
||||||
|
|
||||||
let result = runner.run_pre_tool_use("bash", r#"{"command":"pwd"}"#);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
result.permission_override(),
|
|
||||||
Some(PermissionOverride::Allow)
|
|
||||||
);
|
|
||||||
assert_eq!(result.permission_reason(), Some("hook ok"));
|
|
||||||
assert_eq!(result.updated_input(), Some(r#"{"command":"git status"}"#));
|
|
||||||
assert!(result.messages().iter().any(|message| message == "updated"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn runs_post_tool_use_failure_hooks() {
|
|
||||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
|
||||||
Vec::new(),
|
|
||||||
Vec::new(),
|
|
||||||
vec![shell_snippet("printf 'failure hook ran'")],
|
|
||||||
));
|
|
||||||
|
|
||||||
let result =
|
|
||||||
runner.run_post_tool_use_failure("bash", r#"{"command":"false"}"#, "command failed");
|
|
||||||
|
|
||||||
assert!(!result.is_denied());
|
|
||||||
assert_eq!(result.messages(), &["failure hook ran".to_string()]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn abort_signal_cancels_long_running_hook_and_reports_progress() {
|
|
||||||
let runner = HookRunner::new(RuntimeHookConfig::new(
|
|
||||||
vec![shell_snippet("sleep 5")],
|
|
||||||
Vec::new(),
|
|
||||||
Vec::new(),
|
|
||||||
));
|
|
||||||
let abort_signal = HookAbortSignal::new();
|
|
||||||
let abort_signal_for_thread = abort_signal.clone();
|
|
||||||
let mut reporter = RecordingReporter { events: Vec::new() };
|
|
||||||
|
|
||||||
thread::spawn(move || {
|
|
||||||
thread::sleep(Duration::from_millis(100));
|
|
||||||
abort_signal_for_thread.abort();
|
|
||||||
});
|
|
||||||
|
|
||||||
let result = runner.run_pre_tool_use_with_context(
|
|
||||||
"bash",
|
|
||||||
r#"{"command":"sleep 5"}"#,
|
|
||||||
Some(&abort_signal),
|
|
||||||
Some(&mut reporter),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(result.is_cancelled());
|
|
||||||
assert!(reporter.events.iter().any(|event| matches!(
|
|
||||||
event,
|
|
||||||
HookProgressEvent::Started {
|
|
||||||
event: HookEvent::PreToolUse,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
)));
|
|
||||||
assert!(reporter.events.iter().any(|event| matches!(
|
|
||||||
event,
|
|
||||||
HookProgressEvent::Cancelled {
|
|
||||||
event: HookEvent::PreToolUse,
|
|
||||||
..
|
|
||||||
}
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
fn shell_snippet(script: &str) -> String {
|
fn shell_snippet(script: &str) -> String {
|
||||||
script.replace('\'', "\"")
|
script.replace('\'', "\"")
|
||||||
|
|||||||
@@ -24,31 +24,28 @@ pub use compact::{
|
|||||||
get_compact_continuation_message, should_compact, CompactionConfig, CompactionResult,
|
get_compact_continuation_message, should_compact, CompactionConfig, CompactionResult,
|
||||||
};
|
};
|
||||||
pub use config::{
|
pub use config::{
|
||||||
ConfigEntry, ConfigError, ConfigLoader, ConfigSource, McpClaudeAiProxyServerConfig,
|
ConfigEntry, ConfigError, ConfigLoader, ConfigSource, McpManagedProxyServerConfig,
|
||||||
McpConfigCollection, McpOAuthConfig, McpRemoteServerConfig, McpSdkServerConfig,
|
McpConfigCollection, McpOAuthConfig, McpRemoteServerConfig, McpSdkServerConfig,
|
||||||
McpServerConfig, McpStdioServerConfig, McpTransport, McpWebSocketServerConfig, OAuthConfig,
|
McpServerConfig, McpStdioServerConfig, McpTransport, McpWebSocketServerConfig, OAuthConfig,
|
||||||
ResolvedPermissionMode, RuntimeConfig, RuntimeFeatureConfig, RuntimeHookConfig,
|
ResolvedPermissionMode, RuntimeConfig, RuntimeFeatureConfig, RuntimeHookConfig,
|
||||||
RuntimePermissionRuleConfig, RuntimePluginConfig, ScopedMcpServerConfig,
|
RuntimePluginConfig, ScopedMcpServerConfig, CLAW_SETTINGS_SCHEMA_NAME,
|
||||||
CLAUDE_CODE_SETTINGS_SCHEMA_NAME,
|
|
||||||
};
|
};
|
||||||
pub use conversation::{
|
pub use conversation::{
|
||||||
auto_compaction_threshold_from_env, ApiClient, ApiRequest, AssistantEvent, AutoCompactionEvent,
|
ApiClient, ApiRequest, AssistantEvent, ConversationRuntime, RuntimeError, StaticToolExecutor,
|
||||||
ConversationRuntime, RuntimeError, StaticToolExecutor, ToolError, ToolExecutor, TurnSummary,
|
ToolError, ToolExecutor, TurnSummary,
|
||||||
};
|
};
|
||||||
pub use file_ops::{
|
pub use file_ops::{
|
||||||
edit_file, glob_search, grep_search, read_file, write_file, EditFileOutput, GlobSearchOutput,
|
edit_file, glob_search, grep_search, read_file, write_file, EditFileOutput, GlobSearchOutput,
|
||||||
GrepSearchInput, GrepSearchOutput, ReadFileOutput, StructuredPatchHunk, TextFilePayload,
|
GrepSearchInput, GrepSearchOutput, ReadFileOutput, StructuredPatchHunk, TextFilePayload,
|
||||||
WriteFileOutput,
|
WriteFileOutput,
|
||||||
};
|
};
|
||||||
pub use hooks::{
|
pub use hooks::{HookEvent, HookRunResult, HookRunner};
|
||||||
HookAbortSignal, HookEvent, HookProgressEvent, HookProgressReporter, HookRunResult, HookRunner,
|
|
||||||
};
|
|
||||||
pub use mcp::{
|
pub use mcp::{
|
||||||
mcp_server_signature, mcp_tool_name, mcp_tool_prefix, normalize_name_for_mcp,
|
mcp_server_signature, mcp_tool_name, mcp_tool_prefix, normalize_name_for_mcp,
|
||||||
scoped_mcp_config_hash, unwrap_ccr_proxy_url,
|
scoped_mcp_config_hash, unwrap_ccr_proxy_url,
|
||||||
};
|
};
|
||||||
pub use mcp_client::{
|
pub use mcp_client::{
|
||||||
McpClaudeAiProxyTransport, McpClientAuth, McpClientBootstrap, McpClientTransport,
|
McpManagedProxyTransport, McpClientAuth, McpClientBootstrap, McpClientTransport,
|
||||||
McpRemoteTransport, McpSdkTransport, McpStdioTransport,
|
McpRemoteTransport, McpSdkTransport, McpStdioTransport,
|
||||||
};
|
};
|
||||||
pub use mcp_stdio::{
|
pub use mcp_stdio::{
|
||||||
@@ -67,8 +64,8 @@ pub use oauth::{
|
|||||||
PkceChallengeMethod, PkceCodePair,
|
PkceChallengeMethod, PkceCodePair,
|
||||||
};
|
};
|
||||||
pub use permissions::{
|
pub use permissions::{
|
||||||
PermissionContext, PermissionMode, PermissionOutcome, PermissionOverride, PermissionPolicy,
|
PermissionMode, PermissionOutcome, PermissionPolicy, PermissionPromptDecision,
|
||||||
PermissionPromptDecision, PermissionPrompter, PermissionRequest,
|
PermissionPrompter, PermissionRequest,
|
||||||
};
|
};
|
||||||
pub use prompt::{
|
pub use prompt::{
|
||||||
load_system_prompt, prepend_bullets, ContextFile, ProjectContext, PromptBuildError,
|
load_system_prompt, prepend_bullets, ContextFile, ProjectContext, PromptBuildError,
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ pub fn mcp_server_signature(config: &McpServerConfig) -> Option<String> {
|
|||||||
Some(format!("url:{}", unwrap_ccr_proxy_url(&config.url)))
|
Some(format!("url:{}", unwrap_ccr_proxy_url(&config.url)))
|
||||||
}
|
}
|
||||||
McpServerConfig::Ws(config) => Some(format!("url:{}", unwrap_ccr_proxy_url(&config.url))),
|
McpServerConfig::Ws(config) => Some(format!("url:{}", unwrap_ccr_proxy_url(&config.url))),
|
||||||
McpServerConfig::ClaudeAiProxy(config) => {
|
McpServerConfig::ManagedProxy(config) => {
|
||||||
Some(format!("url:{}", unwrap_ccr_proxy_url(&config.url)))
|
Some(format!("url:{}", unwrap_ccr_proxy_url(&config.url)))
|
||||||
}
|
}
|
||||||
McpServerConfig::Sdk(_) => None,
|
McpServerConfig::Sdk(_) => None,
|
||||||
@@ -110,7 +110,7 @@ pub fn scoped_mcp_config_hash(config: &ScopedMcpServerConfig) -> String {
|
|||||||
ws.headers_helper.as_deref().unwrap_or("")
|
ws.headers_helper.as_deref().unwrap_or("")
|
||||||
),
|
),
|
||||||
McpServerConfig::Sdk(sdk) => format!("sdk|{}", sdk.name),
|
McpServerConfig::Sdk(sdk) => format!("sdk|{}", sdk.name),
|
||||||
McpServerConfig::ClaudeAiProxy(proxy) => {
|
McpServerConfig::ManagedProxy(proxy) => {
|
||||||
format!("claudeai-proxy|{}|{}", proxy.url, proxy.id)
|
format!("claudeai-proxy|{}|{}", proxy.url, proxy.id)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ pub enum McpClientTransport {
|
|||||||
Http(McpRemoteTransport),
|
Http(McpRemoteTransport),
|
||||||
WebSocket(McpRemoteTransport),
|
WebSocket(McpRemoteTransport),
|
||||||
Sdk(McpSdkTransport),
|
Sdk(McpSdkTransport),
|
||||||
ClaudeAiProxy(McpClaudeAiProxyTransport),
|
ManagedProxy(McpManagedProxyTransport),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -34,7 +34,7 @@ pub struct McpSdkTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct McpClaudeAiProxyTransport {
|
pub struct McpManagedProxyTransport {
|
||||||
pub url: String,
|
pub url: String,
|
||||||
pub id: String,
|
pub id: String,
|
||||||
}
|
}
|
||||||
@@ -97,8 +97,8 @@ impl McpClientTransport {
|
|||||||
McpServerConfig::Sdk(config) => Self::Sdk(McpSdkTransport {
|
McpServerConfig::Sdk(config) => Self::Sdk(McpSdkTransport {
|
||||||
name: config.name.clone(),
|
name: config.name.clone(),
|
||||||
}),
|
}),
|
||||||
McpServerConfig::ClaudeAiProxy(config) => {
|
McpServerConfig::ManagedProxy(config) => {
|
||||||
Self::ClaudeAiProxy(McpClaudeAiProxyTransport {
|
Self::ManagedProxy(McpManagedProxyTransport {
|
||||||
url: config.url.clone(),
|
url: config.url.clone(),
|
||||||
id: config.id.clone(),
|
id: config.id.clone(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -324,12 +324,12 @@ fn generate_random_token(bytes: usize) -> io::Result<String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn credentials_home_dir() -> io::Result<PathBuf> {
|
fn credentials_home_dir() -> io::Result<PathBuf> {
|
||||||
if let Some(path) = std::env::var_os("CLAUDE_CONFIG_HOME") {
|
if let Some(path) = std::env::var_os("CLAW_CONFIG_HOME") {
|
||||||
return Ok(PathBuf::from(path));
|
return Ok(PathBuf::from(path));
|
||||||
}
|
}
|
||||||
let home = std::env::var_os("HOME")
|
let home = std::env::var_os("HOME")
|
||||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "HOME is not set"))?;
|
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "HOME is not set"))?;
|
||||||
Ok(PathBuf::from(home).join(".claude"))
|
Ok(PathBuf::from(home).join(".claw"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_credentials_root(path: &PathBuf) -> io::Result<Map<String, Value>> {
|
fn read_credentials_root(path: &PathBuf) -> io::Result<Map<String, Value>> {
|
||||||
@@ -541,7 +541,7 @@ mod tests {
|
|||||||
fn oauth_credentials_round_trip_and_clear_preserves_other_fields() {
|
fn oauth_credentials_round_trip_and_clear_preserves_other_fields() {
|
||||||
let _guard = env_lock();
|
let _guard = env_lock();
|
||||||
let config_home = temp_config_home();
|
let config_home = temp_config_home();
|
||||||
std::env::set_var("CLAUDE_CONFIG_HOME", &config_home);
|
std::env::set_var("CLAW_CONFIG_HOME", &config_home);
|
||||||
let path = credentials_path().expect("credentials path");
|
let path = credentials_path().expect("credentials path");
|
||||||
std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
|
std::fs::create_dir_all(path.parent().expect("parent")).expect("create parent");
|
||||||
std::fs::write(&path, "{\"other\":\"value\"}\n").expect("seed credentials");
|
std::fs::write(&path, "{\"other\":\"value\"}\n").expect("seed credentials");
|
||||||
@@ -567,7 +567,7 @@ mod tests {
|
|||||||
assert!(cleared.contains("\"other\": \"value\""));
|
assert!(cleared.contains("\"other\": \"value\""));
|
||||||
assert!(!cleared.contains("\"oauth\""));
|
assert!(!cleared.contains("\"oauth\""));
|
||||||
|
|
||||||
std::env::remove_var("CLAUDE_CONFIG_HOME");
|
std::env::remove_var("CLAW_CONFIG_HOME");
|
||||||
std::fs::remove_dir_all(config_home).expect("cleanup temp dir");
|
std::fs::remove_dir_all(config_home).expect("cleanup temp dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use serde_json::Value;
|
|
||||||
|
|
||||||
use crate::config::RuntimePermissionRuleConfig;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum PermissionMode {
|
pub enum PermissionMode {
|
||||||
ReadOnly,
|
ReadOnly,
|
||||||
@@ -26,49 +22,12 @@ impl PermissionMode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub enum PermissionOverride {
|
|
||||||
Allow,
|
|
||||||
Deny,
|
|
||||||
Ask,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
||||||
pub struct PermissionContext {
|
|
||||||
override_decision: Option<PermissionOverride>,
|
|
||||||
override_reason: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PermissionContext {
|
|
||||||
#[must_use]
|
|
||||||
pub fn new(
|
|
||||||
override_decision: Option<PermissionOverride>,
|
|
||||||
override_reason: Option<String>,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
override_decision,
|
|
||||||
override_reason,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn override_decision(&self) -> Option<PermissionOverride> {
|
|
||||||
self.override_decision
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn override_reason(&self) -> Option<&str> {
|
|
||||||
self.override_reason.as_deref()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct PermissionRequest {
|
pub struct PermissionRequest {
|
||||||
pub tool_name: String,
|
pub tool_name: String,
|
||||||
pub input: String,
|
pub input: String,
|
||||||
pub current_mode: PermissionMode,
|
pub current_mode: PermissionMode,
|
||||||
pub required_mode: PermissionMode,
|
pub required_mode: PermissionMode,
|
||||||
pub reason: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -91,9 +50,6 @@ pub enum PermissionOutcome {
|
|||||||
pub struct PermissionPolicy {
|
pub struct PermissionPolicy {
|
||||||
active_mode: PermissionMode,
|
active_mode: PermissionMode,
|
||||||
tool_requirements: BTreeMap<String, PermissionMode>,
|
tool_requirements: BTreeMap<String, PermissionMode>,
|
||||||
allow_rules: Vec<PermissionRule>,
|
|
||||||
deny_rules: Vec<PermissionRule>,
|
|
||||||
ask_rules: Vec<PermissionRule>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PermissionPolicy {
|
impl PermissionPolicy {
|
||||||
@@ -102,9 +58,6 @@ impl PermissionPolicy {
|
|||||||
Self {
|
Self {
|
||||||
active_mode,
|
active_mode,
|
||||||
tool_requirements: BTreeMap::new(),
|
tool_requirements: BTreeMap::new(),
|
||||||
allow_rules: Vec::new(),
|
|
||||||
deny_rules: Vec::new(),
|
|
||||||
ask_rules: Vec::new(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,26 +72,6 @@ impl PermissionPolicy {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn with_permission_rules(mut self, config: &RuntimePermissionRuleConfig) -> Self {
|
|
||||||
self.allow_rules = config
|
|
||||||
.allow()
|
|
||||||
.iter()
|
|
||||||
.map(|rule| PermissionRule::parse(rule))
|
|
||||||
.collect();
|
|
||||||
self.deny_rules = config
|
|
||||||
.deny()
|
|
||||||
.iter()
|
|
||||||
.map(|rule| PermissionRule::parse(rule))
|
|
||||||
.collect();
|
|
||||||
self.ask_rules = config
|
|
||||||
.ask()
|
|
||||||
.iter()
|
|
||||||
.map(|rule| PermissionRule::parse(rule))
|
|
||||||
.collect();
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn active_mode(&self) -> PermissionMode {
|
pub fn active_mode(&self) -> PermissionMode {
|
||||||
self.active_mode
|
self.active_mode
|
||||||
@@ -157,121 +90,38 @@ impl PermissionPolicy {
|
|||||||
&self,
|
&self,
|
||||||
tool_name: &str,
|
tool_name: &str,
|
||||||
input: &str,
|
input: &str,
|
||||||
prompter: Option<&mut dyn PermissionPrompter>,
|
mut prompter: Option<&mut dyn PermissionPrompter>,
|
||||||
) -> PermissionOutcome {
|
) -> PermissionOutcome {
|
||||||
self.authorize_with_context(tool_name, input, &PermissionContext::default(), prompter)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
#[allow(clippy::too_many_lines)]
|
|
||||||
pub fn authorize_with_context(
|
|
||||||
&self,
|
|
||||||
tool_name: &str,
|
|
||||||
input: &str,
|
|
||||||
context: &PermissionContext,
|
|
||||||
prompter: Option<&mut dyn PermissionPrompter>,
|
|
||||||
) -> PermissionOutcome {
|
|
||||||
if let Some(rule) = Self::find_matching_rule(&self.deny_rules, tool_name, input) {
|
|
||||||
return PermissionOutcome::Deny {
|
|
||||||
reason: format!(
|
|
||||||
"Permission to use {tool_name} has been denied by rule '{}'",
|
|
||||||
rule.raw
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
||||||
let ask_rule = Self::find_matching_rule(&self.ask_rules, tool_name, input);
|
if current_mode == PermissionMode::Allow || current_mode >= required_mode {
|
||||||
let allow_rule = Self::find_matching_rule(&self.allow_rules, tool_name, input);
|
|
||||||
|
|
||||||
match context.override_decision() {
|
|
||||||
Some(PermissionOverride::Deny) => {
|
|
||||||
return PermissionOutcome::Deny {
|
|
||||||
reason: context.override_reason().map_or_else(
|
|
||||||
|| format!("tool '{tool_name}' denied by hook"),
|
|
||||||
ToOwned::to_owned,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Some(PermissionOverride::Ask) => {
|
|
||||||
let reason = context.override_reason().map_or_else(
|
|
||||||
|| format!("tool '{tool_name}' requires approval due to hook guidance"),
|
|
||||||
ToOwned::to_owned,
|
|
||||||
);
|
|
||||||
return Self::prompt_or_deny(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
current_mode,
|
|
||||||
required_mode,
|
|
||||||
Some(reason),
|
|
||||||
prompter,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Some(PermissionOverride::Allow) => {
|
|
||||||
if let Some(rule) = ask_rule {
|
|
||||||
let reason = format!(
|
|
||||||
"tool '{tool_name}' requires approval due to ask rule '{}'",
|
|
||||||
rule.raw
|
|
||||||
);
|
|
||||||
return Self::prompt_or_deny(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
current_mode,
|
|
||||||
required_mode,
|
|
||||||
Some(reason),
|
|
||||||
prompter,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if allow_rule.is_some()
|
|
||||||
|| current_mode == PermissionMode::Allow
|
|
||||||
|| current_mode >= required_mode
|
|
||||||
{
|
|
||||||
return PermissionOutcome::Allow;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(rule) = ask_rule {
|
|
||||||
let reason = format!(
|
|
||||||
"tool '{tool_name}' requires approval due to ask rule '{}'",
|
|
||||||
rule.raw
|
|
||||||
);
|
|
||||||
return Self::prompt_or_deny(
|
|
||||||
tool_name,
|
|
||||||
input,
|
|
||||||
current_mode,
|
|
||||||
required_mode,
|
|
||||||
Some(reason),
|
|
||||||
prompter,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if allow_rule.is_some()
|
|
||||||
|| current_mode == PermissionMode::Allow
|
|
||||||
|| current_mode >= required_mode
|
|
||||||
{
|
|
||||||
return PermissionOutcome::Allow;
|
return PermissionOutcome::Allow;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let request = PermissionRequest {
|
||||||
|
tool_name: tool_name.to_string(),
|
||||||
|
input: input.to_string(),
|
||||||
|
current_mode,
|
||||||
|
required_mode,
|
||||||
|
};
|
||||||
|
|
||||||
if current_mode == PermissionMode::Prompt
|
if current_mode == PermissionMode::Prompt
|
||||||
|| (current_mode == PermissionMode::WorkspaceWrite
|
|| (current_mode == PermissionMode::WorkspaceWrite
|
||||||
&& required_mode == PermissionMode::DangerFullAccess)
|
&& required_mode == PermissionMode::DangerFullAccess)
|
||||||
{
|
{
|
||||||
let reason = Some(format!(
|
return match prompter.as_mut() {
|
||||||
"tool '{tool_name}' requires approval to escalate from {} to {}",
|
Some(prompter) => match prompter.decide(&request) {
|
||||||
current_mode.as_str(),
|
PermissionPromptDecision::Allow => PermissionOutcome::Allow,
|
||||||
required_mode.as_str()
|
PermissionPromptDecision::Deny { reason } => PermissionOutcome::Deny { reason },
|
||||||
));
|
},
|
||||||
return Self::prompt_or_deny(
|
None => PermissionOutcome::Deny {
|
||||||
tool_name,
|
reason: format!(
|
||||||
input,
|
"tool '{tool_name}' requires approval to escalate from {} to {}",
|
||||||
current_mode,
|
current_mode.as_str(),
|
||||||
required_mode,
|
required_mode.as_str()
|
||||||
reason,
|
),
|
||||||
prompter,
|
},
|
||||||
);
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
PermissionOutcome::Deny {
|
PermissionOutcome::Deny {
|
||||||
@@ -282,191 +132,14 @@ impl PermissionPolicy {
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prompt_or_deny(
|
|
||||||
tool_name: &str,
|
|
||||||
input: &str,
|
|
||||||
current_mode: PermissionMode,
|
|
||||||
required_mode: PermissionMode,
|
|
||||||
reason: Option<String>,
|
|
||||||
mut prompter: Option<&mut dyn PermissionPrompter>,
|
|
||||||
) -> PermissionOutcome {
|
|
||||||
let request = PermissionRequest {
|
|
||||||
tool_name: tool_name.to_string(),
|
|
||||||
input: input.to_string(),
|
|
||||||
current_mode,
|
|
||||||
required_mode,
|
|
||||||
reason: reason.clone(),
|
|
||||||
};
|
|
||||||
|
|
||||||
match prompter.as_mut() {
|
|
||||||
Some(prompter) => match prompter.decide(&request) {
|
|
||||||
PermissionPromptDecision::Allow => PermissionOutcome::Allow,
|
|
||||||
PermissionPromptDecision::Deny { reason } => PermissionOutcome::Deny { reason },
|
|
||||||
},
|
|
||||||
None => PermissionOutcome::Deny {
|
|
||||||
reason: reason.unwrap_or_else(|| {
|
|
||||||
format!(
|
|
||||||
"tool '{tool_name}' requires approval to run while mode is {}",
|
|
||||||
current_mode.as_str()
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_matching_rule<'a>(
|
|
||||||
rules: &'a [PermissionRule],
|
|
||||||
tool_name: &str,
|
|
||||||
input: &str,
|
|
||||||
) -> Option<&'a PermissionRule> {
|
|
||||||
rules.iter().find(|rule| rule.matches(tool_name, input))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
struct PermissionRule {
|
|
||||||
raw: String,
|
|
||||||
tool_name: String,
|
|
||||||
matcher: PermissionRuleMatcher,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
enum PermissionRuleMatcher {
|
|
||||||
Any,
|
|
||||||
Exact(String),
|
|
||||||
Prefix(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PermissionRule {
|
|
||||||
fn parse(raw: &str) -> Self {
|
|
||||||
let trimmed = raw.trim();
|
|
||||||
let open = find_first_unescaped(trimmed, '(');
|
|
||||||
let close = find_last_unescaped(trimmed, ')');
|
|
||||||
|
|
||||||
if let (Some(open), Some(close)) = (open, close) {
|
|
||||||
if close == trimmed.len() - 1 && open < close {
|
|
||||||
let tool_name = trimmed[..open].trim();
|
|
||||||
let content = &trimmed[open + 1..close];
|
|
||||||
if !tool_name.is_empty() {
|
|
||||||
let matcher = parse_rule_matcher(content);
|
|
||||||
return Self {
|
|
||||||
raw: trimmed.to_string(),
|
|
||||||
tool_name: tool_name.to_string(),
|
|
||||||
matcher,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Self {
|
|
||||||
raw: trimmed.to_string(),
|
|
||||||
tool_name: trimmed.to_string(),
|
|
||||||
matcher: PermissionRuleMatcher::Any,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn matches(&self, tool_name: &str, input: &str) -> bool {
|
|
||||||
if self.tool_name != tool_name {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
match &self.matcher {
|
|
||||||
PermissionRuleMatcher::Any => true,
|
|
||||||
PermissionRuleMatcher::Exact(expected) => {
|
|
||||||
extract_permission_subject(input).is_some_and(|candidate| candidate == *expected)
|
|
||||||
}
|
|
||||||
PermissionRuleMatcher::Prefix(prefix) => extract_permission_subject(input)
|
|
||||||
.is_some_and(|candidate| candidate.starts_with(prefix)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_rule_matcher(content: &str) -> PermissionRuleMatcher {
|
|
||||||
let unescaped = unescape_rule_content(content.trim());
|
|
||||||
if unescaped.is_empty() || unescaped == "*" {
|
|
||||||
PermissionRuleMatcher::Any
|
|
||||||
} else if let Some(prefix) = unescaped.strip_suffix(":*") {
|
|
||||||
PermissionRuleMatcher::Prefix(prefix.to_string())
|
|
||||||
} else {
|
|
||||||
PermissionRuleMatcher::Exact(unescaped)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unescape_rule_content(content: &str) -> String {
|
|
||||||
content
|
|
||||||
.replace(r"\(", "(")
|
|
||||||
.replace(r"\)", ")")
|
|
||||||
.replace(r"\\", r"\")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_first_unescaped(value: &str, needle: char) -> Option<usize> {
|
|
||||||
let mut escaped = false;
|
|
||||||
for (idx, ch) in value.char_indices() {
|
|
||||||
if ch == '\\' {
|
|
||||||
escaped = !escaped;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if ch == needle && !escaped {
|
|
||||||
return Some(idx);
|
|
||||||
}
|
|
||||||
escaped = false;
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_last_unescaped(value: &str, needle: char) -> Option<usize> {
|
|
||||||
let chars = value.char_indices().collect::<Vec<_>>();
|
|
||||||
for (pos, (idx, ch)) in chars.iter().enumerate().rev() {
|
|
||||||
if *ch != needle {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let mut backslashes = 0;
|
|
||||||
for (_, prev) in chars[..pos].iter().rev() {
|
|
||||||
if *prev == '\\' {
|
|
||||||
backslashes += 1;
|
|
||||||
} else {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if backslashes % 2 == 0 {
|
|
||||||
return Some(*idx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn extract_permission_subject(input: &str) -> Option<String> {
|
|
||||||
let parsed = serde_json::from_str::<Value>(input).ok();
|
|
||||||
if let Some(Value::Object(object)) = parsed {
|
|
||||||
for key in [
|
|
||||||
"command",
|
|
||||||
"path",
|
|
||||||
"file_path",
|
|
||||||
"filePath",
|
|
||||||
"notebook_path",
|
|
||||||
"notebookPath",
|
|
||||||
"url",
|
|
||||||
"pattern",
|
|
||||||
"code",
|
|
||||||
"message",
|
|
||||||
] {
|
|
||||||
if let Some(value) = object.get(key).and_then(Value::as_str) {
|
|
||||||
return Some(value.to_string());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(!input.trim().is_empty()).then(|| input.to_string())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
PermissionContext, PermissionMode, PermissionOutcome, PermissionOverride, PermissionPolicy,
|
PermissionMode, PermissionOutcome, PermissionPolicy, PermissionPromptDecision,
|
||||||
PermissionPromptDecision, PermissionPrompter, PermissionRequest,
|
PermissionPrompter, PermissionRequest,
|
||||||
};
|
};
|
||||||
use crate::config::RuntimePermissionRuleConfig;
|
|
||||||
|
|
||||||
struct RecordingPrompter {
|
struct RecordingPrompter {
|
||||||
seen: Vec<PermissionRequest>,
|
seen: Vec<PermissionRequest>,
|
||||||
@@ -556,120 +229,4 @@ mod tests {
|
|||||||
PermissionOutcome::Deny { reason } if reason == "not now"
|
PermissionOutcome::Deny { reason } if reason == "not now"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn applies_rule_based_denials_and_allows() {
|
|
||||||
let rules = RuntimePermissionRuleConfig::new(
|
|
||||||
vec!["bash(git:*)".to_string()],
|
|
||||||
vec!["bash(rm -rf:*)".to_string()],
|
|
||||||
Vec::new(),
|
|
||||||
);
|
|
||||||
let policy = PermissionPolicy::new(PermissionMode::ReadOnly)
|
|
||||||
.with_tool_requirement("bash", PermissionMode::DangerFullAccess)
|
|
||||||
.with_permission_rules(&rules);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
policy.authorize("bash", r#"{"command":"git status"}"#, None),
|
|
||||||
PermissionOutcome::Allow
|
|
||||||
);
|
|
||||||
assert!(matches!(
|
|
||||||
policy.authorize("bash", r#"{"command":"rm -rf /tmp/x"}"#, None),
|
|
||||||
PermissionOutcome::Deny { reason } if reason.contains("denied by rule")
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn ask_rules_force_prompt_even_when_mode_allows() {
|
|
||||||
let rules = RuntimePermissionRuleConfig::new(
|
|
||||||
Vec::new(),
|
|
||||||
Vec::new(),
|
|
||||||
vec!["bash(git:*)".to_string()],
|
|
||||||
);
|
|
||||||
let policy = PermissionPolicy::new(PermissionMode::DangerFullAccess)
|
|
||||||
.with_tool_requirement("bash", PermissionMode::DangerFullAccess)
|
|
||||||
.with_permission_rules(&rules);
|
|
||||||
let mut prompter = RecordingPrompter {
|
|
||||||
seen: Vec::new(),
|
|
||||||
allow: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let outcome = policy.authorize("bash", r#"{"command":"git status"}"#, Some(&mut prompter));
|
|
||||||
|
|
||||||
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
||||||
assert_eq!(prompter.seen.len(), 1);
|
|
||||||
assert!(prompter.seen[0]
|
|
||||||
.reason
|
|
||||||
.as_deref()
|
|
||||||
.is_some_and(|reason| reason.contains("ask rule")));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hook_allow_still_respects_ask_rules() {
|
|
||||||
let rules = RuntimePermissionRuleConfig::new(
|
|
||||||
Vec::new(),
|
|
||||||
Vec::new(),
|
|
||||||
vec!["bash(git:*)".to_string()],
|
|
||||||
);
|
|
||||||
let policy = PermissionPolicy::new(PermissionMode::ReadOnly)
|
|
||||||
.with_tool_requirement("bash", PermissionMode::DangerFullAccess)
|
|
||||||
.with_permission_rules(&rules);
|
|
||||||
let context = PermissionContext::new(
|
|
||||||
Some(PermissionOverride::Allow),
|
|
||||||
Some("hook approved".to_string()),
|
|
||||||
);
|
|
||||||
let mut prompter = RecordingPrompter {
|
|
||||||
seen: Vec::new(),
|
|
||||||
allow: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let outcome = policy.authorize_with_context(
|
|
||||||
"bash",
|
|
||||||
r#"{"command":"git status"}"#,
|
|
||||||
&context,
|
|
||||||
Some(&mut prompter),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
||||||
assert_eq!(prompter.seen.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hook_deny_short_circuits_permission_flow() {
|
|
||||||
let policy = PermissionPolicy::new(PermissionMode::DangerFullAccess)
|
|
||||||
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
||||||
let context = PermissionContext::new(
|
|
||||||
Some(PermissionOverride::Deny),
|
|
||||||
Some("blocked by hook".to_string()),
|
|
||||||
);
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
policy.authorize_with_context("bash", "{}", &context, None),
|
|
||||||
PermissionOutcome::Deny {
|
|
||||||
reason: "blocked by hook".to_string(),
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hook_ask_forces_prompt() {
|
|
||||||
let policy = PermissionPolicy::new(PermissionMode::DangerFullAccess)
|
|
||||||
.with_tool_requirement("bash", PermissionMode::DangerFullAccess);
|
|
||||||
let context = PermissionContext::new(
|
|
||||||
Some(PermissionOverride::Ask),
|
|
||||||
Some("hook requested confirmation".to_string()),
|
|
||||||
);
|
|
||||||
let mut prompter = RecordingPrompter {
|
|
||||||
seen: Vec::new(),
|
|
||||||
allow: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
let outcome = policy.authorize_with_context("bash", "{}", &context, Some(&mut prompter));
|
|
||||||
|
|
||||||
assert_eq!(outcome, PermissionOutcome::Allow);
|
|
||||||
assert_eq!(prompter.seen.len(), 1);
|
|
||||||
assert_eq!(
|
|
||||||
prompter.seen[0].reason.as_deref(),
|
|
||||||
Some("hook requested confirmation")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -203,8 +203,8 @@ fn discover_instruction_files(cwd: &Path) -> std::io::Result<Vec<ContextFile>> {
|
|||||||
for candidate in [
|
for candidate in [
|
||||||
dir.join("CLAUDE.md"),
|
dir.join("CLAUDE.md"),
|
||||||
dir.join("CLAUDE.local.md"),
|
dir.join("CLAUDE.local.md"),
|
||||||
dir.join(".claude").join("CLAUDE.md"),
|
dir.join(".claw").join("CLAUDE.md"),
|
||||||
dir.join(".claude").join("instructions.md"),
|
dir.join(".claw").join("instructions.md"),
|
||||||
] {
|
] {
|
||||||
push_context_file(&mut files, candidate)?;
|
push_context_file(&mut files, candidate)?;
|
||||||
}
|
}
|
||||||
@@ -517,23 +517,23 @@ mod tests {
|
|||||||
fn discovers_instruction_files_from_ancestor_chain() {
|
fn discovers_instruction_files_from_ancestor_chain() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let nested = root.join("apps").join("api");
|
let nested = root.join("apps").join("api");
|
||||||
fs::create_dir_all(nested.join(".claude")).expect("nested claude dir");
|
fs::create_dir_all(nested.join(".claw")).expect("nested claw dir");
|
||||||
fs::write(root.join("CLAUDE.md"), "root instructions").expect("write root instructions");
|
fs::write(root.join("CLAUDE.md"), "root instructions").expect("write root instructions");
|
||||||
fs::write(root.join("CLAUDE.local.md"), "local instructions")
|
fs::write(root.join("CLAUDE.local.md"), "local instructions")
|
||||||
.expect("write local instructions");
|
.expect("write local instructions");
|
||||||
fs::create_dir_all(root.join("apps")).expect("apps dir");
|
fs::create_dir_all(root.join("apps")).expect("apps dir");
|
||||||
fs::create_dir_all(root.join("apps").join(".claude")).expect("apps claude dir");
|
fs::create_dir_all(root.join("apps").join(".claw")).expect("apps claw dir");
|
||||||
fs::write(root.join("apps").join("CLAUDE.md"), "apps instructions")
|
fs::write(root.join("apps").join("CLAUDE.md"), "apps instructions")
|
||||||
.expect("write apps instructions");
|
.expect("write apps instructions");
|
||||||
fs::write(
|
fs::write(
|
||||||
root.join("apps").join(".claude").join("instructions.md"),
|
root.join("apps").join(".claw").join("instructions.md"),
|
||||||
"apps dot claude instructions",
|
"apps dot claude instructions",
|
||||||
)
|
)
|
||||||
.expect("write apps dot claude instructions");
|
.expect("write apps dot claude instructions");
|
||||||
fs::write(nested.join(".claude").join("CLAUDE.md"), "nested rules")
|
fs::write(nested.join(".claw").join("CLAUDE.md"), "nested rules")
|
||||||
.expect("write nested rules");
|
.expect("write nested rules");
|
||||||
fs::write(
|
fs::write(
|
||||||
nested.join(".claude").join("instructions.md"),
|
nested.join(".claw").join("instructions.md"),
|
||||||
"nested instructions",
|
"nested instructions",
|
||||||
)
|
)
|
||||||
.expect("write nested instructions");
|
.expect("write nested instructions");
|
||||||
@@ -593,13 +593,14 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn displays_context_paths_compactly() {
|
fn displays_context_paths_compactly() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
display_context_path(Path::new("/tmp/project/.claude/CLAUDE.md")),
|
display_context_path(Path::new("/tmp/project/.claw/CLAUDE.md")),
|
||||||
"CLAUDE.md"
|
"CLAUDE.md"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn discover_with_git_includes_status_snapshot() {
|
fn discover_with_git_includes_status_snapshot() {
|
||||||
|
let _guard = env_lock();
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
fs::create_dir_all(&root).expect("root dir");
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
std::process::Command::new("git")
|
std::process::Command::new("git")
|
||||||
@@ -624,6 +625,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn discover_with_git_includes_diff_snapshot_for_tracked_changes() {
|
fn discover_with_git_includes_diff_snapshot_for_tracked_changes() {
|
||||||
|
let _guard = env_lock();
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
fs::create_dir_all(&root).expect("root dir");
|
fs::create_dir_all(&root).expect("root dir");
|
||||||
std::process::Command::new("git")
|
std::process::Command::new("git")
|
||||||
@@ -667,10 +669,10 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn load_system_prompt_reads_claude_files_and_config() {
|
fn load_system_prompt_reads_claude_files_and_config() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
fs::create_dir_all(root.join(".claude")).expect("claude dir");
|
fs::create_dir_all(root.join(".claw")).expect("claw dir");
|
||||||
fs::write(root.join("CLAUDE.md"), "Project rules").expect("write instructions");
|
fs::write(root.join("CLAUDE.md"), "Project rules").expect("write instructions");
|
||||||
fs::write(
|
fs::write(
|
||||||
root.join(".claude").join("settings.json"),
|
root.join(".claw").join("settings.json"),
|
||||||
r#"{"permissionMode":"acceptEdits"}"#,
|
r#"{"permissionMode":"acceptEdits"}"#,
|
||||||
)
|
)
|
||||||
.expect("write settings");
|
.expect("write settings");
|
||||||
@@ -678,9 +680,9 @@ mod tests {
|
|||||||
let _guard = env_lock();
|
let _guard = env_lock();
|
||||||
let previous = std::env::current_dir().expect("cwd");
|
let previous = std::env::current_dir().expect("cwd");
|
||||||
let original_home = std::env::var("HOME").ok();
|
let original_home = std::env::var("HOME").ok();
|
||||||
let original_claude_home = std::env::var("CLAUDE_CONFIG_HOME").ok();
|
let original_claw_home = std::env::var("CLAW_CONFIG_HOME").ok();
|
||||||
std::env::set_var("HOME", &root);
|
std::env::set_var("HOME", &root);
|
||||||
std::env::set_var("CLAUDE_CONFIG_HOME", root.join("missing-home"));
|
std::env::set_var("CLAW_CONFIG_HOME", root.join("missing-home"));
|
||||||
std::env::set_current_dir(&root).expect("change cwd");
|
std::env::set_current_dir(&root).expect("change cwd");
|
||||||
let prompt = super::load_system_prompt(&root, "2026-03-31", "linux", "6.8")
|
let prompt = super::load_system_prompt(&root, "2026-03-31", "linux", "6.8")
|
||||||
.expect("system prompt should load")
|
.expect("system prompt should load")
|
||||||
@@ -695,10 +697,10 @@ mod tests {
|
|||||||
} else {
|
} else {
|
||||||
std::env::remove_var("HOME");
|
std::env::remove_var("HOME");
|
||||||
}
|
}
|
||||||
if let Some(value) = original_claude_home {
|
if let Some(value) = original_claw_home {
|
||||||
std::env::set_var("CLAUDE_CONFIG_HOME", value);
|
std::env::set_var("CLAW_CONFIG_HOME", value);
|
||||||
} else {
|
} else {
|
||||||
std::env::remove_var("CLAUDE_CONFIG_HOME");
|
std::env::remove_var("CLAW_CONFIG_HOME");
|
||||||
}
|
}
|
||||||
|
|
||||||
assert!(prompt.contains("Project rules"));
|
assert!(prompt.contains("Project rules"));
|
||||||
@@ -709,10 +711,10 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn renders_claude_code_style_sections_with_project_context() {
|
fn renders_claude_code_style_sections_with_project_context() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
fs::create_dir_all(root.join(".claude")).expect("claude dir");
|
fs::create_dir_all(root.join(".claw")).expect("claw dir");
|
||||||
fs::write(root.join("CLAUDE.md"), "Project rules").expect("write CLAUDE.md");
|
fs::write(root.join("CLAUDE.md"), "Project rules").expect("write CLAUDE.md");
|
||||||
fs::write(
|
fs::write(
|
||||||
root.join(".claude").join("settings.json"),
|
root.join(".claw").join("settings.json"),
|
||||||
r#"{"permissionMode":"acceptEdits"}"#,
|
r#"{"permissionMode":"acceptEdits"}"#,
|
||||||
)
|
)
|
||||||
.expect("write settings");
|
.expect("write settings");
|
||||||
@@ -751,9 +753,9 @@ mod tests {
|
|||||||
fn discovers_dot_claude_instructions_markdown() {
|
fn discovers_dot_claude_instructions_markdown() {
|
||||||
let root = temp_dir();
|
let root = temp_dir();
|
||||||
let nested = root.join("apps").join("api");
|
let nested = root.join("apps").join("api");
|
||||||
fs::create_dir_all(nested.join(".claude")).expect("nested claude dir");
|
fs::create_dir_all(nested.join(".claw")).expect("nested claw dir");
|
||||||
fs::write(
|
fs::write(
|
||||||
nested.join(".claude").join("instructions.md"),
|
nested.join(".claw").join("instructions.md"),
|
||||||
"instruction markdown",
|
"instruction markdown",
|
||||||
)
|
)
|
||||||
.expect("write instructions.md");
|
.expect("write instructions.md");
|
||||||
@@ -762,7 +764,7 @@ mod tests {
|
|||||||
assert!(context
|
assert!(context
|
||||||
.instruction_files
|
.instruction_files
|
||||||
.iter()
|
.iter()
|
||||||
.any(|file| file.path.ends_with(".claude/instructions.md")));
|
.any(|file| file.path.ends_with(".claw/instructions.md")));
|
||||||
assert!(
|
assert!(
|
||||||
render_instruction_files(&context.instruction_files).contains("instruction markdown")
|
render_instruction_files(&context.instruction_files).contains("instruction markdown")
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ pulldown-cmark = "0.13"
|
|||||||
rustyline = "15"
|
rustyline = "15"
|
||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
plugins = { path = "../plugins" }
|
plugins = { path = "../plugins" }
|
||||||
serde_json = "1"
|
serde_json.workspace = true
|
||||||
syntect = "5"
|
syntect = "5"
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "signal", "time"] }
|
tokio = { version = "1", features = ["rt-multi-thread", "time"] }
|
||||||
tools = { path = "../tools" }
|
tools = { path = "../tools" }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ use std::io::{self, Read, Write};
|
|||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::Command;
|
use std::process::Command;
|
||||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
|
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::thread::{self, JoinHandle};
|
use std::thread;
|
||||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use api::{
|
use api::{
|
||||||
@@ -22,12 +22,12 @@ use api::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use commands::{
|
use commands::{
|
||||||
handle_plugins_slash_command, render_slash_command_help, resume_supported_slash_commands,
|
handle_agents_slash_command, handle_plugins_slash_command, handle_skills_slash_command,
|
||||||
slash_command_specs, SlashCommand,
|
render_slash_command_help, resume_supported_slash_commands, slash_command_specs, SlashCommand,
|
||||||
};
|
};
|
||||||
use compat_harness::{extract_manifest, UpstreamPaths};
|
use compat_harness::{extract_manifest, UpstreamPaths};
|
||||||
use init::initialize_repo;
|
use init::initialize_repo;
|
||||||
use plugins::{PluginManager, PluginManagerConfig, PluginRegistry};
|
use plugins::{PluginManager, PluginManagerConfig};
|
||||||
use render::{MarkdownStreamState, Spinner, TerminalRenderer};
|
use render::{MarkdownStreamState, 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,
|
||||||
@@ -73,6 +73,8 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
match parse_args(&args)? {
|
match parse_args(&args)? {
|
||||||
CliAction::DumpManifests => dump_manifests(),
|
CliAction::DumpManifests => dump_manifests(),
|
||||||
CliAction::BootstrapPlan => print_bootstrap_plan(),
|
CliAction::BootstrapPlan => print_bootstrap_plan(),
|
||||||
|
CliAction::Agents { args } => LiveCli::print_agents(args.as_deref())?,
|
||||||
|
CliAction::Skills { args } => LiveCli::print_skills(args.as_deref())?,
|
||||||
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
|
CliAction::PrintSystemPrompt { cwd, date } => print_system_prompt(cwd, date),
|
||||||
CliAction::Version => print_version(),
|
CliAction::Version => print_version(),
|
||||||
CliAction::ResumeSession {
|
CliAction::ResumeSession {
|
||||||
@@ -104,6 +106,12 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
enum CliAction {
|
enum CliAction {
|
||||||
DumpManifests,
|
DumpManifests,
|
||||||
BootstrapPlan,
|
BootstrapPlan,
|
||||||
|
Agents {
|
||||||
|
args: Option<String>,
|
||||||
|
},
|
||||||
|
Skills {
|
||||||
|
args: Option<String>,
|
||||||
|
},
|
||||||
PrintSystemPrompt {
|
PrintSystemPrompt {
|
||||||
cwd: PathBuf,
|
cwd: PathBuf,
|
||||||
date: String,
|
date: String,
|
||||||
@@ -267,6 +275,12 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
match rest[0].as_str() {
|
match rest[0].as_str() {
|
||||||
"dump-manifests" => Ok(CliAction::DumpManifests),
|
"dump-manifests" => Ok(CliAction::DumpManifests),
|
||||||
"bootstrap-plan" => Ok(CliAction::BootstrapPlan),
|
"bootstrap-plan" => Ok(CliAction::BootstrapPlan),
|
||||||
|
"agents" => Ok(CliAction::Agents {
|
||||||
|
args: join_optional_args(&rest[1..]),
|
||||||
|
}),
|
||||||
|
"skills" => Ok(CliAction::Skills {
|
||||||
|
args: join_optional_args(&rest[1..]),
|
||||||
|
}),
|
||||||
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
"system-prompt" => parse_system_prompt_args(&rest[1..]),
|
||||||
"login" => Ok(CliAction::Login),
|
"login" => Ok(CliAction::Login),
|
||||||
"logout" => Ok(CliAction::Logout),
|
"logout" => Ok(CliAction::Logout),
|
||||||
@@ -284,14 +298,37 @@ fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||||||
permission_mode,
|
permission_mode,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
other if !other.starts_with('/') => Ok(CliAction::Prompt {
|
other if other.starts_with('/') => parse_direct_slash_cli_action(&rest),
|
||||||
|
_other => Ok(CliAction::Prompt {
|
||||||
prompt: rest.join(" "),
|
prompt: rest.join(" "),
|
||||||
model,
|
model,
|
||||||
output_format,
|
output_format,
|
||||||
allowed_tools,
|
allowed_tools,
|
||||||
permission_mode,
|
permission_mode,
|
||||||
}),
|
}),
|
||||||
other => Err(format!("unknown subcommand: {other}")),
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn join_optional_args(args: &[String]) -> Option<String> {
|
||||||
|
let joined = args.join(" ");
|
||||||
|
let trimmed = joined.trim();
|
||||||
|
(!trimmed.is_empty()).then(|| trimmed.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_direct_slash_cli_action(rest: &[String]) -> Result<CliAction, String> {
|
||||||
|
let raw = rest.join(" ");
|
||||||
|
match SlashCommand::parse(&raw) {
|
||||||
|
Some(SlashCommand::Help) => Ok(CliAction::Help),
|
||||||
|
Some(SlashCommand::Agents { args }) => Ok(CliAction::Agents { args }),
|
||||||
|
Some(SlashCommand::Skills { args }) => Ok(CliAction::Skills { args }),
|
||||||
|
Some(command) => Err(format!(
|
||||||
|
"unsupported direct slash command outside the REPL: {command_name}",
|
||||||
|
command_name = match command {
|
||||||
|
SlashCommand::Unknown(name) => format!("/{name}"),
|
||||||
|
_ => rest[0].clone(),
|
||||||
|
}
|
||||||
|
)),
|
||||||
|
None => Err(format!("unknown subcommand: {}", rest[0])),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -749,10 +786,6 @@ fn format_compact_report(removed: usize, resulting_messages: usize, skipped: boo
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn format_auto_compaction_notice(removed: usize) -> String {
|
|
||||||
format!("[auto-compacted: removed {removed} messages]")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
|
fn parse_git_status_metadata(status: Option<&str>) -> (Option<PathBuf>, Option<String>) {
|
||||||
let Some(status) = status else {
|
let Some(status) = status else {
|
||||||
return (None, None);
|
return (None, None);
|
||||||
@@ -891,6 +924,20 @@ fn run_resume_command(
|
|||||||
)),
|
)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
SlashCommand::Agents { args } => {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
Ok(ResumeCommandOutcome {
|
||||||
|
session: session.clone(),
|
||||||
|
message: Some(handle_agents_slash_command(args.as_deref(), &cwd)?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
SlashCommand::Skills { args } => {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
Ok(ResumeCommandOutcome {
|
||||||
|
session: session.clone(),
|
||||||
|
message: Some(handle_skills_slash_command(args.as_deref(), &cwd)?),
|
||||||
|
})
|
||||||
|
}
|
||||||
SlashCommand::Bughunter { .. }
|
SlashCommand::Bughunter { .. }
|
||||||
| SlashCommand::Commit
|
| SlashCommand::Commit
|
||||||
| SlashCommand::Pr { .. }
|
| SlashCommand::Pr { .. }
|
||||||
@@ -903,8 +950,6 @@ fn run_resume_command(
|
|||||||
| SlashCommand::Permissions { .. }
|
| SlashCommand::Permissions { .. }
|
||||||
| SlashCommand::Session { .. }
|
| SlashCommand::Session { .. }
|
||||||
| SlashCommand::Plugins { .. }
|
| SlashCommand::Plugins { .. }
|
||||||
| SlashCommand::Agents { .. }
|
|
||||||
| SlashCommand::Skills { .. }
|
|
||||||
| SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
|
| SlashCommand::Unknown(_) => Err("unsupported resumed slash command".into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -972,61 +1017,6 @@ struct LiveCli {
|
|||||||
session: SessionHandle,
|
session: SessionHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct HookAbortMonitor {
|
|
||||||
stop_tx: Option<Sender<()>>,
|
|
||||||
join_handle: Option<JoinHandle<()>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl HookAbortMonitor {
|
|
||||||
fn spawn(abort_signal: runtime::HookAbortSignal) -> Self {
|
|
||||||
Self::spawn_with_waiter(abort_signal, move |stop_rx, abort_signal| {
|
|
||||||
let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
|
|
||||||
.enable_all()
|
|
||||||
.build()
|
|
||||||
else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
runtime.block_on(async move {
|
|
||||||
let wait_for_stop = tokio::task::spawn_blocking(move || {
|
|
||||||
let _ = stop_rx.recv();
|
|
||||||
});
|
|
||||||
|
|
||||||
tokio::select! {
|
|
||||||
result = tokio::signal::ctrl_c() => {
|
|
||||||
if result.is_ok() {
|
|
||||||
abort_signal.abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = wait_for_stop => {}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn spawn_with_waiter<F>(abort_signal: runtime::HookAbortSignal, wait_for_interrupt: F) -> Self
|
|
||||||
where
|
|
||||||
F: FnOnce(Receiver<()>, runtime::HookAbortSignal) + Send + 'static,
|
|
||||||
{
|
|
||||||
let (stop_tx, stop_rx) = mpsc::channel();
|
|
||||||
let join_handle = thread::spawn(move || wait_for_interrupt(stop_rx, abort_signal));
|
|
||||||
|
|
||||||
Self {
|
|
||||||
stop_tx: Some(stop_tx),
|
|
||||||
join_handle: Some(join_handle),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stop(mut self) {
|
|
||||||
if let Some(stop_tx) = self.stop_tx.take() {
|
|
||||||
let _ = stop_tx.send(());
|
|
||||||
}
|
|
||||||
if let Some(join_handle) = self.join_handle.take() {
|
|
||||||
let _ = join_handle.join();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LiveCli {
|
impl LiveCli {
|
||||||
fn new(
|
fn new(
|
||||||
model: String,
|
model: String,
|
||||||
@@ -1083,35 +1073,7 @@ impl LiveCli {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prepare_turn_runtime(
|
|
||||||
&self,
|
|
||||||
emit_output: bool,
|
|
||||||
) -> Result<
|
|
||||||
(
|
|
||||||
ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>,
|
|
||||||
HookAbortMonitor,
|
|
||||||
),
|
|
||||||
Box<dyn std::error::Error>,
|
|
||||||
> {
|
|
||||||
let hook_abort_signal = runtime::HookAbortSignal::new();
|
|
||||||
let runtime = build_runtime(
|
|
||||||
self.runtime.session().clone(),
|
|
||||||
self.model.clone(),
|
|
||||||
self.system_prompt.clone(),
|
|
||||||
true,
|
|
||||||
emit_output,
|
|
||||||
self.allowed_tools.clone(),
|
|
||||||
self.permission_mode,
|
|
||||||
None,
|
|
||||||
)?
|
|
||||||
.with_hook_abort_signal(hook_abort_signal.clone());
|
|
||||||
let hook_abort_monitor = HookAbortMonitor::spawn(hook_abort_signal);
|
|
||||||
|
|
||||||
Ok((runtime, hook_abort_monitor))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
|
fn run_turn(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let (mut runtime, hook_abort_monitor) = self.prepare_turn_runtime(true)?;
|
|
||||||
let mut spinner = Spinner::new();
|
let mut spinner = Spinner::new();
|
||||||
let mut stdout = io::stdout();
|
let mut stdout = io::stdout();
|
||||||
spinner.tick(
|
spinner.tick(
|
||||||
@@ -1120,23 +1082,15 @@ impl LiveCli {
|
|||||||
&mut stdout,
|
&mut stdout,
|
||||||
)?;
|
)?;
|
||||||
let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
|
let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
|
||||||
let result = runtime.run_turn(input, Some(&mut permission_prompter));
|
let result = self.runtime.run_turn(input, Some(&mut permission_prompter));
|
||||||
hook_abort_monitor.stop();
|
|
||||||
self.runtime = runtime;
|
|
||||||
match result {
|
match result {
|
||||||
Ok(summary) => {
|
Ok(_) => {
|
||||||
spinner.finish(
|
spinner.finish(
|
||||||
"✨ Done",
|
"✨ Done",
|
||||||
TerminalRenderer::new().color_theme(),
|
TerminalRenderer::new().color_theme(),
|
||||||
&mut stdout,
|
&mut stdout,
|
||||||
)?;
|
)?;
|
||||||
println!();
|
println!();
|
||||||
if let Some(event) = summary.auto_compaction {
|
|
||||||
println!(
|
|
||||||
"{}",
|
|
||||||
format_auto_compaction_notice(event.removed_message_count)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
self.persist_session()?;
|
self.persist_session()?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -1163,11 +1117,19 @@ impl LiveCli {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
|
fn run_prompt_json(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let (mut runtime, hook_abort_monitor) = self.prepare_turn_runtime(false)?;
|
let session = self.runtime.session().clone();
|
||||||
|
let mut runtime = build_runtime(
|
||||||
|
session,
|
||||||
|
self.model.clone(),
|
||||||
|
self.system_prompt.clone(),
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
self.allowed_tools.clone(),
|
||||||
|
self.permission_mode,
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
|
let mut permission_prompter = CliPermissionPrompter::new(self.permission_mode);
|
||||||
let result = runtime.run_turn(input, Some(&mut permission_prompter));
|
let summary = runtime.run_turn(input, Some(&mut permission_prompter))?;
|
||||||
hook_abort_monitor.stop();
|
|
||||||
let summary = result?;
|
|
||||||
self.runtime = runtime;
|
self.runtime = runtime;
|
||||||
self.persist_session()?;
|
self.persist_session()?;
|
||||||
println!(
|
println!(
|
||||||
@@ -1176,10 +1138,6 @@ impl LiveCli {
|
|||||||
"message": final_assistant_text(&summary),
|
"message": final_assistant_text(&summary),
|
||||||
"model": self.model,
|
"model": self.model,
|
||||||
"iterations": summary.iterations,
|
"iterations": summary.iterations,
|
||||||
"auto_compaction": summary.auto_compaction.map(|event| json!({
|
|
||||||
"removed_messages": event.removed_message_count,
|
|
||||||
"notice": format_auto_compaction_notice(event.removed_message_count),
|
|
||||||
})),
|
|
||||||
"tool_uses": collect_tool_uses(&summary),
|
"tool_uses": collect_tool_uses(&summary),
|
||||||
"tool_results": collect_tool_results(&summary),
|
"tool_results": collect_tool_results(&summary),
|
||||||
"usage": {
|
"usage": {
|
||||||
@@ -1276,12 +1234,12 @@ impl LiveCli {
|
|||||||
SlashCommand::Plugins { action, target } => {
|
SlashCommand::Plugins { action, target } => {
|
||||||
self.handle_plugins_command(action.as_deref(), target.as_deref())?
|
self.handle_plugins_command(action.as_deref(), target.as_deref())?
|
||||||
}
|
}
|
||||||
SlashCommand::Agents { .. } => {
|
SlashCommand::Agents { args } => {
|
||||||
eprintln!("/agents is not fully wired yet");
|
Self::print_agents(args.as_deref())?;
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Skills { .. } => {
|
SlashCommand::Skills { args } => {
|
||||||
eprintln!("/skills is not fully wired yet");
|
Self::print_skills(args.as_deref())?;
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
SlashCommand::Unknown(name) => {
|
SlashCommand::Unknown(name) => {
|
||||||
@@ -1484,6 +1442,18 @@ impl LiveCli {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn print_agents(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
println!("{}", handle_agents_slash_command(args, &cwd)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn print_skills(args: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
let cwd = env::current_dir()?;
|
||||||
|
println!("{}", handle_skills_slash_command(args, &cwd)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
|
fn print_diff() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("{}", render_diff_report()?);
|
println!("{}", render_diff_report()?);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -1781,7 +1751,7 @@ 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 cwd = env::current_dir()?;
|
||||||
let path = cwd.join(".claude").join("sessions");
|
let path = cwd.join(".claw").join("sessions");
|
||||||
fs::create_dir_all(&path)?;
|
fs::create_dir_all(&path)?;
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
@@ -2435,25 +2405,14 @@ fn build_system_prompt() -> Result<Vec<String>, Box<dyn std::error::Error>> {
|
|||||||
)?)
|
)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_runtime_plugin_state() -> Result<
|
fn build_runtime_plugin_state(
|
||||||
(
|
) -> Result<(runtime::RuntimeFeatureConfig, GlobalToolRegistry), Box<dyn std::error::Error>> {
|
||||||
runtime::RuntimeFeatureConfig,
|
|
||||||
PluginRegistry,
|
|
||||||
GlobalToolRegistry,
|
|
||||||
),
|
|
||||||
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);
|
||||||
let runtime_config = loader.load()?;
|
let runtime_config = loader.load()?;
|
||||||
let plugin_manager = build_plugin_manager(&cwd, &loader, &runtime_config);
|
let plugin_manager = build_plugin_manager(&cwd, &loader, &runtime_config);
|
||||||
let plugin_registry = plugin_manager.plugin_registry()?;
|
let tool_registry = GlobalToolRegistry::with_plugin_tools(plugin_manager.aggregated_tools()?)?;
|
||||||
let tool_registry = GlobalToolRegistry::with_plugin_tools(plugin_registry.aggregated_tools()?)?;
|
Ok((runtime_config.feature_config().clone(), tool_registry))
|
||||||
Ok((
|
|
||||||
runtime_config.feature_config().clone(),
|
|
||||||
plugin_registry,
|
|
||||||
tool_registry,
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_plugin_manager(
|
fn build_plugin_manager(
|
||||||
@@ -2821,6 +2780,7 @@ fn describe_tool_progress(name: &str, input: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::needless_pass_by_value)]
|
#[allow(clippy::needless_pass_by_value)]
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn build_runtime(
|
fn build_runtime(
|
||||||
session: Session,
|
session: Session,
|
||||||
model: String,
|
model: String,
|
||||||
@@ -2830,10 +2790,9 @@ fn build_runtime(
|
|||||||
allowed_tools: Option<AllowedToolSet>,
|
allowed_tools: Option<AllowedToolSet>,
|
||||||
permission_mode: PermissionMode,
|
permission_mode: PermissionMode,
|
||||||
progress_reporter: Option<InternalPromptProgressReporter>,
|
progress_reporter: Option<InternalPromptProgressReporter>,
|
||||||
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>>
|
) -> Result<ConversationRuntime<AnthropicRuntimeClient, CliToolExecutor>, Box<dyn std::error::Error>> {
|
||||||
{
|
let (feature_config, tool_registry) = build_runtime_plugin_state()?;
|
||||||
let (feature_config, plugin_registry, tool_registry) = build_runtime_plugin_state()?;
|
Ok(ConversationRuntime::new_with_features(
|
||||||
let mut runtime = ConversationRuntime::new_with_plugins(
|
|
||||||
session,
|
session,
|
||||||
AnthropicRuntimeClient::new(
|
AnthropicRuntimeClient::new(
|
||||||
model,
|
model,
|
||||||
@@ -2844,48 +2803,10 @@ fn build_runtime(
|
|||||||
progress_reporter,
|
progress_reporter,
|
||||||
)?,
|
)?,
|
||||||
CliToolExecutor::new(allowed_tools.clone(), emit_output, tool_registry.clone()),
|
CliToolExecutor::new(allowed_tools.clone(), emit_output, tool_registry.clone()),
|
||||||
permission_policy(permission_mode, &feature_config, &tool_registry),
|
permission_policy(permission_mode, &tool_registry),
|
||||||
system_prompt,
|
system_prompt,
|
||||||
feature_config,
|
feature_config,
|
||||||
plugin_registry,
|
))
|
||||||
)?;
|
|
||||||
if emit_output {
|
|
||||||
runtime = runtime.with_hook_progress_reporter(Box::new(CliHookProgressReporter));
|
|
||||||
}
|
|
||||||
Ok(runtime)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct CliHookProgressReporter;
|
|
||||||
|
|
||||||
impl runtime::HookProgressReporter for CliHookProgressReporter {
|
|
||||||
fn on_event(&mut self, event: &runtime::HookProgressEvent) {
|
|
||||||
match event {
|
|
||||||
runtime::HookProgressEvent::Started {
|
|
||||||
event,
|
|
||||||
tool_name,
|
|
||||||
command,
|
|
||||||
} => eprintln!(
|
|
||||||
"[hook {event_name}] {tool_name}: {command}",
|
|
||||||
event_name = event.as_str()
|
|
||||||
),
|
|
||||||
runtime::HookProgressEvent::Completed {
|
|
||||||
event,
|
|
||||||
tool_name,
|
|
||||||
command,
|
|
||||||
} => eprintln!(
|
|
||||||
"[hook done {event_name}] {tool_name}: {command}",
|
|
||||||
event_name = event.as_str()
|
|
||||||
),
|
|
||||||
runtime::HookProgressEvent::Cancelled {
|
|
||||||
event,
|
|
||||||
tool_name,
|
|
||||||
command,
|
|
||||||
} => eprintln!(
|
|
||||||
"[hook cancelled {event_name}] {tool_name}: {command}",
|
|
||||||
event_name = event.as_str()
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct CliPermissionPrompter {
|
struct CliPermissionPrompter {
|
||||||
@@ -3182,7 +3103,12 @@ fn collect_tool_results(summary: &runtime::TurnSummary) -> Vec<serde_json::Value
|
|||||||
fn slash_command_completion_candidates() -> Vec<String> {
|
fn slash_command_completion_candidates() -> Vec<String> {
|
||||||
slash_command_specs()
|
slash_command_specs()
|
||||||
.iter()
|
.iter()
|
||||||
.map(|spec| format!("/{}", spec.name))
|
.flat_map(|spec| {
|
||||||
|
std::iter::once(spec.name)
|
||||||
|
.chain(spec.aliases.iter().copied())
|
||||||
|
.map(|name| format!("/{name}"))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3735,13 +3661,9 @@ impl ToolExecutor for CliToolExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn permission_policy(
|
fn permission_policy(mode: PermissionMode, tool_registry: &GlobalToolRegistry) -> PermissionPolicy {
|
||||||
mode: PermissionMode,
|
|
||||||
feature_config: &runtime::RuntimeFeatureConfig,
|
|
||||||
tool_registry: &GlobalToolRegistry,
|
|
||||||
) -> PermissionPolicy {
|
|
||||||
tool_registry.permission_specs(None).into_iter().fold(
|
tool_registry.permission_specs(None).into_iter().fold(
|
||||||
PermissionPolicy::new(mode).with_permission_rules(feature_config.permission_rules()),
|
PermissionPolicy::new(mode),
|
||||||
|policy, (name, required_permission)| {
|
|policy, (name, required_permission)| {
|
||||||
policy.with_tool_requirement(name, required_permission)
|
policy.with_tool_requirement(name, required_permission)
|
||||||
},
|
},
|
||||||
@@ -3818,6 +3740,8 @@ fn print_help_to(out: &mut impl Write) -> io::Result<()> {
|
|||||||
)?;
|
)?;
|
||||||
writeln!(out, " claw dump-manifests")?;
|
writeln!(out, " claw dump-manifests")?;
|
||||||
writeln!(out, " claw bootstrap-plan")?;
|
writeln!(out, " claw bootstrap-plan")?;
|
||||||
|
writeln!(out, " claw agents")?;
|
||||||
|
writeln!(out, " claw skills")?;
|
||||||
writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?;
|
writeln!(out, " claw system-prompt [--cwd PATH] [--date YYYY-MM-DD]")?;
|
||||||
writeln!(out, " claw login")?;
|
writeln!(out, " claw login")?;
|
||||||
writeln!(out, " claw logout")?;
|
writeln!(out, " claw logout")?;
|
||||||
@@ -3872,6 +3796,8 @@ fn print_help_to(out: &mut impl Write) -> io::Result<()> {
|
|||||||
out,
|
out,
|
||||||
" claw --resume session.json /status /diff /export notes.txt"
|
" claw --resume session.json /status /diff /export notes.txt"
|
||||||
)?;
|
)?;
|
||||||
|
writeln!(out, " claw agents")?;
|
||||||
|
writeln!(out, " claw /skills")?;
|
||||||
writeln!(out, " claw login")?;
|
writeln!(out, " claw login")?;
|
||||||
writeln!(out, " claw init")?;
|
writeln!(out, " claw init")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -3891,18 +3817,14 @@ mod tests {
|
|||||||
normalize_permission_mode, parse_args, parse_git_status_metadata, permission_policy,
|
normalize_permission_mode, parse_args, parse_git_status_metadata, permission_policy,
|
||||||
print_help_to, push_output_block, render_config_report, render_memory_report,
|
print_help_to, push_output_block, render_config_report, render_memory_report,
|
||||||
render_repl_help, resolve_model_alias, response_to_events, resume_supported_slash_commands,
|
render_repl_help, resolve_model_alias, response_to_events, resume_supported_slash_commands,
|
||||||
status_context, CliAction, CliOutputFormat, HookAbortMonitor, InternalPromptProgressEvent,
|
status_context, CliAction, CliOutputFormat, InternalPromptProgressEvent,
|
||||||
InternalPromptProgressState, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
InternalPromptProgressState, SlashCommand, StatusUsage, DEFAULT_MODEL,
|
||||||
};
|
};
|
||||||
use api::{MessageResponse, OutputContentBlock, Usage};
|
use api::{MessageResponse, OutputContentBlock, Usage};
|
||||||
use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};
|
use plugins::{PluginTool, PluginToolDefinition, PluginToolPermission};
|
||||||
use runtime::{
|
use runtime::{AssistantEvent, ContentBlock, ConversationMessage, MessageRole, PermissionMode};
|
||||||
AssistantEvent, ContentBlock, ConversationMessage, HookAbortSignal, MessageRole,
|
|
||||||
PermissionMode,
|
|
||||||
};
|
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::mpsc;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tools::GlobalToolRegistry;
|
use tools::GlobalToolRegistry;
|
||||||
|
|
||||||
@@ -4096,6 +4018,43 @@ mod tests {
|
|||||||
parse_args(&["init".to_string()]).expect("init should parse"),
|
parse_args(&["init".to_string()]).expect("init should parse"),
|
||||||
CliAction::Init
|
CliAction::Init
|
||||||
);
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["agents".to_string()]).expect("agents should parse"),
|
||||||
|
CliAction::Agents { args: None }
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["skills".to_string()]).expect("skills should parse"),
|
||||||
|
CliAction::Skills { args: None }
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["agents".to_string(), "--help".to_string()])
|
||||||
|
.expect("agents help should parse"),
|
||||||
|
CliAction::Agents {
|
||||||
|
args: Some("--help".to_string())
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_direct_agents_and_skills_slash_commands() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["/agents".to_string()]).expect("/agents should parse"),
|
||||||
|
CliAction::Agents { args: None }
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["/skills".to_string()]).expect("/skills should parse"),
|
||||||
|
CliAction::Skills { args: None }
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_args(&["/skills".to_string(), "help".to_string()])
|
||||||
|
.expect("/skills help should parse"),
|
||||||
|
CliAction::Skills {
|
||||||
|
args: Some("help".to_string())
|
||||||
|
}
|
||||||
|
);
|
||||||
|
let error = parse_args(&["/status".to_string()])
|
||||||
|
.expect_err("/status should remain REPL-only when invoked directly");
|
||||||
|
assert!(error.contains("unsupported direct slash command"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -4163,11 +4122,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn permission_policy_uses_plugin_tool_permissions() {
|
fn permission_policy_uses_plugin_tool_permissions() {
|
||||||
let policy = permission_policy(
|
let policy = permission_policy(PermissionMode::ReadOnly, ®istry_with_plugin_tool());
|
||||||
PermissionMode::ReadOnly,
|
|
||||||
&runtime::RuntimeFeatureConfig::default(),
|
|
||||||
®istry_with_plugin_tool(),
|
|
||||||
);
|
|
||||||
let required = policy.required_mode_for("plugin_echo");
|
let required = policy.required_mode_for("plugin_echo");
|
||||||
assert_eq!(required, PermissionMode::WorkspaceWrite);
|
assert_eq!(required, PermissionMode::WorkspaceWrite);
|
||||||
}
|
}
|
||||||
@@ -4198,8 +4153,11 @@ mod tests {
|
|||||||
assert!(help.contains("/export [file]"));
|
assert!(help.contains("/export [file]"));
|
||||||
assert!(help.contains("/session [list|switch <session-id>]"));
|
assert!(help.contains("/session [list|switch <session-id>]"));
|
||||||
assert!(help.contains(
|
assert!(help.contains(
|
||||||
"/plugins [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
|
"/plugin [list|install <path>|enable <name>|disable <name>|uninstall <id>|update <id>]"
|
||||||
));
|
));
|
||||||
|
assert!(help.contains("aliases: /plugins, /marketplace"));
|
||||||
|
assert!(help.contains("/agents"));
|
||||||
|
assert!(help.contains("/skills"));
|
||||||
assert!(help.contains("/exit"));
|
assert!(help.contains("/exit"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4213,7 +4171,7 @@ mod tests {
|
|||||||
names,
|
names,
|
||||||
vec![
|
vec![
|
||||||
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
|
"help", "status", "compact", "clear", "cost", "config", "memory", "init", "diff",
|
||||||
"version", "export",
|
"version", "export", "agents", "skills",
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -4280,6 +4238,9 @@ mod tests {
|
|||||||
print_help_to(&mut help).expect("help should render");
|
print_help_to(&mut help).expect("help should render");
|
||||||
let help = String::from_utf8(help).expect("help should be utf8");
|
let help = String::from_utf8(help).expect("help should be utf8");
|
||||||
assert!(help.contains("claw init"));
|
assert!(help.contains("claw init"));
|
||||||
|
assert!(help.contains("claw agents"));
|
||||||
|
assert!(help.contains("claw skills"));
|
||||||
|
assert!(help.contains("claw /skills"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -4804,43 +4765,4 @@ mod tests {
|
|||||||
));
|
));
|
||||||
assert!(!String::from_utf8(out).expect("utf8").contains("step 1"));
|
assert!(!String::from_utf8(out).expect("utf8").contains("step 1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hook_abort_monitor_stops_without_aborting() {
|
|
||||||
let abort_signal = HookAbortSignal::new();
|
|
||||||
let (ready_tx, ready_rx) = mpsc::channel();
|
|
||||||
let monitor = HookAbortMonitor::spawn_with_waiter(
|
|
||||||
abort_signal.clone(),
|
|
||||||
move |stop_rx, abort_signal| {
|
|
||||||
ready_tx.send(()).expect("ready signal");
|
|
||||||
let _ = stop_rx.recv();
|
|
||||||
assert!(!abort_signal.is_aborted());
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
ready_rx.recv().expect("waiter should be ready");
|
|
||||||
monitor.stop();
|
|
||||||
|
|
||||||
assert!(!abort_signal.is_aborted());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hook_abort_monitor_propagates_interrupt() {
|
|
||||||
let abort_signal = HookAbortSignal::new();
|
|
||||||
let (done_tx, done_rx) = mpsc::channel();
|
|
||||||
let monitor = HookAbortMonitor::spawn_with_waiter(
|
|
||||||
abort_signal.clone(),
|
|
||||||
move |_stop_rx, abort_signal| {
|
|
||||||
abort_signal.abort();
|
|
||||||
done_tx.send(()).expect("done signal");
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
done_rx
|
|
||||||
.recv_timeout(Duration::from_secs(1))
|
|
||||||
.expect("interrupt should complete");
|
|
||||||
monitor.stop();
|
|
||||||
|
|
||||||
assert!(abort_signal.is_aborted());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -286,7 +286,7 @@ impl TerminalRenderer {
|
|||||||
) {
|
) {
|
||||||
match event {
|
match event {
|
||||||
Event::Start(Tag::Heading { level, .. }) => {
|
Event::Start(Tag::Heading { level, .. }) => {
|
||||||
Self::start_heading(state, level as u8, output);
|
self.start_heading(state, level as u8, output);
|
||||||
}
|
}
|
||||||
Event::End(TagEnd::Paragraph) => output.push_str("\n\n"),
|
Event::End(TagEnd::Paragraph) => output.push_str("\n\n"),
|
||||||
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
Event::Start(Tag::BlockQuote(..)) => self.start_quote(state, output),
|
||||||
@@ -426,7 +426,8 @@ impl TerminalRenderer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_heading(state: &mut RenderState, level: u8, output: &mut String) {
|
#[allow(clippy::unused_self)]
|
||||||
|
fn start_heading(&self, state: &mut RenderState, level: u8, output: &mut String) {
|
||||||
state.heading_level = Some(level);
|
state.heading_level = Some(level);
|
||||||
if !output.is_empty() {
|
if !output.is_empty() {
|
||||||
output.push('\n');
|
output.push('\n');
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ plugins = { path = "../plugins" }
|
|||||||
runtime = { path = "../runtime" }
|
runtime = { path = "../runtime" }
|
||||||
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] }
|
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json.workspace = true
|
||||||
tokio = { version = "1", features = ["rt-multi-thread"] }
|
tokio = { version = "1", features = ["rt-multi-thread"] }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user