use crate::{
ArchiveConfig, CompactionConfig, CompactionPrompt, GenerationConfig, HistoryRetention,
ParallelToolCalls, PromptBlock, PromptProfile, ReasoningEffort, ServiceTier, ToolHookFilter,
ToolName,
binding::wire::build_compaction_policy,
profiles::{
CodingAgentProfile, CodingAgentProfileBuildError, CodingAgentProfileBuilder,
WorkspaceToolLimits,
},
};
use std::{
collections::BTreeSet,
num::{NonZeroU64, NonZeroUsize},
path::PathBuf,
};
#[derive(Debug)]
pub enum BindingWorkspaceProfileError {
Config(String),
Profile(CodingAgentProfileBuildError),
}
#[derive(Debug, Clone)]
pub struct WorkspaceProfileInput {
pub root: String,
pub readonly_resource_roots: Vec<String>,
pub enable_patch: bool,
pub patch_write_scope: Option<Vec<String>>,
pub forbidden_paths: Vec<String>,
pub max_read_bytes: Option<usize>,
pub max_read_lines: Option<usize>,
pub max_write_bytes: Option<usize>,
pub max_patch_bytes: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct CompactionPromptInput {
pub instructions: Option<String>,
pub user_context: Option<String>,
}
#[derive(Debug, Clone)]
pub struct CompactionConfigInput {
pub enabled: bool,
pub reasoning_effort: Option<String>,
pub retained_model_turns: Option<usize>,
pub target_output_tokens: Option<u64>,
pub max_accepted_output_bytes: Option<usize>,
pub one_shot_retained_tool_exchanges: Option<usize>,
pub trigger_threshold_percent: Option<u8>,
pub prompt: Option<CompactionPromptInput>,
}
pub fn build_generation_config(
max_output_tokens: Option<u64>,
parallel_tool_calls: Option<&str>,
reasoning_effort: Option<&str>,
service_tier: Option<&str>,
) -> Result<GenerationConfig, String> {
let parallel = match parallel_tool_calls {
None | Some("auto") => ParallelToolCalls::Auto,
Some("enabled") => ParallelToolCalls::Enabled,
Some("disabled") => ParallelToolCalls::Disabled,
Some(other) => {
return Err(format!("unsupported parallel_tool_calls mode: {other}"));
}
};
let reasoning = reasoning_effort
.map(ReasoningEffort::new)
.transpose()
.map_err(|error| error.to_string())?;
let tier = service_tier
.map(ServiceTier::new)
.transpose()
.map_err(|error| error.to_string())?;
Ok(GenerationConfig::new(max_output_tokens, false)
.map_err(|error| error.to_string())?
.with_parallel_tool_calls(parallel)
.with_reasoning_effort(reasoning)
.with_service_tier(tier))
}
pub fn build_prompt_profile(
base_instructions: Option<String>,
progress_commentary_instructions: Option<String>,
stable_blocks: Vec<(String, String)>,
) -> Result<PromptProfile, String> {
let mut profile = PromptProfile::default();
if let Some(base) = base_instructions {
profile = profile
.with_base_instructions(base)
.map_err(|error| error.to_string())?;
}
if let Some(commentary) = progress_commentary_instructions {
profile = profile
.with_progress_commentary_instructions(commentary)
.map_err(|error| error.to_string())?;
}
for (tag, text) in stable_blocks {
let block = PromptBlock::new(tag, text).map_err(|error| error.to_string())?;
profile = profile
.with_stable_block(block)
.map_err(|error| error.to_string())?;
}
Ok(profile)
}
pub fn build_workspace_profile(
input: WorkspaceProfileInput,
) -> Result<CodingAgentProfile, BindingWorkspaceProfileError> {
if input.root.is_empty() {
return Err(BindingWorkspaceProfileError::Config(
"workspace requires a root".to_owned(),
));
}
let defaults = WorkspaceToolLimits::default();
let mut builder = CodingAgentProfileBuilder::new(PathBuf::from(input.root))
.readonly_resource_roots(input.readonly_resource_roots.into_iter().map(PathBuf::from))
.limits(WorkspaceToolLimits {
max_read_bytes: input.max_read_bytes.unwrap_or(defaults.max_read_bytes),
max_read_lines: input.max_read_lines.unwrap_or(defaults.max_read_lines),
max_write_bytes: input.max_write_bytes.unwrap_or(defaults.max_write_bytes),
max_patch_bytes: input.max_patch_bytes.unwrap_or(defaults.max_patch_bytes),
})
.forbidden_paths(input.forbidden_paths.into_iter().map(PathBuf::from));
if input.enable_patch {
builder = builder.patch_tool();
if let Some(scope) = input.patch_write_scope {
builder = builder.patch_write_scope(scope.into_iter().map(PathBuf::from));
}
} else if input.patch_write_scope.is_some() {
return Err(BindingWorkspaceProfileError::Config(
"patch_write_scope requires enable_patch=true".to_owned(),
));
}
builder
.build()
.map_err(BindingWorkspaceProfileError::Profile)
}
pub fn build_history_retention(
mode: &str,
max_segments: Option<usize>,
max_bytes: Option<u64>,
export_markdown: Option<bool>,
) -> Result<HistoryRetention, String> {
match mode {
"archive" => {
let max_segments = max_segments
.map(|value| {
NonZeroUsize::new(value)
.ok_or_else(|| "max_segments must be greater than zero".to_owned())
})
.transpose()?;
let max_bytes = max_bytes
.map(|value| {
NonZeroU64::new(value)
.ok_or_else(|| "max_bytes must be greater than zero".to_owned())
})
.transpose()?;
let config = ArchiveConfig::new()
.with_max_segments(max_segments)
.with_max_bytes(max_bytes)
.with_export_markdown(export_markdown.unwrap_or(true));
Ok(HistoryRetention::Archive(config))
}
"context_only" => {
if max_segments.is_some() || max_bytes.is_some() || export_markdown == Some(true) {
return Err(
"max_segments, max_bytes, and export_markdown are only valid for archive retention"
.to_owned(),
);
}
Ok(HistoryRetention::ContextOnly)
}
other => Err(format!("unsupported history_retention mode: {other}")),
}
}
pub fn build_compaction_config(input: CompactionConfigInput) -> Result<CompactionConfig, String> {
let policy = build_compaction_policy(
input.retained_model_turns,
input.target_output_tokens,
input.max_accepted_output_bytes,
input.one_shot_retained_tool_exchanges,
)?;
let reasoning = input
.reasoning_effort
.as_deref()
.map(ReasoningEffort::new)
.transpose()
.map_err(|error| error.to_string())?;
let mut config = if input.enabled {
CompactionConfig::enabled(policy)
} else {
CompactionConfig::disabled().with_policy(policy)
}
.with_reasoning_effort(reasoning);
if let Some(percent) = input.trigger_threshold_percent {
config = config
.with_trigger_threshold_percent(percent)
.map_err(|error| error.to_string())?;
}
if let Some(prompt_input) = input.prompt {
let mut prompt = match prompt_input.instructions {
Some(instructions) => {
CompactionPrompt::custom(instructions).map_err(|error| error.to_string())?
}
None => CompactionPrompt::default(),
};
if let Some(user_context) = prompt_input.user_context {
prompt = prompt
.with_user_context(user_context)
.map_err(|error| error.to_string())?;
}
config = config.with_prompt(prompt);
}
Ok(config)
}
pub fn build_tool_hook_filter_only(tools: &[String]) -> Result<ToolHookFilter, String> {
let mut set = BTreeSet::new();
for name in tools {
let parsed = ToolName::new(name)
.map_err(|error| format!("hook tool filter name is invalid: {error}"))?;
set.insert(parsed);
}
Ok(if set.is_empty() {
ToolHookFilter::None
} else {
ToolHookFilter::Only(set)
})
}