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.

feat(agent-tools): own tool-call consent in Rust

thinhlpg786bb7bd89a1
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
index c703bf9f4..c78caf745 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
@@ -34,6 +34,13 @@ const COMMANDS: &[&str] = &[
"preview_register_root",
"preview_unregister_root",
"open_artifact",
+ "consent_request",
+ "consent_answer",
+ "consent_consume",
+ "consent_cancel_thread",
+ "consent_saved",
+ "consent_revoke",
+ "consent_set_allow_all_mcp",
];
fn main() {
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
index bc25f1c1e..ae32c4654 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
@@ -21,6 +21,23 @@ export {
WorkspaceCopy,
WorkspaceScope,
} from './types'
+import type {
+ ConsentAnswer,
+ ConsentRequest,
+ ConsentVerdict,
+ GrantKind,
+ SavedGrants,
+ ToolOrigin,
+} from './types'
+
+export type {
+ ConsentAnswer,
+ ConsentRequest,
+ ConsentVerdict,
+ GrantKind,
+ SavedGrants,
+ ToolOrigin,
+}
/**
* Every call takes the Jan data folder, because the plugin derives its
@@ -567,3 +584,73 @@ export async function stopSessionMonitors(threadId: string): Promise<void> {
export async function cancelThreadBash(threadId: string): Promise<void> {
await invoke('plugin:agent-tools|cancel_thread_bash', { threadId })
}
+
+/**
+ * Whether a tool call needs the user's answer before it runs. Rust keeps the
+ * grants and the one-use authorization its executor takes; `allowed` means the
+ * call is authorized, `ask` that it waits for {@link consentAnswer}.
+ */
+export async function consentRequest(
+ request: ConsentRequest
+): Promise<ConsentVerdict> {
+ return await invoke('plugin:agent-tools|consent_request', { request })
+}
+
+/** Record the user's answer to an asked call; resolves whether it may run. */
+export async function consentAnswer(
+ callId: string,
+ answer: ConsentAnswer
+): Promise<boolean> {
+ return await invoke('plugin:agent-tools|consent_answer', { callId, answer })
+}
+
+/**
+ * Use up the authorization of a call the webview runs itself (an extension's
+ * tool). Rejects when the call was not approved as exactly this call.
+ */
+export async function consentConsume(
+ threadId: string,
+ callId: string,
+ tool: string,
+ server: string | undefined,
+ origin: ToolOrigin
+): Promise<void> {
+ await invoke('plugin:agent-tools|consent_consume', {
+ threadId,
+ callId,
+ tool,
+ server,
+ origin,
+ })
+}
+
+/**
+ * Deny a thread's pending asks and drop its unused authorizations; with
+ * `forgetGrants` its thread-scoped grants too.
+ */
+export async function consentCancelThread(
+ threadId: string,
+ forgetGrants = false
+): Promise<void> {
+ await invoke('plugin:agent-tools|consent_cancel_thread', {
+ threadId,
+ forgetGrants,
+ })
+}
+
+/** The saved, configuration-level grants. */
+export async function consentSaved(): Promise<SavedGrants> {
+ return await invoke('plugin:agent-tools|consent_saved')
+}
+
+/** Remove one saved grant; resolves whether it existed. */
+export async function consentRevoke(
+ kind: GrantKind,
+ name: string
+): Promise<boolean> {
+ return await invoke('plugin:agent-tools|consent_revoke', { kind, name })
+}
+
+export async function consentSetAllowAllMcp(allow: boolean): Promise<void> {
+ await invoke('plugin:agent-tools|consent_set_allow_all_mcp', { allow })
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
index 6b2d79cdf..35113b2ed 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
@@ -82,3 +82,32 @@ export type MonitorUpdate = {
text: string
matched: boolean
}
+
+/** Who serves a tool call a consent decision is asked for. */
+export type ToolOrigin = 'mcp' | 'extension' | 'builtin'
+
+export interface ConsentRequest {
+ threadId: string
+ callId: string
+ tool: string
+ server?: string
+ origin: ToolOrigin
+ /** Ask whatever a grant says, and save nothing from the answer. */
+ strict?: boolean
+}
+
+/** `allowed` authorizes the one call; `ask` waits for the user's answer. */
+export type ConsentVerdict = 'allowed' | 'ask'
+
+export type ConsentAnswer = 'allow-once' | 'allow-thread' | 'allow-always' | 'deny'
+
+/** Configuration-level grants: the only ones saved between launches. */
+export interface SavedGrants {
+ allowAllMcp: boolean
+ /** MCP servers trusted whole. */
+ servers: string[]
+ /** Tools trusted on their own, by grant key (`mcp:<server>/<tool>`, `<ext server>/<tool>`). */
+ tools: string[]
+}
+
+export type GrantKind = 'server' | 'tool'
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
index 0ac48077e..b610fac2c 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
@@ -36,4 +36,11 @@ permissions = [
"allow-preview-register-root",
"allow-preview-unregister-root",
"allow-open-artifact",
+ "allow-consent-request",
+ "allow-consent-answer",
+ "allow-consent-consume",
+ "allow-consent-cancel-thread",
+ "allow-consent-saved",
+ "allow-consent-revoke",
+ "allow-consent-set-allow-all-mcp",
]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
index 4cdd26144..2c4081c3d 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
@@ -330,6 +330,90 @@
"const": "deny-cancel-thread-bash",
"markdownDescription": "Denies the cancel_thread_bash command without any pre-configured scope."
},
+ {
+ "description": "Enables the consent_answer command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-answer",
+ "markdownDescription": "Enables the consent_answer command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_answer command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-answer",
+ "markdownDescription": "Denies the consent_answer command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the consent_cancel_thread command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-cancel-thread",
+ "markdownDescription": "Enables the consent_cancel_thread command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_cancel_thread command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-cancel-thread",
+ "markdownDescription": "Denies the consent_cancel_thread command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the consent_consume command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-consume",
+ "markdownDescription": "Enables the consent_consume command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_consume command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-consume",
+ "markdownDescription": "Denies the consent_consume command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the consent_request command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-request",
+ "markdownDescription": "Enables the consent_request command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_request command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-request",
+ "markdownDescription": "Denies the consent_request command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the consent_revoke command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-revoke",
+ "markdownDescription": "Enables the consent_revoke command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_revoke command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-revoke",
+ "markdownDescription": "Denies the consent_revoke command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the consent_saved command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-saved",
+ "markdownDescription": "Enables the consent_saved command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_saved command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-saved",
+ "markdownDescription": "Denies the consent_saved command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the consent_set_allow_all_mcp command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-consent-set-allow-all-mcp",
+ "markdownDescription": "Enables the consent_set_allow_all_mcp command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the consent_set_allow_all_mcp command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-consent-set-allow-all-mcp",
+ "markdownDescription": "Denies the consent_set_allow_all_mcp command without any pre-configured scope."
+ },
{
"description": "Enables the execute_tool command without any pre-configured scope.",
"type": "string",
@@ -715,10 +799,10 @@
"markdownDescription": "Denies the workspace_path command without any pre-configured scope."
},
{
- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-copy-to-thread`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-blackboard-write`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`\n- `allow-open-artifact`",
+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-copy-to-thread`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-blackboard-write`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`\n- `allow-open-artifact`\n- `allow-consent-request`\n- `allow-consent-answer`\n- `allow-consent-consume`\n- `allow-consent-cancel-thread`\n- `allow-consent-saved`\n- `allow-consent-revoke`\n- `allow-consent-set-allow-all-mcp`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-copy-to-thread`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-blackboard-write`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`\n- `allow-open-artifact`"
+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-copy-to-thread`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-skill-invoke`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-blackboard-write`\n- `allow-attachment-import`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-session-monitor-ids`\n- `allow-stop-session-monitors`\n- `allow-cancel-thread-bash`\n- `allow-preview-register-root`\n- `allow-preview-unregister-root`\n- `allow-open-artifact`\n- `allow-consent-request`\n- `allow-consent-answer`\n- `allow-consent-consume`\n- `allow-consent-cancel-thread`\n- `allow-consent-saved`\n- `allow-consent-revoke`\n- `allow-consent-set-allow-all-mcp`"
}
]
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 76b8dd4ca..bed546c23 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -822,6 +822,10 @@ fn resolve_workspace_root(
}
}
+/// Built-in tools that can change a folder attached to a chat: asked for on
+/// every call, never saved.
+const CHAT_FOLDER_ASKED: [&str; 3] = ["write", "edit", crate::tools::SHELL_TOOL];
+
/// Execute one built-in tool.
///
/// The gate decides, not the caller. `write` and `edit` resolve to `Prompt` and
@@ -971,21 +975,35 @@ async fn execute_tool_inner(
// A chat thread's folder comes from its record; one passed by the caller
// is refused rather than ignored, so a caller that believes it attached a
// folder learns it did not.
- let (read_only_project, writable) = match scope.unwrap_or_default() {
- WorkspaceScope::Thread => match chat_folder_record(Path::new(&data_folder), &thread_id)? {
- Some(_) if read_only_project.is_some() || project_writable == Some(true) => {
- return Err(
- "a chat's folder is the one attached to the conversation; it cannot be \
- passed per call"
- .to_string()
- .into(),
- );
- }
- Some((folder, writable)) => (folder, writable),
- None => (read_only_project, project_writable.unwrap_or(false)),
- },
- WorkspaceScope::Session => (read_only_project, project_writable.unwrap_or(false)),
+ let chat_record = match scope.unwrap_or_default() {
+ WorkspaceScope::Thread => chat_folder_record(Path::new(&data_folder), &thread_id)?,
+ WorkspaceScope::Session => None,
+ };
+ let is_chat = chat_record.is_some();
+ let (read_only_project, writable) = match chat_record {
+ Some(_) if read_only_project.is_some() || project_writable == Some(true) => {
+ return Err(
+ "a chat's folder is the one attached to the conversation; it cannot be \
+ passed per call"
+ .to_string()
+ .into(),
+ );
+ }
+ Some((folder, writable)) => (folder, writable),
+ None => (read_only_project, project_writable.unwrap_or(false)),
};
+ // With a folder attached to a chat, a call that can change it runs only on
+ // the user's answer for that one call (see `consent`).
+ if is_chat && read_only_project.is_some() && CHAT_FOLDER_ASKED.contains(&name.as_str())
+ {
+ crate::consent::store().consume(
+ &thread_id,
+ call_id.as_deref().unwrap_or_default(),
+ &name,
+ None,
+ crate::consent::ToolOrigin::Builtin,
+ )?;
+ }
let attached = attach_folder(
read_only_project.as_deref(),
&sandbox,
@@ -1257,6 +1275,68 @@ fn output_sink(
})
}
+/// Whether a tool call needs the user's answer before it runs. `allowed`
+/// authorizes that one call; `ask` waits for [`consent_answer`].
+#[tauri::command]
+pub async fn consent_request(
+ request: crate::consent::ConsentRequest,
+) -> Result<crate::consent::Verdict, AgentToolsError> {
+ Ok(crate::consent::store().request(request))
+}
+
+/// Record the user's answer to an asked call; returns whether it may run.
+#[tauri::command]
+pub async fn consent_answer(
+ call_id: String,
+ answer: crate::consent::ConsentAnswer,
+) -> Result<bool, AgentToolsError> {
+ Ok(crate::consent::store().answer(&call_id, answer))
+}
+
+/// Use up the authorization of a call the webview executes itself (an
+/// extension's tool), so it is single-use like the calls Rust executes.
+#[tauri::command]
+pub async fn consent_consume(
+ thread_id: String,
+ call_id: String,
+ tool: String,
+ server: Option<String>,
+ origin: crate::consent::ToolOrigin,
+) -> Result<(), AgentToolsError> {
+ Ok(crate::consent::store().consume(&thread_id, &call_id, &tool, server.as_deref(), origin)?)
+}
+
+/// Deny a thread's pending asks and drop its unused authorizations (Stop);
+/// with `forget_grants` its thread-scoped grants too (the thread deleted).
+#[tauri::command]
+pub async fn consent_cancel_thread(
+ thread_id: String,
+ forget_grants: Option<bool>,
+) -> Result<(), AgentToolsError> {
+ crate::consent::store().cancel_thread(&thread_id, forget_grants.unwrap_or(false));
+ Ok(())
+}
+
+/// The configuration-level grants, for the settings page.
+#[tauri::command]
+pub async fn consent_saved() -> Result<crate::consent::SavedGrants, AgentToolsError> {
+ Ok(crate::consent::store().saved())
+}
+
+#[tauri::command]
+pub async fn consent_revoke(
+ kind: crate::consent::GrantKind,
+ name: String,
+) -> Result<bool, AgentToolsError> {
+ Ok(crate::consent::store().revoke(kind, &name))
+}
+
+#[tauri::command]
+pub async fn consent_set_allow_all_mcp(allow: bool) -> Result<(), AgentToolsError> {
+ crate::consent::store().set_allow_all_mcp(allow);
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -2530,14 +2610,31 @@ mod tests {
std::fs::write(path, json!({ "id": id, "metadata": metadata }).to_string()).unwrap();
}
- async fn call(
+ /// One call as the chat makes it, the user having approved it when the
+ /// tool is one a chat asks for (`approve`).
+ async fn call_as(
df: &str,
id: &str,
name: &str,
args: serde_json::Value,
folder: Option<&Path>,
writable: Option<bool>,
+ approve: bool,
) -> Result<ToolResult, AgentToolsError> {
+ static CALLS: AtomicUsize = AtomicUsize::new(0);
+ let call_id = format!("call-{id}-{}", CALLS.fetch_add(1, Ordering::Relaxed));
+ if approve {
+ let store = crate::consent::store();
+ store.request(crate::consent::ConsentRequest {
+ thread_id: id.to_string(),
+ call_id: call_id.clone(),
+ tool: name.to_string(),
+ server: None,
+ origin: crate::consent::ToolOrigin::Builtin,
+ strict: true,
+ });
+ assert!(store.answer(&call_id, crate::consent::ConsentAnswer::AllowOnce));
+ }
execute_tool(
df.to_string(),
id.to_string(),
@@ -2549,11 +2646,59 @@ mod tests {
folder.map(|f| f.to_string_lossy().to_string()),
writable,
None,
- None,
+ Some(call_id),
)
.await
}
+ async fn call(
+ df: &str,
+ id: &str,
+ name: &str,
+ args: serde_json::Value,
+ folder: Option<&Path>,
+ writable: Option<bool>,
+ ) -> Result<ToolResult, AgentToolsError> {
+ call_as(df, id, name, args, folder, writable, true).await
+ }
+
+ /// A call that can change a chat's folder runs only with the user's answer
+ /// for that call: none, or one given for another call, is refused.
+ #[tokio::test]
+ async fn a_chat_folder_write_needs_its_own_approval() {
+ let data = unique_data_folder();
+ let df = data.to_string_lossy().to_string();
+ let repo = repo_outside_tmp("chat_consent");
+ let id = "thread-chat-consent";
+ write_thread_record(&data, id, json!({ "folder": repo, "folderAccess": "write" }));
+
+ for name in ["write", "edit", "shell"] {
+ let args = match name {
+ "shell" => json!({"command": "touch made.txt"}),
+ "edit" => json!({"path": "a.md", "old_string": "a", "new_string": "b"}),
+ _ => json!({"path": "a.md", "content": "a"}),
+ };
+ let err = call_as(&df, id, name, args, None, None, false)
+ .await
+ .expect_err("an unapproved call is refused");
+ assert!(format!("{err:?}").contains("not been approved"), "{name}: {err:?}");
+ }
+ assert!(!repo.join("a.md").exists());
+ assert!(!repo.join("made.txt").exists());
+ // Reads still run unasked.
+ std::fs::write(repo.join("r.md"), b"r").unwrap();
+ let read = call_as(&df, id, "read", json!({"path": "r.md"}), None, None, false).await;
+ assert!(read.is_ok_and(|r| !r.is_error));
+ // With no folder attached nothing is asked.
+ write_thread_record(&data, id, json!({}));
+ let write =
+ call_as(&df, id, "write", json!({"path": "s.md", "content": "s"}), None, None, false).await;
+ assert!(write.is_ok_and(|r| !r.is_error));
+
+ let _ = std::fs::remove_dir_all(&data);
+ let _ = std::fs::remove_dir_all(&repo);
+ }
+
/// The folder the user attached to a chat is used with no caller argument,
/// writable unless recorded read-only, and is the root for relative paths.
#[tokio::test]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/consent.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/consent.rs
new file mode 100644
index 000000000..92d7d0c24
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/consent.rs
@@ -0,0 +1,456 @@
+//! The consent store for tool calls the desktop app executes outside the CLI
+//! loop: chat's MCP and extension tools, and the built-in tools that change a
+//! folder attached to a chat.
+//!
+//! The webview shows the prompt; this store decides whether one is needed,
+//! records the answer and holds the one-use authorization the executor takes
+//! before it runs the call. An executor that finds no authorization refuses the
+//! call, so a call the user was never asked about, or one asked for under
+//! another tool, server or thread, cannot run.
+//!
+//! Grant scopes:
+//! - once: the authorization itself, used up by the one call it was given for;
+//! - thread: in memory, dropped on restart, never covering another thread;
+//! - configuration: saved through the installed [`GrantsPersistence`], listed
+//! by [`saved`] and removed by [`revoke`]. Only an explicit "Allow always"
+//! creates one; nothing else is saved between launches.
+//!
+//! A `strict` request (a turn an extension's model serves, or a built-in call
+//! that changes the attached folder) is asked every time and saves nothing,
+//! whatever "allow all MCP" or a saved grant says.
+
+use std::collections::{BTreeSet, HashMap};
+use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
+
+use serde::{Deserialize, Serialize};
+
+/// Server-name prefix of the tools an extension contributes. An MCP server the
+/// user named this way is never trusted whole: that trust would also cover the
+/// real extension's tools.
+pub const EXTENSION_SERVER_PREFIX: &str = "ext:";
+
+/// Who serves a tool, as the caller resolved it when the call arrived.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ToolOrigin {
+ Mcp,
+ Extension,
+ /// A built-in agent tool (`write`, `edit`, `shell`, ...).
+ Builtin,
+}
+
+/// One tool call a consent decision is asked for.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConsentRequest {
+ pub thread_id: String,
+ pub call_id: String,
+ pub tool: String,
+ #[serde(default)]
+ pub server: Option<String>,
+ pub origin: ToolOrigin,
+ /// Ask whatever a grant says, and save nothing from the answer.
+ #[serde(default)]
+ pub strict: bool,
+}
+
+/// What the store decided for a request.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Verdict {
+ /// Covered by a grant: authorized for this one call.
+ Allowed,
+ /// The user must answer ([`answer`]) before the call may run.
+ Ask,
+}
+
+/// The user's answer to a prompt. Same wire values as the web app's
+/// `ApprovalDecision`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum ConsentAnswer {
+ AllowOnce,
+ AllowThread,
+ AllowAlways,
+ Deny,
+}
+
+/// Configuration-level grants: the only ones saved between launches.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SavedGrants {
+ /// Every MCP call runs unasked (never an extension's, never a strict one).
+ #[serde(default)]
+ pub allow_all_mcp: bool,
+ /// MCP servers trusted whole, tools included.
+ #[serde(default)]
+ pub servers: BTreeSet<String>,
+ /// Tools trusted on their own, by grant key (see [`grant_key`]).
+ #[serde(default)]
+ pub tools: BTreeSet<String>,
+}
+
+/// Which saved grant [`revoke`] removes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum GrantKind {
+ Server,
+ Tool,
+}
+
+/// Where configuration-level grants are kept. The app installs one backed by
+/// its settings store; without one (tests, the CLI) grants live in memory.
+pub trait GrantsPersistence: Send + Sync {
+ fn load(&self) -> SavedGrants;
+ fn save(&self, grants: &SavedGrants);
+}
+
+#[derive(Default)]
+struct Inner {
+ loaded: bool,
+ saved: SavedGrants,
+ thread: HashMap<String, BTreeSet<String>>,
+ /// Asked and not answered yet, by call id.
+ asked: HashMap<String, ConsentRequest>,
+ /// Allowed and not executed yet, by call id.
+ authorized: HashMap<String, ConsentRequest>,
+}
+
+#[derive(Default)]
+pub struct ConsentStore {
+ inner: Mutex<Inner>,
+ persistence: OnceLock<Arc<dyn GrantsPersistence>>,
+}
+
+/// The name a grant is recorded under. A tool with a server is keyed by it as
+/// well, so a grant never covers a same-named tool of another server; MCP keys
+/// carry an `mcp:` namespace so no extension can spell one.
+pub fn grant_key(tool: &str, server: Option<&str>, origin: ToolOrigin) -> String {
+ match (server, origin) {
+ (None, _) => tool.to_string(),
+ (Some(server), ToolOrigin::Extension) => format!("{server}/{tool}"),
+ (Some(server), _) => format!("mcp:{server}/{tool}"),
+ }
+}
+
+impl ConsentStore {
+ fn lock(&self) -> MutexGuard<'_, Inner> {
+ let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
+ if !inner.loaded {
+ inner.loaded = true;
+ if let Some(p) = self.persistence.get() {
+ inner.saved = p.load();
+ }
+ }
+ inner
+ }
+
+ fn persist(&self, saved: &SavedGrants) {
+ if let Some(p) = self.persistence.get() {
+ p.save(saved);
+ }
+ }
+
+ /// Install where saved grants live. Once per process; a later call is
+ /// ignored and returns `false`.
+ pub fn set_persistence(&self, persistence: Arc<dyn GrantsPersistence>) -> bool {
+ self.persistence.set(persistence).is_ok()
+ }
+
+ pub fn request(&self, req: ConsentRequest) -> Verdict {
+ let mut inner = self.lock();
+ // A call id already decided keeps its first answer: asking again under
+ // other parameters must not swap what the user saw.
+ inner.asked.remove(&req.call_id);
+ inner.authorized.remove(&req.call_id);
+ if covered(&inner, &req) {
+ inner.authorized.insert(req.call_id.clone(), req);
+ Verdict::Allowed
+ } else {
+ inner.asked.insert(req.call_id.clone(), req);
+ Verdict::Ask
+ }
+ }
+
+ /// Record the user's answer to an asked call. Returns whether the call may
+ /// run. An id that was not asked (or was cancelled meanwhile) is denied.
+ pub fn answer(&self, call_id: &str, answer: ConsentAnswer) -> bool {
+ let mut inner = self.lock();
+ let Some(req) = inner.asked.remove(call_id) else {
+ return false;
+ };
+ if answer == ConsentAnswer::Deny {
+ return false;
+ }
+ let key = grant_key(&req.tool, req.server.as_deref(), req.origin);
+ let mut changed = false;
+ if !req.strict {
+ match answer {
+ ConsentAnswer::AllowThread => {
+ inner.thread.entry(req.thread_id.clone()).or_default().insert(key);
+ }
+ ConsentAnswer::AllowAlways => {
+ // An MCP server is trusted whole. An extension is not: an
+ // update can add tools, and those must ask before they run.
+ changed = match req.server.as_deref() {
+ Some(server)
+ if req.origin == ToolOrigin::Mcp
+ && !server.starts_with(EXTENSION_SERVER_PREFIX) =>
+ {
+ inner.saved.servers.insert(server.to_string())
+ }
+ _ => inner.saved.tools.insert(key),
+ };
+ }
+ ConsentAnswer::AllowOnce | ConsentAnswer::Deny => {}
+ }
+ }
+ inner.authorized.insert(call_id.to_string(), req);
+ let saved = changed.then(|| inner.saved.clone());
+ drop(inner);
+ if let Some(saved) = saved {
+ self.persist(&saved);
+ }
+ true
+ }
+
+ /// Take the authorization for one call. Fails unless the call was allowed
+ /// for exactly this thread, tool, server and origin; either way the call id
+ /// is used up.
+ pub fn consume(
+ &self,
+ thread_id: &str,
+ call_id: &str,
+ tool: &str,
+ server: Option<&str>,
+ origin: ToolOrigin,
+ ) -> Result<(), String> {
+ let granted = self.lock().authorized.remove(call_id);
+ match granted {
+ Some(req)
+ if req.thread_id == thread_id
+ && req.tool == tool
+ && req.server.as_deref() == server
+ && req.origin == origin =>
+ {
+ Ok(())
+ }
+ Some(_) => Err(format!(
+ "tool '{tool}' was not run: it was approved as a different tool call"
+ )),
+ None => Err(format!("tool '{tool}' was not run: it has not been approved")),
+ }
+ }
+
+ /// End every pending ask and unused authorization of a thread (Stop, the
+ /// thread deleted). Its thread grants stay unless `forget_grants`.
+ pub fn cancel_thread(&self, thread_id: &str, forget_grants: bool) {
+ let mut inner = self.lock();
+ inner.asked.retain(|_, r| r.thread_id != thread_id);
+ inner.authorized.retain(|_, r| r.thread_id != thread_id);
+ if forget_grants {
+ inner.thread.remove(thread_id);
+ }
+ }
+
+ pub fn saved(&self) -> SavedGrants {
+ self.lock().saved.clone()
+ }
+
+ pub fn revoke(&self, kind: GrantKind, name: &str) -> bool {
+ let mut inner = self.lock();
+ let removed = match kind {
+ GrantKind::Server => inner.saved.servers.remove(name),
+ GrantKind::Tool => inner.saved.tools.remove(name),
+ };
+ let saved = removed.then(|| inner.saved.clone());
+ drop(inner);
+ if let Some(saved) = saved {
+ self.persist(&saved);
+ }
+ removed
+ }
+
+ pub fn set_allow_all_mcp(&self, allow: bool) {
+ let mut inner = self.lock();
+ if inner.saved.allow_all_mcp == allow {
+ return;
+ }
+ inner.saved.allow_all_mcp = allow;
+ let saved = inner.saved.clone();
+ drop(inner);
+ self.persist(&saved);
+ }
+}
+
+fn covered(inner: &Inner, req: &ConsentRequest) -> bool {
+ if req.strict || req.origin == ToolOrigin::Builtin {
+ return false;
+ }
+ if req.origin == ToolOrigin::Mcp && inner.saved.allow_all_mcp {
+ return true;
+ }
+ let key = grant_key(&req.tool, req.server.as_deref(), req.origin);
+ if inner.saved.tools.contains(&key) {
+ return true;
+ }
+ if req.origin == ToolOrigin::Mcp
+ && req
+ .server
+ .as_deref()
+ .is_some_and(|s| !s.starts_with(EXTENSION_SERVER_PREFIX) && inner.saved.servers.contains(s))
+ {
+ return true;
+ }
+ inner.thread.get(&req.thread_id).is_some_and(|keys| keys.contains(&key))
+}
+
+/// The process-wide store every executor checks.
+pub fn store() -> &'static ConsentStore {
+ static STORE: OnceLock<ConsentStore> = OnceLock::new();
+ STORE.get_or_init(ConsentStore::default)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn req(thread: &str, call: &str, tool: &str, server: Option<&str>, origin: ToolOrigin) -> ConsentRequest {
+ ConsentRequest {
+ thread_id: thread.into(),
+ call_id: call.into(),
+ tool: tool.into(),
+ server: server.map(Into::into),
+ origin,
+ strict: false,
+ }
+ }
+
+ struct Memory(Mutex<Option<SavedGrants>>);
+ impl GrantsPersistence for Memory {
+ fn load(&self) -> SavedGrants {
+ self.0.lock().unwrap().clone().unwrap_or_default()
+ }
+ fn save(&self, grants: &SavedGrants) {
+ *self.0.lock().unwrap() = Some(grants.clone());
+ }
+ }
+
+ #[test]
+ fn an_approval_runs_its_one_call_only() {
+ let s = ConsentStore::default();
+ let r = req("t1", "c1", "search", Some("web"), ToolOrigin::Mcp);
+ assert_eq!(s.request(r.clone()), Verdict::Ask);
+ assert!(s.consume("t1", "c1", "search", Some("web"), ToolOrigin::Mcp).is_err());
+ assert!(s.answer("c1", ConsentAnswer::AllowOnce));
+ assert!(s.consume("t1", "c1", "search", Some("web"), ToolOrigin::Mcp).is_ok());
+ assert!(s.consume("t1", "c1", "search", Some("web"), ToolOrigin::Mcp).is_err());
+ // Once saves nothing: the next call asks again.
+ assert_eq!(s.request(req("t1", "c2", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Ask);
+ }
+
+ #[test]
+ fn an_authorization_does_not_cover_another_tool_server_thread_or_origin() {
+ let s = ConsentStore::default();
+ for (thread, tool, server, origin) in [
+ ("t2", "search", Some("web"), ToolOrigin::Mcp),
+ ("t1", "fetch", Some("web"), ToolOrigin::Mcp),
+ ("t1", "search", Some("other"), ToolOrigin::Mcp),
+ ("t1", "search", Some("web"), ToolOrigin::Extension),
+ ] {
+ s.request(req("t1", "c", "search", Some("web"), ToolOrigin::Mcp));
+ assert!(s.answer("c", ConsentAnswer::AllowOnce));
+ assert!(s.consume(thread, "c", tool, server, origin).is_err());
+ // Used up by the mismatched attempt.
+ assert!(s.consume("t1", "c", "search", Some("web"), ToolOrigin::Mcp).is_err());
+ }
+ }
+
+ #[test]
+ fn a_thread_grant_stays_in_its_thread_and_is_never_saved() {
+ let s = ConsentStore::default();
+ let p = Arc::new(Memory(Mutex::new(None)));
+ s.set_persistence(p.clone());
+ s.request(req("t1", "c1", "search", Some("web"), ToolOrigin::Mcp));
+ assert!(s.answer("c1", ConsentAnswer::AllowThread));
+ assert_eq!(s.request(req("t1", "c2", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Allowed);
+ assert_eq!(s.request(req("t2", "c3", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Ask);
+ assert!(p.0.lock().unwrap().is_none(), "a thread grant is not persisted");
+ s.cancel_thread("t1", true);
+ assert_eq!(s.request(req("t1", "c4", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Ask);
+ }
+
+ #[test]
+ fn allow_always_trusts_an_mcp_server_but_only_the_tool_of_an_extension() {
+ let s = ConsentStore::default();
+ let p = Arc::new(Memory(Mutex::new(None)));
+ s.set_persistence(p.clone());
+ s.request(req("t1", "c1", "search", Some("web"), ToolOrigin::Mcp));
+ assert!(s.answer("c1", ConsentAnswer::AllowAlways));
+ assert_eq!(s.request(req("t9", "c2", "fetch", Some("web"), ToolOrigin::Mcp)), Verdict::Allowed);
+
+ s.request(req("t1", "c3", "notes", Some("ext:acme"), ToolOrigin::Extension));
+ assert!(s.answer("c3", ConsentAnswer::AllowAlways));
+ assert_eq!(s.request(req("t1", "c4", "notes", Some("ext:acme"), ToolOrigin::Extension)), Verdict::Allowed);
+ assert_eq!(s.request(req("t1", "c5", "other", Some("ext:acme"), ToolOrigin::Extension)), Verdict::Ask);
+ // An MCP server named like an extension is not trusted whole either.
+ s.request(req("t1", "c6", "x", Some("ext:acme"), ToolOrigin::Mcp));
+ assert!(s.answer("c6", ConsentAnswer::AllowAlways));
+ assert_eq!(s.request(req("t1", "c7", "notes", Some("ext:acme"), ToolOrigin::Extension)), Verdict::Allowed);
+ assert_eq!(s.request(req("t1", "c8", "y", Some("ext:acme"), ToolOrigin::Mcp)), Verdict::Ask);
+
+ let saved = p.0.lock().unwrap().clone().unwrap();
+ assert!(saved.servers.contains("web"));
+ assert!(saved.tools.contains("ext:acme/notes"));
+ assert!(saved.tools.contains("mcp:ext:acme/x"));
+ assert!(s.revoke(GrantKind::Server, "web"));
+ assert_eq!(s.request(req("t1", "c9", "fetch", Some("web"), ToolOrigin::Mcp)), Verdict::Ask);
+ assert!(!p.0.lock().unwrap().clone().unwrap().servers.contains("web"));
+ }
+
+ #[test]
+ fn strict_and_builtin_requests_always_ask_and_save_nothing() {
+ let s = ConsentStore::default();
+ s.set_allow_all_mcp(true);
+ let mut strict = req("t1", "c1", "search", Some("web"), ToolOrigin::Mcp);
+ strict.strict = true;
+ assert_eq!(s.request(strict.clone()), Verdict::Ask);
+ assert!(s.answer("c1", ConsentAnswer::AllowAlways));
+ assert!(s.saved().servers.is_empty());
+ assert_eq!(s.request(req("t1", "c2", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Allowed);
+
+ let write = req("t1", "c3", "write", None, ToolOrigin::Builtin);
+ assert_eq!(s.request(write.clone()), Verdict::Ask);
+ assert!(s.answer("c3", ConsentAnswer::AllowThread));
+ assert_eq!(s.request(req("t1", "c4", "write", None, ToolOrigin::Builtin)), Verdict::Ask);
+ // "Allow all MCP" never covers an extension's tool.
+ assert_eq!(s.request(req("t1", "c5", "n", Some("ext:a"), ToolOrigin::Extension)), Verdict::Ask);
+ }
+
+ #[test]
+ fn deny_cancel_and_unknown_ids_never_authorize() {
+ let s = ConsentStore::default();
+ s.request(req("t1", "c1", "search", Some("web"), ToolOrigin::Mcp));
+ assert!(!s.answer("c1", ConsentAnswer::Deny));
+ assert!(s.consume("t1", "c1", "search", Some("web"), ToolOrigin::Mcp).is_err());
+ assert!(!s.answer("never-asked", ConsentAnswer::AllowOnce));
+
+ s.request(req("t1", "c2", "search", Some("web"), ToolOrigin::Mcp));
+ s.cancel_thread("t1", false);
+ assert!(!s.answer("c2", ConsentAnswer::AllowOnce), "a cancelled ask is denied");
+
+ s.set_allow_all_mcp(true);
+ assert_eq!(s.request(req("t1", "c3", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Allowed);
+ s.cancel_thread("t1", false);
+ assert!(s.consume("t1", "c3", "search", Some("web"), ToolOrigin::Mcp).is_err());
+ }
+
+ #[test]
+ fn saved_grants_load_lazily_from_persistence() {
+ let s = ConsentStore::default();
+ let mut saved = SavedGrants::default();
+ saved.servers.insert("web".into());
+ s.set_persistence(Arc::new(Memory(Mutex::new(Some(saved)))));
+ assert_eq!(s.request(req("t1", "c1", "search", Some("web"), ToolOrigin::Mcp)), Verdict::Allowed);
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
index 740169c83..5e1eb4289 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
@@ -10,6 +10,7 @@
//! `commands` are gated.
pub mod artifact;
+pub mod consent;
pub mod memory;
pub mod permissions;
pub mod preview;
@@ -84,7 +85,14 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
commands::cancel_thread_bash,
commands::preview_register_root,
commands::preview_unregister_root,
- commands::open_artifact
+ commands::open_artifact,
+ commands::consent_request,
+ commands::consent_answer,
+ commands::consent_consume,
+ commands::consent_cancel_thread,
+ commands::consent_saved,
+ commands::consent_revoke,
+ commands::consent_set_allow_all_mcp
])
.setup(|app, _api| {
use tauri::Manager;