use crate::mcp::budget::{self, ToolBudget};
use crate::mcp::registry::{self, ToolExposure, ToolListAudience, ToolSpec};
use crate::mcp::response::{truncate_response, ToolResponse};
use crate::mcp::schema_validation;
use serde_json::Value;
use std::fmt;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use crate::calc::context::EvalContext;
pub use crate::mcp::compat::CompatibilityMode;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum Profile {
#[default]
Full,
Default,
CodeggCoreMin,
CodeggCore,
CodeggPreflight,
CodeggPatch,
CodeggConfig,
CodeggUnicodeSecurity,
CodeggShell,
CodeggRepoAudit,
HumanMath,
Custom(String),
}
impl Profile {
pub fn as_str(&self) -> &str {
match self {
Profile::Full => "full",
Profile::Default => "default",
Profile::CodeggCoreMin => "codegg_core_min",
Profile::CodeggCore => "codegg_core",
Profile::CodeggPreflight => "codegg_preflight",
Profile::CodeggPatch => "codegg_patch",
Profile::CodeggConfig => "codegg_config",
Profile::CodeggUnicodeSecurity => "codegg_unicode_security",
Profile::CodeggShell => "codegg_shell",
Profile::CodeggRepoAudit => "codegg_repo_audit",
Profile::HumanMath => "human_math",
Profile::Custom(name) => name,
}
}
pub fn custom(name: impl Into<String>) -> Self {
Profile::Custom(name.into())
}
pub fn from_str_opt(name: &str) -> Option<Self> {
match name {
"full" => Some(Profile::Full),
"default" => Some(Profile::Default),
"codegg_core_min" => Some(Profile::CodeggCoreMin),
"codegg_core" => Some(Profile::CodeggCore),
"codegg_preflight" => Some(Profile::CodeggPreflight),
"codegg_patch" => Some(Profile::CodeggPatch),
"codegg_config" => Some(Profile::CodeggConfig),
"codegg_unicode_security" => Some(Profile::CodeggUnicodeSecurity),
"codegg_shell" => Some(Profile::CodeggShell),
"codegg_repo_audit" => Some(Profile::CodeggRepoAudit),
"human_math" => Some(Profile::HumanMath),
_ => None,
}
}
}
impl fmt::Display for Profile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ToolAudience {
#[default]
Model,
Harness,
Debug,
}
impl ToolAudience {
pub fn as_str(self) -> &'static str {
match self {
ToolAudience::Model => "model",
ToolAudience::Harness => "harness",
ToolAudience::Debug => "debug",
}
}
pub fn as_registry_audience(self) -> ToolListAudience {
match self {
ToolAudience::Model => ToolListAudience::Model,
ToolAudience::Harness => ToolListAudience::Harness,
ToolAudience::Debug => ToolListAudience::Debug,
}
}
pub fn can_execute_exposure(self, exposure: ToolExposure) -> bool {
match self {
ToolAudience::Model => {
exposure != ToolExposure::HarnessOnly && exposure != ToolExposure::Hidden
}
ToolAudience::Harness => exposure != ToolExposure::Hidden,
ToolAudience::Debug => exposure != ToolExposure::Hidden,
}
}
}
impl fmt::Display for ToolAudience {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[derive(Debug, Clone)]
pub enum ToolCallError {
UnknownTool(String),
ToolUnavailable { tool: String, profile: String },
ToolNotAllowedForAudience {
tool: String,
profile: String,
audience: String,
exposure: String,
},
InvalidArguments(String),
Internal(String),
}
impl fmt::Display for ToolCallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ToolCallError::UnknownTool(name) => write!(f, "Unknown tool: {}", name),
ToolCallError::ToolUnavailable { tool, profile } => {
write!(
f,
"Tool '{}' is not available in profile '{}'",
tool, profile
)
}
ToolCallError::ToolNotAllowedForAudience {
tool,
profile,
audience,
exposure,
} => {
write!(
f,
"Tool '{}' (exposure: {}) is not executable by {} audience in profile '{}'",
tool, exposure, audience, profile
)
}
ToolCallError::InvalidArguments(msg) => write!(f, "Invalid arguments: {}", msg),
ToolCallError::Internal(msg) => write!(f, "Internal error: {}", msg),
}
}
}
impl std::error::Error for ToolCallError {}
#[derive(Clone, Debug)]
pub struct ToolView {
pub name: String,
pub description: String,
pub category: String,
pub tier: u8,
pub profiles: Vec<String>,
pub tags: Vec<String>,
pub exposure: String,
pub cost: String,
pub stability: String,
pub composite: bool,
}
impl ToolView {
fn from_spec(spec: &ToolSpec) -> Self {
Self {
name: spec.name.to_string(),
description: spec.description.to_string(),
category: spec.category.to_string(),
tier: spec.tier,
profiles: spec.profiles.iter().map(|s| s.to_string()).collect(),
tags: spec.tags.iter().map(|s| s.to_string()).collect(),
exposure: spec.exposure.as_str().to_string(),
cost: spec.cost.as_str().to_string(),
stability: spec.stability.as_str().to_string(),
composite: spec.composite,
}
}
}
#[derive(Clone, Debug)]
pub struct ToolSpecView {
pub view: ToolView,
pub input_schema: Value,
pub output_schema: Value,
}
impl ToolSpecView {
fn from_spec(spec: &ToolSpec) -> Self {
Self {
view: ToolView::from_spec(spec),
input_schema: (spec.input_schema)(),
output_schema: (spec.output_schema)(),
}
}
}
pub struct ToolRegistry {
profile: Profile,
audience: ToolAudience,
compat_mode: CompatibilityMode,
}
impl ToolRegistry {
pub fn new() -> Self {
Self {
profile: Profile::Full,
audience: ToolAudience::Model,
compat_mode: CompatibilityMode::default(),
}
}
pub fn with_profile(profile: Profile) -> Self {
Self {
profile,
audience: ToolAudience::Model,
compat_mode: CompatibilityMode::default(),
}
}
pub fn with_profile_and_audience(profile: Profile, audience: ToolAudience) -> Self {
Self {
profile,
audience,
compat_mode: CompatibilityMode::default(),
}
}
pub fn with_compat_mode(mut self, compat_mode: CompatibilityMode) -> Self {
self.compat_mode = compat_mode;
self
}
pub fn profile(&self) -> &Profile {
&self.profile
}
pub fn audience(&self) -> ToolAudience {
self.audience
}
pub fn compat_mode(&self) -> CompatibilityMode {
self.compat_mode
}
#[deprecated(
since = "1.1.4",
note = "use available_tools_model_safe, available_tools_for_audience, or available_tools_for_current_audience"
)]
pub fn available_tools(&self) -> Vec<ToolView> {
registry::tools_for_profile(self.profile.as_str())
.into_iter()
.filter(|spec| spec.exposure != ToolExposure::Hidden)
.map(ToolView::from_spec)
.collect()
}
pub fn available_tools_for_audience(&self, audience: ToolAudience) -> Vec<ToolView> {
registry::tools_for_profile_audience(self.profile.as_str(), audience.as_registry_audience())
.into_iter()
.map(ToolView::from_spec)
.collect()
}
pub fn available_tools_model_safe(&self) -> Vec<ToolView> {
self.available_tools_for_audience(ToolAudience::Model)
}
pub fn available_tools_for_current_audience(&self) -> Vec<ToolView> {
self.available_tools_for_audience(self.audience)
}
pub fn get_tool(&self, name: &str) -> Option<ToolSpecView> {
let spec = registry::get_tool(name)?;
let profile_tools = registry::tools_for_profile(self.profile.as_str());
if !profile_tools.iter().any(|s| s.name == name) {
return None;
}
if !self.audience.can_execute_exposure(spec.exposure) {
return None;
}
Some(ToolSpecView::from_spec(spec))
}
pub fn has_tool(&self, name: &str) -> bool {
let profile_tools = registry::tools_for_profile(self.profile.as_str());
if !profile_tools.iter().any(|s| s.name == name) {
return false;
}
if let Some(spec) = registry::get_tool(name) {
self.audience.can_execute_exposure(spec.exposure)
} else {
false
}
}
pub fn get_tool_unfiltered(&self, name: &str) -> Option<ToolSpecView> {
let spec = registry::get_tool(name)?;
Some(ToolSpecView::from_spec(spec))
}
pub fn has_registered_tool(&self, name: &str) -> bool {
registry::get_tool(name).is_some()
}
pub fn prepare_tool_call(&self, name: &str, args: &Value) -> ToolCallOutcome {
self.prepare_tool_call_with_policy(
name,
args,
&self.profile,
self.audience,
self.compat_mode,
)
}
pub fn prepare_tool_call_with_policy(
&self,
name: &str,
args: &Value,
effective_profile: &Profile,
effective_audience: ToolAudience,
effective_compat: CompatibilityMode,
) -> ToolCallOutcome {
match self.prepare_tool_call_internal(
name,
args,
effective_profile,
effective_audience,
effective_compat,
) {
Ok(prepared) => ToolCallOutcome::Ready {
handler: prepared.handler,
},
Err(error) => ToolCallOutcome::PreExecutionError(error),
}
}
pub(crate) fn prepare_tool_call_internal(
&self,
name: &str,
args: &Value,
effective_profile: &Profile,
effective_audience: ToolAudience,
effective_compat: CompatibilityMode,
) -> Result<PreparedToolCall, ToolCallError> {
let spec =
registry::get_tool(name).ok_or_else(|| ToolCallError::UnknownTool(name.to_string()))?;
let in_profile = effective_profile.as_str() == "full"
&& spec.exposure != ToolExposure::Hidden
|| spec.profiles.contains(&effective_profile.as_str());
if !in_profile {
return Err(ToolCallError::ToolUnavailable {
tool: name.to_string(),
profile: effective_profile.to_string(),
});
}
if !effective_audience.can_execute_exposure(spec.exposure) {
return Err(ToolCallError::ToolNotAllowedForAudience {
tool: name.to_string(),
profile: effective_profile.to_string(),
audience: format!("{:?}", effective_audience),
exposure: spec.exposure.as_str().to_string(),
});
}
if let Some(msg) = schema_validation::validate_arguments(name, args, effective_compat) {
return Err(ToolCallError::InvalidArguments(msg));
}
Ok(PreparedToolCall {
handler: spec.handler,
cost: spec.cost,
})
}
pub fn call_json(&self, name: &str, args: Value) -> Result<ToolResponse, ToolCallError> {
match self.prepare_tool_call(name, &args) {
ToolCallOutcome::Ready { handler } => {
let mut eval_ctx = EvalContext::new();
Ok(budget::with_eval_context(&mut eval_ctx, || handler(&args)))
}
ToolCallOutcome::PreExecutionError(e) => Err(e),
}
}
pub fn call_json_with_budget(
&self,
name: &str,
args: Value,
budget: Option<ToolBudget>,
) -> Result<ToolResponse, ToolCallError> {
let outcome = self.prepare_tool_call(name, &args);
let handler = match outcome {
ToolCallOutcome::Ready { handler } => handler,
ToolCallOutcome::PreExecutionError(e) => return Err(e),
};
let effective_budget = Self::resolve_budget(name, budget)?;
if let Some(resp) = Self::check_input_size(&args, &effective_budget, name) {
return Ok(resp);
}
self.run_bounded(handler, args, None, &effective_budget, name)
}
pub fn call_json_with_context(
&self,
name: &str,
args: Value,
budget: Option<ToolBudget>,
cancel_flag: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
) -> Result<ToolResponse, ToolCallError> {
let outcome = self.prepare_tool_call(name, &args);
let handler = match outcome {
ToolCallOutcome::Ready { handler } => handler,
ToolCallOutcome::PreExecutionError(e) => return Err(e),
};
let effective_budget = Self::resolve_budget(name, budget)?;
if let Some(resp) = Self::check_input_size(&args, &effective_budget, name) {
return Ok(resp);
}
self.run_bounded(handler, args, cancel_flag, &effective_budget, name)
}
pub fn call_json_with_execution_context(
&self,
name: &str,
args: Value,
ctx: &ExecutionContext,
) -> Result<ToolResponse, ToolCallError> {
let effective_profile = ctx.profile.clone().unwrap_or_else(|| self.profile.clone());
let effective_audience = ctx.audience.unwrap_or(self.audience);
let effective_compat = ctx.compatibility_mode;
let outcome = self.prepare_tool_call_with_policy(
name,
&args,
&effective_profile,
effective_audience,
effective_compat,
);
let handler = match outcome {
ToolCallOutcome::Ready { handler } => handler,
ToolCallOutcome::PreExecutionError(e) => return Err(e),
};
let effective_budget = Self::resolve_budget(name, ctx.budget)?;
if let Some(resp) = Self::check_input_size(&args, &effective_budget, name) {
return Ok(resp);
}
let eval_ctx_clone = ctx.eval_ctx.clone();
let cancel_flag = ctx
.cancellation
.clone()
.unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
self.run_bounded_with_ctx(
handler,
args,
eval_ctx_clone,
cancel_flag,
&effective_budget,
name,
)
}
pub fn call_json_with_execution_template(
&self,
name: &str,
args: Value,
template: &ExecutionContext,
) -> Result<ToolResponse, ToolCallError> {
self.call_json_with_execution_context(name, args, template)
}
#[deprecated(
since = "1.0.0",
note = "Does not persist calculator state through math_eval. Use evaluate_with_context() or run_with_context() directly for persistent calculator sessions. The method remains useful for transaction safety on failure paths."
)]
pub fn call_json_with_execution_context_mut(
&self,
name: &str,
args: Value,
ctx: &mut ExecutionContext,
) -> Result<ToolResponse, ToolCallError> {
self.call_json_with_execution_context(name, args, ctx)
}
pub fn call_json_value(&self, name: &str, args: Value) -> Value {
match self.call_json(name, args) {
Ok(response) => response.result.unwrap_or(Value::Null),
Err(_) => Value::Null,
}
}
fn resolve_budget(
name: &str,
budget_override: Option<ToolBudget>,
) -> Result<ToolBudget, ToolCallError> {
match budget_override {
Some(b) => Ok(b),
None => {
let spec = registry::get_tool(name)
.ok_or_else(|| ToolCallError::UnknownTool(name.to_string()))?;
Ok(budget_for_tool_resolved(name, spec))
}
}
}
fn check_input_size(args: &Value, budget: &ToolBudget, name: &str) -> Option<ToolResponse> {
struct Counter(usize);
impl std::io::Write for Counter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0 = self.0.saturating_add(bytes.len());
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
let mut counter = Counter(0);
let serialized_len = serde_json::to_writer(&mut counter, args)
.map(|_| counter.0)
.unwrap_or(0);
if serialized_len > budget.max_input_bytes {
Some(ToolResponse::error_with_code(
"input_too_large",
crate::mcp::machine_codes::INPUT_TOO_LARGE,
&format!(
"Serialized arguments ({} bytes) exceed budget max_input_bytes ({} bytes)",
serialized_len, budget.max_input_bytes
),
None,
Some(name),
))
} else {
None
}
}
fn run_bounded(
&self,
handler: registry::ToolHandler,
args: Value,
cancel_flag: Option<Arc<AtomicBool>>,
budget: &ToolBudget,
name: &str,
) -> Result<ToolResponse, ToolCallError> {
let eval_ctx = crate::calc::EvalContext::mcp_mode();
let flag = cancel_flag.unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
self.run_bounded_with_ctx(handler, args, eval_ctx, flag, budget, name)
}
fn run_bounded_with_ctx(
&self,
handler: registry::ToolHandler,
args: Value,
eval_ctx: EvalContext,
cancel_flag: Arc<AtomicBool>,
budget: &ToolBudget,
name: &str,
) -> Result<ToolResponse, ToolCallError> {
let timeout = Duration::from_millis(budget.max_elapsed_ms);
let handler_cancel = cancel_flag.clone();
let result = crate::mcp::sync_pool::sync_pool().submit_cancellable(
move || {
budget::with_cancel_flag(Some(handler_cancel), || {
let mut eval_ctx = eval_ctx;
crate::mcp::budget::with_eval_context(&mut eval_ctx, || handler(&args))
})
},
timeout,
cancel_flag,
);
match result {
Ok(mut response) => {
truncate_response(&mut response, budget);
Ok(response)
}
Err(pool_error) => Ok(pool_error.to_tool_response(name)),
}
}
}
pub enum ToolCallOutcome {
Ready { handler: registry::ToolHandler },
PreExecutionError(ToolCallError),
}
pub(crate) struct PreparedToolCall {
pub(crate) handler: registry::ToolHandler,
pub(crate) cost: crate::mcp::registry::ToolCost,
}
impl Default for ToolRegistry {
fn default() -> Self {
Self::new()
}
}
fn budget_for_tool_resolved(name: &str, spec: &ToolSpec) -> ToolBudget {
budget::budget_for_tool(name, spec.cost)
}
pub use crate::mcp::budget::{BudgetContext, BudgetTier, ToolBudget as ToolBudgetType};
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum ExecutionSource {
Cli,
Library,
Mcp,
Agent,
#[default]
Test,
}
pub struct ExecutionContext {
pub eval_ctx: EvalContext,
pub compatibility_mode: CompatibilityMode,
pub profile: Option<Profile>,
pub audience: Option<ToolAudience>,
pub budget: Option<ToolBudget>,
pub cancellation: Option<Arc<AtomicBool>>,
pub request_id: Option<String>,
pub source: ExecutionSource,
}
impl ExecutionContext {
pub fn cli_default() -> Self {
Self {
eval_ctx: EvalContext::new(),
compatibility_mode: CompatibilityMode::default(),
profile: None,
audience: None,
budget: None,
cancellation: None,
request_id: None,
source: ExecutionSource::Cli,
}
}
pub fn library_default() -> Self {
Self {
eval_ctx: EvalContext::new(),
compatibility_mode: CompatibilityMode::StrictNative,
profile: None,
audience: None,
budget: None,
cancellation: None,
request_id: None,
source: ExecutionSource::Library,
}
}
pub fn mcp_default(profile: Profile, audience: ToolAudience) -> Self {
Self {
eval_ctx: EvalContext::mcp_mode(),
compatibility_mode: CompatibilityMode::EggcalcPython,
profile: Some(profile),
audience: Some(audience),
budget: None,
cancellation: None,
request_id: None,
source: ExecutionSource::Mcp,
}
}
pub fn agent_default(profile: Profile, audience: ToolAudience) -> Self {
Self {
eval_ctx: EvalContext::new(),
compatibility_mode: CompatibilityMode::StrictNative,
profile: Some(profile),
audience: Some(audience),
budget: None,
cancellation: None,
request_id: None,
source: ExecutionSource::Agent,
}
}
pub fn test_default() -> Self {
Self {
eval_ctx: EvalContext::new(),
compatibility_mode: CompatibilityMode::default(),
profile: None,
audience: None,
budget: None,
cancellation: None,
request_id: None,
source: ExecutionSource::Test,
}
}
pub fn with_budget(mut self, budget: ToolBudget) -> Self {
self.budget = Some(budget);
self
}
pub fn with_cancellation(mut self, flag: Arc<AtomicBool>) -> Self {
self.cancellation = Some(flag);
self
}
pub fn with_request_id(mut self, id: impl Into<String>) -> Self {
self.request_id = Some(id.into());
self
}
pub fn with_eval_context(mut self, eval_ctx: &EvalContext) -> Self {
self.eval_ctx = eval_ctx.clone();
self
}
pub fn builder() -> ExecutionContextBuilder {
ExecutionContextBuilder::default()
}
}
#[derive(Default)]
pub struct ExecutionContextBuilder {
eval_ctx: Option<EvalContext>,
compatibility_mode: Option<CompatibilityMode>,
profile: Option<Profile>,
audience: Option<ToolAudience>,
budget: Option<ToolBudget>,
cancellation: Option<Arc<AtomicBool>>,
request_id: Option<String>,
source: Option<ExecutionSource>,
}
impl ExecutionContextBuilder {
pub fn eval_ctx(mut self, eval_ctx: EvalContext) -> Self {
self.eval_ctx = Some(eval_ctx);
self
}
pub fn compatibility_mode(mut self, mode: CompatibilityMode) -> Self {
self.compatibility_mode = Some(mode);
self
}
pub fn profile(mut self, profile: Profile) -> Self {
self.profile = Some(profile);
self
}
pub fn audience(mut self, audience: ToolAudience) -> Self {
self.audience = Some(audience);
self
}
pub fn budget(mut self, budget: ToolBudget) -> Self {
self.budget = Some(budget);
self
}
pub fn cancellation(mut self, flag: Arc<AtomicBool>) -> Self {
self.cancellation = Some(flag);
self
}
pub fn request_id(mut self, id: impl Into<String>) -> Self {
self.request_id = Some(id.into());
self
}
pub fn source(mut self, source: ExecutionSource) -> Self {
self.source = Some(source);
self
}
pub fn build(self) -> ExecutionContext {
ExecutionContext {
eval_ctx: self.eval_ctx.unwrap_or_default(),
compatibility_mode: self.compatibility_mode.unwrap_or_default(),
profile: self.profile,
audience: self.audience,
budget: self.budget,
cancellation: self.cancellation,
request_id: self.request_id,
source: self.source.unwrap_or_default(),
}
}
}
impl Default for ExecutionContext {
fn default() -> Self {
Self::test_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[allow(deprecated)]
fn tool_registry_default_lists_tools() {
let registry = ToolRegistry::default();
let tools = registry.available_tools();
assert!(!tools.is_empty(), "should have tools in full profile");
assert!(tools.iter().any(|t| t.name == "text_equal"));
}
#[test]
#[allow(deprecated)]
fn tool_registry_profile_filters_tools() {
let registry = ToolRegistry::with_profile(Profile::CodeggCoreMin);
let tools = registry.available_tools();
let full_count = ToolRegistry::default().available_tools().len();
assert!(tools.len() <= full_count);
for tool in &tools {
assert!(
tool.profiles.contains(&"codegg_core_min".to_string()),
"tool {} not in codegg_core_min profile",
tool.name
);
}
}
#[test]
fn tool_registry_unknown_tool_returns_error() {
let registry = ToolRegistry::default();
let result = registry.call_json("nonexistent_tool", serde_json::json!({}));
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::UnknownTool(name) => assert_eq!(name, "nonexistent_tool"),
other => panic!("expected UnknownTool, got {:?}", other),
}
}
#[test]
fn tool_registry_outside_profile_returns_error() {
let registry = ToolRegistry::with_profile(Profile::HumanMath);
assert!(registry.has_tool("math_eval"));
let result = registry.call_json("text_equal", serde_json::json!({"a": "x", "b": "x"}));
if let Err(ToolCallError::ToolUnavailable { tool, .. }) = &result {
assert_eq!(tool, "text_equal");
}
}
#[test]
fn tool_registry_invalid_arguments_returns_error() {
let registry = ToolRegistry::default();
let result = registry.call_json("math_eval", serde_json::json!({}));
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::InvalidArguments(msg) => {
assert!(msg.contains("Missing required argument"));
}
other => panic!("expected InvalidArguments, got {:?}", other),
}
}
#[test]
fn tool_registry_call_json_succeeds() {
let registry = ToolRegistry::default();
let response = registry
.call_json("text_equal", serde_json::json!({"a": "foo", "b": "foo"}))
.unwrap();
assert!(response.ok);
}
#[test]
fn tool_registry_call_json_value_succeeds() {
let registry = ToolRegistry::default();
let value =
registry.call_json_value("text_equal", serde_json::json!({"a": "foo", "b": "foo"}));
assert!(value.get("equal").and_then(|v| v.as_bool()) == Some(true));
}
#[test]
fn tool_registry_get_tool_returns_spec() {
let registry = ToolRegistry::default();
let spec = registry.get_tool("text_equal");
assert!(spec.is_some());
let spec = spec.unwrap();
assert_eq!(spec.view.name, "text_equal");
assert!(spec.input_schema.is_object());
}
#[test]
fn tool_registry_profile_display() {
assert_eq!(Profile::Full.to_string(), "full");
assert_eq!(Profile::CodeggCore.to_string(), "codegg_core");
assert_eq!(Profile::Custom("test".to_string()).to_string(), "test");
}
#[test]
fn tool_registry_profile_from_str() {
assert_eq!(Profile::from_str_opt("full"), Some(Profile::Full));
assert_eq!(
Profile::from_str_opt("codegg_core"),
Some(Profile::CodeggCore)
);
assert_eq!(Profile::from_str_opt("nonexistent"), None);
assert_eq!(Profile::from_str_opt("coddeg_core_typo"), None);
}
#[test]
fn profile_custom_constructor() {
let p = Profile::custom("my_custom");
assert_eq!(p, Profile::Custom("my_custom".to_string()));
assert_eq!(p.as_str(), "my_custom");
assert_eq!(p.to_string(), "my_custom");
let p2 = Profile::custom("full");
assert_eq!(p2, Profile::Custom("full".to_string()));
}
#[test]
fn tool_audience_default_is_model() {
let registry = ToolRegistry::default();
assert_eq!(registry.audience(), ToolAudience::Model);
}
#[test]
fn tool_audience_getter_returns_constructor_value() {
let registry =
ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Harness);
assert_eq!(registry.audience(), ToolAudience::Harness);
}
#[test]
fn model_safe_excludes_harness_only_tools() {
let registry = ToolRegistry::default();
let model_tools = registry.available_tools_model_safe();
let harness_only_names: Vec<String> = registry::tools_for_profile("full")
.into_iter()
.filter(|t| t.exposure == ToolExposure::HarnessOnly)
.map(|t| t.name.to_string())
.collect();
for name in &harness_only_names {
assert!(
!model_tools.iter().any(|t| t.name == *name),
"harness_only tool '{}' should not appear in model-safe listing",
name
);
}
}
#[test]
#[allow(deprecated)]
fn model_safe_is_subset_of_available_tools() {
let registry = ToolRegistry::default();
let all_tools = registry.available_tools();
let model_tools = registry.available_tools_model_safe();
assert!(model_tools.len() <= all_tools.len());
for tool in &model_tools {
assert!(
all_tools.iter().any(|t| t.name == tool.name),
"model-safe tool '{}' should also appear in available_tools()",
tool.name
);
}
}
#[test]
fn harness_audience_includes_harness_only_tools() {
let registry = ToolRegistry::with_profile(Profile::CodeggPreflight);
let harness_tools = registry.available_tools_for_audience(ToolAudience::Harness);
let harness_only_in_profile: Vec<String> = registry::tools_for_profile("codegg_preflight")
.into_iter()
.filter(|t| t.exposure == ToolExposure::HarnessOnly)
.map(|t| t.name.to_string())
.collect();
assert!(
!harness_only_in_profile.is_empty(),
"codegg_preflight should have harness-only tools"
);
for name in &harness_only_in_profile {
assert!(
harness_tools.iter().any(|t| t.name == *name),
"harness audience for codegg_preflight should include '{}'",
name
);
}
}
#[test]
fn harness_audience_for_codegg_core_min_excludes_harness_only() {
let registry = ToolRegistry::with_profile(Profile::CodeggCoreMin);
let harness_tools = registry.available_tools_for_audience(ToolAudience::Harness);
for spec in registry::tools_for_profile("codegg_core_min") {
if spec.exposure == ToolExposure::HarnessOnly {
assert!(
!harness_tools.iter().any(|t| t.name == spec.name),
"harness audience for codegg_core_min should not include harness-only '{}'",
spec.name
);
}
}
}
#[test]
fn debug_audience_includes_all_non_hidden() {
let registry = ToolRegistry::default();
let debug_tools = registry.available_tools_for_audience(ToolAudience::Debug);
let all_non_hidden: Vec<String> = registry::tools_for_profile("full")
.into_iter()
.filter(|t| t.exposure != ToolExposure::Hidden)
.map(|t| t.name.to_string())
.collect();
assert_eq!(debug_tools.len(), all_non_hidden.len());
}
#[test]
fn with_profile_and_audience_combines_both() {
let registry =
ToolRegistry::with_profile_and_audience(Profile::CodeggPreflight, ToolAudience::Model);
assert_eq!(registry.profile(), &Profile::CodeggPreflight);
assert_eq!(registry.audience(), ToolAudience::Model);
let tools = registry.available_tools_model_safe();
for spec in registry::tools_for_profile("codegg_preflight") {
if spec.exposure == ToolExposure::HarnessOnly {
assert!(
!tools.iter().any(|t| t.name == spec.name),
"Model audience for codegg_preflight should not include harness-only '{}'",
spec.name
);
}
}
}
#[test]
fn current_audience_model_excludes_harness_only() {
let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
let current = registry.available_tools_for_current_audience();
let explicit = registry.available_tools_for_audience(ToolAudience::Model);
assert_eq!(current.len(), explicit.len());
for t in ¤t {
assert!(!t.exposure.contains("harness_only"));
}
}
#[test]
fn current_audience_harness_includes_preflight_harness_tools() {
let registry = ToolRegistry::with_profile_and_audience(
Profile::CodeggPreflight,
ToolAudience::Harness,
);
let tools = registry.available_tools_for_current_audience();
assert!(
tools.iter().any(|t| t.name == "shell_split"),
"harness audience should include shell_split"
);
assert!(
tools.iter().any(|t| t.name == "path_scope_check"),
"harness audience should include path_scope_check"
);
}
#[test]
fn current_audience_debug_matches_debug_listing() {
let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Debug);
let current = registry.available_tools_for_current_audience();
let explicit = registry.available_tools_for_audience(ToolAudience::Debug);
assert_eq!(current.len(), explicit.len());
}
#[test]
fn model_audience_allows_default_exposure() {
assert!(ToolAudience::Model.can_execute_exposure(ToolExposure::Default));
}
#[test]
fn model_audience_allows_contextual_exposure() {
assert!(ToolAudience::Model.can_execute_exposure(ToolExposure::Contextual));
}
#[test]
fn model_audience_allows_expert_only_exposure() {
assert!(ToolAudience::Model.can_execute_exposure(ToolExposure::ExpertOnly));
}
#[test]
fn model_audience_rejects_harness_only_exposure() {
assert!(!ToolAudience::Model.can_execute_exposure(ToolExposure::HarnessOnly));
}
#[test]
fn model_audience_rejects_hidden_exposure() {
assert!(!ToolAudience::Model.can_execute_exposure(ToolExposure::Hidden));
}
#[test]
fn harness_audience_allows_default_exposure() {
assert!(ToolAudience::Harness.can_execute_exposure(ToolExposure::Default));
}
#[test]
fn harness_audience_allows_harness_only_exposure() {
assert!(ToolAudience::Harness.can_execute_exposure(ToolExposure::HarnessOnly));
}
#[test]
fn harness_audience_rejects_hidden_exposure() {
assert!(!ToolAudience::Harness.can_execute_exposure(ToolExposure::Hidden));
}
#[test]
fn debug_audience_allows_default_exposure() {
assert!(ToolAudience::Debug.can_execute_exposure(ToolExposure::Default));
}
#[test]
fn debug_audience_allows_harness_only_exposure() {
assert!(ToolAudience::Debug.can_execute_exposure(ToolExposure::HarnessOnly));
}
#[test]
fn debug_audience_rejects_hidden_exposure() {
assert!(!ToolAudience::Debug.can_execute_exposure(ToolExposure::Hidden));
}
#[test]
fn model_audience_rejects_harness_only_tool_call() {
let harness_tool = registry::tools_for_profile("full")
.into_iter()
.find(|t| t.exposure == ToolExposure::HarnessOnly)
.expect("full profile should have harness-only tools");
let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
let result = registry.call_json(harness_tool.name, serde_json::json!({}));
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolNotAllowedForAudience { tool, exposure, .. } => {
assert_eq!(tool, harness_tool.name);
assert_eq!(exposure, "harness_only");
}
other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
}
}
#[test]
fn harness_audience_allows_harness_only_tool_call() {
let harness_tool = registry::tools_for_profile("codegg_preflight")
.into_iter()
.find(|t| t.exposure == ToolExposure::HarnessOnly)
.expect("codegg_preflight should have harness-only tools");
let registry = ToolRegistry::with_profile_and_audience(
Profile::CodeggPreflight,
ToolAudience::Harness,
);
let result = registry.call_json(harness_tool.name, serde_json::json!({}));
if let Err(ToolCallError::ToolNotAllowedForAudience { .. }) = result {
panic!(
"harness audience should allow harness-only tool: {}",
harness_tool.name
);
}
}
#[test]
fn restricted_profile_rejects_out_of_profile_tool() {
let registry = ToolRegistry::with_profile(Profile::HumanMath);
let result = registry.call_json("math_eval", serde_json::json!({"expression": "1+1"}));
assert!(result.is_ok());
}
#[test]
fn model_audience_error_includes_tool_profile_audience_exposure() {
let harness_tool = registry::tools_for_profile("full")
.into_iter()
.find(|t| t.exposure == ToolExposure::HarnessOnly)
.expect("full profile should have harness-only tools");
let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
let result = registry.call_json(harness_tool.name, serde_json::json!({}));
let err = result.unwrap_err();
let msg = err.to_string();
assert!(msg.contains(harness_tool.name));
assert!(msg.contains("harness_only"));
assert!(msg.contains("Model"));
}
#[test]
fn call_json_with_budget_succeeds() {
let registry = ToolRegistry::default();
let response = registry
.call_json_with_budget(
"text_equal",
serde_json::json!({"a": "foo", "b": "foo"}),
None,
)
.unwrap();
assert!(response.ok);
}
#[test]
fn call_json_with_budget_explicit_cheap() {
let registry = ToolRegistry::default();
let response = registry
.call_json_with_budget(
"text_equal",
serde_json::json!({"a": "hello", "b": "hello"}),
Some(ToolBudget::CHEAP),
)
.unwrap();
assert!(response.ok);
}
#[test]
fn call_json_with_budget_truncates_findings() {
let registry = ToolRegistry::default();
let response = registry
.call_json_with_budget(
"validate_json",
serde_json::json!({"text": "not valid json at all"}),
Some(ToolBudget::CHEAP.with_max_findings(1)),
)
.unwrap();
assert!(response.ok);
if let Some(ref findings) = response.findings {
assert!(findings.len() <= 2); }
}
#[test]
fn call_json_with_budget_unknown_tool_error() {
let registry = ToolRegistry::default();
let result = registry.call_json_with_budget("nonexistent", serde_json::json!({}), None);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::UnknownTool(name) => assert_eq!(name, "nonexistent"),
other => panic!("expected UnknownTool, got {:?}", other),
}
}
#[test]
fn human_math_rejects_text_equal_with_budget() {
let registry = ToolRegistry::with_profile(Profile::HumanMath);
let result = registry.call_json_with_budget(
"text_equal",
serde_json::json!({"a": "x", "b": "x"}),
None,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
other => panic!("expected ToolUnavailable, got {:?}", other),
}
}
#[test]
fn full_harness_allows_shell_split_with_budget() {
let registry =
ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Harness);
let result = registry.call_json_with_budget(
"shell_split",
serde_json::json!({"command": "echo hello"}),
None,
);
assert!(result.is_ok());
}
#[test]
fn full_model_rejects_shell_split_with_budget() {
let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
let result = registry.call_json_with_budget(
"shell_split",
serde_json::json!({"command": "echo hello"}),
None,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolNotAllowedForAudience { .. } => {}
other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
}
}
#[test]
fn unknown_tool_with_budget_returns_error() {
let registry = ToolRegistry::default();
let result =
registry.call_json_with_budget("nonexistent_tool_xyz", serde_json::json!({}), None);
assert!(result.is_err());
assert!(matches!(result.unwrap_err(), ToolCallError::UnknownTool(_)));
}
#[test]
fn invalid_args_with_budget_returns_error() {
let registry = ToolRegistry::default();
let result = registry.call_json_with_budget("math_eval", serde_json::json!({}), None);
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ToolCallError::InvalidArguments(_)
));
}
#[test]
fn human_math_rejects_text_equal_with_context() {
let registry = ToolRegistry::with_profile(Profile::HumanMath);
let result = registry.call_json_with_context(
"text_equal",
serde_json::json!({"a": "x", "b": "x"}),
None,
None,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
other => panic!("expected ToolUnavailable, got {:?}", other),
}
}
#[test]
fn full_model_rejects_shell_split_with_context() {
let registry = ToolRegistry::with_profile_and_audience(Profile::Full, ToolAudience::Model);
let result = registry.call_json_with_context(
"shell_split",
serde_json::json!({"command": "echo hello"}),
None,
None,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolNotAllowedForAudience { .. } => {}
other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
}
}
#[test]
fn execution_context_overrides_profile_for_budget_call() {
let registry = ToolRegistry::default();
let ctx = ExecutionContext {
profile: Some(Profile::HumanMath),
..ExecutionContext::test_default()
};
let result = registry.call_json_with_execution_context(
"text_equal",
serde_json::json!({"a": "x", "b": "x"}),
&ctx,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
other => panic!("expected ToolUnavailable, got {:?}", other),
}
}
#[test]
fn execution_context_audience_enforced_for_budget_call() {
let registry = ToolRegistry::default();
let ctx = ExecutionContext {
profile: Some(Profile::Full),
audience: Some(ToolAudience::Model),
..ExecutionContext::test_default()
};
let result = registry.call_json_with_execution_context(
"shell_split",
serde_json::json!({"command": "echo hello"}),
&ctx,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolNotAllowedForAudience { .. } => {}
other => panic!("expected ToolNotAllowedForAudience, got {:?}", other),
}
}
#[test]
#[allow(deprecated)]
fn execution_context_mut_routes_through_pool() {
let registry = ToolRegistry::default();
let mut ctx = ExecutionContext::test_default();
let result = registry.call_json_with_execution_context_mut(
"text_equal",
serde_json::json!({"a": "foo", "b": "foo"}),
&mut ctx,
);
assert!(result.is_ok());
assert!(result.unwrap().ok);
}
#[test]
#[allow(deprecated)]
fn execution_context_mut_rejects_unavailable_tool() {
let registry = ToolRegistry::with_profile(Profile::HumanMath);
let mut ctx = ExecutionContext {
profile: Some(Profile::HumanMath),
..ExecutionContext::test_default()
};
let result = registry.call_json_with_execution_context_mut(
"text_equal",
serde_json::json!({"a": "x", "b": "x"}),
&mut ctx,
);
assert!(result.is_err());
match result.unwrap_err() {
ToolCallError::ToolUnavailable { tool, .. } => assert_eq!(tool, "text_equal"),
other => panic!("expected ToolUnavailable, got {:?}", other),
}
}
}