Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

style(agent): cargo fmt newly created agent module files

Akarshan Biswas28f9008cd505
diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rs
index 136611c06..c836f4c8d 100644
--- a/src-tauri/src/core/agent/commands.rs
+++ b/src-tauri/src/core/agent/commands.rs
@@ -5,6 +5,7 @@
//! cancellable by `run_id` via `agent_cancel`.
use std::collections::HashMap;
+use std::path::Path;
use std::sync::Arc;
use tauri::ipc::Channel;
@@ -13,7 +14,10 @@ use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, oneshot, Mutex};
use crate::core::agent::events::StreamEvent;
+use crate::core::agent::permissions::ToolPermissions;
+use crate::core::agent::project::{init_project, load_agent_config, permissions_from};
use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs};
+use crate::core::agent::tools::gate::PermissionDecision;
use crate::core::app::commands::get_jan_data_folder_path;
use crate::core::state::AppState;
@@ -22,6 +26,11 @@ use crate::core::state::AppState;
#[derive(Default)]
pub struct AgentRuns(pub Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>);
+/// Registry of in-flight permission prompts keyed by request_id, shared with the
+/// agent loop so `agent_permission_respond` can resolve the awaiting tool call.
+#[derive(Default)]
+pub struct AgentPermissions(pub Arc<Mutex<HashMap<String, oneshot::Sender<PermissionDecision>>>>);
+
fn build_orchestration_args<R: Runtime>(
app_handle: &AppHandle<R>,
state: &AppState,
@@ -36,9 +45,8 @@ fn build_orchestration_args<R: Runtime>(
mlx_state.mlx_server_process.clone()
};
#[cfg(not(target_os = "macos"))]
- let mlx_sessions: Arc<
- Mutex<HashMap<i32, crate::core::server::MlxBackendSession>>,
- > = Arc::new(Mutex::new(HashMap::new()));
+ let mlx_sessions: Arc<Mutex<HashMap<i32, crate::core::server::MlxBackendSession>>> =
+ Arc::new(Mutex::new(HashMap::new()));
OrchestrationArgs {
client: reqwest::Client::new(),
@@ -50,6 +58,9 @@ fn build_orchestration_args<R: Runtime>(
jan_data_folder: get_jan_data_folder_path(app_handle.clone())
.to_string_lossy()
.into_owned(),
+ permissions: ToolPermissions::allow_all(),
+ project_root: None,
+ permission_requests: Arc::new(Mutex::new(HashMap::new())),
}
}
@@ -61,11 +72,21 @@ pub async fn agent_run<R: Runtime>(
app_handle: AppHandle<R>,
state: State<'_, AppState>,
runs: State<'_, AgentRuns>,
+ perms_registry: State<'_, AgentPermissions>,
run_id: String,
body: serde_json::Value,
on_event: Channel<StreamEvent>,
) -> Result<(), String> {
- let args = build_orchestration_args(&app_handle, &state);
+ let mut args = build_orchestration_args(&app_handle, &state);
+ args.permission_requests = perms_registry.0.clone();
+
+ // When a project is explicitly named, its agent.toml governs tool permissions.
+ // A missing/malformed config is a hard error (never silently permissive).
+ if let Some(project) = body.get("project").and_then(|v| v.as_str()) {
+ let cfg = load_agent_config(Path::new(project))?;
+ args.permissions = permissions_from(&cfg);
+ args.project_root = Some(std::path::PathBuf::from(project));
+ }
let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();
let forward = tokio::spawn(async move {
@@ -108,3 +129,22 @@ pub async fn agent_cancel(runs: State<'_, AgentRuns>, run_id: String) -> Result<
}
Ok(())
}
+
+/// Resolve an in-flight permission prompt emitted by the agent loop.
+#[tauri::command]
+pub async fn agent_permission_respond(
+ perms_registry: State<'_, AgentPermissions>,
+ request_id: String,
+ decision: PermissionDecision,
+) -> Result<(), String> {
+ if let Some(tx) = perms_registry.0.lock().await.remove(&request_id) {
+ let _ = tx.send(decision);
+ }
+ Ok(())
+}
+
+/// Scaffold a `.jan/agent/` project skeleton under `project_root`.
+#[tauri::command]
+pub async fn agent_init(project_root: String) -> Result<String, String> {
+ init_project(Path::new(&project_root)).map(|p| p.to_string_lossy().into_owned())
+}
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index df64c73f1..6fc1bd9b8 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -31,6 +31,16 @@ pub enum StreamEvent {
},
/// Terminal failure (setup error, upstream/tool failure, or max_turns).
Error { code: String, message: String },
+ /// The loop needs the user to approve a gated tool call. The client replies via
+ /// the `agent_permission_respond` command referencing `request_id`.
+ PermissionRequest {
+ request_id: String,
+ tool_name: String,
+ capability: String,
+ path: Option<String>,
+ prompt_kind: String,
+ offers_always: bool,
+ },
}
#[derive(Clone, Debug, serde::Serialize)]
@@ -116,6 +126,31 @@ mod tests {
);
}
+ #[test]
+ fn permission_request_serializes_to_wire_shape() {
+ let v = serde_json::to_value(StreamEvent::PermissionRequest {
+ request_id: "perm-1".into(),
+ tool_name: "write".into(),
+ capability: "write".into(),
+ path: Some("out.txt".into()),
+ prompt_kind: "write".into(),
+ offers_always: true,
+ })
+ .unwrap();
+ assert_eq!(
+ v,
+ json!({
+ "type": "permission_request",
+ "request_id": "perm-1",
+ "tool_name": "write",
+ "capability": "write",
+ "path": "out.txt",
+ "prompt_kind": "write",
+ "offers_always": true
+ })
+ );
+ }
+
#[test]
fn usage_parses_present_fields_and_none_when_absent() {
let parsed = Usage::from_completion(&json!({
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index a37cf4d8e..7641c9351 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -7,11 +7,14 @@
use std::collections::HashMap;
use std::sync::Arc;
+use async_trait::async_trait;
use reqwest::Client;
use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, Mutex};
use crate::core::agent::events::{StreamEvent, Usage};
+use crate::core::agent::session::SessionBudget;
+use crate::core::agent::tools::gate::PermissionDecision;
use crate::core::agent::upstream::{
collect_mcp_openai_tools, copy_optional_chat_params, execute_mcp_tool_calls,
extract_choice_message, extract_tool_calls, load_assistant_config, parse_openai_messages,
@@ -24,6 +27,21 @@ use crate::core::{
state::{ProviderConfig, SharedMcpServers},
};
+/// In-flight permission prompts keyed by `request_id`, shared between the loop
+/// (which inserts a one-shot sender before awaiting) and the respond command
+/// (which removes and resolves it).
+pub(crate) type PermissionRegistry =
+ Arc<Mutex<HashMap<String, tokio::sync::oneshot::Sender<PermissionDecision>>>>;
+
+static PERMISSION_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+
+fn next_permission_id() -> String {
+ format!(
+ "perm-{}",
+ PERMISSION_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+ )
+}
+
/// All state the orchestration loop threads from multiple subsystems. Grouped
/// into a struct so the streaming and non-streaming entry points share one
/// argument surface instead of a ten-parameter signature.
@@ -35,6 +53,207 @@ pub(crate) struct OrchestrationArgs {
pub mcp_servers: SharedMcpServers,
pub mcp_settings: Arc<Mutex<McpSettings>>,
pub jan_data_folder: String,
+ pub permissions: crate::core::agent::permissions::ToolPermissions,
+ pub project_root: Option<std::path::PathBuf>,
+ pub permission_requests: PermissionRegistry,
+}
+
+#[async_trait]
+pub(crate) trait ModelInvoker: Send + Sync {
+ async fn invoke(
+ &self,
+ request: &serde_json::Value,
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ ) -> Result<serde_json::Value, String>;
+}
+
+#[async_trait]
+pub(crate) trait ToolInvoker: Send + Sync {
+ async fn invoke(
+ &self,
+ tool_calls: &[serde_json::Value],
+ ) -> Result<Vec<(String, String)>, String>;
+}
+
+struct HttpModelInvoker {
+ client: Client,
+ upstream_url: String,
+ api_keys: Vec<String>,
+}
+
+#[async_trait]
+impl ModelInvoker for HttpModelInvoker {
+ async fn invoke(
+ &self,
+ request: &serde_json::Value,
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ ) -> Result<serde_json::Value, String> {
+ stream_openai_chat_completions(
+ &self.client,
+ &self.upstream_url,
+ &self.api_keys,
+ request,
+ events,
+ )
+ .await
+ }
+}
+
+struct McpToolInvoker {
+ tool_to_server: HashMap<String, String>,
+ mcp_servers: SharedMcpServers,
+ mcp_settings: Arc<Mutex<McpSettings>>,
+}
+
+#[async_trait]
+impl ToolInvoker for McpToolInvoker {
+ async fn invoke(
+ &self,
+ tool_calls: &[serde_json::Value],
+ ) -> Result<Vec<(String, String)>, String> {
+ execute_mcp_tool_calls(
+ tool_calls,
+ &self.tool_to_server,
+ &self.mcp_servers,
+ &self.mcp_settings,
+ )
+ .await
+ }
+}
+
+/// Dispatches built-in tool calls to native handlers (gated by `resolve_decision`)
+/// and everything else to the existing `McpToolInvoker`, preserving input order.
+struct CompositeToolInvoker {
+ mcp: McpToolInvoker,
+ project_root: std::path::PathBuf,
+ permissions: crate::core::agent::permissions::ToolPermissions,
+ events: mpsc::UnboundedSender<StreamEvent>,
+ permission_requests: PermissionRegistry,
+ grants: std::sync::Mutex<crate::core::agent::tools::gate::SessionGrants>,
+}
+
+#[async_trait]
+impl ToolInvoker for CompositeToolInvoker {
+ async fn invoke(
+ &self,
+ tool_calls: &[serde_json::Value],
+ ) -> Result<Vec<(String, String)>, String> {
+ use crate::core::agent::tools::{
+ gate::{resolve_decision, Decision, PromptKind},
+ handlers::execute_builtin,
+ is_builtin, lookup, Capability,
+ };
+ let mut out: Vec<(String, String)> = Vec::with_capacity(tool_calls.len());
+ let mut mcp_calls: Vec<serde_json::Value> = Vec::new();
+ for tc in tool_calls {
+ let name = tc
+ .get("function")
+ .and_then(|f| f.get("name"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if !is_builtin(name) {
+ mcp_calls.push(tc.clone());
+ continue;
+ }
+ let id = tc
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ let args: serde_json::Value = tc
+ .get("function")
+ .and_then(|f| f.get("arguments"))
+ .and_then(|v| v.as_str())
+ .and_then(|s| serde_json::from_str(s).ok())
+ .unwrap_or(serde_json::Value::Object(Default::default()));
+ let tool = lookup(name).expect("is_builtin implies lookup");
+ let snapshot = { *self.grants.lock().unwrap() };
+ let decision = resolve_decision(
+ tool,
+ &args,
+ &self.project_root,
+ &self.permissions,
+ &snapshot,
+ );
+ let text = match decision {
+ Decision::Allow => execute_builtin(tool, &args, &self.project_root).await,
+ Decision::HardDeny => {
+ format!("ERROR: tool '{name}' denied by project policy")
+ }
+ Decision::Prompt(kind) => {
+ let request_id = next_permission_id();
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ self.permission_requests
+ .lock()
+ .await
+ .insert(request_id.clone(), tx);
+ let capability = match tool.capability {
+ Capability::Read => "read",
+ Capability::Write => "write",
+ Capability::Exec => "exec",
+ };
+ let prompt_kind = match kind {
+ PromptKind::ReadEscape => "read_escape",
+ PromptKind::Write => "write",
+ PromptKind::Exec => "exec",
+ };
+ let path = tool
+ .path_args
+ .first()
+ .and_then(|k| args.get(*k))
+ .and_then(|v| v.as_str())
+ .map(String::from);
+ let _ = self.events.send(StreamEvent::PermissionRequest {
+ request_id: request_id.clone(),
+ tool_name: name.to_string(),
+ capability: capability.to_string(),
+ path,
+ prompt_kind: prompt_kind.to_string(),
+ offers_always: true,
+ });
+ // Sender dropped (client gone / run cancelled) => Deny. No timeout:
+ // the run is cancellable via agent_cancel, which drops this future.
+ let decision = rx.await.unwrap_or(PermissionDecision::Deny);
+ // Best-effort cleanup if the respond command didn't consume it.
+ self.permission_requests.lock().await.remove(&request_id);
+ match decision {
+ PermissionDecision::AllowOnce => {
+ execute_builtin(tool, &args, &self.project_root).await
+ }
+ PermissionDecision::AllowAlways => {
+ self.grants.lock().unwrap().grant(kind);
+ // Persist for future runs (best-effort; the session
+ // grant above already covers the rest of this run).
+ let write_capable =
+ matches!(tool.capability, Capability::Write | Capability::Exec);
+ if let Err(e) = crate::core::agent::project::grant_tool_in_agent_toml(
+ &self.project_root,
+ name,
+ write_capable,
+ ) {
+ log::warn!("failed to persist always-allow for '{name}': {e}");
+ }
+ execute_builtin(tool, &args, &self.project_root).await
+ }
+ PermissionDecision::Deny => {
+ format!("ERROR: tool '{name}' denied by user")
+ }
+ }
+ }
+ };
+ out.push((id, text));
+ }
+ if !mcp_calls.is_empty() {
+ out.extend(self.mcp.invoke(&mcp_calls).await?);
+ }
+ let order: HashMap<&str, usize> = tool_calls
+ .iter()
+ .enumerate()
+ .filter_map(|(i, tc)| tc.get("id").and_then(|v| v.as_str()).map(|id| (id, i)))
+ .collect();
+ out.sort_by_key(|(id, _)| *order.get(id.as_str()).unwrap_or(&usize::MAX));
+ Ok(out)
+ }
}
/// API-server entry point. Preserves the original single-final-JSON contract by
@@ -59,6 +278,9 @@ pub(crate) async fn run_server_side_openai_orchestration(
mcp_servers,
mcp_settings,
jan_data_folder: jan_data_folder.to_string(),
+ permissions: crate::core::agent::permissions::ToolPermissions::allow_all(),
+ project_root: None,
+ permission_requests: Arc::new(Mutex::new(HashMap::new())),
};
run_orchestration_streamed(&tx, json_body, &args).await
}
@@ -131,6 +353,9 @@ async fn orchestrate_inner(
mcp_servers,
mcp_settings,
jan_data_folder,
+ permissions,
+ project_root,
+ permission_requests,
} = args;
let messages_value = json_body
@@ -188,6 +413,44 @@ async fn orchestrate_inner(
apply_tool_allowlist(&mut openai_tools, &mut tool_to_server, &names);
}
+ // Permission gate: prune tools the agent is not permitted to call before the
+ // model sees them. Proxy path uses `allow_all()` (unchanged behavior).
+ openai_tools.retain(|t| {
+ t.get("function")
+ .and_then(|f| f.get("name"))
+ .and_then(|n| n.as_str())
+ .map(|n| permissions.permits(n))
+ .unwrap_or(false)
+ });
+ tool_to_server.retain(|name, _| permissions.permits(name));
+
+ if project_root.is_some() {
+ // Built-ins are governed by the capability gate at execution time, so here
+ // we only drop tools explicitly denied in agent.toml (and honor allowed_tools
+ // if the request set one). Advertisement is independent of the read-only
+ // default that applies to opaque MCP tools.
+ let allowed_names: Option<std::collections::HashSet<String>> = json_body
+ .get("allowed_tools")
+ .and_then(|v| v.as_array())
+ .map(|a| {
+ a.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect()
+ });
+ for schema in crate::core::agent::tools::schema::builtin_tool_schemas() {
+ let name = schema["function"]["name"].as_str().unwrap_or_default();
+ if permissions.is_denied(name) {
+ continue;
+ }
+ if let Some(allow) = &allowed_names {
+ if !allow.contains(name) {
+ continue;
+ }
+ }
+ openai_tools.push(schema);
+ }
+ }
+
let (upstream_url, session_api_keys) = resolve_upstream_for_model(
&model_id,
provider_configs.clone(),
@@ -200,8 +463,71 @@ async fn orchestrate_inner(
.get("max_turns")
.and_then(|v| v.as_u64())
.unwrap_or(8)
- .clamp(1, 20) as usize;
+ .clamp(1, 400) as usize;
+
+ let http_model = HttpModelInvoker {
+ client: client.clone(),
+ upstream_url,
+ api_keys: session_api_keys,
+ };
+ let mcp_tools = McpToolInvoker {
+ tool_to_server,
+ mcp_servers: mcp_servers.clone(),
+ mcp_settings: mcp_settings.clone(),
+ };
+ let max_session_tokens = json_body.get("max_session_tokens").and_then(|v| v.as_u64());
+ let mut budget = SessionBudget::new(max_session_tokens);
+
+ if let Some(root) = project_root {
+ let tools = CompositeToolInvoker {
+ mcp: mcp_tools,
+ project_root: root.clone(),
+ permissions: permissions.clone(),
+ events: events.clone(),
+ permission_requests: permission_requests.clone(),
+ grants: std::sync::Mutex::new(crate::core::agent::tools::gate::SessionGrants::default()),
+ };
+ run_turn_cycle(
+ events,
+ json_body,
+ &model_id,
+ &openai_tools,
+ conversation_messages,
+ max_turns,
+ &mut budget,
+ &http_model,
+ &tools,
+ )
+ .await
+ } else {
+ run_turn_cycle(
+ events,
+ json_body,
+ &model_id,
+ &openai_tools,
+ conversation_messages,
+ max_turns,
+ &mut budget,
+ &http_model,
+ &mcp_tools,
+ )
+ .await
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn run_turn_cycle(
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ json_body: &serde_json::Value,
+ model_id: &str,
+ openai_tools: &[serde_json::Value],
+ mut conversation_messages: Vec<serde_json::Value>,
+ max_turns: usize,
+ budget: &mut SessionBudget,
+ model: &dyn ModelInvoker,
+ tools: &dyn ToolInvoker,
+) -> Result<serde_json::Value, String> {
let mut last_response: Option<serde_json::Value> = None;
for turn in 0..max_turns {
@@ -221,21 +547,16 @@ async fn orchestrate_inner(
if !openai_tools.is_empty() {
completion_map.insert(
"tools".to_string(),
- serde_json::Value::Array(openai_tools.clone()),
+ serde_json::Value::Array(openai_tools.to_vec()),
);
}
copy_optional_chat_params(json_body, &mut completion_map);
let request_value = serde_json::Value::Object(completion_map);
- let completion = stream_openai_chat_completions(
- client,
- &upstream_url,
- &session_api_keys,
- &request_value,
- events,
- )
- .await?;
+ let completion = model.invoke(&request_value, events).await?;
+
+ budget.record(&Usage::from_completion(&completion));
let tool_calls = extract_tool_calls(&completion);
last_response = Some(completion.clone());
@@ -244,9 +565,20 @@ async fn orchestrate_inner(
return Ok(completion);
}
+ if budget.exhausted() {
+ return Err(format!(
+ "session token budget exhausted ({} tokens) before resolving tool calls",
+ budget.spent()
+ ));
+ }
+
for tc in &tool_calls {
let _ = events.send(StreamEvent::ToolCall {
- id: tc.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string(),
+ id: tc
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string(),
name: tc
.get("function")
.and_then(|f| f.get("name"))
@@ -280,8 +612,7 @@ async fn orchestrate_inner(
}));
}
- let tool_results =
- execute_mcp_tool_calls(&tool_calls, &tool_to_server, mcp_servers, mcp_settings).await?;
+ let tool_results = tools.invoke(&tool_calls).await?;
for (tool_call_id, result_text) in tool_results {
let _ = events.send(StreamEvent::ToolResult {
@@ -308,6 +639,155 @@ async fn orchestrate_inner(
mod tests {
use super::*;
use serde_json::json;
+ use std::collections::VecDeque;
+ use std::sync::Mutex as StdMutex;
+
+ struct MockModel {
+ responses: StdMutex<VecDeque<serde_json::Value>>,
+ }
+ impl MockModel {
+ fn new(responses: Vec<serde_json::Value>) -> Self {
+ Self {
+ responses: StdMutex::new(responses.into_iter().collect()),
+ }
+ }
+ }
+ #[async_trait]
+ impl ModelInvoker for MockModel {
+ async fn invoke(
+ &self,
+ _request: &serde_json::Value,
+ _events: &mpsc::UnboundedSender<StreamEvent>,
+ ) -> Result<serde_json::Value, String> {
+ self.responses
+ .lock()
+ .unwrap()
+ .pop_front()
+ .ok_or_else(|| "mock model exhausted".to_string())
+ }
+ }
+
+ #[derive(Default)]
+ struct MockTool {
+ calls: StdMutex<Vec<Vec<serde_json::Value>>>,
+ }
+ #[async_trait]
+ impl ToolInvoker for MockTool {
+ async fn invoke(
+ &self,
+ tool_calls: &[serde_json::Value],
+ ) -> Result<Vec<(String, String)>, String> {
+ self.calls.lock().unwrap().push(tool_calls.to_vec());
+ Ok(tool_calls
+ .iter()
+ .map(|tc| {
+ let id = tc
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ (id, "MOCK_RESULT".to_string())
+ })
+ .collect())
+ }
+ }
+
+ fn tool_call_completion() -> serde_json::Value {
+ json!({
+ "choices": [{
+ "message": {
+ "content": serde_json::Value::Null,
+ "tool_calls": [{
+ "id": "call_1",
+ "type": "function",
+ "function": { "name": "search", "arguments": "{\"q\":\"rust\"}" }
+ }]
+ },
+ "finish_reason": "tool_calls"
+ }]
+ })
+ }
+
+ #[tokio::test]
+ async fn turn_cycle_executes_tool_then_returns_final() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let model = MockModel::new(vec![
+ tool_call_completion(),
+ json!({ "choices": [{ "message": { "content": "final answer" }, "finish_reason": "stop" }] }),
+ ]);
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(None);
+ let convo = vec![json!({ "role": "user", "content": "hi" })];
+
+ let result = run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ convo,
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result["choices"][0]["message"]["content"], "final answer");
+ assert_eq!(tool.calls.lock().unwrap().len(), 1);
+ assert_eq!(tool.calls.lock().unwrap()[0][0]["id"], "call_1");
+
+ drop(tx);
+ let mut saw_tool_call = false;
+ let mut saw_tool_result = false;
+ while let Some(ev) = rx.recv().await {
+ match ev {
+ StreamEvent::ToolCall { name, .. } => {
+ if name == "search" {
+ saw_tool_call = true;
+ }
+ }
+ StreamEvent::ToolResult { content, .. } => {
+ if content == "MOCK_RESULT" {
+ saw_tool_result = true;
+ }
+ }
+ _ => {}
+ }
+ }
+ assert!(saw_tool_call && saw_tool_result);
+ }
+
+ #[tokio::test]
+ async fn turn_cycle_stops_when_budget_exhausted() {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let mut over_budget = tool_call_completion();
+ over_budget["usage"] = json!({ "total_tokens": 100 });
+ let model = MockModel::new(vec![over_budget]);
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(Some(50));
+ let convo = vec![json!({ "role": "user", "content": "hi" })];
+
+ let err = run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ convo,
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(err.contains("budget"), "unexpected error: {err}");
+ assert!(
+ tool.calls.lock().unwrap().is_empty(),
+ "tool must not run once budget is exhausted"
+ );
+ }
#[test]
fn stop_reason_reads_first_choice() {
@@ -339,6 +819,171 @@ mod tests {
assert_eq!(map.keys().collect::<Vec<_>>(), vec!["search"]);
}
+ use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};
+ use crate::core::agent::tools::gate::{PermissionDecision, SessionGrants};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ static TEST_ROOT_SEQ: AtomicUsize = AtomicUsize::new(0);
+
+ fn unique_project_root() -> std::path::PathBuf {
+ let n = TEST_ROOT_SEQ.fetch_add(1, Ordering::SeqCst);
+ let dir =
+ std::env::temp_dir().join(format!("jan_loop_perm_test_{}_{}", std::process::id(), n));
+ std::fs::create_dir_all(&dir).expect("create test root");
+ dir
+ }
+
+ fn write_call() -> serde_json::Value {
+ json!({
+ "id": "c1",
+ "type": "function",
+ "function": {
+ "name": "write",
+ "arguments": "{\"path\":\"out.txt\",\"content\":\"hi\"}"
+ }
+ })
+ }
+
+ fn build_prompting_invoker(
+ root: std::path::PathBuf,
+ events: mpsc::UnboundedSender<StreamEvent>,
+ registry: PermissionRegistry,
+ ) -> CompositeToolInvoker {
+ CompositeToolInvoker {
+ mcp: McpToolInvoker {
+ tool_to_server: HashMap::new(),
+ mcp_servers: Arc::new(Mutex::new(HashMap::new())),
+ mcp_settings: Arc::new(Mutex::new(McpSettings::default())),
+ },
+ project_root: root,
+ // Read-only default => write PROMPTS.
+ permissions: ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),
+ events,
+ permission_requests: registry,
+ grants: std::sync::Mutex::new(SessionGrants::default()),
+ }
+ }
+
+ async fn respond_once(
+ rx: &mut mpsc::UnboundedReceiver<StreamEvent>,
+ registry: &PermissionRegistry,
+ decision: PermissionDecision,
+ ) {
+ loop {
+ match rx.recv().await {
+ Some(StreamEvent::PermissionRequest { request_id, .. }) => {
+ let tx = registry.lock().await.remove(&request_id);
+ if let Some(tx) = tx {
+ let _ = tx.send(decision);
+ }
+ return;
+ }
+ Some(_) => continue,
+ None => return,
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn prompt_allow_once_executes_and_writes() {
+ let root = unique_project_root();
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let invoker = Arc::new(build_prompting_invoker(root.clone(), tx, registry.clone()));
+
+ let responder = {
+ let registry = registry.clone();
+ tokio::spawn(async move {
+ respond_once(&mut rx, &registry, PermissionDecision::AllowOnce).await;
+ })
+ };
+
+ let calls = vec![write_call()];
+ let out = invoker.invoke(&calls).await.unwrap();
+ responder.await.unwrap();
+
+ assert_eq!(out.len(), 1);
+ assert!(!out[0].1.starts_with("ERROR"), "unexpected: {}", out[0].1);
+ assert_eq!(std::fs::read_to_string(root.join("out.txt")).unwrap(), "hi");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn prompt_deny_reports_error_and_skips_write() {
+ let root = unique_project_root();
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let invoker = Arc::new(build_prompting_invoker(root.clone(), tx, registry.clone()));
+
+ let responder = {
+ let registry = registry.clone();
+ tokio::spawn(async move {
+ respond_once(&mut rx, &registry, PermissionDecision::Deny).await;
+ })
+ };
+
+ let calls = vec![write_call()];
+ let out = invoker.invoke(&calls).await.unwrap();
+ responder.await.unwrap();
+
+ assert_eq!(out.len(), 1);
+ assert!(out[0].1.contains("denied by user"), "got: {}", out[0].1);
+ assert!(!root.join("out.txt").exists());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn allow_always_grants_and_second_call_skips_prompt() {
+ let root = unique_project_root();
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let invoker = Arc::new(build_prompting_invoker(root.clone(), tx, registry.clone()));
+
+ // Responder answers ONLY the first request with AllowAlways, then counts
+ // any further PermissionRequests (there must be none).
+ let extra_requests = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let responder = {
+ let registry = registry.clone();
+ let extra = extra_requests.clone();
+ tokio::spawn(async move {
+ respond_once(&mut rx, &registry, PermissionDecision::AllowAlways).await;
+ while let Some(ev) = rx.recv().await {
+ if matches!(ev, StreamEvent::PermissionRequest { .. }) {
+ extra.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+ })
+ };
+
+ let out1 = invoker.invoke(&[write_call()]).await.unwrap();
+ assert!(!out1[0].1.starts_with("ERROR"), "first: {}", out1[0].1);
+
+ let second = json!({
+ "id": "c2",
+ "type": "function",
+ "function": {
+ "name": "write",
+ "arguments": "{\"path\":\"out2.txt\",\"content\":\"yo\"}"
+ }
+ });
+ let out2 = invoker.invoke(&[second]).await.unwrap();
+ assert!(!out2[0].1.starts_with("ERROR"), "second: {}", out2[0].1);
+
+ drop(invoker); // close events channel so responder loop ends
+ responder.await.unwrap();
+
+ assert_eq!(
+ extra_requests.load(Ordering::SeqCst),
+ 0,
+ "second write must not prompt again after AllowAlways"
+ );
+ assert_eq!(
+ std::fs::read_to_string(root.join("out2.txt")).unwrap(),
+ "yo"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[test]
fn tool_allowlist_empty_removes_all() {
let mut tools = vec![json!({ "type": "function", "function": { "name": "search" } })];
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index ef74b203c..19c1e838a 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -4,4 +4,8 @@
pub mod commands;
pub mod events;
pub mod r#loop;
+pub mod permissions;
+pub mod project;
+pub mod session;
+pub mod tools;
pub mod upstream;
diff --git a/src-tauri/src/core/agent/permissions.rs b/src-tauri/src/core/agent/permissions.rs
new file mode 100644
index 000000000..7526e859a
--- /dev/null
+++ b/src-tauri/src/core/agent/permissions.rs
@@ -0,0 +1,175 @@
+//! Tool-permission gate built from the `[tools]` section of `agent.toml`.
+//! Tools are MCP-only, so read/write cannot be inferred from a tool; classification
+//! is purely by the explicit name/glob lists. Deny always wins.
+
+use glob::Pattern;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub(crate) enum PermissionDefault {
+ Allow,
+ Deny,
+ #[default]
+ ReadOnly,
+}
+
+impl PermissionDefault {
+ /// Lenient parser: unknown/empty falls back to the secure default (ReadOnly).
+ pub(crate) fn from_str_lenient(s: &str) -> Self {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "allow" => PermissionDefault::Allow,
+ "deny" => PermissionDefault::Deny,
+ "read-only" | "readonly" => PermissionDefault::ReadOnly,
+ _ => PermissionDefault::ReadOnly,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct ToolPermissions {
+ default: PermissionDefault,
+ allow: Vec<Pattern>,
+ deny: Vec<Pattern>,
+ allow_write: Vec<Pattern>,
+}
+
+fn compile(patterns: &[String]) -> Vec<Pattern> {
+ patterns
+ .iter()
+ .filter_map(|p| Pattern::new(p).ok())
+ .collect()
+}
+
+impl ToolPermissions {
+ pub(crate) fn new(
+ default: PermissionDefault,
+ allow: &[String],
+ deny: &[String],
+ allow_write: &[String],
+ ) -> Self {
+ Self {
+ default,
+ allow: compile(allow),
+ deny: compile(deny),
+ allow_write: compile(allow_write),
+ }
+ }
+
+ /// Permissive: allow-by-default with no lists. Used when no `[tools]` section
+ /// is configured, preserving the loop's historical "run all tools" behavior.
+ pub(crate) fn allow_all() -> Self {
+ Self {
+ default: PermissionDefault::Allow,
+ allow: Vec::new(),
+ deny: Vec::new(),
+ allow_write: Vec::new(),
+ }
+ }
+
+ pub(crate) fn is_denied(&self, name: &str) -> bool {
+ self.deny.iter().any(|p| p.matches(name))
+ }
+
+ /// Explicit allow-list membership (allow OR allow_write); does NOT consider deny or default.
+ pub(crate) fn is_allowed(&self, name: &str) -> bool {
+ self.allow.iter().any(|p| p.matches(name))
+ || self.allow_write.iter().any(|p| p.matches(name))
+ }
+
+ /// Deny always wins. Then an explicit allow / allow_write match permits.
+ /// Otherwise fall back to the default policy: Allow permits, Deny/ReadOnly block.
+ pub(crate) fn permits(&self, tool_name: &str) -> bool {
+ if self.is_denied(tool_name) {
+ return false;
+ }
+ self.is_allowed(tool_name) || matches!(self.default, PermissionDefault::Allow)
+ }
+}
+
+impl Default for ToolPermissions {
+ fn default() -> Self {
+ Self::allow_all()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn s(items: &[&str]) -> Vec<String> {
+ items.iter().map(|v| v.to_string()).collect()
+ }
+
+ #[test]
+ fn read_only_default_blocks_unlisted_tools() {
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ assert!(!perms.permits("mcp.search"));
+
+ let perms =
+ ToolPermissions::new(PermissionDefault::ReadOnly, &s(&["mcp.search"]), &[], &[]);
+ assert!(perms.permits("mcp.search"));
+ }
+
+ #[test]
+ fn deny_wins_over_allow() {
+ let perms = ToolPermissions::new(
+ PermissionDefault::ReadOnly,
+ &s(&["fs.*"]),
+ &s(&["fs.delete"]),
+ &[],
+ );
+ assert!(perms.permits("fs.read"));
+ assert!(!perms.permits("fs.delete"));
+ }
+
+ #[test]
+ fn write_is_opt_in() {
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ assert!(!perms.permits("fs.write"));
+
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &s(&["fs.write"]));
+ assert!(perms.permits("fs.write"));
+ }
+
+ #[test]
+ fn allow_default_permits_unlisted_but_deny_blocks() {
+ let perms = ToolPermissions::new(PermissionDefault::Allow, &[], &s(&["secret.*"]), &[]);
+ assert!(perms.permits("anything"));
+ assert!(!perms.permits("secret.key"));
+ }
+
+ #[test]
+ fn glob_matching() {
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &s(&["rag.*"]), &[], &[]);
+ assert!(perms.permits("rag.query"));
+ assert!(!perms.permits("mcp.search"));
+ }
+
+ #[test]
+ fn allow_all_is_permissive() {
+ assert!(ToolPermissions::allow_all().permits("x"));
+ }
+
+ #[test]
+ fn lenient_parse() {
+ assert_eq!(
+ PermissionDefault::from_str_lenient("allow"),
+ PermissionDefault::Allow
+ );
+ assert_eq!(
+ PermissionDefault::from_str_lenient("DENY"),
+ PermissionDefault::Deny
+ );
+ assert_eq!(
+ PermissionDefault::from_str_lenient("read-only"),
+ PermissionDefault::ReadOnly
+ );
+ assert_eq!(
+ PermissionDefault::from_str_lenient("readonly"),
+ PermissionDefault::ReadOnly
+ );
+ assert_eq!(
+ PermissionDefault::from_str_lenient("bogus"),
+ PermissionDefault::ReadOnly
+ );
+ }
+}
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
new file mode 100644
index 000000000..de468dfe0
--- /dev/null
+++ b/src-tauri/src/core/agent/project.rs
@@ -0,0 +1,241 @@
+//! `agent.toml` project config parsing and `.jan/agent/` scaffolding.
+
+use std::path::{Path, PathBuf};
+
+use serde::Deserialize;
+
+use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};
+
+/// Only `[tools]` is modeled this phase. serde ignores unknown sections
+/// (`[agent]`/`[budget]`/`[skills]`), which return when their consumers land.
+#[derive(Debug, Clone, Default, Deserialize)]
+pub(crate) struct AgentToml {
+ #[serde(default)]
+ pub tools: ToolsSection,
+}
+
+#[derive(Debug, Clone, Default, Deserialize)]
+pub(crate) struct ToolsSection {
+ #[serde(default)]
+ pub default: Option<String>,
+ #[serde(default)]
+ pub allow: Vec<String>,
+ #[serde(default)]
+ pub deny: Vec<String>,
+ #[serde(default)]
+ pub allow_write: Vec<String>,
+}
+
+const AGENT_TOML_TEMPLATE: &str = r#"[agent]
+# model = "Jan-V4"
+max_turns = 8
+instructions_file = "AGENT.md"
+
+[budget]
+max_steps = 40
+max_tokens = 200000
+
+[tools]
+# read-only | deny | allow. Secure default: read-only.
+default = "read-only"
+allow = []
+deny = []
+# Write tools are opt-in only:
+# allow_write = ["fs.write"]
+allow_write = []
+
+[skills]
+enabled = []
+# always | relevance
+inject = "always"
+"#;
+
+const AGENT_MD_TEMPLATE: &str =
+ "# Agent Instructions\n\nDescribe how this project's agent should behave.\n";
+
+/// Path to `<project_root>/.jan/agent/agent.toml`.
+pub(crate) fn agent_toml_path(project_root: &Path) -> PathBuf {
+ project_root.join(".jan").join("agent").join("agent.toml")
+}
+
+/// Load + parse agent.toml. Err if missing or malformed (path included in message).
+pub(crate) fn load_agent_config(project_root: &Path) -> Result<AgentToml, String> {
+ let path = agent_toml_path(project_root);
+ let raw = std::fs::read_to_string(&path)
+ .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
+ toml::from_str(&raw).map_err(|e| format!("Failed to parse {}: {e}", path.display()))
+}
+
+/// Build a `ToolPermissions` from the parsed `[tools]` section.
+pub(crate) fn permissions_from(cfg: &AgentToml) -> ToolPermissions {
+ let default = cfg
+ .tools
+ .default
+ .as_deref()
+ .map(PermissionDefault::from_str_lenient)
+ .unwrap_or_default();
+ ToolPermissions::new(
+ default,
+ &cfg.tools.allow,
+ &cfg.tools.deny,
+ &cfg.tools.allow_write,
+ )
+}
+
+/// Scaffold `<project_root>/.jan/agent/{agent.toml, AGENT.md, skills/, memory/}`.
+/// Err if `agent.toml` already exists (no clobber). Returns the created agent dir.
+pub(crate) fn init_project(project_root: &Path) -> Result<PathBuf, String> {
+ let agent_dir = project_root.join(".jan").join("agent");
+ let toml_path = agent_dir.join("agent.toml");
+ if toml_path.exists() {
+ return Err(format!(
+ "agent.toml already exists at {}",
+ toml_path.display()
+ ));
+ }
+
+ std::fs::create_dir_all(agent_dir.join("skills"))
+ .map_err(|e| format!("Failed to create skills dir: {e}"))?;
+ std::fs::create_dir_all(agent_dir.join("memory"))
+ .map_err(|e| format!("Failed to create memory dir: {e}"))?;
+
+ std::fs::write(&toml_path, AGENT_TOML_TEMPLATE)
+ .map_err(|e| format!("Failed to write {}: {e}", toml_path.display()))?;
+ let md_path = agent_dir.join("AGENT.md");
+ std::fs::write(&md_path, AGENT_MD_TEMPLATE)
+ .map_err(|e| format!("Failed to write {}: {e}", md_path.display()))?;
+
+ Ok(agent_dir)
+}
+
+/// Persist an always-allow grant for `tool_name` into agent.toml, format-preserving
+/// (comments kept). Write/exec tools go into `[tools].allow_write`, read tools into
+/// `[tools].allow`. Idempotent (no duplicate entries). Errs if agent.toml is missing.
+pub(crate) fn grant_tool_in_agent_toml(
+ project_root: &Path,
+ tool_name: &str,
+ write_capable: bool,
+) -> Result<(), String> {
+ let path = agent_toml_path(project_root);
+ let raw = std::fs::read_to_string(&path)
+ .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
+ let mut doc = raw
+ .parse::<toml_edit::DocumentMut>()
+ .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
+
+ let tools = doc["tools"].or_insert(toml_edit::Item::Table(toml_edit::Table::new()));
+ let key = if write_capable {
+ "allow_write"
+ } else {
+ "allow"
+ };
+ let list = tools[key].or_insert(toml_edit::value(toml_edit::Array::new()));
+ let arr = list
+ .as_array_mut()
+ .ok_or_else(|| format!("[tools].{key} is not an array in {}", path.display()))?;
+
+ if arr.iter().any(|v| v.as_str() == Some(tool_name)) {
+ return Ok(());
+ }
+ arr.push(tool_name);
+
+ std::fs::write(&path, doc.to_string())
+ .map_err(|e| format!("Failed to write {}: {e}", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicU32, Ordering};
+
+ static COUNTER: AtomicU32 = AtomicU32::new(0);
+
+ fn unique_root(tag: &str) -> PathBuf {
+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);
+ std::env::temp_dir().join(format!("jan_agent_test_{tag}_{n}"))
+ }
+
+ #[test]
+ fn init_creates_artifacts_and_refuses_clobber() {
+ let root = unique_root("init");
+ let dir = init_project(&root).expect("init");
+ assert!(dir.join("agent.toml").exists());
+ assert!(dir.join("AGENT.md").exists());
+ assert!(dir.join("skills").is_dir());
+ assert!(dir.join("memory").is_dir());
+
+ assert!(init_project(&root).is_err());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn load_roundtrips_template() {
+ let root = unique_root("roundtrip");
+ init_project(&root).expect("init");
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.tools.default.as_deref(), Some("read-only"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn load_missing_errors() {
+ let root = unique_root("missing");
+ assert!(load_agent_config(&root).is_err());
+ }
+
+ #[test]
+ fn full_template_parses_ignoring_deferred_sections() {
+ let root = unique_root("full");
+ init_project(&root).expect("init");
+ // The template carries [agent]/[budget]/[skills] we don't model yet;
+ // parsing must succeed and read [tools].
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.tools.default.as_deref(), Some("read-only"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn permissions_from_default_template_is_read_only() {
+ let root = unique_root("perms");
+ init_project(&root).expect("init");
+ let cfg = load_agent_config(&root).expect("load");
+ let perms = permissions_from(&cfg);
+ assert!(!perms.permits("mcp.search"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn permissions_from_respects_allow_list() {
+ let mut cfg = AgentToml::default();
+ cfg.tools.default = Some("read-only".to_string());
+ cfg.tools.allow = vec!["mcp.search".to_string()];
+ let perms = permissions_from(&cfg);
+ assert!(perms.permits("mcp.search"));
+ }
+
+ #[test]
+ fn grant_persists_by_capability_and_is_idempotent_and_keeps_comments() {
+ let root = unique_root("grant");
+ init_project(&root).expect("init");
+
+ grant_tool_in_agent_toml(&root, "write", true).expect("grant write");
+ grant_tool_in_agent_toml(&root, "read", false).expect("grant read");
+ // Idempotent: a second identical grant does not duplicate.
+ grant_tool_in_agent_toml(&root, "write", true).expect("grant write again");
+
+ let cfg = load_agent_config(&root).expect("load");
+ assert_eq!(cfg.tools.allow_write, vec!["write".to_string()]);
+ assert_eq!(cfg.tools.allow, vec!["read".to_string()]);
+
+ // Format-preserving: the template's comment survives the edit.
+ let raw = std::fs::read_to_string(agent_toml_path(&root)).expect("read raw");
+ assert!(raw.contains("Secure default"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn grant_missing_agent_toml_errors() {
+ let root = unique_root("grant_missing");
+ assert!(grant_tool_in_agent_toml(&root, "write", true).is_err());
+ }
+}
diff --git a/src-tauri/src/core/agent/session.rs b/src-tauri/src/core/agent/session.rs
new file mode 100644
index 000000000..a2b7c8c5d
--- /dev/null
+++ b/src-tauri/src/core/agent/session.rs
@@ -0,0 +1,74 @@
+//! Session-level budget caps for the agent loop. Tracks cumulative token usage
+//! across turns and signals when a configured ceiling is reached.
+
+use crate::core::agent::events::Usage;
+
+#[derive(Debug, Default)]
+pub(crate) struct SessionBudget {
+ max_tokens: Option<u64>,
+ spent_tokens: u64,
+}
+
+impl SessionBudget {
+ pub(crate) fn new(max_tokens: Option<u64>) -> Self {
+ Self {
+ max_tokens,
+ spent_tokens: 0,
+ }
+ }
+
+ /// Fold a completion's usage into the running total, returning the new total.
+ pub(crate) fn record(&mut self, usage: &Option<Usage>) -> u64 {
+ if let Some(total) = usage.as_ref().and_then(|u| u.total_tokens) {
+ self.spent_tokens = self.spent_tokens.saturating_add(total);
+ }
+ self.spent_tokens
+ }
+
+ pub(crate) fn spent(&self) -> u64 {
+ self.spent_tokens
+ }
+
+ /// True only when a ceiling is configured and has been reached or exceeded.
+ pub(crate) fn exhausted(&self) -> bool {
+ matches!(self.max_tokens, Some(max) if self.spent_tokens >= max)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::events::Usage;
+
+ fn usage(total: Option<u64>) -> Option<Usage> {
+ Some(Usage {
+ prompt_tokens: None,
+ completion_tokens: None,
+ total_tokens: total,
+ })
+ }
+
+ #[test]
+ fn no_ceiling_is_never_exhausted() {
+ let mut b = SessionBudget::new(None);
+ assert_eq!(b.record(&usage(Some(1_000_000))), 1_000_000);
+ assert!(!b.exhausted());
+ }
+
+ #[test]
+ fn accumulates_and_exhausts_at_or_over_ceiling() {
+ let mut b = SessionBudget::new(Some(100));
+ b.record(&usage(Some(60)));
+ assert!(!b.exhausted());
+ b.record(&usage(Some(40)));
+ assert!(b.exhausted());
+ assert_eq!(b.spent(), 100);
+ }
+
+ #[test]
+ fn absent_usage_does_not_advance_spend() {
+ let mut b = SessionBudget::new(Some(10));
+ assert_eq!(b.record(&None), 0);
+ assert!(!b.exhausted());
+ }
+}
diff --git a/src-tauri/src/core/agent/tools/gate.rs b/src-tauri/src/core/agent/tools/gate.rs
new file mode 100644
index 000000000..2077712ff
--- /dev/null
+++ b/src-tauri/src/core/agent/tools/gate.rs
@@ -0,0 +1,257 @@
+use std::path::Path;
+
+use serde::{Deserialize, Serialize};
+
+use crate::core::agent::permissions::ToolPermissions;
+use crate::core::agent::tools::sandbox::escapes_project;
+use crate::core::agent::tools::{BuiltinTool, Capability};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PromptKind {
+ ReadEscape,
+ Write,
+ Exec,
+}
+
+/// The user's answer to a permission prompt (wire shape for a later IPC command).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PermissionDecision {
+ AllowOnce,
+ AllowAlways,
+ Deny,
+}
+
+#[derive(Debug, Clone, Copy, Default)]
+pub struct SessionGrants {
+ read_escape: bool,
+ write: bool,
+ exec: bool,
+}
+
+impl SessionGrants {
+ pub fn covers(&self, kind: PromptKind) -> bool {
+ match kind {
+ PromptKind::ReadEscape => self.read_escape,
+ PromptKind::Write => self.write,
+ PromptKind::Exec => self.exec,
+ }
+ }
+
+ pub fn grant(&mut self, kind: PromptKind) {
+ match kind {
+ PromptKind::ReadEscape => self.read_escape = true,
+ PromptKind::Write => self.write = true,
+ PromptKind::Exec => self.exec = true,
+ }
+ }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub enum Decision {
+ Allow,
+ HardDeny,
+ Prompt(PromptKind),
+}
+
+/// Decide how a built-in tool call should be gated, combining the static
+/// agent.toml policy, capability class, sandbox escape, and session grants.
+///
+/// Precedence: deny (agent.toml) > explicit allow/allow_write (agent.toml) >
+/// session grant > capability rules. Reads inside the project are silently
+/// allowed; reads that escape the project, and all writes/exec, prompt (unless
+/// already granted this session or pre-approved in agent.toml).
+pub fn resolve_decision(
+ tool: &BuiltinTool,
+ args: &serde_json::Value,
+ project_root: &Path,
+ perms: &ToolPermissions,
+ grants: &SessionGrants,
+) -> Decision {
+ if perms.is_denied(tool.name) {
+ return Decision::HardDeny;
+ }
+ if perms.is_allowed(tool.name) {
+ return Decision::Allow;
+ }
+ match tool.capability {
+ Capability::Read => {
+ let escapes = tool.path_args.iter().any(|key| {
+ args.get(key)
+ .and_then(|v| v.as_str())
+ .map(|p| escapes_project(project_root, p).unwrap_or(true))
+ .unwrap_or(false)
+ });
+ if !escapes || grants.covers(PromptKind::ReadEscape) {
+ Decision::Allow
+ } else {
+ Decision::Prompt(PromptKind::ReadEscape)
+ }
+ }
+ Capability::Write => gated(PromptKind::Write, grants),
+ Capability::Exec => gated(PromptKind::Exec, grants),
+ }
+}
+
+fn gated(kind: PromptKind, grants: &SessionGrants) -> Decision {
+ if grants.covers(kind) {
+ Decision::Allow
+ } else {
+ Decision::Prompt(kind)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};
+ use crate::core::agent::tools::lookup;
+ use serde_json::json;
+ use std::path::PathBuf;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ static COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+ fn unique_root() -> PathBuf {
+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let dir = std::env::temp_dir().join(format!("jan_gate_test_{}_{}", std::process::id(), n));
+ std::fs::create_dir_all(&dir).expect("create test root");
+ dir
+ }
+
+ fn s(items: &[&str]) -> Vec<String> {
+ items.iter().map(|v| v.to_string()).collect()
+ }
+
+ #[test]
+ fn in_project_read_allows() {
+ let root = unique_root();
+ std::fs::write(root.join("inner.txt"), b"x").unwrap();
+ let perms = ToolPermissions::allow_all();
+ let grants = SessionGrants::default();
+ let d = resolve_decision(
+ lookup("read").unwrap(),
+ &json!({"path": "inner.txt"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Allow);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn escaping_read_prompts() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ let grants = SessionGrants::default();
+ let d = resolve_decision(
+ lookup("read").unwrap(),
+ &json!({"path": "../x"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Prompt(PromptKind::ReadEscape));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn write_prompts_by_default() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ let grants = SessionGrants::default();
+ let d = resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": "out.txt"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Prompt(PromptKind::Write));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn bash_prompts_exec() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ let grants = SessionGrants::default();
+ let d = resolve_decision(
+ lookup("bash").unwrap(),
+ &json!({"command": "ls"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Prompt(PromptKind::Exec));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn deny_wins_over_prompt() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &s(&["write"]), &[]);
+ let grants = SessionGrants::default();
+ let d = resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": "out.txt"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::HardDeny);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn explicit_allow_write_skips_prompt() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &s(&["write"]));
+ let grants = SessionGrants::default();
+ let d = resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": "out.txt"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Allow);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn session_grant_allows_write() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ let mut grants = SessionGrants::default();
+ grants.grant(PromptKind::Write);
+ let d = resolve_decision(
+ lookup("write").unwrap(),
+ &json!({"path": "out.txt"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Allow);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn session_grant_allows_read_escape() {
+ let root = unique_root();
+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);
+ let mut grants = SessionGrants::default();
+ grants.grant(PromptKind::ReadEscape);
+ let d = resolve_decision(
+ lookup("read").unwrap(),
+ &json!({"path": "../x"}),
+ &root,
+ &perms,
+ &grants,
+ );
+ assert_eq!(d, Decision::Allow);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/src/core/agent/tools/handlers.rs
new file mode 100644
index 000000000..637c5b411
--- /dev/null
+++ b/src-tauri/src/core/agent/tools/handlers.rs
@@ -0,0 +1,695 @@
+//! Native execution of the built-in tools. Sandbox escape is enforced by the
+//! gate before these run; handlers only resolve paths and perform the operation.
+//! Errors are returned as a String starting with "ERROR" (matching
+//! `execute_mcp_tool_calls`) so the loop flags `is_error` correctly.
+
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use ignore::WalkBuilder;
+
+use crate::core::agent::tools::BuiltinTool;
+
+const MAX_BYTES: usize = 64 * 1024;
+const MAX_LINES: usize = 2000;
+const GREP_MAX_LINE: usize = 500;
+const LS_DEFAULT_LIMIT: usize = 500;
+const FIND_DEFAULT_LIMIT: usize = 1000;
+const GREP_DEFAULT_LIMIT: usize = 100;
+
+/// Counter for unique temp-file names for truncated bash output.
+static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+fn resolve(project_root: &Path, raw: &str) -> PathBuf {
+ if Path::new(raw).is_absolute() {
+ PathBuf::from(raw)
+ } else {
+ project_root.join(raw)
+ }
+}
+
+fn arg_str<'a>(args: &'a serde_json::Value, key: &str) -> Option<&'a str> {
+ args.get(key).and_then(|v| v.as_str())
+}
+
+fn arg_u64(args: &serde_json::Value, key: &str) -> Option<u64> {
+ args.get(key).and_then(|v| v.as_u64())
+}
+
+fn arg_bool(args: &serde_json::Value, key: &str) -> bool {
+ args.get(key).and_then(|v| v.as_bool()).unwrap_or(false)
+}
+
+fn rel_to(base: &Path, path: &Path) -> String {
+ path.strip_prefix(base)
+ .unwrap_or(path)
+ .to_string_lossy()
+ .replace('\\', "/")
+}
+
+/// Truncate `s` to the smaller of the line cap or the byte cap, appending
+/// `note` when truncation occurred.
+fn cap_output(s: &str, max_lines: usize, note: &str) -> String {
+ let mut out = String::new();
+ let mut truncated = false;
+ for (lines, line) in s.split_inclusive('\n').enumerate() {
+ if lines >= max_lines || out.len() + line.len() > MAX_BYTES {
+ truncated = true;
+ break;
+ }
+ out.push_str(line);
+ }
+ if truncated {
+ out.push_str(note);
+ }
+ out
+}
+
+/// Execute a built-in tool. Returns the tool-result text. Errors are returned
+/// as a String STARTING WITH "ERROR" rather than as Err.
+pub async fn execute_builtin(
+ tool: &BuiltinTool,
+ args: &serde_json::Value,
+ project_root: &Path,
+) -> String {
+ match tool.name {
+ "read" => read(args, project_root).await,
+ "ls" => ls(args, project_root).await,
+ "write" => write(args, project_root).await,
+ "edit" => edit(args, project_root).await,
+ "bash" => bash(args, project_root).await,
+ "find" => find(args, project_root).await,
+ "grep" => grep(args, project_root).await,
+ other => format!("ERROR: unknown built-in tool '{other}'"),
+ }
+}
+
+async fn read(args: &serde_json::Value, root: &Path) -> String {
+ let Some(path) = arg_str(args, "path") else {
+ return "ERROR: missing required argument 'path'".to_string();
+ };
+ let offset = arg_u64(args, "offset").map(|v| v as usize);
+ let limit = arg_u64(args, "limit").map(|v| v as usize);
+ let target = resolve(root, path);
+
+ let bytes = match tokio::fs::read(&target).await {
+ Ok(b) => b,
+ Err(e) => return format!("ERROR: {e}"),
+ };
+ let content = match String::from_utf8(bytes) {
+ Ok(c) => c,
+ Err(_) => return "ERROR: not a UTF-8 text file".to_string(),
+ };
+
+ let selected = if offset.is_some() || limit.is_some() {
+ let lines: Vec<&str> = content.split('\n').collect();
+ let start = offset.map(|o| o.saturating_sub(1)).unwrap_or(0);
+ if start >= lines.len() {
+ return format!(
+ "ERROR: offset {} is beyond end of file ({} lines total)",
+ offset.unwrap_or(1),
+ lines.len()
+ );
+ }
+ let end = match limit {
+ Some(l) => (start + l).min(lines.len()),
+ None => lines.len(),
+ };
+ lines[start..end].join("\n")
+ } else {
+ content
+ };
+
+ cap_output(
+ &selected,
+ MAX_LINES,
+ "\n[truncated: use offset/limit to read more]",
+ )
+}
+
+async fn ls(args: &serde_json::Value, root: &Path) -> String {
+ let path = arg_str(args, "path").unwrap_or(".");
+ let limit = arg_u64(args, "limit")
+ .map(|v| v as usize)
+ .unwrap_or(LS_DEFAULT_LIMIT);
+ let mut entries = match tokio::fs::read_dir(resolve(root, path)).await {
+ Ok(rd) => rd,
+ Err(e) => return format!("ERROR: {e}"),
+ };
+ let mut names: Vec<String> = Vec::new();
+ loop {
+ match entries.next_entry().await {
+ Ok(Some(entry)) => {
+ let mut name = entry.file_name().to_string_lossy().into_owned();
+ if entry.file_type().await.map(|t| t.is_dir()).unwrap_or(false) {
+ name.push('/');
+ }
+ names.push(name);
+ }
+ Ok(None) => break,
+ Err(e) => return format!("ERROR: {e}"),
+ }
+ }
+ names.sort_by_key(|n| n.to_lowercase());
+ let entry_limited = names.len() > limit;
+ names.truncate(limit);
+ let mut joined = names.join("\n");
+ if entry_limited {
+ joined.push_str(&format!("\n[truncated: {limit} entry limit]"));
+ }
+ cap_output(&joined, usize::MAX, "\n[truncated: 64KB limit]")
+}
+
+async fn write(args: &serde_json::Value, root: &Path) -> String {
+ let Some(path) = arg_str(args, "path") else {
+ return "ERROR: missing required argument 'path'".to_string();
+ };
+ let Some(content) = arg_str(args, "content") else {
+ return "ERROR: missing required argument 'content'".to_string();
+ };
+ let target = resolve(root, path);
+ if let Some(parent) = target.parent() {
+ if let Err(e) = tokio::fs::create_dir_all(parent).await {
+ return format!("ERROR: {e}");
+ }
+ }
+ match tokio::fs::write(&target, content).await {
+ Ok(()) => format!("Wrote {} bytes to {}", content.len(), path),
+ Err(e) => format!("ERROR: {e}"),
+ }
+}
+
+async fn edit(args: &serde_json::Value, root: &Path) -> String {
+ let Some(path) = arg_str(args, "path") else {
+ return "ERROR: missing required argument 'path'".to_string();
+ };
+ let Some(edits) = args.get("edits").and_then(|v| v.as_array()) else {
+ return "ERROR: missing required argument 'edits'".to_string();
+ };
+ if edits.is_empty() {
+ return "ERROR: edits must contain at least one replacement".to_string();
+ }
+ let target = resolve(root, path);
+ let mut content = match tokio::fs::read_to_string(&target).await {
+ Ok(c) => c,
+ Err(e) => return format!("ERROR: {e}"),
+ };
+
+ for (i, e) in edits.iter().enumerate() {
+ let Some(old_string) = e.get("old_string").and_then(|v| v.as_str()) else {
+ return format!("ERROR: edit {}: missing 'old_string'", i + 1);
+ };
+ let Some(new_string) = e.get("new_string").and_then(|v| v.as_str()) else {
+ return format!("ERROR: edit {}: missing 'new_string'", i + 1);
+ };
+ let count = content.matches(old_string).count();
+ if count == 0 {
+ return format!("ERROR: edit {}: old_string not found", i + 1);
+ }
+ if count > 1 {
+ return format!(
+ "ERROR: edit {}: old_string not unique ({count} matches)",
+ i + 1
+ );
+ }
+ content = content.replacen(old_string, new_string, 1);
+ }
+
+ match tokio::fs::write(&target, content).await {
+ Ok(()) => format!("Applied {} edit(s) to {}", edits.len(), path),
+ Err(e) => format!("ERROR: {e}"),
+ }
+}
+
+async fn bash(args: &serde_json::Value, root: &Path) -> String {
+ let Some(command) = arg_str(args, "command") else {
+ return "ERROR: missing required argument 'command'".to_string();
+ };
+ let timeout = arg_u64(args, "timeout");
+
+ let child = match tokio::process::Command::new("sh")
+ .arg("-c")
+ .arg(command)
+ .current_dir(root)
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped())
+ .kill_on_drop(true)
+ .spawn()
+ {
+ Ok(c) => c,
+ Err(e) => return format!("ERROR: failed to run command: {e}"),
+ };
+
+ let output = match timeout {
+ Some(secs) => {
+ let dur = std::time::Duration::from_secs(secs);
+ match tokio::time::timeout(dur, child.wait_with_output()).await {
+ Ok(res) => res,
+ Err(_) => {
+ return format!("ERROR: command timed out after {secs}s");
+ }
+ }
+ }
+ None => child.wait_with_output().await,
+ };
+
+ match output {
+ Ok(out) => {
+ let mut combined = String::new();
+ combined.push_str(&String::from_utf8_lossy(&out.stdout));
+ combined.push_str(&String::from_utf8_lossy(&out.stderr));
+ match out.status.code() {
+ Some(0) => {}
+ Some(code) => combined.push_str(&format!("[exit {code}]")),
+ None => combined.push_str("[terminated by signal]"),
+ }
+ let capped = cap_output(&combined, MAX_LINES, "");
+ if capped.len() < combined.len() {
+ let full_path = write_temp_output(&combined);
+ match full_path {
+ Some(p) => format!("{capped}\n[truncated; full output at {p}]"),
+ None => format!("{capped}\n[truncated]"),
+ }
+ } else {
+ capped
+ }
+ }
+ Err(e) => format!("ERROR: failed to run command: {e}"),
+ }
+}
+
+/// Write `content` to a uniquely named temp file, returning its path on success.
+fn write_temp_output(content: &str) -> Option<String> {
+ let n = TEMP_COUNTER.fetch_add(1, Ordering::SeqCst);
+ let path = std::env::temp_dir().join(format!("jan-bash-{}-{}.txt", std::process::id(), n));
+ std::fs::write(&path, content).ok()?;
+ Some(path.to_string_lossy().into_owned())
+}
+
+async fn find(args: &serde_json::Value, root: &Path) -> String {
+ let pattern = arg_str(args, "pattern").map(String::from);
+ let path = arg_str(args, "path").unwrap_or(".").to_string();
+ let limit = arg_u64(args, "limit")
+ .map(|v| v as usize)
+ .unwrap_or(FIND_DEFAULT_LIMIT);
+ let base = resolve(root, &path);
+
+ let Some(pattern) = pattern else {
+ return "ERROR: missing required argument 'pattern'".to_string();
+ };
+ let res = tokio::task::spawn_blocking(move || {
+ let pat = match glob::Pattern::new(&pattern) {
+ Ok(p) => p,
+ Err(e) => return format!("ERROR: invalid pattern: {e}"),
+ };
+ let opts = glob::MatchOptions {
+ case_sensitive: true,
+ require_literal_separator: false,
+ require_literal_leading_dot: false,
+ };
+ let mut matches: Vec<String> = Vec::new();
+ for entry in WalkBuilder::new(&base)
+ .hidden(false)
+ .require_git(false)
+ .build()
+ .flatten()
+ {
+ if entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {
+ continue;
+ }
+ let rel = rel_to(&base, entry.path());
+ if pat.matches_with(&rel, opts) {
+ matches.push(rel);
+ if matches.len() >= limit {
+ break;
+ }
+ }
+ }
+ if matches.is_empty() {
+ "No matches.".to_string()
+ } else {
+ matches.join("\n")
+ }
+ })
+ .await;
+ res.unwrap_or_else(|e| format!("ERROR: {e}"))
+}
+
+async fn grep(args: &serde_json::Value, root: &Path) -> String {
+ let pattern = arg_str(args, "pattern").map(String::from);
+ let path = arg_str(args, "path").unwrap_or(".").to_string();
+ let glob_filter = arg_str(args, "glob").map(String::from);
+ let ignore_case = arg_bool(args, "ignore_case");
+ let literal = arg_bool(args, "literal");
+ let context = arg_u64(args, "context").map(|v| v as usize).unwrap_or(0);
+ let limit = arg_u64(args, "limit")
+ .map(|v| v as usize)
+ .unwrap_or(GREP_DEFAULT_LIMIT);
+ let base = resolve(root, &path);
+
+ let Some(pattern) = pattern else {
+ return "ERROR: missing required argument 'pattern'".to_string();
+ };
+ let res = tokio::task::spawn_blocking(move || {
+ let effective = if literal {
+ regex::escape(&pattern)
+ } else {
+ pattern.clone()
+ };
+ let re = match regex::RegexBuilder::new(&effective)
+ .case_insensitive(ignore_case)
+ .build()
+ {
+ Ok(r) => r,
+ Err(e) => return format!("ERROR: invalid pattern: {e}"),
+ };
+ let glob_pat = match &glob_filter {
+ Some(g) => match glob::Pattern::new(g) {
+ Ok(p) => Some(p),
+ Err(e) => return format!("ERROR: invalid glob: {e}"),
+ },
+ None => None,
+ };
+
+ let is_file = base.is_file();
+ let mut matches: Vec<String> = Vec::new();
+ let mut count = 0usize;
+
+ let mut search_file = |file: &Path, rel_base: &Path| -> bool {
+ if let Some(gp) = &glob_pat {
+ let rel = rel_to(rel_base, file);
+ if !gp.matches(&rel)
+ && !gp.matches(
+ &file
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default(),
+ )
+ {
+ return true;
+ }
+ }
+ let content = match std::fs::read_to_string(file) {
+ Ok(c) => c,
+ Err(_) => return true,
+ };
+ let rel = rel_to(rel_base, file);
+ let lines: Vec<&str> = content.lines().collect();
+ for (i, line) in lines.iter().enumerate() {
+ if re.is_match(line) {
+ if context > 0 {
+ let start = i.saturating_sub(context);
+ let end = (i + context + 1).min(lines.len());
+ for (j, item) in lines.iter().enumerate().take(end).skip(start) {
+ let text = truncate_line(item);
+ if j == i {
+ matches.push(format!("{rel}:{}:{text}", j + 1));
+ } else {
+ matches.push(format!("{rel}-{}-{text}", j + 1));
+ }
+ }
+ } else {
+ matches.push(format!("{rel}:{}:{}", i + 1, truncate_line(line)));
+ }
+ count += 1;
+ if count >= limit {
+ return false;
+ }
+ }
+ }
+ true
+ };
+
+ if is_file {
+ let rel_base = base.parent().unwrap_or(&base);
+ search_file(&base, rel_base);
+ } else {
+ for entry in WalkBuilder::new(&base)
+ .hidden(false)
+ .require_git(false)
+ .build()
+ .flatten()
+ {
+ if entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {
+ continue;
+ }
+ if !search_file(entry.path(), &base) {
+ break;
+ }
+ }
+ }
+
+ if matches.is_empty() {
+ "No matches.".to_string()
+ } else {
+ cap_output(&matches.join("\n"), usize::MAX, "\n[truncated: 64KB limit]")
+ }
+ })
+ .await;
+ res.unwrap_or_else(|e| format!("ERROR: {e}"))
+}
+
+fn truncate_line(line: &str) -> String {
+ if line.chars().count() > GREP_MAX_LINE {
+ let truncated: String = line.chars().take(GREP_MAX_LINE).collect();
+ format!("{truncated}...")
+ } else {
+ line.to_string()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::tools::lookup;
+ use serde_json::json;
+
+ static COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+ fn unique_root() -> PathBuf {
+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let dir =
+ std::env::temp_dir().join(format!("jan_handlers_test_{}_{}", std::process::id(), n));
+ std::fs::create_dir_all(&dir).expect("create test root");
+ dir
+ }
+
+ #[tokio::test]
+ async fn read_returns_contents() {
+ let root = unique_root();
+ std::fs::write(root.join("a.txt"), b"hello").unwrap();
+ let out = execute_builtin(lookup("read").unwrap(), &json!({"path": "a.txt"}), &root).await;
+ assert_eq!(out, "hello");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn read_with_offset_and_limit_slices_lines() {
+ let root = unique_root();
+ std::fs::write(root.join("lines.txt"), b"l1\nl2\nl3\nl4\nl5").unwrap();
+ let out = execute_builtin(
+ lookup("read").unwrap(),
+ &json!({"path": "lines.txt", "offset": 2, "limit": 2}),
+ &root,
+ )
+ .await;
+ assert_eq!(out, "l2\nl3");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn read_rejects_binary() {
+ let root = unique_root();
+ std::fs::write(root.join("bin"), [0xff, 0xfe, 0x00]).unwrap();
+ let out = execute_builtin(lookup("read").unwrap(), &json!({"path": "bin"}), &root).await;
+ assert!(out.starts_with("ERROR"), "unexpected: {out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn write_then_read_roundtrips() {
+ let root = unique_root();
+ let w = execute_builtin(
+ lookup("write").unwrap(),
+ &json!({"path": "sub/b.txt", "content": "data"}),
+ &root,
+ )
+ .await;
+ assert!(w.starts_with("Wrote"), "unexpected: {w}");
+ let r = execute_builtin(
+ lookup("read").unwrap(),
+ &json!({"path": "sub/b.txt"}),
+ &root,
+ )
+ .await;
+ assert_eq!(r, "data");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn edit_applies_two_edits_atomically() {
+ let root = unique_root();
+ std::fs::write(root.join("c.txt"), b"foo bar baz").unwrap();
+ let ok = execute_builtin(
+ lookup("edit").unwrap(),
+ &json!({"path": "c.txt", "edits": [
+ {"old_string": "foo", "new_string": "FOO"},
+ {"old_string": "baz", "new_string": "BAZ"}
+ ]}),
+ &root,
+ )
+ .await;
+ assert_eq!(ok, "Applied 2 edit(s) to c.txt");
+ assert_eq!(
+ std::fs::read_to_string(root.join("c.txt")).unwrap(),
+ "FOO bar BAZ"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn edit_errors_without_partial_write() {
+ let root = unique_root();
+ std::fs::write(root.join("d.txt"), b"one two two").unwrap();
+ // First edit ok, second not unique -> whole op fails, file unchanged.
+ let out = execute_builtin(
+ lookup("edit").unwrap(),
+ &json!({"path": "d.txt", "edits": [
+ {"old_string": "one", "new_string": "ONE"},
+ {"old_string": "two", "new_string": "TWO"}
+ ]}),
+ &root,
+ )
+ .await;
+ assert!(
+ out.starts_with("ERROR: edit 2: old_string not unique"),
+ "unexpected: {out}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(root.join("d.txt")).unwrap(),
+ "one two two"
+ );
+
+ let miss = execute_builtin(
+ lookup("edit").unwrap(),
+ &json!({"path": "d.txt", "edits": [{"old_string": "nope", "new_string": "x"}]}),
+ &root,
+ )
+ .await;
+ assert!(
+ miss.starts_with("ERROR: edit 1: old_string not found"),
+ "unexpected: {miss}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn ls_lists_created_file() {
+ let root = unique_root();
+ std::fs::write(root.join("listed.txt"), b"x").unwrap();
+ let out = execute_builtin(lookup("ls").unwrap(), &json!({}), &root).await;
+ assert!(out.contains("listed.txt"), "unexpected: {out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn find_glob_respects_gitignore() {
+ let root = unique_root();
+ std::fs::create_dir_all(root.join("keep")).unwrap();
+ std::fs::create_dir_all(root.join("skip")).unwrap();
+ std::fs::write(root.join("keep/a.txt"), b"x").unwrap();
+ std::fs::write(root.join("skip/b.txt"), b"x").unwrap();
+ std::fs::write(root.join(".gitignore"), b"skip/\n").unwrap();
+ let out = execute_builtin(
+ lookup("find").unwrap(),
+ &json!({"pattern": "**/*.txt"}),
+ &root,
+ )
+ .await;
+ assert!(out.contains("keep/a.txt"), "should include keep: {out}");
+ assert!(
+ !out.contains("skip/b.txt"),
+ "should exclude gitignored skip: {out}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn grep_regex_and_literal_and_ignore_case() {
+ let root = unique_root();
+ std::fs::write(
+ root.join("code.rs"),
+ b"fn main() {}\nLet x = 1.5;\nother line",
+ )
+ .unwrap();
+
+ let re = execute_builtin(
+ lookup("grep").unwrap(),
+ &json!({"pattern": "fn \\w+"}),
+ &root,
+ )
+ .await;
+ assert!(re.contains("code.rs:1:fn main"), "regex: {re}");
+
+ // Literal: "1.5" as regex would match "1x5" too; literal must match exactly.
+ let lit = execute_builtin(
+ lookup("grep").unwrap(),
+ &json!({"pattern": "1.5", "literal": true}),
+ &root,
+ )
+ .await;
+ assert!(lit.contains("code.rs:2:"), "literal: {lit}");
+
+ let ci = execute_builtin(
+ lookup("grep").unwrap(),
+ &json!({"pattern": "let", "ignore_case": true}),
+ &root,
+ )
+ .await;
+ assert!(ci.contains("code.rs:2:"), "ignore_case: {ci}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn grep_invalid_pattern_errors() {
+ let root = unique_root();
+ std::fs::write(root.join("f.txt"), b"x").unwrap();
+ let out = execute_builtin(lookup("grep").unwrap(), &json!({"pattern": "("}), &root).await;
+ assert!(
+ out.starts_with("ERROR: invalid pattern"),
+ "unexpected: {out}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn bash_timeout_returns_error() {
+ let root = unique_root();
+ let out = execute_builtin(
+ lookup("bash").unwrap(),
+ &json!({"command": "sleep 5", "timeout": 1}),
+ &root,
+ )
+ .await;
+ assert!(
+ out.starts_with("ERROR: command timed out"),
+ "unexpected: {out}"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn bash_nonzero_exit_is_not_error() {
+ let root = unique_root();
+ let out = execute_builtin(
+ lookup("bash").unwrap(),
+ &json!({"command": "echo hi; exit 3"}),
+ &root,
+ )
+ .await;
+ assert!(!out.starts_with("ERROR"), "unexpected: {out}");
+ assert!(out.contains("hi"), "unexpected: {out}");
+ assert!(out.contains("[exit 3]"), "unexpected: {out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/src/core/agent/tools/mod.rs b/src-tauri/src/core/agent/tools/mod.rs
new file mode 100644
index 000000000..b4cb41816
--- /dev/null
+++ b/src-tauri/src/core/agent/tools/mod.rs
@@ -0,0 +1,100 @@
+//! Built-in agent tools: capability classification + the 7 tools pi's
+//! coding-agent exposes. Handlers and loop wiring land in a later phase; this
+//! module is the pure metadata + gate surface.
+
+pub mod gate;
+pub mod handlers;
+pub mod sandbox;
+pub mod schema;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Capability {
+ Read,
+ Write,
+ Exec,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct BuiltinTool {
+ pub name: &'static str,
+ pub capability: Capability,
+ /// JSON argument keys that carry a filesystem path to sandbox-check.
+ pub path_args: &'static [&'static str],
+}
+
+/// The 7 tools mirror pi's coding-agent set exactly (read/ls/find/grep/write/edit/bash).
+pub const BUILTIN_TOOLS: &[BuiltinTool] = &[
+ BuiltinTool {
+ name: "read",
+ capability: Capability::Read,
+ path_args: &["path"],
+ },
+ BuiltinTool {
+ name: "ls",
+ capability: Capability::Read,
+ path_args: &["path"],
+ },
+ BuiltinTool {
+ name: "find",
+ capability: Capability::Read,
+ path_args: &["path"],
+ },
+ BuiltinTool {
+ name: "grep",
+ capability: Capability::Read,
+ path_args: &["path"],
+ },
+ BuiltinTool {
+ name: "write",
+ capability: Capability::Write,
+ path_args: &["path"],
+ },
+ BuiltinTool {
+ name: "edit",
+ capability: Capability::Write,
+ path_args: &["path"],
+ },
+ BuiltinTool {
+ name: "bash",
+ capability: Capability::Exec,
+ path_args: &[],
+ },
+];
+
+pub fn lookup(name: &str) -> Option<&'static BuiltinTool> {
+ BUILTIN_TOOLS.iter().find(|t| t.name == name)
+}
+
+pub fn is_builtin(name: &str) -> bool {
+ lookup(name).is_some()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn lookup_read_is_read_capability() {
+ let t = lookup("read").expect("read is builtin");
+ assert_eq!(t.capability, Capability::Read);
+ assert_eq!(t.path_args, &["path"]);
+ }
+
+ #[test]
+ fn lookup_bash_is_exec_no_paths() {
+ let t = lookup("bash").expect("bash is builtin");
+ assert_eq!(t.capability, Capability::Exec);
+ assert!(t.path_args.is_empty());
+ }
+
+ #[test]
+ fn unknown_is_not_builtin() {
+ assert!(lookup("nope").is_none());
+ assert!(!is_builtin("nope"));
+ }
+
+ #[test]
+ fn builtin_count_is_seven() {
+ assert_eq!(BUILTIN_TOOLS.len(), 7);
+ }
+}
diff --git a/src-tauri/src/core/agent/tools/sandbox.rs b/src-tauri/src/core/agent/tools/sandbox.rs
new file mode 100644
index 000000000..a3f48ecf8
--- /dev/null
+++ b/src-tauri/src/core/agent/tools/sandbox.rs
@@ -0,0 +1,135 @@
+use std::path::{Path, PathBuf};
+
+/// True iff `raw` resolves to a path outside `project_root`.
+/// Relative paths are resolved against `project_root`. Canonicalizes (resolving
+/// `..` and symlinks) so string tricks and symlink escapes are caught. For a
+/// not-yet-existing leaf (new-file writes), the deepest existing ancestor is
+/// canonicalized and the remaining tail re-joined.
+pub fn escapes_project(project_root: &Path, raw: &str) -> Result<bool, String> {
+ let root = project_root
+ .canonicalize()
+ .map_err(|e| format!("project root {:?}: {e}", project_root))?;
+ let abs = if Path::new(raw).is_absolute() {
+ PathBuf::from(raw)
+ } else {
+ root.join(raw)
+ };
+ let resolved = canonicalize_lenient(&abs)?;
+ Ok(!resolved.starts_with(&root))
+}
+
+/// Canonicalize a path that may not fully exist: canonicalize the deepest
+/// existing ancestor, then re-append the non-existing tail (resolving `.`/`..`
+/// lexically). Errors only if no ancestor up to root exists.
+fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {
+ if let Ok(p) = path.canonicalize() {
+ return Ok(p);
+ }
+ let mut existing = path;
+ let mut tail: Vec<&std::ffi::OsStr> = Vec::new();
+ loop {
+ match existing.parent() {
+ Some(parent) => {
+ if let Some(name) = existing.file_name() {
+ tail.push(name);
+ }
+ existing = parent;
+ if let Ok(base) = existing.canonicalize() {
+ let mut result = base;
+ for comp in tail.iter().rev() {
+ if *comp == std::ffi::OsStr::new(".") {
+ continue;
+ }
+ if *comp == std::ffi::OsStr::new("..") {
+ result.pop();
+ } else {
+ result.push(comp);
+ }
+ }
+ return Ok(result);
+ }
+ }
+ None => {
+ return Err(format!("no existing ancestor for {:?}", path));
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ static COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+ fn unique_root() -> PathBuf {
+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);
+ let dir =
+ std::env::temp_dir().join(format!("jan_sandbox_test_{}_{}", std::process::id(), n));
+ std::fs::create_dir_all(&dir).expect("create test root");
+ dir
+ }
+
+ #[test]
+ fn in_project_file_does_not_escape() {
+ let root = unique_root();
+ std::fs::write(root.join("inner.txt"), b"x").unwrap();
+ assert_eq!(escapes_project(&root, "inner.txt"), Ok(false));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn nested_in_project_does_not_escape() {
+ let root = unique_root();
+ std::fs::create_dir_all(root.join("sub")).unwrap();
+ std::fs::write(root.join("sub/inner.txt"), b"x").unwrap();
+ assert_eq!(escapes_project(&root, "sub/inner.txt"), Ok(false));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn dotdot_escapes() {
+ let root = unique_root();
+ assert_eq!(escapes_project(&root, "../outside.txt"), Ok(true));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn absolute_outside_escapes() {
+ let root = unique_root();
+ let outside = std::env::temp_dir().join("definitely_outside_the_root.txt");
+ assert_eq!(escapes_project(&root, outside.to_str().unwrap()), Ok(true));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn absolute_inside_does_not_escape() {
+ let root = unique_root();
+ std::fs::write(root.join("inner.txt"), b"x").unwrap();
+ let inside = root.join("inner.txt");
+ assert_eq!(escapes_project(&root, inside.to_str().unwrap()), Ok(false));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn new_file_in_project_dir_does_not_escape() {
+ let root = unique_root();
+ std::fs::create_dir_all(root.join("sub")).unwrap();
+ assert_eq!(escapes_project(&root, "sub/newfile.txt"), Ok(false));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlink_escape_is_caught() {
+ let root = unique_root();
+ let outside = unique_root();
+ std::fs::write(outside.join("secret.txt"), b"x").unwrap();
+ let link = root.join("link");
+ std::os::unix::fs::symlink(&outside, &link).unwrap();
+ assert_eq!(escapes_project(&root, "link/secret.txt"), Ok(true));
+ let _ = std::fs::remove_dir_all(&root);
+ let _ = std::fs::remove_dir_all(&outside);
+ }
+}
diff --git a/src-tauri/src/core/agent/tools/schema.rs b/src-tauri/src/core/agent/tools/schema.rs
new file mode 100644
index 000000000..37eb14e58
--- /dev/null
+++ b/src-tauri/src/core/agent/tools/schema.rs
@@ -0,0 +1,155 @@
+//! OpenAI `tools` array entries for the built-in tools, one per BUILTIN_TOOLS
+//! entry. These are advertised to the model when a project is active; execution
+//! is dispatched by `handlers::execute_builtin` and gated by `gate`.
+
+use serde_json::{json, Value};
+
+/// OpenAI function schemas for the 7 built-in tools.
+pub fn builtin_tool_schemas() -> Vec<Value> {
+ vec![
+ json!({
+ "type": "function",
+ "function": {
+ "name": "read",
+ "description": "Read the contents of a UTF-8 text file. Output is truncated to 2000 lines or 64KB (whichever is hit first). Use offset/limit for large files.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "File path relative to the project root (or absolute)." },
+ "offset": { "type": "integer", "description": "Line number to start reading from (1-indexed)." },
+ "limit": { "type": "integer", "description": "Maximum number of lines to read." }
+ },
+ "required": ["path"]
+ }
+ }
+ }),
+ json!({
+ "type": "function",
+ "function": {
+ "name": "ls",
+ "description": "List directory contents sorted alphabetically, with '/' suffix for directories. Includes dotfiles. Truncated to the entry limit or 64KB.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "Directory to list (default '.')." },
+ "limit": { "type": "integer", "description": "Maximum number of entries to return (default 500)." }
+ },
+ "required": []
+ }
+ }
+ }),
+ json!({
+ "type": "function",
+ "function": {
+ "name": "find",
+ "description": "Search for files by glob pattern, e.g. '*.ts', '**/*.json', or 'src/**/*.rs'. Returns paths relative to the search directory. Respects .gitignore.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": { "type": "string", "description": "Glob pattern to match files." },
+ "path": { "type": "string", "description": "Directory to search in (default '.')." },
+ "limit": { "type": "integer", "description": "Maximum number of results (default 1000)." }
+ },
+ "required": ["pattern"]
+ }
+ }
+ }),
+ json!({
+ "type": "function",
+ "function": {
+ "name": "grep",
+ "description": "Search file contents for a pattern. Returns matching lines with file paths and line numbers. Respects .gitignore. Truncated to the match limit or 64KB.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "pattern": { "type": "string", "description": "Search pattern (regex or literal string)." },
+ "path": { "type": "string", "description": "Directory or file to search (default '.')." },
+ "glob": { "type": "string", "description": "Filter files by glob pattern, e.g. '*.ts' or '**/*.rs'." },
+ "ignore_case": { "type": "boolean", "description": "Case-insensitive search (default false)." },
+ "literal": { "type": "boolean", "description": "Treat pattern as a literal string instead of regex (default false)." },
+ "context": { "type": "integer", "description": "Number of lines to show before and after each match (default 0)." },
+ "limit": { "type": "integer", "description": "Maximum number of matches to return (default 100)." }
+ },
+ "required": ["pattern"]
+ }
+ }
+ }),
+ json!({
+ "type": "function",
+ "function": {
+ "name": "write",
+ "description": "Create or overwrite a file relative to the project root.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "File path relative to the project root." },
+ "content": { "type": "string", "description": "Full file contents to write." }
+ },
+ "required": ["path", "content"]
+ }
+ }
+ }),
+ json!({
+ "type": "function",
+ "function": {
+ "name": "edit",
+ "description": "Edit a file using one or more exact text replacements applied in order. Each old_string must match exactly once in the current file state.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "path": { "type": "string", "description": "File path relative to the project root." },
+ "edits": {
+ "type": "array",
+ "description": "Targeted replacements applied in order.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "old_string": { "type": "string", "description": "Exact text to replace (must be unique at apply time)." },
+ "new_string": { "type": "string", "description": "Replacement text." }
+ },
+ "required": ["old_string", "new_string"]
+ }
+ }
+ },
+ "required": ["path", "edits"]
+ }
+ }
+ }),
+ json!({
+ "type": "function",
+ "function": {
+ "name": "bash",
+ "description": "Run a shell command in the project root. Returns combined stdout and stderr. Output is truncated to 2000 lines or 64KB; full output is saved to a temp file when truncated. Optional timeout in seconds.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "command": { "type": "string", "description": "Shell command to run." },
+ "timeout": { "type": "integer", "description": "Timeout in seconds (optional, no default timeout)." }
+ },
+ "required": ["command"]
+ }
+ }
+ }),
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::core::agent::tools::BUILTIN_TOOLS;
+
+ #[test]
+ fn schemas_match_builtin_tools() {
+ let schemas = builtin_tool_schemas();
+ assert_eq!(schemas.len(), 7);
+ for schema in &schemas {
+ assert_eq!(schema["type"], "function");
+ }
+ let names: Vec<&str> = schemas
+ .iter()
+ .map(|s| s["function"]["name"].as_str().unwrap())
+ .collect();
+ let expected: Vec<&str> = BUILTIN_TOOLS.iter().map(|t| t.name).collect();
+ assert_eq!(names, expected);
+ }
+}
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 3bd3cf672..705e9fc69 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -628,8 +628,14 @@ mod tests {
fn accumulates_content_and_emits_token_per_delta() {
let (tx, mut rx) = sink();
let mut acc = SseAccumulator::default();
- acc.ingest(&json!({ "choices": [{ "delta": { "content": "Hel" } }] }).to_string(), &tx);
- acc.ingest(&json!({ "choices": [{ "delta": { "content": "lo" } }] }).to_string(), &tx);
+ acc.ingest(
+ &json!({ "choices": [{ "delta": { "content": "Hel" } }] }).to_string(),
+ &tx,
+ );
+ acc.ingest(
+ &json!({ "choices": [{ "delta": { "content": "lo" } }] }).to_string(),
+ &tx,
+ );
acc.ingest(
&json!({ "choices": [{ "delta": {}, "finish_reason": "stop" }] }).to_string(),
&tx,
@@ -638,7 +644,9 @@ mod tests {
let completion = acc.into_completion();
assert_eq!(completion["choices"][0]["message"]["content"], "Hello");
assert_eq!(completion["choices"][0]["finish_reason"], "stop");
- assert!(completion["choices"][0]["message"].get("tool_calls").is_none());
+ assert!(completion["choices"][0]["message"]
+ .get("tool_calls")
+ .is_none());
drop(tx);
let mut tokens = Vec::new();