use std::path::{Path, PathBuf};
use agent_client_protocol::schema::v1::{
AuthMethod, AuthMethodId, Meta, RequestPermissionRequest, SessionModeId, SessionUpdate,
};
use serde_json::{json, Map, Value};
use crate::{
acp_runtime::{permission::PermissionDecision, AcpAgentPolicy, AcpSpawnPlan, ExtensionAnswer},
agent::PromptPolicy,
cli_runtime::{
status_sink::{RateLimitRecorder, RuntimeLabel},
stream_effect::{RateLimitInfo, StatusPatch, StreamEffect},
CliExecutable,
},
permission::PermissionMode,
};
use super::{
executable,
fence::{self, ClaudeFence, ClaudeFenceError},
rate_limit::ClaudeRateLimitRecorder,
session::CLAUDE_LABEL,
};
const RATE_LIMIT_META: &str = "_claude/rateLimit";
const MODEL_META: &str = "_claude/model";
const MODEL_ENV: &str = "ANTHROPIC_MODEL";
#[derive(Clone, Debug)]
pub(crate) struct ClaudeSessionShape {
pub(crate) system_prompt: PromptPolicy,
pub(crate) model: Option<String>,
pub(crate) reasoning: Option<crate::agent::ReasoningLevel>,
pub(crate) tools: Vec<String>,
pub(crate) max_turns: u64,
pub(crate) persistence: SessionPersistence,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum SessionPersistence {
Keep,
Discard,
}
pub(crate) struct ClaudeAcpPolicy {
shape: ClaudeSessionShape,
fence: Result<ClaudeFence, ClaudeFenceError>,
cwd: PathBuf,
rate_limit_state_path: Option<PathBuf>,
}
impl ClaudeAcpPolicy {
pub(crate) fn delegated(
shape: ClaudeSessionShape,
permission_mode: PermissionMode,
inherit_claude_config: bool,
cwd: PathBuf,
rate_limit_state_path: Option<PathBuf>,
) -> Self {
Self {
fence: ClaudeFence::new(permission_mode, &shape.tools, inherit_claude_config),
shape,
cwd,
rate_limit_state_path,
}
}
pub(crate) fn headless(shape: ClaudeSessionShape, cwd: PathBuf) -> Self {
Self {
shape,
fence: Ok(ClaudeFence::headless()),
cwd,
rate_limit_state_path: None,
}
}
fn fence(&self) -> Option<&ClaudeFence> {
self.fence.as_ref().ok()
}
fn meta(&self, fence: &ClaudeFence) -> Meta {
let shape = &self.shape;
let mut options = Map::new();
options.insert("tools".into(), json!(fence::tool_base_names(&shape.tools)));
let allowed = fence::allowed_tool_entries(&shape.tools);
if !allowed.is_empty() {
options.insert("allowedTools".into(), json!(allowed));
}
options.insert(
"disallowedTools".into(),
json!(fence::DISALLOWED_NESTED_AGENT_TOOLS),
);
options.insert("settingSources".into(), json!(fence.setting_sources()));
options.insert("strictMcpConfig".into(), json!(true));
options.insert("maxTurns".into(), json!(shape.max_turns));
options.insert("promptSuggestions".into(), json!(false));
if let Some(model) = &shape.model {
options.insert("model".into(), json!(model));
}
if let Some(effort) = shape.reasoning.and_then(fence::claude_effort) {
options.insert("effort".into(), json!(effort));
}
if shape.persistence == SessionPersistence::Discard {
options.insert("persistSession".into(), json!(false));
}
let mut meta = Map::new();
match &shape.system_prompt {
PromptPolicy::Replace(text) => {
meta.insert("systemPrompt".into(), json!(text));
}
PromptPolicy::Extend(text) if !text.trim().is_empty() => {
meta.insert("systemPrompt".into(), json!({ "append": text }));
}
PromptPolicy::Extend(_) => {}
}
meta.insert("claudeCode".into(), json!({ "options": options }));
meta
}
}
impl AcpAgentPolicy for ClaudeAcpPolicy {
fn label(&self) -> RuntimeLabel {
CLAUDE_LABEL
}
fn resolve_executable(&self) -> Result<CliExecutable, String> {
executable::resolve().map_err(|error| error.to_string())
}
fn spawn_plan(&self, _frozen: Option<Vec<String>>) -> Result<AcpSpawnPlan, String> {
let env = self
.shape
.model
.iter()
.map(|model| (MODEL_ENV.into(), model.into()))
.collect();
Ok(AcpSpawnPlan {
argv: Vec::new(),
cwd: self.cwd.clone(),
env,
})
}
fn prepare(&mut self, _run_dir: &Path) -> Result<Vec<String>, String> {
self.fence
.as_ref()
.map(|_| Vec::new())
.map_err(ToString::to_string)
}
fn log_path(&self, output_file: &Path) -> PathBuf {
output_file.with_file_name(crate::subagent::LOG_FILE_NAME)
}
fn auth_method(&self, _advertised: &[AuthMethod]) -> Option<AuthMethodId> {
None
}
fn session_mode(&self) -> Option<SessionModeId> {
self.fence()
.map(|fence| SessionModeId::new(fence.session_mode()))
}
fn session_meta(&self) -> Option<Meta> {
self.fence().map(|fence| self.meta(fence))
}
fn decide_permission(&self, _request: &RequestPermissionRequest) -> PermissionDecision {
PermissionDecision::Reject
}
fn answer_extension(&self, _method: &str, _params: &Value) -> Option<ExtensionAnswer> {
None
}
fn rate_limit_recorder(&self) -> Option<Box<dyn RateLimitRecorder>> {
Some(Box::new(ClaudeRateLimitRecorder::new(
self.rate_limit_state_path.clone(),
)))
}
fn status_effects(&self, update: &SessionUpdate) -> Vec<StreamEffect> {
let SessionUpdate::UsageUpdate(usage) = update else {
return Vec::new();
};
let Some(meta) = usage.meta.as_ref() else {
return Vec::new();
};
let mut effects = Vec::new();
if let Some(info) = meta.get(RATE_LIMIT_META).and_then(rate_limit_info) {
effects.push(StreamEffect::RateLimit(info));
}
if let Some(model) = meta.get(MODEL_META).and_then(Value::as_str) {
effects.push(StreamEffect::Status(StatusPatch {
claude_model: Some(model.to_owned()),
..StatusPatch::default()
}));
}
effects
}
}
fn rate_limit_info(event: &Value) -> Option<RateLimitInfo> {
let mut info: RateLimitInfo = serde_json::from_value(event.clone()).ok()?;
if info.utilization.is_none() {
info.utilization = event
.get("unifiedWindows")
.and_then(|windows| windows.get(info.window_key()))
.and_then(|window| window.get("utilization"))
.and_then(Value::as_f64);
}
Some(info)
}
#[cfg(test)]
#[path = "policy_tests.rs"]
mod tests;