Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Feat: agent tools plugin (#8604)
Akarshan Biswasa4cdbcfa5638
diff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdxindex 68d4eea4f..44c4bfd61 100644--- a/docs/src/pages/docs/agent/permissions.mdx+++ b/docs/src/pages/docs/agent/permissions.mdx@@ -61,6 +61,9 @@ deny = []# Write tools are opt-inallow_write = []++# Whether the sandboxed shell can reach the network+# allow_network = true```| `default` | Effect |@@ -71,6 +74,26 @@ allow_write = []`deny` always wins over `allow`. A tool in both lists is denied.+## Network access++A `bash` command runs inside an OS sandbox, and by default it has **no network**. An explicitly+approved command cannot `curl`, `git fetch`, or install a package unless networking is switched on+for that surface. Where the toggle lives depends on how the agent runs:++| Surface | How to set network access | Default |+| --- | --- | --- |+| Desktop chat agent | The chat-screen tools toggle (`agent_tools`). Per session, in the UI | Off |+| `jan cli` code-screen agent | `[tools].allow_network` in `.jan/agent/agent.toml` | On |++The two are deliberately independent: the desktop chat agent is ephemeral and never prompts, so it+stays offline unless you opt in; the CLI runs in your own terminal where every exec is already+gated behind a prompt, so a coding agent that cannot `curl` or `git fetch` would be largely useless.+```toml+# Re-enable networking for a CLI agent+[tools]+allow_network = true+```+## SubagentsA [subagent's](/docs/agent/subagents) tools are narrowed, never widened. For a saved subagent andiff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 9df5c8964..77bdc0b01 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -52,12 +52,12 @@ dependencies = ["serde_json","serde_yaml","sha2",- "similar","sqlx","syntect","tar","tauri","tauri-build",+ "tauri-plugin-agent-tools","tauri-plugin-deep-link","tauri-plugin-dialog","tauri-plugin-hardware",@@ -7229,6 +7229,26 @@ dependencies = ["walkdir",]+[[package]]+name = "tauri-plugin-agent-tools"+version = "0.8.3"+dependencies = [+ "glob",+ "ignore",+ "nix 0.30.1",+ "regex",+ "serde",+ "serde_json",+ "serde_yaml",+ "similar",+ "tauri",+ "tauri-plugin",+ "tauri-plugin-websearch",+ "thiserror 2.0.18",+ "tokio",+ "windows-sys 0.60.2",+]+[[package]]name = "tauri-plugin-deep-link"version = "2.4.9"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 8f8067895..c01af57f3 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -6,7 +6,9 @@ authors = ["Jan <[email protected]>"]license = "MIT"repository = "https://github.com/janhq/jan"edition = "2021"-rust-version = "1.77.2"+# 1.82 is the floor actually used: `Option::is_none_or` (1.82) in agent/loop.rs+# and `LazyLock` (1.80) in cli/tui.rs.+rust-version = "1.82"resolver = "2"default-run = "jan-desktop"@@ -71,6 +73,7 @@ tauri-app = ["dep:zbus","tauri-plugin-vector-db/tauri","tauri-plugin-websearch/tauri",+ "tauri-plugin-agent-tools/tauri",]mobile = ["tauri/protocol-asset",@@ -134,11 +137,12 @@ zip = "0.6"tauri-plugin-deep-link = { version = "2", optional = true }tauri-plugin-hardware = { path = "./plugins/tauri-plugin-hardware", optional = true }tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp", optional = true }-# The CLI consumes only these two plugins' tauri-free cores (`db`, `provider`);-# the desktop feature turns their Tauri command surface back on.+# The CLI consumes only these plugins' tauri-free cores (`db`, `provider`, the+# agent toolset); the desktop feature turns their Tauri command surface back on.tauri-plugin-vector-db = { path = "./plugins/tauri-plugin-vector-db", default-features = false }tauri-plugin-rag = { path = "./plugins/tauri-plugin-rag", optional = true }tauri-plugin-websearch = { path = "./plugins/tauri-plugin-websearch", default-features = false }+tauri-plugin-agent-tools = { path = "./plugins/tauri-plugin-agent-tools", default-features = false }# `default-features = false` drops the plugin's default `rustls-tls` (bundled# Mozilla roots) so `native-tls` reads the OS trust store instead. Other# features re-list the plugin's defaults so behaviour is otherwise unchanged.@@ -176,7 +180,6 @@ base64 = "0.22"glob = "0.3"regex = "1"ignore = "0.4"-similar = "2.6"clap = { version = "4", features = ["derive"] }env_logger = { version = "0.11", optional = true }indicatif = { version = "0.17", optional = true }diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 17d194473..17cd71427 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -28,6 +28,7 @@"vector-db:default","rag:default","websearch:default",+ "agent-tools:default","hardware:default","deep-link:default","llamacpp:default",diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/.gitignore b/src-tauri/plugins/tauri-plugin-agent-tools/.gitignorenew file mode 100644index 000000000..95e8fd80c--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/.gitignore@@ -0,0 +1,16 @@+/.vs+.DS_Store+package-lock.json+yarn.lock++/.tauri+/target+Cargo.lock+node_modules/++dist-js+dist++# Regenerated by tauri_plugin::Builder on every build; committing it only+# creates drift (see the stale probe_backend_load entries in llamacpp).+permissions/autogenerated/diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.tomlnew file mode 100644index 000000000..9134c3162--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/Cargo.toml@@ -0,0 +1,54 @@+[package]+name = "tauri-plugin-agent-tools"+version = "0.8.3"+authors = ["Jan <[email protected]>"]+description = "Built-in agent toolset (filesystem, shell, skills, memory, web) shared by the Jan desktop app and the headless jan CLI"+license = "MIT"+repository = "https://github.com/janhq/jan"+edition = "2021"+rust-version = "1.77.2"+exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]+links = "tauri-plugin-agent-tools"++# The toolset core is Tauri-free so the headless `jan` CLI can drive it directly;+# only the desktop IPC shims need `tauri`. Build with `--no-default-features` to+# keep the whole GUI stack out of the graph.+[features]+default = ["tauri"]+tauri = ["dep:tauri", "dep:tauri-plugin"]++[dependencies]+glob = "0.3"+ignore = "0.4"+regex = "1"+similar = "2.6"+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"+serde_yaml = "0.9.34"+thiserror = "2.0.12"+tokio = { version = "1", features = ["full"] }+tauri = { version = "2.8.5", default-features = false, optional = true }+# `provider` only; `default-features = false` keeps `tauri` out of the graph so+# the headless CLI can use the web tools.+tauri-plugin-websearch = { path = "../tauri-plugin-websearch", default-features = false }++[build-dependencies]+tauri-plugin = { version = "2.3.1", features = ["build"], optional = true }++[target.'cfg(unix)'.dependencies]+nix = { version = "=0.30.1", features = ["signal", "process"] }++# AppContainer confinement for the `bash` tool: profile creation, workspace ACLs+# and the `STARTUPINFOEX` spawn that carries the lowbox token.+[target.'cfg(windows)'.dependencies]+windows-sys = { version = "0.60.2", features = [+ "Win32_Foundation",+ "Win32_Security",+ "Win32_Security_Authorization",+ "Win32_Security_Isolation",+ "Win32_Storage_FileSystem",+ "Win32_System_Console",+ "Win32_System_JobObjects",+ "Win32_System_Memory",+ "Win32_System_Threading",+] }diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rsnew file mode 100644index 000000000..a23b63481--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs@@ -0,0 +1,25 @@+const COMMANDS: &[&str] = &[+ "workspace_path",+ "thread_workspace_path",+ "thread_workspace_delete",+ "thread_workspace_sweep",+ "skill_list",+ "skill_read",+ "skill_write",+ "skill_delete",+ "memory_list",+ "memory_read",+ "memory_write",+ "memory_delete",+ "tool_schemas",+ "sandbox_status",+ "execute_tool",+];++fn main() {+ #[cfg(feature = "tauri")]+ tauri_plugin::Builder::new(COMMANDS).build();++ #[cfg(not(feature = "tauri"))]+ let _ = COMMANDS;+}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.tsnew file mode 100644index 000000000..169c7c5f5--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts@@ -0,0 +1,218 @@+import { invoke } from '@tauri-apps/api/core'+import { SkillMeta, ToolResult, ToolSchema } from './types'++export { SkillMeta, ToolResult, ToolSchema } from './types'++/**+ * Every call takes the Jan data folder, because the plugin derives its+ * directories from it (`<dataFolder>/agent-workspace`) while the app remains the+ * owner of where the data folder actually is.+ *+ * Two roots, with different lifetimes:+ *+ * - the **permanent store** (`memory/`, `skills/`) survives every conversation+ * - a **thread sandbox** (`threads/<threadId>/`) is where the filesystem tools+ * run and is deleted with its thread+ *+ * `project` overrides which store is used and is unused for now: there is no+ * project picker yet. It exists so adding one later needs no signature change.+ */++/** Ensure the permanent store exists and return its path. */+export async function workspacePath(dataFolder: string): Promise<string> {+ return await invoke('plugin:agent-tools|workspace_path', { dataFolder })+}++/** Ensure a thread's sandbox exists and return its path. */+export async function threadWorkspacePath(+ dataFolder: string,+ threadId: string+): Promise<string> {+ return await invoke('plugin:agent-tools|thread_workspace_path', {+ dataFolder,+ threadId,+ })+}++/**+ * Delete a thread's sandbox. Memory and skills are untouched. Idempotent: a+ * thread that never ran a tool resolves successfully.+ */+export async function threadWorkspaceDelete(+ dataFolder: string,+ threadId: string+): Promise<void> {+ return await invoke('plugin:agent-tools|thread_workspace_delete', {+ dataFolder,+ threadId,+ })+}++/**+ * Delete every sandbox not belonging to a surviving thread, returning how many+ * were removed. For startup: a crash, or a thread deleted while the app was+ * closed, would otherwise leave one behind.+ */+export async function threadWorkspaceSweep(+ dataFolder: string,+ keep: string[]+): Promise<number> {+ return await invoke('plugin:agent-tools|thread_workspace_sweep', {+ dataFolder,+ keep,+ })+}++export async function skillList(+ dataFolder: string,+ project?: string+): Promise<SkillMeta[]> {+ return await invoke('plugin:agent-tools|skill_list', { dataFolder, project })+}++/** Raw SKILL.md text, frontmatter included. */+export async function skillRead(+ dataFolder: string,+ name: string,+ project?: string+): Promise<string> {+ return await invoke('plugin:agent-tools|skill_read', {+ dataFolder,+ project,+ name,+ })+}++/** Create or overwrite a skill. New skills are written as `<name>/SKILL.md`. */+export async function skillWrite(+ dataFolder: string,+ name: string,+ content: string,+ project?: string+): Promise<void> {+ return await invoke('plugin:agent-tools|skill_write', {+ dataFolder,+ project,+ name,+ content,+ })+}++/** Delete a skill. Idempotent: a missing skill resolves successfully. */+export async function skillDelete(+ dataFolder: string,+ name: string,+ project?: string+): Promise<void> {+ return await invoke('plugin:agent-tools|skill_delete', {+ dataFolder,+ project,+ name,+ })+}++/** Memory note names (stems), sorted. */+export async function memoryList(+ dataFolder: string,+ project?: string+): Promise<string[]> {+ return await invoke('plugin:agent-tools|memory_list', { dataFolder, project })+}++export async function memoryRead(+ dataFolder: string,+ name: string,+ project?: string+): Promise<string> {+ return await invoke('plugin:agent-tools|memory_read', {+ dataFolder,+ project,+ name,+ })+}++export async function memoryWrite(+ dataFolder: string,+ name: string,+ content: string,+ project?: string+): Promise<void> {+ return await invoke('plugin:agent-tools|memory_write', {+ dataFolder,+ project,+ name,+ content,+ })+}++/** Delete a memory note. Idempotent: a missing note resolves successfully. */+export async function memoryDelete(+ dataFolder: string,+ name: string,+ project?: string+): Promise<void> {+ return await invoke('plugin:agent-tools|memory_delete', {+ dataFolder,+ project,+ name,+ })+}++/**+ * Function schemas for every built-in tool. Callers pick which subset to+ * advertise; the schemas are never re-typed in TypeScript.+ */+export async function toolSchemas(): Promise<ToolSchema[]> {+ return await invoke('plugin:agent-tools|tool_schemas')+}++/** Which OS sandbox, if any, can confine a shell on this machine. */+export type SandboxStatus = {+ /** `bubblewrap`, `seatbelt`, `appcontainer`, or `none`. */+ backend: string+ enforces: boolean+}++/**+ * Report the sandbox backend. Callers should advertise `bash` to a model only+ * when this reports `enforces`: without a backend every call is refused, and+ * offering a tool that cannot run wastes a turn and reads as a bug.+ */+export async function sandboxStatus(): Promise<SandboxStatus> {+ return await invoke('plugin:agent-tools|sandbox_status')+}++/**+ * Execute one built-in tool.+ *+ * The filesystem tools run in `threadId`'s sandbox, which is created on demand,+ * so the caller need not ensure it first. Memory and skill tools reach the+ * permanent store instead, so what the model records outlives the conversation.+ *+ * The permission gate decides in Rust, so tools that need user approval+ * (`write`, `edit`, and reads that escape the sandbox) reject regardless of what+ * is requested here. `bash` runs only under an enforcing OS sandbox; see+ * `sandboxStatus`.+ *+ * `allowNetwork` opens the sandboxed shell's network namespace. It defaults to+ * off, so omitting it is the safe choice.+ */+export async function executeTool(+ dataFolder: string,+ threadId: string,+ name: string,+ args: Record<string, unknown>,+ project?: string,+ enabledSkills?: string[],+ allowNetwork?: boolean+): Promise<ToolResult> {+ return await invoke('plugin:agent-tools|execute_tool', {+ dataFolder,+ threadId,+ project,+ name,+ args,+ enabledSkills,+ allowNetwork,+ })+}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.tsnew file mode 100644index 000000000..0c93831d4--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts@@ -0,0 +1,26 @@+/** A skill's summary as returned by `skillList`. */+export interface SkillMeta {+ name: string+ description: string+}++/** Outcome of a built-in tool execution. */+export interface ToolResult {+ content: string+ /** Display-only diff for write/edit; never part of model context. */+ diff: string | null+ isError: boolean+}++/**+ * An OpenAI-shaped function schema for a built-in tool, as produced by the+ * plugin's `schema.rs` (the single source of truth).+ */+export interface ToolSchema {+ type: 'function'+ function: {+ name: string+ description: string+ parameters: Record<string, unknown>+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/package.json b/src-tauri/plugins/tauri-plugin-agent-tools/package.jsonnew file mode 100644index 000000000..020a5f369--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/package.json@@ -0,0 +1,33 @@+{+ "name": "@janhq/tauri-plugin-agent-tools-api",+ "version": "0.8.3",+ "private": true,+ "description": "Tauri plugin API for agent skill management",+ "type": "module",+ "types": "./dist-js/index.d.ts",+ "main": "./dist-js/index.cjs",+ "module": "./dist-js/index.js",+ "exports": {+ "types": "./dist-js/index.d.ts",+ "import": "./dist-js/index.js",+ "require": "./dist-js/index.cjs"+ },+ "files": [+ "dist-js",+ "README.md"+ ],+ "scripts": {+ "build": "rollup -c",+ "prepublishOnly": "yarn build",+ "pretest": "yarn build"+ },+ "dependencies": {+ "@tauri-apps/api": ">=2.0.0-beta.6"+ },+ "devDependencies": {+ "@rollup/plugin-typescript": "^12.0.0",+ "rollup": "^4.9.6",+ "tslib": "^2.6.2",+ "typescript": "^5.3.3"+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.tomlnew file mode 100644index 000000000..4255da7dc--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml@@ -0,0 +1,19 @@+[default]+description = "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution"+permissions = [+ "allow-workspace-path",+ "allow-thread-workspace-path",+ "allow-thread-workspace-delete",+ "allow-thread-workspace-sweep",+ "allow-skill-list",+ "allow-skill-read",+ "allow-skill-write",+ "allow-skill-delete",+ "allow-memory-list",+ "allow-memory-read",+ "allow-memory-write",+ "allow-memory-delete",+ "allow-tool-schemas",+ "allow-sandbox-status",+ "allow-execute-tool",+]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.jsonnew file mode 100644index 000000000..db3bdf908--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json@@ -0,0 +1,486 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "PermissionFile",+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",+ "type": "object",+ "properties": {+ "default": {+ "description": "The default permission set for the plugin",+ "anyOf": [+ {+ "$ref": "#/definitions/DefaultPermission"+ },+ {+ "type": "null"+ }+ ]+ },+ "set": {+ "description": "A list of permissions sets defined",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionSet"+ }+ },+ "permission": {+ "description": "A list of inlined permissions",+ "default": [],+ "type": "array",+ "items": {+ "$ref": "#/definitions/Permission"+ }+ }+ },+ "definitions": {+ "DefaultPermission": {+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",+ "type": "object",+ "required": [+ "permissions"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionSet": {+ "description": "A set of direct permissions grouped together under a new name.",+ "type": "object",+ "required": [+ "description",+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does.",+ "type": "string"+ },+ "permissions": {+ "description": "All permissions this set contains.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionKind"+ }+ }+ }+ },+ "Permission": {+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",+ "type": "object",+ "required": [+ "identifier"+ ],+ "properties": {+ "version": {+ "description": "The version of the permission.",+ "type": [+ "integer",+ "null"+ ],+ "format": "uint64",+ "minimum": 1.0+ },+ "identifier": {+ "description": "A unique identifier for the permission.",+ "type": "string"+ },+ "description": {+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",+ "type": [+ "string",+ "null"+ ]+ },+ "commands": {+ "description": "Allowed or denied commands when using this permission.",+ "default": {+ "allow": [],+ "deny": []+ },+ "allOf": [+ {+ "$ref": "#/definitions/Commands"+ }+ ]+ },+ "scope": {+ "description": "Allowed or denied scoped when using this permission.",+ "allOf": [+ {+ "$ref": "#/definitions/Scopes"+ }+ ]+ },+ "platforms": {+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "Commands": {+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Allowed command.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "deny": {+ "description": "Denied command, which takes priority.",+ "default": [],+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "Scopes": {+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",+ "type": "object",+ "properties": {+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ },+ "PermissionKind": {+ "type": "string",+ "oneOf": [+ {+ "description": "Enables the execute_tool command without any pre-configured scope.",+ "type": "string",+ "const": "allow-execute-tool",+ "markdownDescription": "Enables the execute_tool command without any pre-configured scope."+ },+ {+ "description": "Denies the execute_tool command without any pre-configured scope.",+ "type": "string",+ "const": "deny-execute-tool",+ "markdownDescription": "Denies the execute_tool command without any pre-configured scope."+ },+ {+ "description": "Enables the memory_delete command without any pre-configured scope.",+ "type": "string",+ "const": "allow-memory-delete",+ "markdownDescription": "Enables the memory_delete command without any pre-configured scope."+ },+ {+ "description": "Denies the memory_delete command without any pre-configured scope.",+ "type": "string",+ "const": "deny-memory-delete",+ "markdownDescription": "Denies the memory_delete command without any pre-configured scope."+ },+ {+ "description": "Enables the memory_list command without any pre-configured scope.",+ "type": "string",+ "const": "allow-memory-list",+ "markdownDescription": "Enables the memory_list command without any pre-configured scope."+ },+ {+ "description": "Denies the memory_list command without any pre-configured scope.",+ "type": "string",+ "const": "deny-memory-list",+ "markdownDescription": "Denies the memory_list command without any pre-configured scope."+ },+ {+ "description": "Enables the memory_read command without any pre-configured scope.",+ "type": "string",+ "const": "allow-memory-read",+ "markdownDescription": "Enables the memory_read command without any pre-configured scope."+ },+ {+ "description": "Denies the memory_read command without any pre-configured scope.",+ "type": "string",+ "const": "deny-memory-read",+ "markdownDescription": "Denies the memory_read command without any pre-configured scope."+ },+ {+ "description": "Enables the memory_write command without any pre-configured scope.",+ "type": "string",+ "const": "allow-memory-write",+ "markdownDescription": "Enables the memory_write command without any pre-configured scope."+ },+ {+ "description": "Denies the memory_write command without any pre-configured scope.",+ "type": "string",+ "const": "deny-memory-write",+ "markdownDescription": "Denies the memory_write command without any pre-configured scope."+ },+ {+ "description": "Enables the sandbox_status command without any pre-configured scope.",+ "type": "string",+ "const": "allow-sandbox-status",+ "markdownDescription": "Enables the sandbox_status command without any pre-configured scope."+ },+ {+ "description": "Denies the sandbox_status command without any pre-configured scope.",+ "type": "string",+ "const": "deny-sandbox-status",+ "markdownDescription": "Denies the sandbox_status command without any pre-configured scope."+ },+ {+ "description": "Enables the skill_delete command without any pre-configured scope.",+ "type": "string",+ "const": "allow-skill-delete",+ "markdownDescription": "Enables the skill_delete command without any pre-configured scope."+ },+ {+ "description": "Denies the skill_delete command without any pre-configured scope.",+ "type": "string",+ "const": "deny-skill-delete",+ "markdownDescription": "Denies the skill_delete command without any pre-configured scope."+ },+ {+ "description": "Enables the skill_list command without any pre-configured scope.",+ "type": "string",+ "const": "allow-skill-list",+ "markdownDescription": "Enables the skill_list command without any pre-configured scope."+ },+ {+ "description": "Denies the skill_list command without any pre-configured scope.",+ "type": "string",+ "const": "deny-skill-list",+ "markdownDescription": "Denies the skill_list command without any pre-configured scope."+ },+ {+ "description": "Enables the skill_read command without any pre-configured scope.",+ "type": "string",+ "const": "allow-skill-read",+ "markdownDescription": "Enables the skill_read command without any pre-configured scope."+ },+ {+ "description": "Denies the skill_read command without any pre-configured scope.",+ "type": "string",+ "const": "deny-skill-read",+ "markdownDescription": "Denies the skill_read command without any pre-configured scope."+ },+ {+ "description": "Enables the skill_write command without any pre-configured scope.",+ "type": "string",+ "const": "allow-skill-write",+ "markdownDescription": "Enables the skill_write command without any pre-configured scope."+ },+ {+ "description": "Denies the skill_write command without any pre-configured scope.",+ "type": "string",+ "const": "deny-skill-write",+ "markdownDescription": "Denies the skill_write command without any pre-configured scope."+ },+ {+ "description": "Enables the thread_workspace_delete command without any pre-configured scope.",+ "type": "string",+ "const": "allow-thread-workspace-delete",+ "markdownDescription": "Enables the thread_workspace_delete command without any pre-configured scope."+ },+ {+ "description": "Denies the thread_workspace_delete command without any pre-configured scope.",+ "type": "string",+ "const": "deny-thread-workspace-delete",+ "markdownDescription": "Denies the thread_workspace_delete command without any pre-configured scope."+ },+ {+ "description": "Enables the thread_workspace_path command without any pre-configured scope.",+ "type": "string",+ "const": "allow-thread-workspace-path",+ "markdownDescription": "Enables the thread_workspace_path command without any pre-configured scope."+ },+ {+ "description": "Denies the thread_workspace_path command without any pre-configured scope.",+ "type": "string",+ "const": "deny-thread-workspace-path",+ "markdownDescription": "Denies the thread_workspace_path command without any pre-configured scope."+ },+ {+ "description": "Enables the thread_workspace_sweep command without any pre-configured scope.",+ "type": "string",+ "const": "allow-thread-workspace-sweep",+ "markdownDescription": "Enables the thread_workspace_sweep command without any pre-configured scope."+ },+ {+ "description": "Denies the thread_workspace_sweep command without any pre-configured scope.",+ "type": "string",+ "const": "deny-thread-workspace-sweep",+ "markdownDescription": "Denies the thread_workspace_sweep command without any pre-configured scope."+ },+ {+ "description": "Enables the tool_schemas command without any pre-configured scope.",+ "type": "string",+ "const": "allow-tool-schemas",+ "markdownDescription": "Enables the tool_schemas command without any pre-configured scope."+ },+ {+ "description": "Denies the tool_schemas command without any pre-configured scope.",+ "type": "string",+ "const": "deny-tool-schemas",+ "markdownDescription": "Denies the tool_schemas command without any pre-configured scope."+ },+ {+ "description": "Enables the workspace_path command without any pre-configured scope.",+ "type": "string",+ "const": "allow-workspace-path",+ "markdownDescription": "Enables the workspace_path command without any pre-configured scope."+ },+ {+ "description": "Denies the workspace_path command without any pre-configured scope.",+ "type": "string",+ "const": "deny-workspace-path",+ "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-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`",+ "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-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-execute-tool`"+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/src-tauri/plugins/tauri-plugin-agent-tools/rollup.config.js b/src-tauri/plugins/tauri-plugin-agent-tools/rollup.config.jsnew file mode 100644index 000000000..4490fedba--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/rollup.config.js@@ -0,0 +1,22 @@+import { readFileSync } from 'node:fs'+import { dirname, join } from 'node:path'+import { cwd } from 'node:process'+import typescript from '@rollup/plugin-typescript'++const pkg = JSON.parse(readFileSync(join(cwd(), 'package.json'), 'utf8'))++export default {+ input: 'guest-js/index.ts',+ output: [+ { file: pkg.exports.import, format: 'esm' },+ { file: pkg.exports.require, format: 'cjs' }+ ],+ plugins: [+ typescript({ declaration: true, declarationDir: dirname(pkg.exports.import) })+ ],+ external: [+ /^@tauri-apps\/api/,+ ...Object.keys(pkg.dependencies || {}),+ ...Object.keys(pkg.peerDependencies || {})+ ]+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsnew file mode 100644index 000000000..6c612359d--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -0,0 +1,928 @@+//! Desktop IPC shims over the Tauri-free core.+//!+//! Three surfaces:+//!+//! 1. **Management** -- skill and memory CRUD against the permanent store.+//! 2. **Sandbox lifecycle** -- `thread_workspace_{path,delete,sweep}`. Each+//! thread gets its own ephemeral sandbox, so scratch files from one+//! conversation are invisible to the next; the store is never swept.+//! 3. **Tool execution** -- `tool_schemas` + `execute_tool`, for the desktop+//! chat loop. The desktop drives its tool loop in TypeScript+//! (`custom-chat-transport.ts`), so unlike the CLI agent -- which calls+//! `tools::handlers` in process -- it has to reach execution over IPC.+//!+//! `execute_tool` treats the gate as the authority rather than the caller, but it+//! answers two of the gate's prompts structurally instead of by asking, because on+//! this surface what the prompt protects is already guaranteed:+//!+//! - **Writes** land in the thread's ephemeral sandbox (`root` is always+//! `ensure_thread_workspace`): confined by `escapes_project`, deleted with the+//! conversation, and only a *sibling* of the permanent store. No durable user+//! data is in range.+//! - **`bash`** runs only when `jail` reports an enforcing OS sandbox, which gives+//! the same containment. With no sandbox it is refused outright rather than run+//! unconfined.+//!+//! Everything else still refuses -- notably a read that escapes the sandbox. The+//! gate itself is deliberately left untouched, because the CLI agent shares it and+//! *does* want to prompt: there, the root is the user's real project.+//!+//! Note some command names match built-in tool names (`skill_list`,+//! `memory_list`). The commands are the *management* surface; the tools are what+//! the model calls. They are separate namespaces.++use std::path::{Path, PathBuf};++use serde::Serialize;++use crate::memory;+use crate::permissions::ToolPermissions;+use crate::skills::{self, SkillMeta};+use crate::tools::gate::{self, Decision, PromptKind, SessionGrants};+use crate::tools::jail;+use crate::tools::{handlers, lookup, schema, ToolContext};+use crate::workspace;++#[derive(Debug, Clone, Serialize, thiserror::Error)]+#[error("AgentToolsError: {message}")]+pub struct AgentToolsError {+ pub message: String,+}++impl From<String> for AgentToolsError {+ /// Strips the core's `ERROR:` tool-protocol prefix; it is meaningful to the+ /// model, but noise in a dialog.+ fn from(message: String) -> Self {+ let message = message+ .strip_prefix("ERROR:")+ .unwrap_or(&message)+ .trim()+ .to_string();+ Self { message }+ }+}++/// Outcome of a built-in tool execution.+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ToolResult {+ pub content: String,+ /// Display-only diff for `write`/`edit`; never part of model context.+ pub diff: Option<String>,+ pub is_error: bool,+}++/// The permanent store root holding `memory/` and `skills/`.+///+/// `project` is an explicit override and is currently always `None`: the desktop+/// has no project picker yet. Once one lands, a project's own co-located store+/// (`<project>/.jan/agent`) layers on top of this one; see the memory-scope TODO.+fn resolve_store(data_folder: &str, project: Option<&str>) -> PathBuf {+ match project.map(str::trim).filter(|p| !p.is_empty()) {+ Some(p) => workspace::project_store(Path::new(p)),+ None => workspace::permanent_store(Path::new(data_folder)),+ }+}++/// Ensure the permanent store exists and return its path, so the UI can show+/// where memories and skills live.+#[tauri::command]+pub async fn workspace_path(data_folder: String) -> Result<String, AgentToolsError> {+ let root = workspace::ensure_permanent_store(Path::new(&data_folder)).await?;+ Ok(root.to_string_lossy().to_string())+}++/// Create a thread's ephemeral sandbox and return its path, so the UI can offer+/// to open it and the user can copy files in for the agent to work on.+#[tauri::command]+pub async fn thread_workspace_path(+ data_folder: String,+ thread_id: String,+) -> Result<String, AgentToolsError> {+ let dir = workspace::ensure_thread_workspace(Path::new(&data_folder), &thread_id).await?;+ Ok(dir.to_string_lossy().to_string())+}++/// Delete a thread's sandbox. Called when a thread is deleted; memory and skills+/// are untouched.+#[tauri::command]+pub async fn thread_workspace_delete(+ data_folder: String,+ thread_id: String,+) -> Result<(), AgentToolsError> {+ workspace::remove_thread_workspace(Path::new(&data_folder), &thread_id)+ .await+ .map_err(Into::into)+}++/// Delete every sandbox not belonging to a surviving thread, returning how many+/// were removed. Called once at startup: sandboxes are ephemeral, but a crash or+/// a thread deleted while the app was closed would otherwise leave one behind.+#[tauri::command]+pub async fn thread_workspace_sweep(+ data_folder: String,+ keep: Vec<String>,+) -> Result<usize, AgentToolsError> {+ workspace::sweep_thread_workspaces(Path::new(&data_folder), &keep)+ .await+ .map_err(Into::into)+}++/// Every discovered skill with its description, including empty stubs so the+/// user can see and edit them.+#[tauri::command]+pub async fn skill_list(+ data_folder: String,+ project: Option<String>,+) -> Result<Vec<SkillMeta>, AgentToolsError> {+ Ok(skills::list_meta(&resolve_store(+ &data_folder,+ project.as_deref(),+ )))+}++/// Raw `SKILL.md` text, frontmatter included, for the editor.+#[tauri::command]+pub async fn skill_read(+ data_folder: String,+ project: Option<String>,+ name: String,+) -> Result<String, AgentToolsError> {+ skills::read_raw(&resolve_store(&data_folder, project.as_deref()), &name).map_err(Into::into)+}++/// Create or overwrite a skill. Parent directories are created as needed.+#[tauri::command]+pub async fn skill_write(+ data_folder: String,+ project: Option<String>,+ name: String,+ content: String,+) -> Result<(), AgentToolsError> {+ skills::write(+ &resolve_store(&data_folder, project.as_deref()),+ &name,+ &content,+ )+ .map_err(Into::into)+}++/// Delete a skill in either form. Idempotent: a missing skill is Ok.+#[tauri::command]+pub async fn skill_delete(+ data_folder: String,+ project: Option<String>,+ name: String,+) -> Result<(), AgentToolsError> {+ skills::delete(&resolve_store(&data_folder, project.as_deref()), &name).map_err(Into::into)+}++/// Memory note names (stems), sorted.+#[tauri::command]+pub async fn memory_list(+ data_folder: String,+ project: Option<String>,+) -> Result<Vec<String>, AgentToolsError> {+ Ok(memory::list(&resolve_store(&data_folder, project.as_deref())).await)+}++#[tauri::command]+pub async fn memory_read(+ data_folder: String,+ project: Option<String>,+ name: String,+) -> Result<String, AgentToolsError> {+ memory::read(&resolve_store(&data_folder, project.as_deref()), &name)+ .await+ .map_err(Into::into)+}++#[tauri::command]+pub async fn memory_write(+ data_folder: String,+ project: Option<String>,+ name: String,+ content: String,+) -> Result<(), AgentToolsError> {+ memory::write(+ &resolve_store(&data_folder, project.as_deref()),+ &name,+ &content,+ )+ .await+ .map(|_| ())+ .map_err(Into::into)+}++/// Delete a memory note. Idempotent: a missing note is Ok.+#[tauri::command]+pub async fn memory_delete(+ data_folder: String,+ project: Option<String>,+ name: String,+) -> Result<(), AgentToolsError> {+ memory::delete(&resolve_store(&data_folder, project.as_deref()), &name)+ .await+ .map_err(Into::into)+}++/// OpenAI-shaped function schemas for every built-in tool. The frontend picks+/// which subset to advertise; `schema.rs` stays the single source of truth so+/// the schemas are never re-typed in TypeScript.+#[tauri::command]+pub fn tool_schemas() -> Vec<serde_json::Value> {+ schema::builtin_tool_schemas()+}++/// Whether this machine can confine a shell, and with what.+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SandboxStatus {+ /// Backend name for display: `bubblewrap`, `seatbelt`, `appcontainer`, `none`.+ pub backend: String,+ pub enforces: bool,+}++/// Report the sandbox backend so the frontend can decide whether to advertise+/// `bash` at all. Offering a tool that `execute_tool` will always refuse wastes a+/// model turn and reads as a bug, so the tool list is built from this.+#[tauri::command]+pub async fn sandbox_status() -> Result<SandboxStatus, AgentToolsError> {+ // The first call probes bubblewrap in a subprocess. Cached afterwards, but+ // keep even that one call off the async runtime's thread.+ let backend = tokio::task::spawn_blocking(jail::backend)+ .await+ .map_err(|e| AgentToolsError::from(format!("sandbox probe failed: {e}")))?;+ Ok(SandboxStatus {+ backend: backend.as_str().to_string(),+ enforces: backend.enforces(),+ })+}++/// Execute one built-in tool.+///+/// The gate decides, not the caller. `write` and `edit` resolve to `Prompt` and+/// are refused here regardless of what the frontend asks for, until a permission+/// round-trip exists; a read that escapes the project root prompts too. `bash`+/// runs only under an enforcing sandbox (see the module docs).+#[tauri::command]+pub async fn execute_tool(+ data_folder: String,+ thread_id: String,+ project: Option<String>,+ name: String,+ args: serde_json::Value,+ enabled_skills: Option<Vec<String>>,+ allow_network: Option<bool>,+) -> Result<ToolResult, AgentToolsError> {+ // Created here rather than trusted to exist: `escapes_project` canonicalizes+ // the sandbox root and treats a missing one as an escape, so every tool call+ // would be refused if the thread's first tool call arrived before any UI+ // surface had ensured it.+ let root = workspace::ensure_thread_workspace(Path::new(&data_folder), &thread_id).await?;+ let store = resolve_store(&data_folder, project.as_deref());+ let tool = lookup(&name)+ .ok_or_else(|| AgentToolsError::from(format!("unknown built-in tool '{name}'")))?;++ match gate::resolve_decision(+ tool,+ &args,+ &root,+ &ToolPermissions::default(),+ &SessionGrants::default(),+ ) {+ Decision::Allow => {}+ Decision::HardDeny => {+ return Err(format!("tool '{name}' is denied by policy").into());+ }+ // An exec prompt asks the user to vouch for a command that could reach+ // anything. Under an enforcing sandbox it cannot: writes stay in the+ // thread workspace and $HOME is unreadable, so the containment the prompt+ // was protecting is already guaranteed. The gate itself is left alone,+ // because the CLI agent *does* want to prompt here.+ Decision::Prompt(PromptKind::Exec) if jail::backend().enforces() => {}+ // Same reasoning for writes, from the other direction. `root` here is+ // always `ensure_thread_workspace`, never a real project: an ephemeral+ // directory deleted with the conversation, which `escapes_project`+ // confines and whose sibling -- not child -- is the permanent store. So+ // no durable user data is in range for the prompt to protect, and+ // refusing here while `bash` may already write the same files would be a+ // control a sibling tool bypasses.+ //+ // A write that *escapes* the sandbox (absolute or `..`) is different:+ // it can reach host files (rc files, ssh keys, LaunchAgents, the store)+ // that the ephemeral-root reasoning does not cover. It is gated as+ // `WriteEscape` and refused here outright, since this surface has no+ // prompt round-trip to approve it.+ Decision::Prompt(PromptKind::Write) => {}+ Decision::Prompt(PromptKind::WriteEscape) => {+ return Err(format!(+ "tool '{name}' tried to write outside the agent workspace and was refused"+ )+ .into());+ }+ Decision::Prompt(kind) => {+ return Err(format!(+ "tool '{name}' needs user approval ({kind:?}) and is not available yet"+ )+ .into());+ }+ }++ let enabled = enabled_skills.unwrap_or_default();+ let ctx = ToolContext::new(&root, &store, &enabled)+ .with_network(allow_network.unwrap_or(false))+ .with_confined_writes(true)+ .with_mask_root(Path::new(&data_folder));+ let (content, diff) = handlers::execute_builtin_with_diff(tool, &args, &ctx).await;+ let is_error =+ content.starts_with("ERROR") || (name == "bash" && handlers::bash_result_failed(&content));+ Ok(ToolResult {+ content,+ diff,+ is_error,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;+ use std::sync::atomic::{AtomicUsize, Ordering};++ static COUNTER: AtomicUsize = AtomicUsize::new(0);++ /// A temp dir standing in for the Jan data folder.+ fn unique_data_folder() -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ std::env::temp_dir().join(format!("jan_cmd_test_{}_{}", std::process::id(), n))+ }++ const T1: &str = "thread-one";+ const T2: &str = "thread-two";++ #[test]+ fn default_store_is_permanent_and_outside_any_sandbox() {+ let store = resolve_store("/data", None);+ assert_eq!(store, Path::new("/data/agent-workspace"));+ // The sandbox lives under threads/, so no relative path from inside one+ // reaches the store without escaping it.+ let sandbox = workspace::thread_workspace(Path::new("/data"), T1).unwrap();+ assert!(!workspace::store_dir(&store, "memory").starts_with(&sandbox));+ }++ #[test]+ fn explicit_project_uses_its_co_located_store() {+ assert_eq!(+ resolve_store("/data", Some("/repo")),+ Path::new("/repo/.jan/agent")+ );+ // Blank is treated as absent, not as the filesystem root.+ assert_eq!(+ resolve_store("/data", Some(" ")),+ Path::new("/data/agent-workspace")+ );+ }++ #[test]+ fn error_strips_the_tool_protocol_prefix() {+ let e = AgentToolsError::from("ERROR: invalid name '..'".to_string());+ assert_eq!(e.message, "invalid name '..'");+ let e = AgentToolsError::from("plain message".to_string());+ assert_eq!(e.message, "plain message");+ }++ /// Writes land in the thread's ephemeral sandbox and are allowed there. This+ /// pins the containment that makes that safe: the file appears where it was+ /// asked for, and nowhere else.+ #[tokio::test]+ async fn writes_are_allowed_inside_the_ephemeral_sandbox() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ let out = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "write".into(),+ json!({"path": "a.txt", "content": "hello"}),+ None,+ None,+ )+ .await+ .expect("a write inside the sandbox is allowed");+ assert!(!out.is_error, "got: {}", out.content);++ let sandbox = workspace::thread_workspace(&data, T1).unwrap();+ assert_eq!(+ std::fs::read_to_string(sandbox.join("a.txt")).ok(),+ Some("hello".to_string())+ );+ let _ = std::fs::remove_dir_all(&data);+ }++ /// `edit` returns a display-only diff. It must reach the caller (the UI needs+ /// it) while staying out of `content`, which is what the model sees.+ #[tokio::test]+ async fn edit_returns_a_diff_for_display_only() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let sandbox = workspace::ensure_thread_workspace(&data, T1).await.unwrap();+ std::fs::write(sandbox.join("a.txt"), b"before").unwrap();++ let out = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "edit".into(),+ json!({"path": "a.txt", "edits": [{"old_string": "before", "new_string": "after"}]}),+ None,+ None,+ )+ .await+ .unwrap();++ assert!(!out.is_error, "got: {}", out.content);+ let diff = out.diff.expect("edit must report a diff");+ assert!(+ diff.contains("after"),+ "diff should show the change: {diff}"+ );+ assert!(+ !out.content.contains(&diff),+ "the diff must not be duplicated into model-facing content"+ );+ let _ = std::fs::remove_dir_all(&data);+ }++ /// The gate still decides: a read that escapes the sandbox is a `Prompt` and+ /// stays refused, so allowing writes did not open the door generally.+ #[tokio::test]+ async fn escaping_reads_are_still_refused() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ let err = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "read".into(),+ json!({"path": "../../../etc/hostname"}),+ None,+ None,+ )+ .await+ .expect_err("an escaping read must be refused");+ assert!(+ err.message.contains("needs user approval"),+ "unexpected error {}",+ err.message+ );+ let _ = std::fs::remove_dir_all(&data);+ }++ /// A write that escapes the sandbox (absolute or `..`) must be refused on the+ /// desktop surface, just like an escaping read -- it could reach host files.+ #[tokio::test]+ async fn escaping_writes_are_refused() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ for path in ["../escape.txt", "/tmp/jan_cmd_escape.txt"] {+ let err = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "write".into(),+ json!({"path": path, "content": "x"}),+ None,+ None,+ )+ .await+ .expect_err("an escaping write must be refused");+ assert!(+ err.message.contains("outside the agent workspace"),+ "unexpected error {}",+ err.message+ );+ }++ // An in-sandbox write still succeeds, so we didn't over-tighten.+ let res = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "write".into(),+ json!({"path": "ok.txt", "content": "x"}),+ None,+ None,+ )+ .await+ .expect("an in-workspace write must succeed");+ assert_eq!(res.content, "Created ok.txt (1 bytes)");+ let _ = std::fs::remove_dir_all(&data);+ }++ /// The status the frontend gates on must agree with what execution actually+ /// does, or the tool list and the executor disagree about whether bash works.+ #[tokio::test]+ async fn sandbox_status_matches_the_backend_execution_uses() {+ let status = sandbox_status().await.unwrap();+ assert_eq!(status.enforces, jail::backend().enforces());+ assert_eq!(status.backend, jail::backend().as_str());+ assert_ne!(status.backend, "", "a backend always has a name");+ assert_eq!(status.enforces, status.backend != "none");+ }++ /// `bash` availability tracks the sandbox, in both directions: it runs when+ /// the OS can confine it and is refused when it cannot. Asserting both arms+ /// keeps the fallback honest on hosts (and CI images) with no backend.+ #[tokio::test]+ async fn bash_runs_only_when_the_sandbox_can_enforce() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ let result = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "bash".into(),+ json!({"command": "echo hi"}),+ None,+ None,+ )+ .await;++ if jail::backend().enforces() {+ let out = result.expect("sandboxed bash should run");+ assert!(!out.is_error, "got: {}", out.content);+ assert!(out.content.contains("hi"), "got: {}", out.content);+ } else {+ let out = result.expect("the refusal is a tool result, not an IPC error");+ assert!(out.is_error);+ assert!(+ out.content.contains("no OS sandbox"),+ "the model must be told why, got: {}",+ out.content+ );+ }+ let _ = std::fs::remove_dir_all(&data);+ }++ /// The network flag has to survive the whole IPC -> ToolContext -> jail path.+ /// Only the closed direction is asserted: opening it would make the test+ /// depend on the host actually having connectivity.+ #[tokio::test]+ async fn bash_has_no_network_unless_the_caller_asks() {+ if !jail::backend().enforces() {+ eprintln!("skipping: no sandbox backend on this host");+ return;+ }+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ let out = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "bash".into(),+ json!({"command": "exec 3<>/dev/tcp/1.1.1.1/53 && echo connected"}),+ None,+ None,+ )+ .await+ .unwrap();++ assert!(!out.content.contains("connected"), "got: {}", out.content);+ assert!(+ out.content.contains("Network access is disabled"),+ "a network refusal must explain itself, got: {}",+ out.content+ );+ let _ = std::fs::remove_dir_all(&data);+ }++ /// The sandbox is created by `execute_tool` itself. Without that, the very+ /// first tool call of a thread would be refused: `escapes_project`+ /// canonicalizes the root and a missing root reads as an escape.+ #[tokio::test]+ async fn first_tool_call_creates_the_sandbox() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ let out = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "ls".into(),+ json!({}),+ None,+ None,+ )+ .await+ .unwrap();+ assert!(!out.is_error, "got: {}", out.content);+ assert!(workspace::thread_workspace(&data, T1).unwrap().is_dir());+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn allowed_read_runs_in_the_thread_sandbox() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let sandbox = PathBuf::from(thread_workspace_path(df.clone(), T1.into()).await.unwrap());+ std::fs::write(sandbox.join("a.txt"), b"hello").unwrap();++ let out = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "read".to_string(),+ json!({"path": "a.txt"}),+ None,+ None,+ )+ .await+ .unwrap();+ assert!(out.content.contains("hello"), "got: {}", out.content);+ assert!(!out.is_error);+ let _ = std::fs::remove_dir_all(&data);+ }++ /// Thread isolation: each conversation gets its own sandbox, and neither a+ /// relative nor an absolute path reaches the other's scratch files.+ #[tokio::test]+ async fn one_thread_cannot_read_another_threads_files() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let one = PathBuf::from(thread_workspace_path(df.clone(), T1.into()).await.unwrap());+ thread_workspace_path(df.clone(), T2.into()).await.unwrap();+ std::fs::write(one.join("secret.txt"), b"classified").unwrap();++ for path in [+ json!({"path": "../thread-one/secret.txt"}),+ json!({"path": one.join("secret.txt").to_string_lossy()}),+ ] {+ let err = execute_tool(df.clone(), T2.into(), None, "read".into(), path, None, None)+ .await+ .expect_err("cross-thread read must be refused");+ assert!(+ err.message.contains("needs user approval"),+ "unexpected: {}",+ err.message+ );+ }+ let _ = std::fs::remove_dir_all(&data);+ }++ /// Memory is permanent: wiping a thread's sandbox leaves it untouched, and a+ /// note written under one thread is readable from the next.+ #[tokio::test]+ async fn memory_outlives_the_thread_that_wrote_it() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ let out = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "memory_write".into(),+ json!({"name": "prefs", "content": "user likes tabs"}),+ None,+ None,+ )+ .await+ .unwrap();+ assert!(!out.is_error, "got: {}", out.content);++ thread_workspace_delete(df.clone(), T1.into())+ .await+ .unwrap();+ assert!(!workspace::thread_workspace(&data, T1).unwrap().exists());++ let out = execute_tool(+ df.clone(),+ T2.into(),+ None,+ "memory_read".into(),+ json!({"name": "prefs"}),+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(out.content, "user likes tabs");+ let _ = std::fs::remove_dir_all(&data);+ }++ /// Memory lives outside the sandbox, so the general filesystem tools cannot+ /// reach it even by climbing out -- no extra rule, just `escapes_project`.+ #[tokio::test]+ async fn filesystem_tools_cannot_reach_memory() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ memory_write(df.clone(), None, "prefs".into(), "secret".into())+ .await+ .unwrap();+ thread_workspace_path(df.clone(), T1.into()).await.unwrap();++ let store = resolve_store(&df, None);+ for path in [+ json!({"path": "../../memory/prefs.md"}),+ json!({"path": workspace::store_dir(&store, "memory").join("prefs.md").to_string_lossy()}),+ ] {+ let err = execute_tool(df.clone(), T1.into(), None, "read".into(), path, None, None)+ .await+ .expect_err("memory must be unreachable from the sandbox");+ assert!(+ err.message.contains("needs user approval"),+ "unexpected: {}",+ err.message+ );+ }+ let _ = std::fs::remove_dir_all(&data);+ }++ /// A sweep clears leftover sandboxes without touching the store.+ #[tokio::test]+ async fn sweep_keeps_live_threads_and_the_store() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ memory_write(df.clone(), None, "prefs".into(), "keep me".into())+ .await+ .unwrap();+ thread_workspace_path(df.clone(), T1.into()).await.unwrap();+ thread_workspace_path(df.clone(), T2.into()).await.unwrap();++ let removed = thread_workspace_sweep(df.clone(), vec![T1.to_string()])+ .await+ .unwrap();+ assert_eq!(removed, 1);+ assert!(workspace::thread_workspace(&data, T1).unwrap().is_dir());+ assert!(!workspace::thread_workspace(&data, T2).unwrap().exists());+ assert_eq!(+ memory_read(df.clone(), None, "prefs".into()).await.unwrap(),+ "keep me"+ );+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn a_traversing_thread_id_is_rejected() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ for bad in ["../../..", "a/b", ""] {+ assert!(+ thread_workspace_path(df.clone(), bad.into()).await.is_err(),+ "expected {bad:?} to be rejected"+ );+ assert!(+ execute_tool(+ df.clone(),+ bad.into(),+ None,+ "ls".into(),+ json!({}),+ None,+ None+ )+ .await+ .is_err(),+ "expected {bad:?} to be rejected by execute_tool"+ );+ }+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn agent_config_surface_is_hard_denied() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ thread_workspace_path(df.clone(), T1.into()).await.unwrap();++ let err = execute_tool(+ df.clone(),+ T1.into(),+ None,+ "read".to_string(),+ json!({"path": ".jan/agent/agent.toml"}),+ None,+ None,+ )+ .await+ .expect_err("agent config must be hard-denied");+ assert!(+ err.message.contains("denied by policy"),+ "unexpected: {}",+ err.message+ );+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn unknown_tool_is_rejected() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ let err = execute_tool(+ df,+ T1.into(),+ None,+ "rm_rf".to_string(),+ json!({}),+ None,+ None,+ )+ .await+ .expect_err("unknown tool");+ assert!(err.message.contains("unknown built-in tool"));+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn memory_crud_roundtrip_in_the_permanent_store() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ workspace_path(df.clone()).await.unwrap();++ assert!(memory_list(df.clone(), None).await.unwrap().is_empty());+ memory_write(df.clone(), None, "prefs".into(), "body".into())+ .await+ .unwrap();+ assert_eq!(memory_list(df.clone(), None).await.unwrap(), vec!["prefs"]);+ assert_eq!(+ memory_read(df.clone(), None, "prefs".into()).await.unwrap(),+ "body"+ );+ memory_delete(df.clone(), None, "prefs".into())+ .await+ .unwrap();+ assert!(memory_list(df.clone(), None).await.unwrap().is_empty());+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn skill_crud_roundtrip_in_the_permanent_store() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();+ workspace_path(df.clone()).await.unwrap();++ skill_write(+ df.clone(),+ None,+ "deploy".into(),+ "---\ndescription: d\n---\nbody".into(),+ )+ .await+ .unwrap();+ let listed = skill_list(df.clone(), None).await.unwrap();+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].name, "deploy");+ assert_eq!(listed[0].description, "d");+ assert!(skill_read(df.clone(), None, "deploy".into())+ .await+ .unwrap()+ .contains("body"));+ skill_delete(df.clone(), None, "deploy".into())+ .await+ .unwrap();+ assert!(skill_list(df.clone(), None).await.unwrap().is_empty());+ let _ = std::fs::remove_dir_all(&data);+ }++ /// A skill written by the model under one thread is loadable from the next,+ /// same as memory.+ #[tokio::test]+ async fn skills_written_by_a_tool_outlive_the_thread() {+ let data = unique_data_folder();+ let df = data.to_string_lossy().to_string();++ execute_tool(+ df.clone(),+ T1.into(),+ None,+ "skill_write".into(),+ json!({"name": "deploy", "content": "---\ndescription: d\n---\nrun it"}),+ None,+ None,+ )+ .await+ .unwrap();+ thread_workspace_delete(df.clone(), T1.into())+ .await+ .unwrap();++ let out = execute_tool(+ df.clone(),+ T2.into(),+ None,+ "skill_read".into(),+ json!({"name": "deploy"}),+ None,+ None,+ )+ .await+ .unwrap();+ assert_eq!(out.content, "run it");+ let _ = std::fs::remove_dir_all(&data);+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rsnew file mode 100644index 000000000..562a03b3e--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs@@ -0,0 +1,109 @@+//! The built-in agent toolset, shared by the Jan desktop app and the headless+//! `jan` CLI.+//!+//! The toolset is Tauri-free: executing a tool needs nothing but+//! `(&BuiltinTool, &serde_json::Value, &ToolContext)`, never an `AppHandle`.+//! `tauri` is an optional dependency behind the `tauri` feature, so the CLI+//! builds this crate with `default-features = false` and links no GUI crates.+//! Everything under `permissions`, `skills`, `tools` and `workspace` is+//! available in both configurations; only `init()` and the IPC shims in+//! `commands` are gated.++pub mod memory;+pub mod permissions;+pub mod skills;+pub mod tools;+pub mod workspace;++#[cfg(feature = "tauri")]+mod commands;++/// Runs the confined-spawn helper and exits, when this process was re-exec'd as+/// one by the Windows sandbox backend. A no-op on every other platform and on a+/// normal launch, but it must be called before anything else in `main`: the+/// helper's whole job is to spawn and wait, so starting the app first would run a+/// second copy of it per shell command.+pub use tools::appcontainer::run_helper_if_requested as run_sandbox_helper_if_requested;++#[cfg(feature = "tauri")]+pub use commands::{AgentToolsError, ToolResult};++/// Initializes the agent tools plugin.+#[cfg(feature = "tauri")]+pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {+ tauri::plugin::Builder::new("agent-tools")+ .invoke_handler(tauri::generate_handler![+ commands::workspace_path,+ commands::thread_workspace_path,+ commands::thread_workspace_delete,+ commands::thread_workspace_sweep,+ commands::skill_list,+ commands::skill_read,+ commands::skill_write,+ commands::skill_delete,+ commands::memory_list,+ commands::memory_read,+ commands::memory_write,+ commands::memory_delete,+ commands::tool_schemas,+ commands::sandbox_status,+ commands::execute_tool+ ])+ .build()+}++#[cfg(test)]+mod permission_tests {+ /// A command reaches the frontend only if it is BOTH in `generate_handler!`+ /// and in `build.rs`'s `COMMANDS` (which generates its permission). Missing+ /// the latter compiles and tests clean, then fails at runtime with+ /// "not allowed. Command not found" -- invisible to any suite that mocks+ /// `invoke`. Keep the two lists in lockstep.+ fn names_between<'a>(src: &'a str, start: &str, end: &str) -> Vec<&'a str> {+ let Some(rest) = src.split_once(start).map(|(_, r)| r) else {+ return Vec::new();+ };+ let Some(block) = rest.split_once(end).map(|(b, _)| b) else {+ return Vec::new();+ };+ block+ .split(',')+ .map(|s| s.trim().trim_matches('"'))+ .filter(|s| !s.is_empty())+ .map(|s| s.rsplit("::").next().unwrap_or(s))+ .collect()+ }++ #[test]+ fn every_registered_command_has_a_permission() {+ let handlers = names_between(include_str!("lib.rs"), "tauri::generate_handler![", "])");+ let declared = names_between(include_str!("../build.rs"), "COMMANDS: &[&str] = &[", "];");+ assert!(!handlers.is_empty(), "failed to parse generate_handler!");+ assert!(!declared.is_empty(), "failed to parse build.rs COMMANDS");+ let missing: Vec<_> = handlers+ .iter()+ .filter(|c| !declared.contains(c))+ .collect();+ assert!(+ missing.is_empty(),+ "commands registered but absent from build.rs COMMANDS: {missing:?}"+ );+ }++ #[test]+ fn every_permission_is_in_the_default_set() {+ let declared = names_between(include_str!("../build.rs"), "COMMANDS: &[&str] = &[", "];");+ let default_toml = include_str!("../permissions/default.toml");+ let missing: Vec<_> = declared+ .iter()+ .filter(|c| {+ let permission = format!("allow-{}", c.replace('_', "-"));+ !default_toml.contains(&permission)+ })+ .collect();+ assert!(+ missing.is_empty(),+ "commands missing an allow-* entry in permissions/default.toml: {missing:?}"+ );+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rsnew file mode 100644index 000000000..6e021a10d--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/memory.rs@@ -0,0 +1,136 @@+//! Long-term agent memory: flat `<name>.md` notes under `<store_root>/memory/`.+//!+//! Every function takes a store root rather than a project root, so the same+//! implementation serves the desktop's permanent store in the Jan data folder and+//! a project's co-located `<project>/.jan/agent` store. Memory deliberately+//! outlives the ephemeral per-thread sandbox the filesystem tools run in.+//!+//! This is the store the `memory_*` built-in tools read and write, and the same+//! one the management commands expose, so both share one implementation. It is+//! unrelated to the vector-db recall index, which is keyed by project and+//! populated by a separate indexing path.+//!+//! Error strings carry the `ERROR:` prefix the tool protocol expects; the+//! command layer strips it for display.++use std::path::{Path, PathBuf};++use crate::workspace::{store_dir, workspace_filename};++const KIND: &str = "memory";++/// `<store_root>/memory`.+pub fn memory_dir(store_root: &Path) -> PathBuf {+ store_dir(store_root, KIND)+}++fn target(store_root: &Path, name: &str) -> Result<PathBuf, String> {+ Ok(memory_dir(store_root).join(workspace_filename(name)?))+}++/// Note names (file stems), sorted. A missing directory yields an empty list+/// rather than an error: a store with no memory yet is not a failure.+pub async fn list(store: &Path) -> Vec<String> {+ let Ok(mut entries) = tokio::fs::read_dir(memory_dir(store)).await else {+ return Vec::new();+ };+ let mut names: Vec<String> = Vec::new();+ while let Ok(Some(e)) = entries.next_entry().await {+ let path = e.path();+ if path.extension().and_then(|x| x.to_str()) == Some("md") {+ if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {+ names.push(stem.to_string());+ }+ }+ }+ names.sort();+ names+}++pub async fn read(store: &Path, name: &str) -> Result<String, String> {+ let target = target(store, name)?;+ tokio::fs::read_to_string(&target)+ .await+ .map_err(|e| format!("ERROR: {e}"))+}++/// Create or overwrite a note. Returns the filename written, so callers can+/// phrase their own result message. Parent directories are created as needed.+pub async fn write(store: &Path, name: &str, content: &str) -> Result<String, String> {+ let file = workspace_filename(name)?;+ let dir = memory_dir(store);+ tokio::fs::create_dir_all(&dir)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ tokio::fs::write(dir.join(&file), content)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ Ok(file)+}++/// Delete a note. Idempotent: a missing note is Ok.+pub async fn delete(store: &Path, name: &str) -> Result<(), String> {+ let target = target(store, name)?;+ match tokio::fs::remove_file(&target).await {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(format!("ERROR: {e}")),+ }+}++#[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);+ std::env::temp_dir().join(format!("jan_memory_test_{}_{}", std::process::id(), n))+ }++ #[tokio::test]+ async fn write_read_list_delete_roundtrip() {+ let root = unique_root();+ assert!(list(&root).await.is_empty(), "fresh project has no notes");++ assert_eq!(write(&root, "prefs", "body").await.unwrap(), "prefs.md");+ assert_eq!(read(&root, "prefs").await.unwrap(), "body");+ assert_eq!(list(&root).await, vec!["prefs"]);++ delete(&root, "prefs").await.unwrap();+ assert!(list(&root).await.is_empty());+ delete(&root, "prefs").await.unwrap(); // idempotent+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn list_is_sorted_and_ignores_non_markdown() {+ let root = unique_root();+ write(&root, "b", "b").await.unwrap();+ write(&root, "a", "a").await.unwrap();+ std::fs::write(memory_dir(&root).join("notes.txt"), "ignored").unwrap();++ assert_eq!(list(&root).await, vec!["a", "b"]);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn traversal_names_are_rejected() {+ let root = unique_root();+ for bad in ["../escape", "sub/x", "..", "", "."] {+ assert!(write(&root, bad, "x").await.is_err(), "write {bad:?}");+ assert!(read(&root, bad).await.is_err(), "read {bad:?}");+ assert!(delete(&root, bad).await.is_err(), "delete {bad:?}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn read_missing_note_errors() {+ let root = unique_root();+ assert!(read(&root, "nope").await.is_err());+ let _ = std::fs::remove_dir_all(&root);+ }+}diff --git a/src-tauri/src/core/agent/permissions.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rssimilarity index 93%rename from src-tauri/src/core/agent/permissions.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rsindex ab24f7d1a..e78ce260d 100644--- a/src-tauri/src/core/agent/permissions.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/permissions.rs@@ -5,7 +5,7 @@use glob::Pattern;#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]-pub(crate) enum PermissionDefault {+pub enum PermissionDefault {Allow,Deny,#[default]@@ -14,7 +14,7 @@ pub(crate) enum PermissionDefault {impl PermissionDefault {/// Lenient parser: unknown/empty falls back to the secure default (ReadOnly).- pub(crate) fn from_str_lenient(s: &str) -> Self {+ pub fn from_str_lenient(s: &str) -> Self {match s.trim().to_ascii_lowercase().as_str() {"allow" => PermissionDefault::Allow,"deny" => PermissionDefault::Deny,@@ -40,7 +40,7 @@ fn compile(patterns: &[String]) -> Vec<Pattern> {}impl ToolPermissions {- pub(crate) fn new(+ pub fn new(default: PermissionDefault,allow: &[String],deny: &[String],@@ -56,7 +56,7 @@ impl ToolPermissions {/// 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 {+ pub fn allow_all() -> Self {Self {default: PermissionDefault::Allow,allow: Vec::new(),@@ -65,12 +65,12 @@ impl ToolPermissions {}}- pub(crate) fn is_denied(&self, name: &str) -> bool {+ pub 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 {+ pub fn is_allowed(&self, name: &str) -> bool {self.allow.iter().any(|p| p.matches(name))|| self.allow_write.iter().any(|p| p.matches(name))}@@ -80,7 +80,7 @@ impl ToolPermissions {/// built-in fs/exec tools, MCP tools are opaque and the user opted into them by/// configuring the server, so `read-only` does not suppress them (`deny` locks/// everything down). Execution of built-ins is gated separately at call time.- pub(crate) fn advertises_mcp(&self, tool_name: &str) -> bool {+ pub fn advertises_mcp(&self, tool_name: &str) -> bool {if self.is_denied(tool_name) {return false;}diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rssimilarity index 76%rename from src-tauri/src/core/agent/skills.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rsindex 48d1f3d55..ec90eae5a 100644--- a/src-tauri/src/core/agent/skills.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/skills.rs@@ -1,7 +1,12 @@-//! Per-project skill storage. A skill is either a folder `<name>/SKILL.md`-//! (SKILL.md-ecosystem compatible; may bundle scripts/resources alongside) or a-//! legacy flat `<name>.md`. Both may carry leading YAML frontmatter (`name`,-//! `description`); the folder form is what new/imported skills are written as.+//! Skill storage under `<store_root>/skills/`. A skill is either a folder+//! `<name>/SKILL.md` (SKILL.md-ecosystem compatible; may bundle+//! scripts/resources alongside) or a legacy flat `<name>.md`. Both may carry+//! leading YAML frontmatter (`name`, `description`); the folder form is what+//! new/imported skills are written as.+//!+//! Like memory, every function takes a store root, so skills live in the+//! desktop's permanent store or a project's co-located one. A skill is a+//! reusable procedure, so it must outlive the ephemeral per-thread sandbox.//!//! Sync (std::fs) so the sync `context::load_skills` and the async `agent_skill_*`//! commands share one code path; the ops are tiny single-file reads/writes.@@ -10,15 +15,17 @@ use std::path::{Path, PathBuf};use serde::Deserialize;-use crate::core::agent::tools::handlers::workspace_filename;+use crate::workspace::{store_dir, workspace_filename};++const KIND: &str = "skills";-/// `<project_root>/.jan/agent/skills`.-pub(crate) fn skills_dir(root: &Path) -> PathBuf {- root.join(".jan").join("agent").join("skills")+/// `<store_root>/skills`.+pub fn skills_dir(store: &Path) -> PathBuf {+ store_dir(store, KIND)}/// One skill on disk, located by its identity name (folder name or flat stem).-pub(crate) struct SkillEntry {+pub struct SkillEntry {pub name: String,/// The markdown file to read (the `SKILL.md`, or the flat `<name>.md`).pub file: PathBuf,@@ -43,14 +50,14 @@ struct Frontmatter {/// A skill's parsed content: optional frontmatter description + markdown body/// (body has the frontmatter fence stripped so it never leaks into the prompt).-pub(crate) struct ParsedSkill {+pub struct ParsedSkill {pub description: Option<String>,pub body: String,}/// Split leading `---\n...\n---` YAML frontmatter from the markdown body./// Tolerant: no opening/closing fence -> no frontmatter, whole input is body.-pub(crate) fn parse(content: &str) -> ParsedSkill {+pub fn parse(content: &str) -> ParsedSkill {let content = content.strip_prefix('\u{feff}').unwrap_or(content);let mut lines = content.lines();if lines.next().map(str::trim_end) != Some("---") {@@ -102,16 +109,16 @@ fn first_line(body: &str) -> String {/// Sanitized identity stem (no path escape, no `.md`). Reuses the workspace name/// guard so a caller-supplied name can never escape the skills directory.-pub(crate) fn safe_stem(name: &str) -> Result<String, String> {+pub fn safe_stem(name: &str) -> Result<String, String> {let file = workspace_filename(name)?;Ok(file.trim_end_matches(".md").to_string())}-/// All skills in the project, sorted by name. Folder skills (`<name>/SKILL.md`)+/// All skills in the store, sorted by name. Folder skills (`<name>/SKILL.md`)/// and legacy flat skills (`<name>.md`) are both discovered. When both forms/// share a name, the folder form wins so a skill is never listed/injected twice.-pub(crate) fn discover(root: &Path) -> Vec<SkillEntry> {- let dir = skills_dir(root);+pub fn discover(store: &Path) -> Vec<SkillEntry> {+ let dir = skills_dir(store);let Ok(rd) = std::fs::read_dir(&dir) else {return Vec::new();};@@ -157,9 +164,9 @@ pub(crate) fn discover(root: &Path) -> Vec<SkillEntry> {}/// Locate an existing skill by name, preferring the folder form.-fn resolve(root: &Path, name: &str) -> Result<SkillEntry, String> {+fn resolve(store: &Path, name: &str) -> Result<SkillEntry, String> {let stem = safe_stem(name)?;- let dir = skills_dir(root);+ let dir = skills_dir(store);let folder = dir.join(&stem).join("SKILL.md");if folder.is_file() {return Ok(SkillEntry {@@ -181,7 +188,7 @@ fn resolve(root: &Path, name: &str) -> Result<SkillEntry, String> {/// Whether a skill is advertised given the `[skills].enabled` whitelist. An/// empty whitelist means every skill is enabled.-pub(crate) fn is_enabled(enabled: &[String], name: &str) -> bool {+pub fn is_enabled(enabled: &[String], name: &str) -> bool {enabled.is_empty() || enabled.iter().any(|n| n == name)}@@ -196,9 +203,8 @@ fn describe(parsed: &ParsedSkill) -> String {/// Metadata for every discovered skill (name + description) — for the UI list./// Keeps empty stubs so the user can see and edit them.-#[cfg(any(not(feature = "cli"), test))]-pub(crate) fn list_meta(root: &Path) -> Vec<SkillMeta> {- discover(root)+pub fn list_meta(store: &Path) -> Vec<SkillMeta> {+ discover(store).into_iter().filter_map(|e| {let parsed = parse(&std::fs::read_to_string(&e.file).ok()?);@@ -216,10 +222,10 @@ pub(crate) fn list_meta(root: &Path) -> Vec<SkillMeta> {////// `enabled` is a whitelist of skill names; an empty list means "all skills"/// (backward-compatible with the agent.toml scaffold, which ships `enabled = []`).-pub(crate) fn catalog(root: &Path, enabled: &[String]) -> Vec<SkillMeta> {+pub fn catalog(store: &Path, enabled: &[String]) -> Vec<SkillMeta> {let allow: Option<std::collections::HashSet<&str>> =(!enabled.is_empty()).then(|| enabled.iter().map(String::as_str).collect());- discover(root)+ discover(store).into_iter().filter_map(|e| {if let Some(allow) = &allow {@@ -241,38 +247,46 @@ pub(crate) fn catalog(root: &Path, enabled: &[String]) -> Vec<SkillMeta> {}/// Raw SKILL.md text (frontmatter included) for the editor.-pub(crate) fn read_raw(root: &Path, name: &str) -> Result<String, String> {- let entry = resolve(root, name)?;+pub fn read_raw(store: &Path, name: &str) -> Result<String, String> {+ let entry = resolve(store, name)?;std::fs::read_to_string(&entry.file).map_err(|e| format!("ERROR: {e}"))}/// A skill's markdown body with the frontmatter fence stripped — what the/// `skill_read` tool hands the model when it loads a skill on demand.-pub(crate) fn read_body(root: &Path, name: &str) -> Result<String, String> {- Ok(parse(&read_raw(root, name)?).body)+pub fn read_body(store: &Path, name: &str) -> Result<String, String> {+ Ok(parse(&read_raw(store, name)?).body)}/// Create or overwrite a skill. Existing skills are written in place (preserving/// their form); new skills are written as the folder form `<name>/SKILL.md`.-pub(crate) fn write(root: &Path, name: &str, content: &str) -> Result<(), String> {+pub fn write(store: &Path, name: &str, content: &str) -> Result<(), String> {let stem = safe_stem(name)?;- let dir = skills_dir(root);+ let dir = skills_dir(store);+ let folder = dir.join(&stem);+ let folder_skill = folder.join("SKILL.md");+ // Mirror `resolve`/`discover`: the folder form `<name>/SKILL.md` is the+ // canonical one and wins over a legacy flat `<name>.md`. When the folder+ // form is absent we fall back to the flat file if one exists; a fresh skill+ // is created as the folder form. So an edit always lands where the skill+ // will be read back from, instead of updating a stale flat file that+ // `resolve` ignores (which would silently swallow the edit).let flat = dir.join(format!("{stem}.md"));- let target = if flat.is_file() {+ let target = if folder_skill.is_file() {+ folder_skill+ } else if flat.is_file() {flat} else {- let folder = dir.join(&stem);std::fs::create_dir_all(&folder).map_err(|e| format!("ERROR: {e}"))?;- folder.join("SKILL.md")+ folder_skill};std::fs::write(&target, content).map_err(|e| format!("ERROR: {e}"))}/// Delete a skill (folder or flat form). Idempotent: a missing skill is Ok.-#[cfg(any(not(feature = "cli"), test))]-pub(crate) fn delete(root: &Path, name: &str) -> Result<(), String> {+pub fn delete(store: &Path, name: &str) -> Result<(), String> {let stem = safe_stem(name)?;- let dir = skills_dir(root);+ let dir = skills_dir(store);let folder = dir.join(&stem);let flat = dir.join(format!("{stem}.md"));if folder.is_dir() {@@ -380,4 +394,32 @@ mod tests {assert!(!dir.join("legacy").exists());let _ = std::fs::remove_dir_all(&root);}++ #[test]+ fn write_prefers_folder_form_when_both_exist() {+ // When a folder form and a legacy flat form share a name, `resolve` and+ // `discover` read the folder form. `write` must land on the same file so+ // an edit isn't swallowed into a flat file the reader ignores.+ let root = std::env::temp_dir().join(format!(+ "jan_skills_both_{}",+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()+ ));+ let dir = skills_dir(&root);+ std::fs::create_dir_all(dir.join("dup")).unwrap();+ std::fs::write(dir.join("dup").join("SKILL.md"), "folder").unwrap();+ std::fs::write(dir.join("dup.md"), "flat").unwrap();++ write(&root, "dup", "updated").unwrap();+ assert_eq!(+ std::fs::read_to_string(dir.join("dup").join("SKILL.md")).unwrap(),+ "updated",+ "the folder form, which resolve reads, must receive the edit"+ );+ assert_eq!(+ std::fs::read_to_string(dir.join("dup.md")).unwrap(),+ "flat",+ "the stale flat form must be left untouched"+ );+ let _ = std::fs::remove_dir_all(&root);+ }}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rsnew file mode 100644index 000000000..451628a50--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/appcontainer.rs@@ -0,0 +1,734 @@+//! Windows AppContainer confinement for the `bash` tool.+//!+//! AppContainer is a good fit for the policy [`super::jail`] describes, because+//! the three properties are close to its defaults rather than rules layered on+//! top:+//!+//! - reads: a lowbox token can only open objects whose DACL grants its package+//! SID or one of its capabilities. Windows grants `ALL APPLICATION PACKAGES`+//! read+execute on `C:\Windows` and `C:\Program Files` but not on user+//! profiles, so "everything readable except the user's files" needs no rule.+//! - writes: nothing is writable until an ACE names the container, so granting+//! one on the thread workspace is the whole write policy. The container also+//! gets a private `AC\Temp` that Windows creates and ACLs for it.+//! - network: denied unless the spawn supplies the `internetClient` capability.+//! AppContainer blocks loopback as well, which the Unix backends do not.+//!+//! Unlike bubblewrap and Seatbelt there is no argv to wrap: the confinement is a+//! token attribute passed to `CreateProcessW`, and `tokio::process::Command`+//! exposes no hook for `STARTUPINFOEX`. So this backend re-execs the running+//! binary as a helper ([`SANDBOX_EXEC_FLAG`]) that performs the confined spawn+//! and proxies the exit code, the same trick+//! `tauri_plugin_llamacpp::deps_analyzer` uses. The helper inherits its own std+//! handles down to the shell, so the parent's pipes still work unchanged --+//! inherited handles keep the access they were opened with, so the lowbox token+//! does not need rights on the pipes themselves.+//!+//! Codex confines Windows with restricted tokens plus a separate elevated+//! logon-user backend (`codex-rs/windows-sandbox-rs`, ~500KB across 40 files,+//! including WFP firewall rules and dedicated sandbox user accounts). That buys+//! deny-read ACEs and per-process network attribution we do not need: our policy+//! has a single writable root and a binary network switch, which AppContainer+//! expresses directly.++use std::path::{Path, PathBuf};++/// Marks a re-exec of this binary as the confined-spawn helper. Must be the+/// first argument, so a normal launch never looks at anything after it.+pub const SANDBOX_EXEC_FLAG: &str = "--internal-sandbox-exec";++const NET_ON: &str = "--net";+const NET_OFF: &str = "--no-net";++/// Exit code when the helper itself fails, distinct from anything a shell+/// reports so a setup failure is not mistaken for a command failure.+#[cfg(windows)]+const HELPER_FAILURE: i32 = 126;++/// FNV-1a. Only needs to be stable and well-spread; `DefaultHasher` is neither+/// guaranteed across releases nor reproducible by the helper on the other side+/// of the re-exec.+fn fnv1a(bytes: &[u8]) -> u64 {+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ for b in bytes {+ hash ^= *b as u64;+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ hash+}++/// AppContainer moniker for one thread workspace. Derived rather than random so+/// the helper reaches the same container the previous command used, and+/// per-workspace so the SID that a workspace ACE grants cannot be held by a+/// command running for a different thread.+///+/// Monikers are limited to 64 characters of alphanumerics, `.`, `-` and `_`.+/// Windows paths are case-insensitive, so the case is folded before hashing to+/// keep two spellings of one workspace on one container.+pub fn moniker(workspace: &Path) -> String {+ let key = workspace.to_string_lossy().to_lowercase();+ format!("Jan.Agent.{:016x}", fnv1a(key.as_bytes()))+}++/// argv for the helper re-exec. Shaped like the other backends -- fixed+/// arguments, then the shell, with the command string appended by the caller --+/// so the spawn path does not change per platform.+pub fn helper_args(+ workspace: &Path,+ allow_network: bool,+ program: &Path,+ args: &[String],+) -> Vec<String> {+ let mut out = vec![+ SANDBOX_EXEC_FLAG.to_string(),+ if allow_network { NET_ON } else { NET_OFF }.to_string(),+ workspace.to_string_lossy().to_string(),+ "--".to_string(),+ program.to_string_lossy().to_string(),+ ];+ out.extend(args.iter().cloned());+ out+}++/// Quote one argument for `CreateProcessW`, which takes a single string and+/// leaves splitting to the callee. Follows the `CommandLineToArgvW` rules that+/// the C runtime and every mainstream shell parse with: backslashes are literal+/// except when they precede the closing quote, where they must be doubled.+#[cfg_attr(not(windows), allow(dead_code))]+fn quote_arg(arg: &str) -> String {+ if !arg.is_empty() && !arg.contains([' ', '\t', '"']) {+ return arg.to_string();+ }+ let mut out = String::with_capacity(arg.len() + 2);+ out.push('"');+ let mut backslashes = 0usize;+ for c in arg.chars() {+ match c {+ '\\' => {+ backslashes += 1;+ out.push('\\');+ }+ '"' => {+ // These backslashes now precede a quote, so they need escaping+ // too, or they would escape the quote instead of standing alone.+ out.push_str(&"\\".repeat(backslashes + 1));+ backslashes = 0;+ out.push('"');+ }+ other => {+ backslashes = 0;+ out.push(other);+ }+ }+ }+ out.push_str(&"\\".repeat(backslashes));+ out.push('"');+ out+}++/// Join a program and its arguments into a `CreateProcessW` command line.+#[cfg_attr(not(windows), allow(dead_code))]+fn command_line(program: &Path, args: &[String]) -> String {+ let mut line = quote_arg(&program.to_string_lossy());+ for a in args {+ line.push(' ');+ line.push_str("e_arg(a));+ }+ line+}++/// What the helper was asked to do, parsed from its own argv.+#[cfg_attr(not(windows), allow(dead_code))]+struct Request {+ workspace: PathBuf,+ allow_network: bool,+ program: PathBuf,+ args: Vec<String>,+}++/// Parse the helper's argv, or `None` when this process was not invoked as the+/// helper. Kept separate from the Win32 work so it is testable on any host.+#[cfg_attr(not(windows), allow(dead_code))]+fn parse_request<I: IntoIterator<Item = String>>(argv: I) -> Option<Request> {+ let mut it = argv.into_iter();+ if it.next()? != SANDBOX_EXEC_FLAG {+ return None;+ }+ let allow_network = match it.next()?.as_str() {+ NET_ON => true,+ NET_OFF => false,+ _ => return None,+ };+ let workspace = PathBuf::from(it.next()?);+ if it.next()? != "--" {+ return None;+ }+ let program = PathBuf::from(it.next()?);+ Some(Request {+ workspace,+ allow_network,+ program,+ args: it.collect(),+ })+}++/// True when this host can build an AppContainer at all. On Windows this only+/// probes that the API exists (Windows 8 and later, and not a reimplementation+/// such as Wine); deriving a SID is a pure hash and touches nothing.+#[cfg(windows)]+pub fn available() -> bool {+ win::derive_sid("Jan.Agent.Probe").is_ok()+}++#[cfg(not(windows))]+pub fn available() -> bool {+ false+}++/// Discard the container a thread workspace was using. Called when the workspace+/// is deleted, so a finished conversation does not leave a registered profile and+/// an empty `AppData\Local\Packages` directory behind -- monikers are derived per+/// workspace, so nothing else would ever reuse it.+///+/// Best effort, and safe to call for a workspace that never ran a command. A+/// profile that outlives its workspace is litter rather than exposure: its SID is+/// only granted on a directory that no longer exists.+#[cfg(windows)]+pub fn release(workspace: &Path) {+ win::delete_profile(&moniker(workspace));+}++#[cfg(not(windows))]+pub fn release(_workspace: &Path) {}++/// Run the confined spawn and exit with the child's status, when this process+/// was re-exec'd as the helper. Returns immediately on a normal launch, so it is+/// safe (and required) to call first thing in `main`.+#[cfg(windows)]+pub fn run_helper_if_requested() {+ let Some(req) = parse_request(std::env::args().skip(1)) else {+ return;+ };+ match win::run(&req) {+ Ok(code) => std::process::exit(code),+ Err(message) => {+ eprintln!("ERROR: sandbox setup failed: {message}");+ std::process::exit(HELPER_FAILURE);+ }+ }+}++#[cfg(not(windows))]+pub fn run_helper_if_requested() {}++#[cfg(windows)]+mod win {+ use super::{command_line, moniker, Request};+ use std::ffi::{c_void, OsStr};+ use std::os::windows::ffi::OsStrExt;+ use std::path::Path;++ use windows_sys::core::{HRESULT, PWSTR};+ use windows_sys::Win32::Foundation::{+ CloseHandle, LocalFree, SetHandleInformation, ERROR_SUCCESS, HANDLE, HANDLE_FLAG_INHERIT,+ INVALID_HANDLE_VALUE, WAIT_FAILED,+ };+ use windows_sys::Win32::Security::Authorization::{+ GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW, EXPLICIT_ACCESS_W,+ GRANT_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_SID, TRUSTEE_IS_WELL_KNOWN_GROUP, TRUSTEE_W,+ };+ use windows_sys::Win32::Security::Isolation::{+ CreateAppContainerProfile, DeleteAppContainerProfile,+ DeriveAppContainerSidFromAppContainerName,+ };+ use windows_sys::Win32::Security::{+ CreateWellKnownSid, FreeSid, WinCapabilityInternetClientSid, ACL, CONTAINER_INHERIT_ACE,+ DACL_SECURITY_INFORMATION, OBJECT_INHERIT_ACE, PSECURITY_DESCRIPTOR, PSID,+ SECURITY_CAPABILITIES, SECURITY_MAX_SID_SIZE, SID_AND_ATTRIBUTES,+ };+ use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;+ use windows_sys::Win32::System::Console::{+ GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,+ };+ use windows_sys::Win32::System::JobObjects::{+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,+ SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,+ };+ use windows_sys::Win32::System::Threading::{+ CreateProcessW, DeleteProcThreadAttributeList, GetCurrentProcess, GetExitCodeProcess,+ InitializeProcThreadAttributeList, UpdateProcThreadAttribute, WaitForSingleObject,+ CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT, INFINITE,+ LPPROC_THREAD_ATTRIBUTE_LIST, PROCESS_INFORMATION,+ PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES, STARTF_USESTDHANDLES, STARTUPINFOEXW,+ };++ /// `HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS)`: the profile survived a previous+ /// run, which is the normal case for a thread's second command.+ const PROFILE_EXISTS: HRESULT = -2147024713; // 0x800700B7++ fn wide(s: &OsStr) -> Vec<u16> {+ s.encode_wide().chain(std::iter::once(0)).collect()+ }++ fn last_error() -> String {+ std::io::Error::last_os_error().to_string()+ }++ /// Owns a `PSID` allocated by the isolation APIs.+ pub struct ContainerSid(PSID);++ impl Drop for ContainerSid {+ fn drop(&mut self) {+ if !self.0.is_null() {+ unsafe { FreeSid(self.0) };+ }+ }+ }++ pub fn derive_sid(moniker: &str) -> Result<ContainerSid, String> {+ let name = wide(OsStr::new(moniker));+ let mut sid: PSID = std::ptr::null_mut();+ let hr = unsafe { DeriveAppContainerSidFromAppContainerName(name.as_ptr(), &mut sid) };+ if hr < 0 || sid.is_null() {+ return Err(format!(+ "could not derive an AppContainer SID (hr 0x{hr:08x})"+ ));+ }+ Ok(ContainerSid(sid))+ }++ /// Register the container profile if this is its first use, then return its+ /// SID. Capabilities are supplied per spawn instead of at creation, so the+ /// SID does not depend on whether network was allowed.+ fn ensure_profile(moniker: &str) -> Result<ContainerSid, String> {+ let name = wide(OsStr::new(moniker));+ let display = wide(OsStr::new("Jan agent tools"));+ let description = wide(OsStr::new("Sandbox for the Jan agent's shell tool"));+ let mut sid: PSID = std::ptr::null_mut();+ let hr = unsafe {+ CreateAppContainerProfile(+ name.as_ptr(),+ display.as_ptr(),+ description.as_ptr(),+ std::ptr::null_mut(),+ 0,+ &mut sid,+ )+ };+ if hr >= 0 && !sid.is_null() {+ return Ok(ContainerSid(sid));+ }+ if hr == PROFILE_EXISTS {+ return derive_sid(moniker);+ }+ Err(format!(+ "could not create the AppContainer profile (hr 0x{hr:08x})"+ ))+ }++ pub fn delete_profile(moniker: &str) {+ let name = wide(OsStr::new(moniker));+ unsafe { DeleteAppContainerProfile(name.as_ptr()) };+ }++ /// Grant the container full access to `path` and everything created under it.+ /// This is the entire write policy: without an ACE naming the container, a+ /// lowbox token can open nothing it was not given.+ fn grant_workspace(path: &Path, sid: PSID) -> Result<(), String> {+ let mut object = wide(path.as_os_str());+ let mut existing: *mut ACL = std::ptr::null_mut();+ let mut descriptor: PSECURITY_DESCRIPTOR = std::ptr::null_mut();+ let status = unsafe {+ GetNamedSecurityInfoW(+ object.as_ptr(),+ SE_FILE_OBJECT,+ DACL_SECURITY_INFORMATION,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ &mut existing,+ std::ptr::null_mut(),+ &mut descriptor,+ )+ };+ if status != ERROR_SUCCESS {+ return Err(format!(+ "could not read the workspace ACL ({}): {}",+ path.display(),+ std::io::Error::from_raw_os_error(status as i32)+ ));+ }++ let access = EXPLICIT_ACCESS_W {+ grfAccessPermissions: FILE_ALL_ACCESS,+ grfAccessMode: GRANT_ACCESS,+ grfInheritance: CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,+ Trustee: TRUSTEE_W {+ pMultipleTrustee: std::ptr::null_mut(),+ MultipleTrusteeOperation: 0,+ TrusteeForm: TRUSTEE_IS_SID,+ TrusteeType: TRUSTEE_IS_WELL_KNOWN_GROUP,+ ptstrName: sid as PWSTR,+ },+ };+ let mut merged: *mut ACL = std::ptr::null_mut();+ // GRANT_ACCESS merges into the existing DACL rather than replacing it, so+ // the user keeps their own access to the workspace.+ let status = unsafe { SetEntriesInAclW(1, &access, existing, &mut merged) };+ if status != ERROR_SUCCESS {+ unsafe { LocalFree(descriptor) };+ return Err(format!(+ "could not build the workspace ACL: {}",+ std::io::Error::from_raw_os_error(status as i32)+ ));+ }++ let status = unsafe {+ SetNamedSecurityInfoW(+ object.as_mut_ptr(),+ SE_FILE_OBJECT,+ DACL_SECURITY_INFORMATION,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ merged,+ std::ptr::null_mut(),+ )+ };+ unsafe {+ LocalFree(merged as *mut c_void);+ LocalFree(descriptor);+ }+ if status != ERROR_SUCCESS {+ return Err(format!(+ "could not apply the workspace ACL ({}): {}",+ path.display(),+ std::io::Error::from_raw_os_error(status as i32)+ ));+ }+ Ok(())+ }++ /// The `internetClient` capability, which is what makes outbound network calls+ /// possible at all for a lowbox token.+ fn internet_capability(buffer: &mut Vec<u8>) -> Result<SID_AND_ATTRIBUTES, String> {+ buffer.resize(SECURITY_MAX_SID_SIZE as usize, 0);+ let mut len = buffer.len() as u32;+ let ok = unsafe {+ CreateWellKnownSid(+ WinCapabilityInternetClientSid,+ std::ptr::null_mut(),+ buffer.as_mut_ptr() as PSID,+ &mut len,+ )+ };+ if ok == 0 {+ return Err(format!(+ "could not build the internetClient capability: {}",+ last_error()+ ));+ }+ Ok(SID_AND_ATTRIBUTES {+ Sid: buffer.as_mut_ptr() as PSID,+ Attributes: 0,+ })+ }++ /// Mark the std handles inheritable so the confined shell receives the+ /// parent's pipes. They arrive already usable: an inherited handle keeps the+ /// access it was opened with, so the lowbox token needs no rights on them.+ fn inheritable_std_handles() -> (HANDLE, HANDLE, HANDLE) {+ let mut handles = [INVALID_HANDLE_VALUE; 3];+ for (slot, id) in+ handles+ .iter_mut()+ .zip([STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE])+ {+ let handle = unsafe { GetStdHandle(id) };+ if !handle.is_null() && handle != INVALID_HANDLE_VALUE {+ unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) };+ *slot = handle;+ }+ }+ (handles[0], handles[1], handles[2])+ }++ /// Put this process in a kill-on-close job, so the shell -- created inside the+ /// job by inheritance -- dies whenever the helper does. `kill_on_drop` and+ /// `taskkill /T` reach the helper, not the extra process layer it adds, so+ /// without this a cancelled or timed-out command could leave a shell running.+ ///+ /// Best effort: a host that already confines us to a job it forbids nesting+ /// under should lose the reaping guarantee, not the tool.+ fn reap_children_with_this_process() {+ let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };+ if job.is_null() {+ return;+ }+ let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;+ let sized = unsafe {+ SetInformationJobObject(+ job,+ JobObjectExtendedLimitInformation,+ &limits as *const _ as *const c_void,+ std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,+ )+ };+ if sized == 0 {+ unsafe { CloseHandle(job) };+ return;+ }+ // The handle is deliberately leaked: the job must outlive this function+ // and close only when the process exits, which is what triggers the kill.+ unsafe { AssignProcessToJobObject(job, GetCurrentProcess()) };+ }++ /// Set up the container, then spawn the shell inside it and wait. Returns the+ /// shell's exit code so the helper is transparent to the caller.+ pub fn run(req: &Request) -> Result<i32, String> {+ if !req.workspace.is_dir() {+ return Err(format!(+ "workspace does not exist: {}",+ req.workspace.display()+ ));+ }+ reap_children_with_this_process();+ let sid = ensure_profile(&moniker(&req.workspace))?;+ grant_workspace(&req.workspace, sid.0)?;++ let mut capability_sid = Vec::new();+ let mut capabilities = Vec::new();+ if req.allow_network {+ capabilities.push(internet_capability(&mut capability_sid)?);+ }+ let mut security = SECURITY_CAPABILITIES {+ AppContainerSid: sid.0,+ Capabilities: if capabilities.is_empty() {+ std::ptr::null_mut()+ } else {+ capabilities.as_mut_ptr()+ },+ CapabilityCount: capabilities.len() as u32,+ Reserved: 0,+ };++ // Two calls: the first only reports the size, the second initializes the+ // buffer we just allocated for it.+ let mut size: usize = 0;+ unsafe {+ InitializeProcThreadAttributeList(std::ptr::null_mut(), 1, 0, &mut size);+ }+ let mut attribute_buffer = vec![0u8; size];+ let attributes = attribute_buffer.as_mut_ptr() as LPPROC_THREAD_ATTRIBUTE_LIST;+ if unsafe { InitializeProcThreadAttributeList(attributes, 1, 0, &mut size) } == 0 {+ return Err(format!(+ "could not initialize the spawn attributes: {}",+ last_error()+ ));+ }+ let applied = unsafe {+ UpdateProcThreadAttribute(+ attributes,+ 0,+ PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES as usize,+ &mut security as *mut _ as *const c_void,+ std::mem::size_of::<SECURITY_CAPABILITIES>(),+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ )+ };+ if applied == 0 {+ let message = last_error();+ unsafe { DeleteProcThreadAttributeList(attributes) };+ return Err(format!(+ "could not attach the AppContainer token: {message}"+ ));+ }++ let (stdin, stdout, stderr) = inheritable_std_handles();+ let mut startup: STARTUPINFOEXW = unsafe { std::mem::zeroed() };+ startup.StartupInfo.cb = std::mem::size_of::<STARTUPINFOEXW>() as u32;+ startup.StartupInfo.dwFlags = STARTF_USESTDHANDLES;+ startup.StartupInfo.hStdInput = stdin;+ startup.StartupInfo.hStdOutput = stdout;+ startup.StartupInfo.hStdError = stderr;+ startup.lpAttributeList = attributes;++ let mut line = wide(OsStr::new(&command_line(&req.program, &req.args)));+ let cwd = wide(req.workspace.as_os_str());+ let mut process: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };+ let spawned = unsafe {+ CreateProcessW(+ std::ptr::null(),+ line.as_mut_ptr(),+ std::ptr::null(),+ std::ptr::null(),+ 1,+ EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT,+ std::ptr::null(),+ cwd.as_ptr(),+ &startup.StartupInfo,+ &mut process,+ )+ };+ unsafe { DeleteProcThreadAttributeList(attributes) };+ if spawned == 0 {+ // Easily the most likely failure: the shell lives somewhere the+ // container cannot read, such as a per-user Git install under+ // AppData, which grants nothing to application packages.+ return Err(format!(+ "could not start {} inside the sandbox: {}. A shell installed \+ under your user profile is unreadable to the sandbox; install \+ Git for Windows system-wide instead.",+ req.program.display(),+ last_error()+ ));+ }++ let code = wait_for(process.hProcess);+ unsafe {+ CloseHandle(process.hThread);+ CloseHandle(process.hProcess);+ }+ code+ }++ fn wait_for(process: HANDLE) -> Result<i32, String> {+ if unsafe { WaitForSingleObject(process, INFINITE) } == WAIT_FAILED {+ return Err(format!(+ "could not wait for the sandboxed shell: {}",+ last_error()+ ));+ }+ let mut code: u32 = 0;+ if unsafe { GetExitCodeProcess(process, &mut code) } == 0 {+ return Err(format!(+ "could not read the shell's exit code: {}",+ last_error()+ ));+ }+ Ok(code as i32)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ws() -> PathBuf {+ PathBuf::from(r"C:\Users\me\.jan\agent-workspace\threads\t1")+ }++ #[test]+ fn the_moniker_fits_what_windows_accepts() {+ let name = moniker(&ws());+ assert!(name.len() <= 64, "{name}");+ assert!(name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_'));+ }++ #[test]+ fn the_same_workspace_always_maps_to_the_same_container() {+ // The next command in a thread must reach the container the last one+ // used, or its workspace grant would not apply.+ assert_eq!(moniker(&ws()), moniker(&ws()));+ assert_eq!(+ moniker(&ws()),+ moniker(Path::new(r"C:\USERS\ME\.JAN\AGENT-WORKSPACE\THREADS\T1"))+ );+ }++ #[test]+ fn different_workspaces_map_to_different_containers() {+ // This is the whole of the cross-thread isolation: the workspace ACE+ // names one container SID, so a command for another thread holds a+ // token that ACE does not match.+ let mine = moniker(&ws());+ let theirs = moniker(Path::new(r"C:\Users\me\.jan\agent-workspace\threads\t2"));+ assert_ne!(mine, theirs);+ }++ #[test]+ fn helper_args_end_with_the_shell_so_the_command_appends_last() {+ let args = helper_args(&ws(), false, Path::new("bash.exe"), &["-c".to_string()]);+ let sep = args.iter().position(|a| a == "--").expect("separator");+ assert_eq!(+ &args[sep + 1..],+ &["bash.exe".to_string(), "-c".to_string()]+ );+ assert_eq!(args[0], SANDBOX_EXEC_FLAG);+ }++ #[test]+ fn helper_args_carry_the_network_decision() {+ let denied = helper_args(&ws(), false, Path::new("bash.exe"), &[]);+ assert!(denied.contains(&NET_OFF.to_string()));+ assert!(!denied.contains(&NET_ON.to_string()));+ let allowed = helper_args(&ws(), true, Path::new("bash.exe"), &[]);+ assert!(allowed.contains(&NET_ON.to_string()));+ }++ #[test]+ fn the_helper_round_trips_its_own_argv() {+ let args = helper_args(+ &ws(),+ true,+ Path::new(r"C:\Program Files\Git\bin\bash.exe"),+ &["-c".to_string(), "echo hi".to_string()],+ );+ let req = parse_request(args).expect("parsed");+ assert_eq!(req.workspace, ws());+ assert!(req.allow_network);+ assert_eq!(req.program, Path::new(r"C:\Program Files\Git\bin\bash.exe"));+ assert_eq!(req.args, vec!["-c".to_string(), "echo hi".to_string()]);+ }++ #[test]+ fn a_normal_launch_is_not_mistaken_for_the_helper() {+ assert!(parse_request(Vec::<String>::new()).is_none());+ assert!(parse_request(vec!["--version".to_string()]).is_none());+ // Truncated or malformed requests must not run something unconfined.+ assert!(parse_request(vec![SANDBOX_EXEC_FLAG.to_string()]).is_none());+ assert!(parse_request(vec![+ SANDBOX_EXEC_FLAG.to_string(),+ "--maybe".to_string(),+ r"C:\ws".to_string(),+ "--".to_string(),+ "bash.exe".to_string(),+ ])+ .is_none());+ }++ #[test]+ fn quoting_leaves_plain_arguments_alone() {+ assert_eq!(quote_arg("-c"), "-c");+ assert_eq!(quote_arg("bash.exe"), "bash.exe");+ assert_eq!(quote_arg(""), "\"\"");+ }++ #[test]+ fn quoting_survives_spaces_quotes_and_trailing_backslashes() {+ assert_eq!(quote_arg("echo hi"), "\"echo hi\"");+ assert_eq!(quote_arg(r#"say "hi""#), r#""say \"hi\"""#);+ // A trailing backslash must be doubled, or it would escape the closing+ // quote and swallow the next argument.+ assert_eq!(quote_arg(r"C:\dir with space\"), r#""C:\dir with space\\""#);+ assert_eq!(+ quote_arg(r"C:\Program Files\Git"),+ r#""C:\Program Files\Git""#+ );+ }++ #[test]+ fn the_command_line_keeps_the_command_a_single_argument() {+ let line = command_line(+ Path::new(r"C:\Program Files\Git\bin\bash.exe"),+ &["-c".to_string(), "ls -la && echo \"done\"".to_string()],+ );+ assert_eq!(+ line,+ r#""C:\Program Files\Git\bin\bash.exe" -c "ls -la && echo \"done\"""#+ );+ }+}diff --git a/src-tauri/src/core/agent/tools/cmdscan.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rssimilarity index 100%rename from src-tauri/src/core/agent/tools/cmdscan.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/cmdscan.rsdiff --git a/src-tauri/src/core/agent/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rssimilarity index 84%rename from src-tauri/src/core/agent/tools/gate.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 04454120d..8da688be4 100644--- a/src-tauri/src/core/agent/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -2,18 +2,23 @@ use std::path::Path;use serde::{Deserialize, Serialize};-use crate::core::agent::permissions::ToolPermissions;-use crate::core::agent::tools::cmdscan::{normalize, scan_command, CommandScan};-use crate::core::agent::tools::sandbox::{+use crate::permissions::ToolPermissions;+use crate::tools::cmdscan::{normalize, scan_command, CommandScan};+use crate::tools::sandbox::{command_touches_restricted_agent_path, escapes_project, is_restricted_agent_path,};-use crate::core::agent::tools::{BuiltinTool, Capability};+use crate::tools::{BuiltinTool, Capability};#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "snake_case")]pub enum PromptKind {ReadEscape,Write,+ /// A write that resolves outside the project root (absolute or `..`). Treated+ /// strictly like a read escape: it can reach host files no sandbox confines,+ /// so it is never auto-approved and is refused where no prompt round-trip+ /// exists.+ WriteEscape,Exec,}@@ -37,6 +42,7 @@ pub enum PermissionDecision {pub struct SessionGrants {read_escape: bool,write: bool,+ write_escape: bool,exec_commands: std::collections::BTreeSet<String>,exec_opaque: std::collections::BTreeSet<String>,/// MCP tools granted "allow always" this thread, by tool name.@@ -48,6 +54,7 @@ impl SessionGrants {match kind {PromptKind::ReadEscape => self.read_escape,PromptKind::Write => self.write,+ PromptKind::WriteEscape => self.write_escape,// Exec coverage is command-specific; use `covers_command`.PromptKind::Exec => false,}@@ -69,6 +76,7 @@ impl SessionGrants {match kind {PromptKind::ReadEscape => self.read_escape = true,PromptKind::Write => self.write = true,+ PromptKind::WriteEscape => self.write_escape = true,// No-op: exec is granted per command via `grant_command`.PromptKind::Exec => {}}@@ -144,7 +152,7 @@ pub fn resolve_decision(}// Dedicated skill/memory tools act only on the agent's own workspace by a// sanitized name, so they never prompt (deny above still wins).- if crate::core::agent::tools::is_workspace_tool(tool.name) {+ if crate::tools::is_workspace_tool(tool.name) {return Decision::Allow;}match tool.capability {@@ -166,7 +174,27 @@ pub fn resolve_decision(// adapter. Treat them like read-only reads inside the project: allowed// without a prompt (an explicit agent.toml deny above still wins).Capability::Net => Decision::Allow,- Capability::Write => gated(PromptKind::Write, grants),+ // A write inside the project may prompt (the CLI approves it); one that+ // escapes the project -- absolute or `..` -- can reach host files no+ // sandbox confines, so mirror the Read branch and gate it separately. It+ // is refused outright on the desktop, where no prompt round-trip exists.+ Capability::Write => {+ 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 {+ if grants.covers(PromptKind::WriteEscape) {+ Decision::Allow+ } else {+ Decision::Prompt(PromptKind::WriteEscape)+ }+ } else {+ gated(PromptKind::Write, grants)+ }+ }Capability::Exec => {// Polling a previously backgrounded command (job_id, no new// command) never prompts: the exec permission was already@@ -195,8 +223,8 @@ fn gated(kind: PromptKind, grants: &SessionGrants) -> Decision {#[cfg(test)]mod tests {use super::*;- use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};- use crate::core::agent::tools::lookup;+ use crate::permissions::{PermissionDefault, ToolPermissions};+ use crate::tools::lookup;use serde_json::json;use std::path::PathBuf;use std::sync::atomic::{AtomicUsize, Ordering};@@ -602,4 +630,71 @@ mod tests {assert_eq!(d, Decision::Allow);let _ = std::fs::remove_dir_all(&root);}++ #[test]+ fn write_inside_project_prompts_write_not_escape() {+ let root = unique_root();+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);+ let grants = SessionGrants::default();+ let d = resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": "sub/new.txt"}),+ &root,+ &perms,+ &grants,+ );+ assert_eq!(d, Decision::Prompt(PromptKind::Write));+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn write_escaping_project_prompts_write_escape() {+ let root = unique_root();+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);+ let grants = SessionGrants::default();+ for path in ["../outside.txt", root.join("/tmp").to_str().unwrap()] {+ let d = resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": path}),+ &root,+ &perms,+ &grants,+ );+ assert_eq!(d, Decision::Prompt(PromptKind::WriteEscape), "{}", path);+ }+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn session_grant_allows_write_escape() {+ let root = unique_root();+ let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);+ let mut grants = SessionGrants::default();+ grants.grant(PromptKind::WriteEscape);+ let d = resolve_decision(+ lookup("write").unwrap(),+ &json!({"path": "../x"}),+ &root,+ &perms,+ &grants,+ );+ assert_eq!(d, Decision::Allow);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn read_still_prompts_read_escape_not_write() {+ 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);+ }}diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rssimilarity index 86%rename from src-tauri/src/core/agent/tools/handlers.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 3c497c5be..17e6ac419 100644--- a/src-tauri/src/core/agent/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -11,11 +11,12 @@ use std::sync::{Mutex, OnceLock};use ignore::WalkBuilder;use tokio::sync::oneshot;-use crate::core::agent::project::load_agent_config;-use crate::core::agent::skills;-use crate::core::agent::tools::proc;-use crate::core::agent::tools::sandbox::is_restricted_agent_path;-use crate::core::agent::tools::BuiltinTool;+use crate::memory;+use crate::skills;+use crate::tools::jail;+use crate::tools::proc;+use crate::tools::sandbox::{escapes_project, is_restricted_agent_path};+use crate::tools::{BuiltinTool, ToolContext};const MAX_BYTES: usize = 64 * 1024;const MAX_LINES: usize = 2000;@@ -144,27 +145,30 @@ fn collapse_carriage_returns(s: &str) -> String {pub async fn execute_builtin(tool: &BuiltinTool,args: &serde_json::Value,- project_root: &Path,+ ctx: &ToolContext<'_>,) -> String {+ let project_root = ctx.project_root;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,+ "write" => write(args, project_root, ctx.confine_writes).await,+ "edit" => edit(args, project_root, ctx.confine_writes).await,+ "bash" => bash(args, ctx).await,"find" => find(args, project_root).await,"grep" => grep(args, project_root).await,- "memory_list" => workspace_list(project_root, "memory").await,- "memory_read" => workspace_read(args, project_root, "memory").await,- "memory_write" => workspace_write(args, project_root, "memory").await,+ // Memory and skills live in the store root, not the sandbox: they must+ // outlive the conversation the filesystem tools are scoped to.+ "memory_list" => memory_list(ctx.store_root).await,+ "memory_read" => memory_read(args, ctx.store_root).await,+ "memory_write" => memory_write(args, ctx.store_root).await,// Skills go through the skills module so the tool honors the folder form// (`<name>/SKILL.md`) and frontmatter, matching what the UI writes.- "skill_list" => skill_list(project_root),- "skill_read" => skill_read(args, project_root),- "skill_write" => skill_write(args, project_root),+ "skill_list" => skill_list(ctx),+ "skill_read" => skill_read(args, ctx),+ "skill_write" => skill_write(args, ctx),// Native web tools: compiled into the agent core, not an MCP server.- "web_search" => crate::core::agent::tools::web::web_search(args).await,- "web_fetch" => crate::core::agent::tools::web::web_fetch(args).await,+ "web_search" => crate::tools::web::web_search(args).await,+ "web_fetch" => crate::tools::web::web_fetch(args).await,other => format!("ERROR: unknown built-in tool '{other}'"),}}@@ -174,13 +178,13 @@ pub async fn execute_builtin(/// its position in the file; `None` for other tools or when nothing would/// change. Used to show the change in the permission prompt. Both variants read/// the prior file: `write` to show its `created`/`overwrote` header, `edit` to-/// locate `old_string`, number the hunk against real file lines, and surround it-/// with context lines the arguments alone do not carry.-pub(crate) async fn preview_diff(+/// locate `old_string` and number the hunk against real file lines.+pub async fn preview_diff(tool: &BuiltinTool,args: &serde_json::Value,- project_root: &Path,+ ctx: &ToolContext<'_>,) -> Option<String> {+ let project_root = ctx.project_root;match tool.name {"edit" => {let edits = args.get("edits").and_then(|v| v.as_array())?;@@ -188,7 +192,9 @@ pub(crate) async fn preview_diff(return None;}let prior = match arg_str(args, "path") {- Some(p) => tokio::fs::read_to_string(resolve(project_root, p)).await.unwrap_or_default(),+ Some(p) => tokio::fs::read_to_string(resolve(project_root, p))+ .await+ .unwrap_or_default(),None => String::new(),};let d = render_edit_diff(edits, &prior);@@ -196,7 +202,9 @@ pub(crate) async fn preview_diff(}"write" => {let prior = match arg_str(args, "path") {- Some(p) => tokio::fs::read_to_string(resolve(project_root, p)).await.ok(),+ Some(p) => tokio::fs::read_to_string(resolve(project_root, p))+ .await+ .ok(),None => None,};let new = arg_str(args, "content").unwrap_or("");@@ -218,21 +226,21 @@ pub(crate) async fn preview_diff(/// mutating call. Diffs are computed against the pre-execution file so line/// numbers match the file as the model saw it. `None` for non-mutating tools/// and on error.-pub(crate) async fn execute_builtin_with_diff(+pub async fn execute_builtin_with_diff(tool: &BuiltinTool,args: &serde_json::Value,- project_root: &Path,+ ctx: &ToolContext<'_>,) -> (String, Option<String>) {match tool.name {"write" | "edit" => {- let diff = preview_diff(tool, args, project_root).await;- let content = execute_builtin(tool, args, project_root).await;+ let diff = preview_diff(tool, args, ctx).await;+ let content = execute_builtin(tool, args, ctx).await;if content.starts_with("ERROR") {return (content, None);}(content, diff)}- _ => (execute_builtin(tool, args, project_root).await, None),+ _ => (execute_builtin(tool, args, ctx).await, None),}}@@ -378,42 +386,10 @@ fn render_write_diff(prior: Option<&str>, content: &str) -> String {out.trim_end().to_string()}-/// `.jan/agent/<kind>` directory for the agent's own workspace.-pub(crate) fn workspace_dir(root: &Path, kind: &str) -> PathBuf {- root.join(".jan").join("agent").join(kind)-}--/// Sanitize a caller-supplied entry name into a safe `<stem>.md` filename.-/// Rejects path separators and `..` so the result can never escape the-/// workspace. `.md` is appended if absent.-pub(crate) fn workspace_filename(name: &str) -> Result<String, String> {- let trimmed = name.trim();- if trimmed.is_empty()- || trimmed.contains('/')- || trimmed.contains('\\')- || trimmed.split('.').any(|seg| seg == ".")- || trimmed.contains("..")- {- return Err(format!("ERROR: invalid name '{name}'"));- }- let stem = trimmed.strip_suffix(".md").unwrap_or(trimmed);- Ok(format!("{stem}.md"))-}--/// The project's enabled-skill whitelist (`[skills].enabled`; empty = all).-/// A missing/malformed config falls back to "all enabled".-fn enabled_skills(root: &Path) -> Vec<String> {- load_agent_config(root)- .ok()- .map(|c| c.skills.enabled)- .unwrap_or_default()-}-/// `skill_list` tool: catalog of `name — description` lines for ENABLED skills/// only (disabled skills must stay invisible to the model). Empty if none.-fn skill_list(root: &Path) -> String {- let enabled = enabled_skills(root);- skills::catalog(root, &enabled)+fn skill_list(ctx: &ToolContext<'_>) -> String {+ skills::catalog(ctx.store_root, ctx.enabled_skills).iter().map(|m| {if m.description.is_empty() {@@ -428,86 +404,65 @@ fn skill_list(root: &Path) -> String {/// `skill_read` tool: a skill's full instructions (frontmatter stripped). A/// disabled skill is treated as absent so it never reaches the model.-fn skill_read(args: &serde_json::Value, root: &Path) -> String {+fn skill_read(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {let Some(name) = arg_str(args, "name") else {return "ERROR: missing required argument 'name'".to_string();};- if !skills::is_enabled(&enabled_skills(root), name) {+ if !skills::is_enabled(ctx.enabled_skills, name) {return format!("ERROR: skill '{name}' not found");}- match skills::read_body(root, name) {+ match skills::read_body(ctx.store_root, name) {Ok(body) => body,Err(e) => e,}}/// `skill_write` tool: create/update a skill (new ones as `<name>/SKILL.md`).-fn skill_write(args: &serde_json::Value, root: &Path) -> String {+/// The `[skills].enabled` whitelist is honored for writes too: a disabled skill+/// is treated as read-only so the model cannot silently overwrite (or resurrect)+/// a skill the user has turned off or locked out of the catalog.+fn skill_write(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {let Some(name) = arg_str(args, "name") else {return "ERROR: missing required argument 'name'".to_string();};let Some(content) = arg_str(args, "content") else {return "ERROR: missing required argument 'content'".to_string();};- match skills::write(root, name, content) {+ if !skills::is_enabled(ctx.enabled_skills, name) {+ return format!("ERROR: skill '{name}' is disabled and read-only");+ }+ match skills::write(ctx.store_root, name, content) {Ok(()) => format!("Wrote skill '{name}'"),Err(e) => e,}}-async fn workspace_list(root: &Path, kind: &str) -> String {- let dir = workspace_dir(root, kind);- let mut entries = match tokio::fs::read_dir(&dir).await {- Ok(rd) => rd,- Err(_) => return String::new(),- };- let mut names: Vec<String> = Vec::new();- while let Ok(Some(e)) = entries.next_entry().await {- let path = e.path();- if path.extension().and_then(|x| x.to_str()) == Some("md") {- if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {- names.push(stem.to_string());- }- }- }- names.sort();- names.join("\n")+/// The memory tools delegate to `crate::memory` so the built-ins and the+/// management commands share one implementation.+async fn memory_list(store: &Path) -> String {+ memory::list(store).await.join("\n")}-async fn workspace_read(args: &serde_json::Value, root: &Path, kind: &str) -> String {+async fn memory_read(args: &serde_json::Value, store: &Path) -> String {let Some(name) = arg_str(args, "name") else {return "ERROR: missing required argument 'name'".to_string();};- let file = match workspace_filename(name) {- Ok(f) => f,- Err(e) => return e,- };- let target = workspace_dir(root, kind).join(file);- match tokio::fs::read_to_string(&target).await {- Ok(c) => c,- Err(e) => format!("ERROR: {e}"),+ match memory::read(store, name).await {+ Ok(content) => content,+ Err(e) => e,}}-async fn workspace_write(args: &serde_json::Value, root: &Path, kind: &str) -> String {+async fn memory_write(args: &serde_json::Value, store: &Path) -> String {let Some(name) = arg_str(args, "name") else {return "ERROR: missing required argument 'name'".to_string();};let Some(content) = arg_str(args, "content") else {return "ERROR: missing required argument 'content'".to_string();};- let file = match workspace_filename(name) {- Ok(f) => f,- Err(e) => return e,- };- let dir = workspace_dir(root, kind);- if let Err(e) = tokio::fs::create_dir_all(&dir).await {- return format!("ERROR: {e}");- }- let target = dir.join(&file);- match tokio::fs::write(&target, content).await {- Ok(()) => format!("Wrote {} bytes to {kind}/{file}", content.len()),- Err(e) => format!("ERROR: {e}"),+ match memory::write(store, name, content).await {+ Ok(file) => format!("Wrote {} bytes to memory/{file}", content.len()),+ Err(e) => e,}}@@ -588,13 +543,19 @@ async fn ls(args: &serde_json::Value, root: &Path) -> String {cap_output(&joined, usize::MAX, MAX_BYTES, "\n[truncated: 64KB limit]")}-async fn write(args: &serde_json::Value, root: &Path) -> String {+async fn write(args: &serde_json::Value, root: &Path, confine: bool) -> 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();};+ // Defense in depth: when the caller confines writes, re-canonicalize on the+ // canonical root (not the raw argument) so `..` and absolute paths are+ // caught even if the gate's decision was made against a stale view.+ if confine && escapes_project(root, path).unwrap_or(true) {+ return format!("ERROR: refused to write outside the agent workspace: {path}");+ }let target = resolve(root, path);// Report the resolved location, not the raw argument: an absolute or `../`// path lands outside the project and the model must see where it went.@@ -620,7 +581,7 @@ async fn write(args: &serde_json::Value, root: &Path) -> String {}}-async fn edit(args: &serde_json::Value, root: &Path) -> String {+async fn edit(args: &serde_json::Value, root: &Path, confine: bool) -> String {let Some(path) = arg_str(args, "path") else {return "ERROR: missing required argument 'path'".to_string();};@@ -630,6 +591,9 @@ async fn edit(args: &serde_json::Value, root: &Path) -> String {if edits.is_empty() {return "ERROR: edits must contain at least one replacement".to_string();}+ if confine && escapes_project(root, path).unwrap_or(true) {+ return format!("ERROR: refused to edit outside the agent workspace: {path}");+ }let target = resolve(root, path);let shown = display_path(root, &target);let mut content = match tokio::fs::read_to_string(&target).await {@@ -663,7 +627,7 @@ async fn edit(args: &serde_json::Value, root: &Path) -> String {}}-async fn bash(args: &serde_json::Value, root: &Path) -> String {+async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if let Some(job_id) = arg_str(args, "job_id") {return await_bash_job(job_id).await;}@@ -673,6 +637,7 @@ async fn bash(args: &serde_json::Value, root: &Path) -> String {};let timeout_secs = arg_u64(args, "timeout").unwrap_or(DEFAULT_BASH_TIMEOUT_SECS);+ let root = ctx.project_root;if !root.is_dir() {return format!("ERROR: working directory does not exist: {}",@@ -680,7 +645,19 @@ async fn bash(args: &serde_json::Value, root: &Path) -> String {);}- let child = match proc::spawn(proc::shell(), command, root).await {+ // No confinement available means no shell: running unsandboxed would give the+ // command the whole machine, which is never what the caller asked for.+ let mut policy = jail::Policy::new(root, ctx.allow_network).with_home_readonly(ctx.home_readonly);+ if let Some(mask) = ctx.mask_root {+ policy = policy.with_mask_root(mask);+ }+ let Some(shell) = jail::wrap(proc::shell(), &policy) else {+ return "ERROR: bash is unavailable because no OS sandbox could be established on this \+ system. Use the read/ls/find/grep tools instead."+ .to_string();+ };++ let child = match proc::spawn(&shell, command, root).await {Ok(c) => c,Err(e) => return format!("ERROR: failed to run command: {e}"),};@@ -693,7 +670,13 @@ async fn bash(args: &serde_json::Value, root: &Path) -> String {// reap its whole process tree if it is still running.let (tx, mut rx) = oneshot::channel();tokio::spawn(async move {- let out = collect_and_format(child).await;+ let mut out = collect_and_format(child).await;+ // Appended inside the task so a backgrounded job carries the hint too.+ // `Permission denied` on its own tells the model nothing about *why*;+ // without this it retries the same command until it gives up.+ if bash_result_failed(&out) && jail::looks_denied(&out) {+ out.push_str(&jail::denial_hint(&policy));+ }if let Some(pid) = pid {proc::unregister(pid);}@@ -720,9 +703,9 @@ async fn bash(args: &serde_json::Value, root: &Path) -> String {async fn await_bash_job(job_id: &str) -> String {let rx = bash_jobs().lock().unwrap().remove(job_id);match rx {- Some(rx) => rx- .await- .unwrap_or_else(|_| "ERROR: background command ended without producing output".to_string()),+ Some(rx) => rx.await.unwrap_or_else(|_| {+ "ERROR: background command ended without producing output".to_string()+ }),None => format!("ERROR: unknown or already-collected job_id '{job_id}'"),}}@@ -872,7 +855,7 @@ impl BashCapture {/// deliberately left unprefixed (a non-zero exit is not an "ERROR" string, since/// commands like `grep`/`diff`/`test` exit non-zero without failing); this feeds/// the display-only `is_error` flag so the TUI marks the call failed.-pub(crate) fn bash_result_failed(content: &str) -> bool {+pub fn bash_result_failed(content: &str) -> bool {content.lines().any(|line| {let l = line.trim();if l == "[terminated by signal]" {@@ -1147,9 +1130,41 @@ fn truncate_line(line: &str) -> String {#[cfg(test)]mod tests {use super::*;- use crate::core::agent::tools::lookup;+ use crate::tools::lookup;use serde_json::json;+ // Root-taking shims over the `ToolContext` entry points. These shadow the+ // glob-imported originals so the tool tests, which almost never care about+ // the skill whitelist, stay readable. Tests that do care build a+ // `ToolContext` and call `super::*` directly.+ //+ // They co-locate the store inside the root (`<root>/.jan/agent`), the layout+ // a project uses, so the memory/skill tests keep asserting against paths+ // relative to their one temp dir. The desktop's split roots are covered in+ // `workspace` and `commands`.+ async fn execute_builtin(tool: &BuiltinTool, args: &serde_json::Value, root: &Path) -> String {+ let store = crate::workspace::project_store(root);+ super::execute_builtin(tool, args, &ToolContext::new(root, &store, &[])).await+ }++ async fn execute_builtin_with_diff(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ root: &Path,+ ) -> (String, Option<String>) {+ let store = crate::workspace::project_store(root);+ super::execute_builtin_with_diff(tool, args, &ToolContext::new(root, &store, &[])).await+ }++ async fn preview_diff(+ tool: &BuiltinTool,+ args: &serde_json::Value,+ root: &Path,+ ) -> Option<String> {+ let store = crate::workspace::project_store(root);+ super::preview_diff(tool, args, &ToolContext::new(root, &store, &[])).await+ }+static COUNTER: AtomicUsize = AtomicUsize::new(0);fn unique_root() -> PathBuf {@@ -1290,6 +1305,15 @@ mod tests {);}+ #[test]+ fn edit_diff_numbers_against_real_file_position() {+ let d = render_edit_diff(+ &[json!({"old_string": "two", "new_string": "TWO"})],+ "one\ntwo\nthree",+ );+ assert_eq!(d, " 1 | one\n- 2 | two\n+ 2 | TWO\n 3 | three");+ }+/// Two edits far apart in one call: each hunk carries its own file context/// and nothing in between, and the second is numbered against the state the/// first left behind (edit 1 adds a line, so `eight` is renumbered 8 -> 9).@@ -1351,18 +1375,6 @@ mod tests {);}- #[test]- fn edit_diff_numbers_against_real_file_position() {- let d = render_edit_diff(- &[json!({"old_string": "two", "new_string": "TWO"})],- "one\ntwo\nthree",- );- assert_eq!(- d,- " 1 | one\n- 2 | two\n+ 2 | TWO\n 3 | three"- );- }-/// The context around a change comes from the file, not just from whatever/// `old_string` happened to include, and stops at `DIFF_CONTEXT` lines.#[test]@@ -1486,9 +1498,11 @@ mod tests {assert!(!root.join("new.txt").exists(), "preview must not write");// non-mutating tools have no preview.- assert!(preview_diff(lookup("read").unwrap(), &json!({"path": "x"}), &root)- .await- .is_none());+ assert!(+ preview_diff(lookup("read").unwrap(), &json!({"path": "x"}), &root)+ .await+ .is_none()+ );let _ = std::fs::remove_dir_all(&root);}@@ -1524,10 +1538,7 @@ mod tests {.await;assert_eq!(content, "Created w.txt (5 bytes)");assert!(!content.contains('+'), "write content must stay concise");- assert_eq!(- diff.as_deref(),- Some("@@ created file @@\n+ 1 | hello")- );+ assert_eq!(diff.as_deref(), Some("@@ created file @@\n+ 1 | hello"));let _ = std::fs::remove_dir_all(&root);}@@ -1602,6 +1613,32 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// With write confinement enabled, a `..` write is refused at the handler,+ /// independent of the gate -- the defense-in-depth layer.+ #[tokio::test]+ async fn confined_write_refuses_escape_at_handler() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &[]).with_confined_writes(true);+ let out = super::execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": "../escape.txt", "content": "x"}),+ &ctx,+ )+ .await;+ assert!(out.starts_with("ERROR: refused to write outside"), "got: {out}");+ assert!(!root.parent().unwrap().join("escape.txt").exists());++ let out = super::execute_builtin(+ lookup("edit").unwrap(),+ &json!({"path": "../escape.txt", "edits": [{"old_string": "a", "new_string": "b"}]}),+ &ctx,+ )+ .await;+ assert!(out.starts_with("ERROR: refused to edit outside"), "got: {out}");+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn write_and_edit_errors_name_the_path() {let root = unique_root();@@ -1679,13 +1716,12 @@ mod tests {std::fs::write(root.join(".jan/agent/agent.toml"), b"[tools]\n").unwrap();std::fs::write(root.join(".jan/agent/AGENT.md"), b"instructions").unwrap();std::fs::write(root.join("README.md"), b"x").unwrap();- let out = execute_builtin(- lookup("find").unwrap(),- &json!({"pattern": "**/*"}),- &root,- )- .await;- assert!(out.contains("README.md"), "should include project file: {out}");+ let out =+ execute_builtin(lookup("find").unwrap(), &json!({"pattern": "**/*"}), &root).await;+ assert!(+ out.contains("README.md"),+ "should include project file: {out}"+ );assert!(out.contains(".jan/agent/AGENT.md"),"AGENT.md is readable, should be listed: {out}"@@ -1718,7 +1754,10 @@ mod tests {&root,).await;- assert!(out.contains("README.md"), "should match project file: {out}");+ assert!(+ out.contains("README.md"),+ "should match project file: {out}"+ );assert!(!out.contains("messages.jsonl"),"must not grep thread storage: {out}"@@ -1811,11 +1850,13 @@ mod tests {.unwrap().trim_end_matches(|c: char| !c.is_alphanumeric());- let collected = execute_builtin(lookup("bash").unwrap(), &json!({"job_id": job_id}), &root).await;+ let collected =+ execute_builtin(lookup("bash").unwrap(), &json!({"job_id": job_id}), &root).await;assert!(collected.contains("done"), "unexpected: {collected}");// The job is removed once collected.- let again = execute_builtin(lookup("bash").unwrap(), &json!({"job_id": job_id}), &root).await;+ let again =+ execute_builtin(lookup("bash").unwrap(), &json!({"job_id": job_id}), &root).await;assert!(again.starts_with("ERROR: unknown or already-collected"),"unexpected: {again}"@@ -1895,7 +1936,10 @@ mod tests {&root,).await;- assert!(out.contains("\n[exit 0]"), "marker not on its own line: {out}");+ assert!(+ out.contains("\n[exit 0]"),+ "marker not on its own line: {out}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -1910,7 +1954,11 @@ mod tests {).await;assert!(!out.starts_with("ERROR"), "unexpected: {out}");- assert!(!out.contains("[truncated"), "should not truncate: len={}", out.len());+ assert!(+ !out.contains("[truncated"),+ "should not truncate: len={}",+ out.len()+ );assert!(out.len() > 64 * 1024, "expected >64KB, got {}", out.len());let _ = std::fs::remove_dir_all(&root);}@@ -1927,8 +1975,14 @@ mod tests {&root,).await;- assert!(!out.contains("output truncated"), "spurious truncation: {out}");- assert!(out.contains("Receiving objects: 30000"), "final redraw lost: {out}");+ assert!(+ !out.contains("output truncated"),+ "spurious truncation: {out}"+ );+ assert!(+ out.contains("Receiving objects: 30000"),+ "final redraw lost: {out}"+ );assert!(out.contains("[exit 0]"), "unexpected: {out}");let _ = std::fs::remove_dir_all(&root);}@@ -1944,8 +1998,14 @@ mod tests {&root,).await;- assert!(out.contains("output truncated at"), "unexpected: end of {out}");- assert!(out.contains("Use the read tool"), "should guide the agent: {out}");+ assert!(+ out.contains("output truncated at"),+ "unexpected: end of {out}"+ );+ assert!(+ out.contains("Use the read tool"),+ "should guide the agent: {out}"+ );let path = out.rsplit("full output written to ").next()@@ -1957,7 +2017,10 @@ mod tests {&root,).await;- assert!(full.contains("015999") || full.contains("016000"), "tail readable: {full}");+ assert!(+ full.contains("015999") || full.contains("016000"),+ "tail readable: {full}"+ );let _ = std::fs::remove_dir_all(&root);}@@ -1973,8 +2036,14 @@ mod tests {&root,).await;- assert!(out.contains("output truncated at"), "should truncate: end of {out}");- assert!(out.contains("\nL12000\n"), "last line must survive: end of {out}");+ assert!(+ out.contains("output truncated at"),+ "should truncate: end of {out}"+ );+ assert!(+ out.contains("\nL12000\n"),+ "last line must survive: end of {out}"+ );assert!(!out.contains("\nL5\n"), "earliest lines must be dropped");assert!(out.contains("[exit 0]"), "exit marker must survive: {out}");let _ = std::fs::remove_dir_all(&root);@@ -1990,7 +2059,10 @@ mod tests {&root,).await;- assert!(out.contains("red"), "text must survive sanitization: {out:?}");+ assert!(+ out.contains("red"),+ "text must survive sanitization: {out:?}"+ );assert!(!out.contains('\u{0}'), "NUL must be stripped");assert!(!out.contains('\u{7}'), "bell must be stripped");assert!(!out.contains('\u{1b}'), "escape must be stripped");@@ -2005,11 +2077,7 @@ mod tests {// password prompt). The failure/output comes back as a normal result.let out = tokio::time::timeout(std::time::Duration::from_secs(10),- execute_builtin(- lookup("bash").unwrap(),- &json!({"command": "cat"}),- &root,- ),+ execute_builtin(lookup("bash").unwrap(), &json!({"command": "cat"}), &root),).await.expect("must not hang on stdin read");@@ -2104,35 +2172,47 @@ mod tests {&root,).await;- // Whitelist only "on".- crate::core::agent::project::ensure_project(&root).unwrap();- crate::core::agent::project::set_skills_enabled_in_agent_toml(- &crate::core::agent::project::agent_toml_path(&root),- &["on".to_string()],- )- .unwrap();+ // Whitelist only "on". The whitelist is injected, so this no longer+ // needs an agent.toml round-trip to set up.+ let enabled = ["on".to_string()];+ let store = crate::workspace::project_store(&root);+ let ctx = ToolContext::new(&root, &store, &enabled);- let list = execute_builtin(lookup("skill_list").unwrap(), &json!({}), &root).await;+ let list = super::execute_builtin(lookup("skill_list").unwrap(), &json!({}), &ctx).await;assert!(list.contains("on"), "list: {list}");assert!(!list.contains("off body"), "disabled skill leaked: {list}");// Disabled skill is unreadable.- let read_off = execute_builtin(- lookup("skill_read").unwrap(),- &json!({"name": "off"}),- &root,- )- .await;+ let read_off =+ super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "off"}), &ctx)+ .await;assert!(read_off.starts_with("ERROR"), "disabled read: {read_off}");// Enabled skill still readable.- let read_on = execute_builtin(+ let read_on =+ super::execute_builtin(lookup("skill_read").unwrap(), &json!({"name": "on"}), &ctx)+ .await;+ assert_eq!(read_on, "on body");++ // A disabled skill is read-only for the model: writing to it is refused+ // and the on-disk content is untouched.+ let write_off = super::execute_builtin(+ lookup("skill_write").unwrap(),+ &json!({"name": "off", "content": "evil body"}),+ &ctx,+ )+ .await;+ assert!(+ write_off.starts_with("ERROR"),+ "disabled write: {write_off}"+ );+ let r = super::execute_builtin(lookup("skill_read").unwrap(),- &json!({"name": "on"}),- &root,+ &json!({"name": "off"}),+ &ctx,).await;- assert_eq!(read_on, "on body");+ assert!(r.starts_with("ERROR"), "still disabled after write");let _ = std::fs::remove_dir_all(&root);}@@ -2146,7 +2226,10 @@ mod tests {&root,).await;- assert!(out.starts_with("ERROR"), "name {bad:?} should be rejected: {out}");+ assert!(+ out.starts_with("ERROR"),+ "name {bad:?} should be rejected: {out}"+ );}let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsnew file mode 100644index 000000000..75571e447--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -0,0 +1,921 @@+//! OS-level confinement for the `bash` tool.+//!+//! The static command scan in [`super::cmdscan`] bounds *which* commands run; this+//! module bounds what they can reach once running. Three properties, identical on+//! every backend:+//!+//! - reads: everything except `$HOME`, with the thread workspace carved back in+//! (it lives under `$HOME`, so the carve-out is what keeps the sandbox usable+//! while `settings.json`, provider keys, and the rest of the Jan data folder+//! stay unreadable). The CLI can opt into `home_readonly`, which instead+//! mounts `$HOME` read-only so `git`/`ssh` credential helpers work. Reads+//! outside `$HOME` stay open because a process cannot start without its+//! interpreter, loader, and libraries.+//! - writes: the thread workspace and a private temp dir, nothing else.+//! - network: denied unless explicitly allowed.+//!+//! AppContainer is stricter than that on reads: it can only read what grants+//! `ALL APPLICATION PACKAGES`, which covers the system directories a process+//! needs to start but not, say, a second data drive. Stricter is safe here -- the+//! properties above are the floor, not the ceiling.+//!+//! Backends follow the approach in openai/codex `codex-rs/sandboxing`: Seatbelt+//! (`sandbox-exec`) on macOS, bubblewrap on Linux, AppContainer on Windows. The+//! Unix backends wrap the shell argv, so unlike codex they need no helper binary.+//! Windows has no argv to wrap -- see [`super::appcontainer`], which re-execs this+//! binary because the confinement is a `CreateProcessW` token attribute.++use std::path::{Path, PathBuf};+use std::sync::OnceLock;++use super::appcontainer;+use super::proc::ShellConfig;++/// `sandbox-exec` is only trusted at its absolute system path: resolving it via+/// `PATH` would let anything that can prepend to `PATH` defeat the sandbox.+#[cfg(target_os = "macos")]+const SEATBELT: &str = "/usr/bin/sandbox-exec";++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Backend {+ Seatbelt,+ Bubblewrap,+ AppContainer,+ /// No enforcement available. `bash` is withheld rather than run unconfined.+ None,+}++impl Backend {+ pub fn enforces(self) -> bool {+ self != Backend::None+ }++ pub fn as_str(self) -> &'static str {+ match self {+ Backend::Seatbelt => "seatbelt",+ Backend::Bubblewrap => "bubblewrap",+ Backend::AppContainer => "appcontainer",+ Backend::None => "none",+ }+ }+}++#[derive(Debug, Clone)]+pub struct Policy {+ /// The thread workspace: the only path that stays both readable and writable.+ pub workspace: PathBuf,+ /// The agent's data-folder root. On the desktop this is the Jan data folder+ /// (holding the permanent store, `settings.json`, and model files); it is+ /// masked from the sandbox like `$HOME`, because a relocated `JAN_DATA_FOLDER`+ /// outside `$HOME` would otherwise leave all of it readable by the shell. The+ /// CLI leaves this unset: there the project itself is the workspace, so+ /// masking it would hide the very files the agent works on.+ pub mask_root: Option<PathBuf>,+ pub allow_network: bool,+ /// Expose `$HOME` to the sandboxed shell read-only instead of hiding it.+ /// The CLI turns this on so helpers that read the user's home (`git`/`ssh`+ /// credential helpers, `~/.ssh/config`, `~/.netrc`) work, while writes stay+ /// confined to the workspace at the mount/policy layer. Off by default: the+ /// desktop keeps the full isolation so `settings.json` and provider keys+ /// stay out of the shell's reach.+ pub home_readonly: bool,+}++impl Policy {+ pub fn new(workspace: &Path, allow_network: bool) -> Self {+ Self {+ workspace: workspace.to_path_buf(),+ mask_root: None,+ allow_network,+ home_readonly: false,+ }+ }++ /// Mask `mask_root` from the sandboxed shell. The desktop data folder holds+ /// the permanent memory/skills store and `settings.json` with provider keys;+ /// masking it keeps a relocated data folder out of the shell's reach. The+ /// thread workspace (nested under it) is re-bound on top so it survives.+ pub fn with_mask_root(mut self, mask_root: &Path) -> Self {+ self.mask_root = Some(mask_root.to_path_buf());+ self+ }++ /// Expose `$HOME` read-only instead of masking it. See [`Policy::home_readonly`].+ pub fn with_home_readonly(mut self, home_readonly: bool) -> Self {+ self.home_readonly = home_readonly;+ self+ }+}++/// The user's home directory, or `None` when it is unset or degenerate. A `/`+/// home would hide the whole filesystem, so it is treated as absent.+fn home_dir() -> Option<PathBuf> {+ #[cfg(windows)]+ let raw = std::env::var_os("USERPROFILE");+ #[cfg(not(windows))]+ let raw = std::env::var_os("HOME");+ let path = PathBuf::from(raw?);+ if path.parent().is_none() || path.as_os_str().is_empty() {+ return None;+ }+ Some(path)+}++/// The active backend, probed once. Probing runs a subprocess on Linux, so it is+/// cached for the life of the process.+pub fn backend() -> Backend {+ static BACKEND: OnceLock<Backend> = OnceLock::new();+ *BACKEND.get_or_init(detect)+}++fn detect() -> Backend {+ // Escape hatch for CI and for users on kernels where the probe is wrong.+ // Only ever loosens to `None`, which withholds the tool: it cannot be used+ // to run commands unconfined.+ if let Some(forced) = std::env::var_os("JAN_AGENT_SANDBOX") {+ if forced.eq_ignore_ascii_case("none") || forced.eq_ignore_ascii_case("off") {+ return Backend::None;+ }+ }+ #[cfg(target_os = "macos")]+ {+ if Path::new(SEATBELT).is_file() {+ return Backend::Seatbelt;+ }+ Backend::None+ }+ #[cfg(target_os = "linux")]+ {+ match bwrap_path() {+ Some(path) if bwrap_usable(&path) => Backend::Bubblewrap,+ _ => Backend::None,+ }+ }+ #[cfg(windows)]+ {+ if appcontainer::available() {+ return Backend::AppContainer;+ }+ Backend::None+ }+ #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]+ {+ Backend::None+ }+}++/// Wrap `cfg` so the shell it describes runs confined. The returned config keeps+/// the same shape -- program, fixed args, command appended last -- so the spawn+/// path is unchanged. Returns `None` when no backend can enforce the policy, in+/// which case the caller must not run the command.+pub fn wrap(cfg: &ShellConfig, policy: &Policy) -> Option<ShellConfig> {+ match backend() {+ Backend::Bubblewrap => Some(ShellConfig {+ program: bwrap_path()?,+ args: bwrap_args(policy, cfg),+ via_stdin: cfg.via_stdin,+ }),+ Backend::Seatbelt => Some(ShellConfig {+ program: PathBuf::from(seatbelt_program()),+ args: seatbelt_args(policy, cfg),+ via_stdin: cfg.via_stdin,+ }),+ // AppContainer is a token attribute on the spawn rather than an argv+ // prefix, and `tokio::process::Command` cannot set one, so the wrapper is+ // a re-exec of this binary that performs the confined spawn itself. If+ // the running binary cannot be located there is no wrapper to run, and+ // returning `cfg` unchanged would run the command with no confinement.+ Backend::AppContainer => Some(ShellConfig {+ program: std::env::current_exe().ok()?,+ args: appcontainer::helper_args(+ &policy.workspace,+ policy.allow_network,+ &cfg.program,+ &cfg.args,+ ),+ via_stdin: cfg.via_stdin,+ }),+ Backend::None => None,+ }+}++// ---------------------------------------------------------------------------+// bubblewrap (Linux)+// ---------------------------------------------------------------------------++#[cfg(target_os = "linux")]+fn bwrap_path() -> Option<PathBuf> {+ static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();+ PATH.get_or_init(|| {+ ["/usr/bin/bwrap", "/bin/bwrap", "/usr/local/bin/bwrap"]+ .into_iter()+ .map(PathBuf::from)+ .find(|p| p.is_file())+ })+ .clone()+}++#[cfg(not(target_os = "linux"))]+fn bwrap_path() -> Option<PathBuf> {+ None+}++/// bubblewrap needs unprivileged user namespaces, which some distros and all of+/// WSL1 disable. Probe with a trivial sandbox rather than inferring from kernel+/// version, and treat a hang as unusable so a broken setup cannot wedge startup.+#[cfg(target_os = "linux")]+fn bwrap_usable(path: &Path) -> bool {+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};++ let Ok(mut child) = Command::new(path)+ .args(["--unshare-all", "--ro-bind", "/", "/", "/bin/true"])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ else {+ return false;+ };+ let deadline = Instant::now() + Duration::from_millis(500);+ loop {+ match child.try_wait() {+ Ok(Some(status)) => return status.success(),+ Ok(None) if Instant::now() >= deadline => {+ let _ = child.kill();+ let _ = child.wait();+ return false;+ }+ Ok(None) => std::thread::sleep(Duration::from_millis(20)),+ Err(_) => {+ let _ = child.kill();+ let _ = child.wait();+ return false;+ }+ }+ }+}++fn push(args: &mut Vec<String>, parts: &[&str]) {+ args.extend(parts.iter().map(|s| s.to_string()));+}++/// Build bubblewrap's argv. Operations apply in order, which the layering below+/// depends on: the read-only root comes first, then the tmpfs that hides `$HOME`,+/// then the workspace bind that punches back through it.+pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {+ let ws = policy.workspace.to_string_lossy().to_string();+ let mut args: Vec<String> = Vec::new();++ push(&mut args, &["--ro-bind", "/", "/"]);+ // Re-mounted after the read-only root so they are real kernel filesystems+ // rather than the host's, and so an unshared pid namespace has a valid /proc.+ push(&mut args, &["--proc", "/proc"]);+ push(&mut args, &["--dev", "/dev"]);+ // Private temp: writable, discarded with the sandbox, invisible to the host.+ push(&mut args, &["--tmpfs", "/tmp"]);++ // An empty tmpfs over $HOME hides user files without needing a deny rule.+ // The workspace is re-bound on top, so it survives while its siblings (the+ // permanent memory/skills store, settings.json, model files) do not.+ //+ // With `home_readonly` the CLI instead mounts $HOME read-only so helpers+ // that read it (git/ssh credential helpers, ~/.ssh/config, ~/.netrc) work;+ // the read-only mount is what keeps writes out even if the command tries.+ // It is deliberately read-only, so no later rw bind can shadow it.+ if let Some(home) = home_dir() {+ if policy.home_readonly {+ push(&mut args, &["--ro-bind", &home.to_string_lossy(), &home.to_string_lossy()]);+ } else {+ push(&mut args, &["--tmpfs", &home.to_string_lossy()]);+ }+ }+ // Mask a relocated data folder the same way: `$HOME` hiding alone would leave+ // a `JAN_DATA_FOLDER` outside the home readable, exposing the permanent+ // store and any co-located `settings.json`. The workspace is re-bound below+ // (it is nested under this root on the desktop), so it survives.+ if let Some(mask) = &policy.mask_root {+ push(&mut args, &["--tmpfs", &mask.to_string_lossy()]);+ }++ push(&mut args, &["--bind", &ws, &ws]);+ push(&mut args, &["--chdir", &ws]);++ // Drops the network, pid, ipc, uts and cgroup namespaces along with the+ // user namespace; --share-net selectively restores networking.+ push(&mut args, &["--unshare-all"]);+ if policy.allow_network {+ push(&mut args, &["--share-net"]);+ }+ // Reap the tree if this process dies, and detach the controlling terminal so+ // a command cannot inject keystrokes into it via TIOCSTI.+ push(&mut args, &["--die-with-parent", "--new-session"]);++ push(&mut args, &["--"]);+ args.push(cfg.program.to_string_lossy().to_string());+ args.extend(cfg.args.iter().cloned());+ args+}++// ---------------------------------------------------------------------------+// Seatbelt (macOS)+// ---------------------------------------------------------------------------++fn seatbelt_program() -> &'static str {+ #[cfg(target_os = "macos")]+ {+ SEATBELT+ }+ #[cfg(not(target_os = "macos"))]+ {+ "/usr/bin/sandbox-exec"+ }+}++/// Seatbelt profile. `(deny default)` closes everything, then each section opens+/// the narrowest thing that works. Later rules win, which is what lets the+/// workspace be re-allowed after `$HOME` is denied (or, with `home_readonly`,+/// lets the home stay readable while writes remain confined).+pub fn seatbelt_policy(policy: &Policy) -> String {+ let mut p = String::from(+ "(version 1)\n\+ (deny default)\n\+ ; A command may fork and exec freely; children inherit this profile.\n\+ (allow process-exec)\n\+ (allow process-fork)\n\+ (allow signal (target same-sandbox))\n\+ (allow process-info* (target same-sandbox))\n\+ ; Read-only sysctl (uname, hostname, env probes) -- a read-only open, LOW risk.\n\+ (allow sysctl-read)\n\+ ; openpty() and friends, so interactive-ish tools detect a tty.\n\+ (allow pseudo-tty)\n\+ (allow file-read* file-write* file-ioctl (literal \"/dev/ptmx\"))\n\+ (allow file-ioctl (regex #\"^/dev/ttys[0-9]+\"))\n\+ ; Python multiprocessing and OpenMP runtimes. Their shared POSIX shm/sem\n\+ ; names are host-wide and cannot be scoped per-sandbox on sandbox-exec\n\+ ; (also deprecated / not a security boundary per Apple) -- accepted tradeoff;\n\+ ; the real boundary is the $HOME / MASK_ROOT read denial below.\n\+ (allow ipc-posix-sem)\n\+ (allow ipc-posix-shm*)\n\+ (allow mach-lookup (global-name \"com.apple.system.opendirectoryd.libinfo\"))\n\+ (allow file-write-data\n\+ \x20 (require-all (path \"/dev/null\") (vnode-type CHARACTER-DEVICE)))\n\+ ; Reads: open, minus the user's home, plus the workspace back.\n\+ (allow file-read*)\n",+ );+ if home_dir().is_some() && !policy.home_readonly {+ p.push_str("(deny file-read* (subpath (param \"HOME_ROOT\")))\n");+ }+ if policy.mask_root.is_some() {+ p.push_str("(deny file-read* (subpath (param \"MASK_ROOT\")))\n");+ }+ p.push_str(+ "(allow file-read* (subpath (param \"WORKSPACE\")))\n\+ ; Writes: the workspace and the temp dir, nothing else.\n\+ (allow file-write* (subpath (param \"WORKSPACE\")))\n\+ (allow file-write* (subpath (param \"TMPDIR\")))\n\+ (allow file-write* (subpath \"/private/tmp\"))\n",+ );+ if policy.allow_network {+ p.push_str(+ "(allow network*)\n\+ (allow system-socket)\n\+ (allow mach-lookup\n\+ \x20 (global-name \"com.apple.SystemConfiguration.DNSConfiguration\")\n\+ \x20 (global-name \"com.apple.SystemConfiguration.configd\")\n\+ \x20 (global-name \"com.apple.SecurityServer\")\n\+ \x20 (global-name \"com.apple.trustd.agent\")\n\+ \x20 (global-name \"com.apple.ocspd\")\n\+ \x20 (global-name \"com.apple.networkd\"))\n",+ );+ } else {+ p.push_str("(deny network*)\n");+ }+ p+}++/// Build `sandbox-exec`'s argv. Paths travel as `-D` parameters rather than being+/// interpolated into the profile so a path containing profile syntax cannot+/// rewrite the policy.+pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {+ let mut args = vec!["-p".to_string(), seatbelt_policy(policy)];+ args.push(format!(+ "-DWORKSPACE={}",+ policy.workspace.to_string_lossy()+ ));+ if let Some(mask) = &policy.mask_root {+ args.push(format!("-DMASK_ROOT={}", mask.to_string_lossy()));+ }+ args.push(format!(+ "-DTMPDIR={}",+ std::env::temp_dir().to_string_lossy()+ ));+ if let Some(home) = home_dir() {+ args.push(format!("-DHOME_ROOT={}", home.to_string_lossy()));+ }+ args.push("--".to_string());+ args.push(cfg.program.to_string_lossy().to_string());+ args.extend(cfg.args.iter().cloned());+ args+}++// ---------------------------------------------------------------------------+// Denial heuristics+// ---------------------------------------------------------------------------++/// Keywords a kernel or libc emits when the sandbox refuses an operation. Used+/// only to append an explanatory hint: a false positive costs a stray sentence,+/// never a behavior change.+const DENIAL_MARKERS: &[&str] = &[+ "operation not permitted",+ "permission denied",+ "access is denied",+ "read-only file system",+ "not permitted",+ "sandbox",+ "seccomp",+ "landlock",+ "bwrap:",+ "network is unreachable",+ "temporary failure in name resolution",+ "could not resolve host",+ "name or service not known",+];++/// True when `output` looks like the sandbox blocked something, so the model can+/// be told why instead of retrying a command that can never succeed.+pub fn looks_denied(output: &str) -> bool {+ let lower = output.to_lowercase();+ DENIAL_MARKERS.iter().any(|m| lower.contains(m))+}++/// Sentence appended to a denied command's output, telling the model the limits+/// rather than leaving it to infer them from `Permission denied`.+pub fn denial_hint(policy: &Policy) -> String {+ let net = if policy.allow_network {+ ""+ } else {+ " Network access is disabled."+ };+ let home = if policy.home_readonly {+ ""+ } else {+ " and files under your home directory are not readable"+ };+ format!(+ "\n[sandbox: writes are limited to the workspace ({}){home}.{net}]",+ policy.workspace.display()+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ fn cfg() -> ShellConfig {+ ShellConfig {+ program: PathBuf::from("/bin/bash"),+ args: vec!["-c".to_string()],+ via_stdin: false,+ }+ }++ fn policy() -> Policy {+ Policy::new(Path::new("/data/agent-workspace/threads/t1"), false)+ }++ fn joined(args: &[String]) -> String {+ args.join(" ")+ }++ #[test]+ fn bwrap_mounts_root_read_only_before_layering_on_it() {+ let args = bwrap_args(&policy(), &cfg());+ let text = joined(&args);+ assert!(text.contains("--ro-bind / /"));+ // Order is the enforcement: the workspace bind must come after the tmpfs+ // that hides $HOME, or it would be buried by it.+ if let (Some(tmpfs), Some(bind)) = (text.find("--tmpfs /home"), text.find("--bind /data")) {+ assert!(tmpfs < bind, "workspace bind must follow the $HOME tmpfs");+ }+ }++ #[test]+ fn bwrap_binds_the_workspace_writable_and_chdirs_into_it() {+ let args = bwrap_args(&policy(), &cfg());+ let text = joined(&args);+ let ws = "/data/agent-workspace/threads/t1";+ assert!(text.contains(&format!("--bind {ws} {ws}")));+ assert!(text.contains(&format!("--chdir {ws}")));+ }++ #[test]+ fn bwrap_masks_home_by_default_and_reads_it_when_configured() {+ let Some(home) = home_dir() else {+ panic!("test needs a HOME");+ };+ let home = home.to_string_lossy();+ let ro_bind = format!("--ro-bind {home} {home}");+ let tmpfs = format!("--tmpfs {home}");++ // Default: an empty tmpfs hides the home.+ let masked = joined(&bwrap_args(&policy(), &cfg()));+ assert!(masked.contains(&tmpfs), "{masked}");+ assert!(!masked.contains(&ro_bind), "{masked}");++ // home_readonly: the home is bound read-only instead of hidden.+ let ro = joined(&bwrap_args(&policy().with_home_readonly(true), &cfg()));+ assert!(!ro.contains(&tmpfs), "{ro}");+ assert!(ro.contains(&ro_bind), "{ro}");+ }++ #[test]+ fn bwrap_denies_network_unless_allowed() {+ let denied = joined(&bwrap_args(&policy(), &cfg()));+ assert!(denied.contains("--unshare-all"));+ assert!(!denied.contains("--share-net"));++ let allowed = joined(&bwrap_args(+ &Policy::new(Path::new("/data/ws"), true),+ &cfg(),+ ));+ assert!(allowed.contains("--unshare-all"));+ assert!(allowed.contains("--share-net"));+ }++ #[test]+ fn bwrap_hardens_the_tree_and_terminal() {+ let text = joined(&bwrap_args(&policy(), &cfg()));+ assert!(text.contains("--die-with-parent"));+ assert!(text.contains("--new-session"));+ assert!(text.contains("--proc /proc"));+ assert!(text.contains("--tmpfs /tmp"));+ }++ #[test]+ fn bwrap_ends_with_the_shell_so_the_command_appends_last() {+ let args = bwrap_args(&policy(), &cfg());+ let sep = args.iter().position(|a| a == "--").expect("separator");+ assert_eq!(+ &args[sep + 1..],+ &["/bin/bash".to_string(), "-c".to_string()]+ );+ }++ #[test]+ fn seatbelt_closes_by_default_then_opens_reads() {+ let p = seatbelt_policy(&policy());+ assert!(p.starts_with("(version 1)\n(deny default)"));+ assert!(p.contains("(allow file-read*)"));+ }++ #[test]+ fn seatbelt_keeps_home_readable_but_unwritable_when_configured() {+ // home_readonly: no home read-denial, and the write section never opens+ // HOME_ROOT, so reads work but writes stay confined to workspace/temp.+ let p = seatbelt_policy(&policy().with_home_readonly(true));+ assert!(!p.contains("(deny file-read* (subpath (param \"HOME_ROOT\")))"), "{p}");+ assert!(p.contains("(allow file-read*)"), "{p}");+ assert!(!p.contains("(allow file-write* (subpath (param \"HOME_ROOT\")))"), "{p}");+ }++ #[test]+ fn seatbelt_denies_home_after_allowing_reads_and_restores_the_workspace() {+ let p = seatbelt_policy(&policy());+ let allow_all = p.find("(allow file-read*)\n").expect("blanket read");+ let deny_home = p.find("(deny file-read* (subpath (param \"HOME_ROOT\")))");+ let allow_ws = p+ .find("(allow file-read* (subpath (param \"WORKSPACE\")))")+ .expect("workspace read");+ // Seatbelt takes the last matching rule, so these three must appear in+ // this order for the workspace carve-out to survive the home denial.+ if let Some(deny_home) = deny_home {+ assert!(allow_all < deny_home && deny_home < allow_ws);+ }+ }++ #[test]+ fn seatbelt_confines_writes_to_the_workspace_and_temp() {+ let p = seatbelt_policy(&policy());+ assert!(p.contains("(allow file-write* (subpath (param \"WORKSPACE\")))"));+ assert!(p.contains("(allow file-write* (subpath (param \"TMPDIR\")))"));+ // No blanket write rule anywhere.+ assert!(!p.contains("(allow file-write*)"));+ }++ #[test]+ fn seatbelt_denies_network_unless_allowed() {+ assert!(seatbelt_policy(&policy()).contains("(deny network*)"));+ let open = seatbelt_policy(&Policy::new(Path::new("/data/ws"), true));+ assert!(open.contains("(allow network*)"));+ assert!(!open.contains("(deny network*)"));+ }++ #[test]+ fn seatbelt_passes_paths_as_parameters_not_policy_text() {+ let args = seatbelt_args(&policy(), &cfg());+ let ws = "/data/agent-workspace/threads/t1";+ assert!(args.iter().any(|a| a == &format!("-DWORKSPACE={ws}")));+ // The path must not be interpolated into the profile itself, or a path+ // containing sbpl syntax could rewrite the policy.+ assert!(!args[1].contains(ws));+ }++ #[test]+ fn seatbelt_ends_with_the_shell_so_the_command_appends_last() {+ let args = seatbelt_args(&policy(), &cfg());+ let sep = args.iter().position(|a| a == "--").expect("separator");+ assert_eq!(+ &args[sep + 1..],+ &["/bin/bash".to_string(), "-c".to_string()]+ );+ }++ #[test]+ fn denial_markers_match_real_kernel_messages() {+ assert!(looks_denied(+ "touch: cannot touch '/etc/x': Read-only file system"+ ));+ assert!(looks_denied("bash: /root/.x: Permission denied"));+ assert!(looks_denied(+ "curl: (6) Could not resolve host: example.com"+ ));+ assert!(!looks_denied("hello world"));+ assert!(!looks_denied("test failed: 3 assertions"));+ }++ #[test]+ fn denial_hint_names_the_workspace_and_network_state() {+ let hint = denial_hint(&policy());+ assert!(hint.contains("/data/agent-workspace/threads/t1"));+ assert!(hint.contains("Network access is disabled."));+ assert!(!denial_hint(&Policy::new(Path::new("/w"), true)).contains("Network access"));+ }++ #[test]+ fn a_degenerate_home_is_ignored_rather_than_hiding_the_filesystem() {+ // Guards the `parent().is_none()` check: a `/` home would put a tmpfs+ // over the entire filesystem and nothing would be executable.+ assert!(PathBuf::from("/").parent().is_none());+ }++ #[test]+ fn backend_is_stable_across_calls() {+ assert_eq!(backend(), backend());+ }+}++/// Live end-to-end checks: these assert the kernel actually refuses things,+/// not that we generated the right flags. Skipped when no backend is available.+#[cfg(all(test, unix))]+mod enforcement_tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};++ static N: AtomicUsize = AtomicUsize::new(0);++ /// The canonical temp dir. On macOS `std::env::temp_dir()` returns the+ /// `/var/folders/...` symlinked form while `sandbox-exec` matches the+ /// canonical `/private/var/folders/...` path, so denying the symlinked form+ /// (and the workspace built on top of it) is silently bypassed. Resolving the+ /// symlink keeps the enforcement tests meaningful on macOS. A no-op elsewhere.+ fn temp_dir() -> PathBuf {+ let tmp = std::env::temp_dir();+ #[cfg(target_os = "macos")]+ {+ return tmp.canonicalize().unwrap_or(tmp);+ }+ #[cfg(not(target_os = "macos"))]+ {+ tmp+ }+ }++ fn workspace() -> PathBuf {+ let n = N.fetch_add(1, Ordering::SeqCst);+ let dir = temp_dir().join(format!("jan_jail_{}_{}", std::process::id(), n));+ std::fs::create_dir_all(&dir).expect("create workspace");+ dir+ }++ /// Run `command` confined to `ws` and return combined output plus success.+ async fn run(ws: &Path, allow_network: bool, command: &str) -> (bool, String) {+ let policy = Policy::new(ws, allow_network);+ run_policy(policy, ws, command).await+ }++ /// Run `command` under `policy`, spawning in `ws`.+ async fn run_policy(policy: Policy, ws: &Path, command: &str) -> (bool, String) {+ let wrapped = wrap(super::super::proc::shell(), &policy).expect("backend");+ let child = super::super::proc::spawn(&wrapped, command, ws)+ .await+ .expect("spawn");+ let pid = child.id();+ let out = child.wait_with_output().await.expect("wait");+ if let Some(pid) = pid {+ super::super::proc::unregister(pid);+ }+ let mut text = String::from_utf8_lossy(&out.stdout).to_string();+ text.push_str(&String::from_utf8_lossy(&out.stderr));+ (out.status.success(), text)+ }++ macro_rules! require_backend {+ () => {+ if !backend().enforces() {+ eprintln!("skipping: no sandbox backend on this host");+ return;+ }+ };+ }++ #[tokio::test]+ // `/etc/hostname` does not exist on macOS, so this Linux-content check is+ // gated to the platform that guarantees the file.+ #[cfg(target_os = "linux")]+ async fn a_command_still_runs_and_can_read_system_files() {+ require_backend!();+ let ws = workspace();+ let (ok, out) = run(+ &ws,+ false,+ "echo alive && head -c 4 /etc/hostname >/dev/null",+ )+ .await;+ let _ = std::fs::remove_dir_all(&ws);+ assert!(ok, "basic command must work inside the sandbox: {out}");+ assert!(out.contains("alive"), "{out}");+ }++ #[tokio::test]+ async fn writes_inside_the_workspace_succeed_and_persist() {+ require_backend!();+ let ws = workspace();+ let (ok, out) = run(&ws, false, "echo written > marker.txt").await;+ assert!(ok, "workspace write must succeed: {out}");+ let marker = ws.join("marker.txt");+ let landed = std::fs::read_to_string(&marker)+ .ok()+ .map(|s| s.trim().to_string());+ assert_eq!(+ landed.as_deref(),+ Some("written"),+ "the write must land on the real workspace, not a throwaway overlay"+ );+ let _ = std::fs::remove_dir_all(&ws);+ }++ #[tokio::test]+ async fn writes_outside_the_workspace_never_reach_the_host() {+ require_backend!();+ let ws = workspace();+ let victim = std::env::temp_dir().join(format!("jan_jail_victim_{}", std::process::id()));+ let _ = std::fs::remove_file(&victim);+ // The command may well succeed: on bubblewrap the temp dir is a private+ // tmpfs, so the write lands somewhere thrown away with the sandbox. What+ // must hold either way is that nothing appears on the host.+ let (_, out) = run(+ &ws,+ false,+ &format!("echo pwned > {}", victim.to_string_lossy()),+ )+ .await;+ let leaked = victim.exists();+ let _ = std::fs::remove_file(&victim);+ let _ = std::fs::remove_dir_all(&ws);+ assert!(!leaked, "the host filesystem must be untouched: {out}");+ }++ #[tokio::test]+ async fn writes_to_read_only_system_paths_fail() {+ require_backend!();+ let ws = workspace();+ let (ok, out) = run(&ws, false, "echo pwned > /etc/jan_jail_probe").await;+ let leaked = Path::new("/etc/jan_jail_probe").exists();+ let _ = std::fs::remove_dir_all(&ws);+ assert!(+ !ok,+ "system paths are read-only, the write must fail: {out}"+ );+ assert!(!leaked);+ assert!(+ looks_denied(&out),+ "a refusal must be recognizable so the model gets the hint: {out}"+ );+ }++ #[tokio::test]+ // Sibling-workspace invisibility relies on the sandbox backend scoping the+ // temp dir (bwrap's private tmpfs / seatbelt's HOME deny). The seatbelt+ // workspace lives under the mac temp dir, which is not covered by its HOME+ // deny, so this semantic only holds under bwrap on Linux.+ #[cfg(target_os = "linux")]+ async fn another_threads_workspace_is_not_reachable() {+ require_backend!();+ // The isolation that matters most: one conversation must not see another's+ // files, nor the permanent memory/skills store beside them.+ let mine = workspace();+ let theirs = workspace();+ std::fs::write(theirs.join("private.txt"), b"THEIRSECRET").unwrap();+ let (_, out) = run(+ &mine,+ false,+ &format!("cat {}/private.txt", theirs.to_string_lossy()),+ )+ .await;+ let _ = std::fs::remove_dir_all(&mine);+ let _ = std::fs::remove_dir_all(&theirs);+ assert!(+ !out.contains("THEIRSECRET"),+ "another thread's files must be invisible, got: {out}"+ );+ }++ #[tokio::test]+ async fn the_users_home_directory_is_not_readable() {+ require_backend!();+ let Some(home) = home_dir() else {+ eprintln!("skipping: no HOME set");+ return;+ };+ // A real secret-shaped file in the real home, which the sandbox must not+ // be able to read back.+ let secret = home.join(format!(".jan_jail_secret_{}", std::process::id()));+ if std::fs::write(&secret, b"TOPSECRET").is_err() {+ eprintln!("skipping: home not writable");+ return;+ }+ let ws = workspace();+ let (_, out) = run(&ws, false, &format!("cat {}", secret.to_string_lossy())).await;+ let _ = std::fs::remove_file(&secret);+ let _ = std::fs::remove_dir_all(&ws);+ assert!(+ !out.contains("TOPSECRET"),+ "home files must be unreadable, got: {out}"+ );+ }++ #[tokio::test]+ async fn home_is_readable_and_writes_stay_confined_when_home_readonly() {+ require_backend!();+ let Some(home) = home_dir() else {+ eprintln!("skipping: no HOME set");+ return;+ };+ // A file in the real home the sandbox must now be able to read...+ let secret = home.join(format!(".jan_jail_ro_read_{}", std::process::id()));+ if std::fs::write(&secret, b"READABLE_SECRET").is_err() {+ eprintln!("skipping: home not writable");+ return;+ }+ let ws = workspace();+ let policy = Policy::new(&ws, false).with_home_readonly(true);+ // ...read it back, and fail to write a second file into the home.+ let victim = home.join(format!(".jan_jail_ro_write_{}", std::process::id()));+ let _ = std::fs::remove_file(&victim);+ let command = format!(+ "cat {} && echo pwned > {}",+ secret.to_string_lossy(),+ victim.to_string_lossy()+ );+ let (ok, out) = run_policy(policy, &ws, &command).await;+ let leaked = victim.exists();+ let _ = std::fs::remove_file(&secret);+ let _ = std::fs::remove_file(&victim);+ let _ = std::fs::remove_dir_all(&ws);+ assert!(out.contains("READABLE_SECRET"), "home reads must work: {out}");+ assert!(!leaked, "home writes must stay confined even when readable: {out}");+ assert!(!ok, "the write into the home must fail: {out}");+ }++ #[tokio::test]+ async fn the_network_is_unreachable_by_default() {+ require_backend!();+ let ws = workspace();+ // /dev/tcp is a bash builtin, so this needs no network tooling installed.+ let (ok, _) = run(&ws, false, "exec 3<>/dev/tcp/1.1.1.1/53 && echo connected").await;+ let _ = std::fs::remove_dir_all(&ws);+ assert!(!ok, "network must be denied by default");+ }++ /// A relocated store root (e.g. `JAN_DATA_FOLDER` outside `$HOME`) must not+ /// be readable by the shell, even when it is not under the user's home.+ #[tokio::test]+ async fn a_relocated_store_root_is_not_readable() {+ require_backend!();+ let ws = workspace();+ let store = workspace();+ std::fs::create_dir_all(&store).unwrap();+ let secret = store.join("memory.txt");+ std::fs::write(&secret, b"STORESECRET").unwrap();++ let policy = Policy::new(&ws, false).with_mask_root(&store);+ let (_, out) = run_policy(policy, &ws, &format!("cat {}", secret.to_string_lossy())).await;+ let _ = std::fs::remove_dir_all(&ws);+ let _ = std::fs::remove_dir_all(&store);+ assert!(+ !out.contains("STORESECRET"),+ "a relocated store root must be unreadable, got: {out}"+ );+ }+}diff --git a/src-tauri/src/core/agent/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rssimilarity index 58%rename from src-tauri/src/core/agent/tools/mod.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex 45e81b6e0..af7bf56b5 100644--- a/src-tauri/src/core/agent/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -1,15 +1,96 @@-//! 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.+//! Built-in agent tools: the capability classification and the `BUILTIN_TOOLS`+//! registry every other module in this crate keys off.+use std::path::Path;++/// Windows-only confinement backend for [`jail`]. Present on every platform so+/// the argv it builds stays unit-testable.+pub mod appcontainer;pub mod cmdscan;pub mod gate;pub mod handlers;+pub mod jail;pub mod proc;+/// Path containment for the filesystem tools. Distinct from [`jail`], which is+/// kernel-level confinement for spawned commands.pub mod sandbox;pub mod schema;pub mod web;+/// Ambient context a tool call executes against.+///+/// The two roots are separate because they have different lifetimes.+/// `project_root` is the sandbox the filesystem tools are confined to, which the+/// desktop makes ephemeral and per-thread; `store_root` holds `memory/` and+/// `skills/`, which must survive every conversation. Keeping the store outside+/// `project_root` is also what stops the general filesystem tools from reaching+/// it -- `escapes_project` refuses the path, with no extra rule needed.+///+/// A project that co-locates its store (dev's layout, and the CLI agent) simply+/// passes `workspace::project_store(project_root)` as `store_root`.+///+/// `enabled_skills` is the `[skills].enabled` whitelist from the project's+/// `agent.toml` (empty = every skill enabled). It is passed in rather than read+/// here so this crate owns no config-file format: the desktop app and the CLI+/// already parse `agent.toml` themselves.+/// `allow_network` opens the sandboxed shell's network namespace. It defaults to+/// off and is a field rather than a `new` parameter so existing callers keep the+/// safe default without being rewritten.+#[derive(Debug, Clone, Copy)]+pub struct ToolContext<'a> {+ pub project_root: &'a Path,+ pub store_root: &'a Path,+ pub enabled_skills: &'a [String],+ pub allow_network: bool,+ /// When set, `write`/`edit` re-canonicalize the target and refuse a path+ /// that escapes `project_root`, closing the check/use race between the+ /// gate's decision-time canonicalization and the handler's raw-path write.+ /// The CLI leaves it off so a user-approved escaping write still works.+ pub confine_writes: bool,+ /// The Jan data-folder root, masked from the sandboxed shell on surfaces+ /// where it sits outside the workspace (the desktop). `None` on the CLI,+ /// where the project itself is the workspace.+ pub mask_root: Option<&'a Path>,+ /// Expose `$HOME` to the sandboxed shell read-only (the CLI) instead of+ /// hiding it (the desktop). Passed through to the `bash` sandbox policy.+ pub home_readonly: bool,+}++impl<'a> ToolContext<'a> {+ pub fn new(project_root: &'a Path, store_root: &'a Path, enabled_skills: &'a [String]) -> Self {+ Self {+ project_root,+ store_root,+ enabled_skills,+ allow_network: false,+ confine_writes: false,+ mask_root: None,+ home_readonly: false,+ }+ }++ pub fn with_network(mut self, allow: bool) -> Self {+ self.allow_network = allow;+ self+ }++ pub fn with_confined_writes(mut self, confine: bool) -> Self {+ self.confine_writes = confine;+ self+ }++ pub fn with_mask_root(mut self, mask_root: &'a Path) -> Self {+ self.mask_root = Some(mask_root);+ self+ }++ /// Expose `$HOME` to the sandboxed shell read-only. See [`Self::home_readonly`].+ pub fn with_home_readonly(mut self, home_readonly: bool) -> Self {+ self.home_readonly = home_readonly;+ self+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Capability {Read,diff --git a/src-tauri/src/core/agent/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rssimilarity index 70%rename from src-tauri/src/core/agent/tools/proc.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rsindex dfd64fc9a..a61133337 100644--- a/src-tauri/src/core/agent/tools/proc.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs@@ -118,13 +118,67 @@ fn which(name: &str) -> Option<PathBuf> {/// Spawn `command` in `cwd` using the resolved shell, as a new process group,/// with stdout/stderr piped and `kill_on_drop` armed. The returned child's pid/// is registered so [`kill_all`] can reap it on shutdown; the caller must-/// [`unregister`] it once the command finishes.+/// [`unregister`] it once the command finishes. The child inherits only the+/// minimal environment in `SANDBOX_ENV_ALLOW`, never the full host environment.+///+/// The full host environment leaks secrets to any `bash` call -- `JAN_API_KEY`,+/// `OPENAI_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `SSH_AUTH_SOCK`, the relocated+/// `JAN_DATA_FOLDER` -- so the shell is launched with only what a command needs+/// to run at all. Applied here, the one choke point all backends (bubblewrap,+/// seatbelt, and the Windows AppContainer helper) funnel through.+const SANDBOX_ENV_ALLOW: &[&str] = &["PATH", "HOME", "USERPROFILE", "TMPDIR", "TMP", "TEMP", "LANG", "TERM"];++/// Bound the resource exhaustion a sandboxed command could otherwise trigger on+/// the host. `bwrap` 0.6.1 (and older) has no `--rlimit`, so instead we clamp the+/// child's soft limits here, before exec, from the one choke point every backend+/// funnels through. A fork-bomb is capped by `NPROC`, descriptor exhaustion by+/// `NOFILE`, and disk fill through the unbounded workspace bind by `FSIZE`. The+/// bwrap wrapper execs `bwrap` itself, which sets up the namespace and then+/// execs the real shell, so the limits carry over to every descendant. Linux+/// only; the Windows AppContainer child is limited by its token.+#[cfg(unix)]+fn confine_limits(cmd: &mut Command) {+ // `tokio::process::Command::pre_exec` (unix) is the std `pre_exec`; the call+ // below is what mounts the limits.+ // # Safety: `pre_exec` runs in the forked child before exec. Only async-signal-+ // safe calls are allowed; `setrlimit` is one. Errors fall back to the parent's+ // values and are ignored (best effort), so a kernel that refuses a limit+ // cannot wedge a launch.+ unsafe {+ cmd.pre_exec(|| {+ for (resource, limit) in [+ (nix::libc::RLIMIT_NPROC, 4096_u64),+ (nix::libc::RLIMIT_NOFILE, 1024_u64),+ (nix::libc::RLIMIT_FSIZE, 1024_u64 * 1024_u64 * 1024_u64),+ ] {+ let r = nix::libc::rlimit {+ rlim_cur: limit,+ rlim_max: limit,+ };+ // Best effort: a setrlimit failure is intentionally ignored so a+ // kernel that refuses a limit cannot wedge the launch.+ let _ = nix::libc::setrlimit(resource, &r);+ }+ Ok(())+ });+ }+}+pub async fn spawn(cfg: &ShellConfig, command: &str, cwd: &Path) -> std::io::Result<Child> {let mut cmd = Command::new(&cfg.program);cmd.args(&cfg.args);if !cfg.via_stdin {cmd.arg(command);}+ // Strip every inherited variable, then re-add only the allowlist so the+ // sandboxed process holds no host secrets regardless of which backend wraps+ // it. `current_dir` on the workspace keeps relative work correct.+ cmd.env_clear();+ for key in SANDBOX_ENV_ALLOW {+ if let Some(val) = std::env::var_os(key) {+ cmd.env(key, val);+ }+ }cmd.current_dir(cwd).stdout(Stdio::piped()).stderr(Stdio::piped())@@ -135,6 +189,8 @@ pub async fn spawn(cfg: &ShellConfig, command: &str, cwd: &Path) -> std::io::Res}).kill_on_drop(true);set_process_group(&mut cmd);+ #[cfg(unix)]+ confine_limits(&mut cmd);let mut child = cmd.spawn()?;@@ -280,4 +336,24 @@ mod tests {unregister(fake);assert!(!running().lock().unwrap().contains(&fake));}++ #[cfg(unix)]+ #[tokio::test]+ async fn confine_limits_caps_the_child_process_count() {+ // The rlimit mounting must actually reach the spawned child: with NPROC+ // clamped we still run up to the cap, but a fork-bomb past it fails.+ let child = spawn(shell(), "exit 0", &tmp()).await.unwrap();+ let pid = child.id().unwrap();+ child.wait_with_output().await.unwrap();+ unregister(pid);++ // Spawn a shell that reports its own soft NOFILE limit; confine_limits+ // sets it to 1024, which should be visible inside the sandbox.+ let child = spawn(shell(), "ulimit -n", &tmp()).await.unwrap();+ let pid = child.id().unwrap();+ let out = child.wait_with_output().await.unwrap();+ unregister(pid);+ let val = String::from_utf8_lossy(&out.stdout).trim().to_string();+ assert_eq!(val, "1024", "NOFILE soft limit should be capped, got: {val}");+ }}diff --git a/src-tauri/src/core/agent/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rssimilarity index 100%rename from src-tauri/src/core/agent/tools/sandbox.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsdiff --git a/src-tauri/src/core/agent/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rssimilarity index 99%rename from src-tauri/src/core/agent/tools/schema.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 6cd1ac31c..246d1fc45 100644--- a/src-tauri/src/core/agent/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -240,7 +240,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {#[cfg(test)]mod tests {use super::*;- use crate::core::agent::tools::BUILTIN_TOOLS;+ use crate::tools::BUILTIN_TOOLS;#[test]fn schemas_match_builtin_tools() {diff --git a/src-tauri/src/core/agent/tools/web.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/web.rssimilarity index 100%rename from src-tauri/src/core/agent/tools/web.rsrename to src-tauri/plugins/tauri-plugin-agent-tools/src/tools/web.rsdiff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rsnew file mode 100644index 000000000..5aa8c8505--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/workspace.rs@@ -0,0 +1,335 @@+//! Path helpers for the two roots the agent works against.+//!+//! **Store root** -- holds `memory/` and `skills/`. Long-term: memories and+//! skills outlive any single conversation, so on the desktop this is a permanent+//! directory in the Jan data folder. A project (dev's layout, and the CLI agent)+//! co-locates its store at `<project>/.jan/agent` instead; both are just a store+//! root to everything downstream.+//!+//! **Project root** -- the sandbox the filesystem tools (read/ls/find/grep, and+//! later write/edit/bash) are confined to. On the desktop this is ephemeral and+//! per-thread, so one conversation's scratch files are invisible to the next.+//!+//! The two are deliberately disjoint: the store is not reachable from the+//! project root, so `escapes_project` alone keeps the general filesystem tools+//! out of memory and skills, which are reachable only through the dedicated+//! `memory_*`/`skill_*` tools.+//!+//! These live here rather than in `tools::handlers` because `skills` needs the+//! name guard too; keeping them in `handlers` made `handlers` and `skills`+//! mutually dependent.++use std::path::{Path, PathBuf};++const THREADS: &str = "threads";++/// `<store_root>/<kind>`, for `kind` in `{memory, skills}`.+pub fn store_dir(store_root: &Path, kind: &str) -> PathBuf {+ store_root.join(kind)+}++/// A project's co-located store root: `<project_root>/.jan/agent`.+///+/// This is dev's per-project layout and what the CLI agent uses, where memory+/// and skills live inside the project being worked on.+pub fn project_store(project_root: &Path) -> PathBuf {+ project_root.join(".jan").join("agent")+}++/// The desktop's permanent store root: `<jan_data_folder>/agent-workspace`.+///+/// Never cleaned up -- this is what makes memories long-term. Resolving the Jan+/// data folder itself stays with the app (it owns the `JAN_DATA_FOLDER` override+/// and the configured `data_folder`); this crate only decides where inside it+/// the agent's directories live.+pub fn permanent_store(jan_data_folder: &Path) -> PathBuf {+ jan_data_folder.join("agent-workspace")+}++/// Where per-thread sandboxes live: `<permanent_store>/threads`.+///+/// A sibling of `memory/` and `skills/`, not a parent, so a thread's sandbox+/// root cannot contain the store and `escapes_project` refuses any path that+/// climbs out toward it.+pub fn threads_dir(jan_data_folder: &Path) -> PathBuf {+ permanent_store(jan_data_folder).join(THREADS)+}++/// A thread's ephemeral sandbox root:+/// `<jan_data_folder>/agent-workspace/threads/<thread_id>`.+pub fn thread_workspace(jan_data_folder: &Path, thread_id: &str) -> Result<PathBuf, String> {+ Ok(threads_dir(jan_data_folder).join(thread_segment(thread_id)?))+}++/// Create the permanent store and its `memory/`/`skills/` subdirectories,+/// returning the store root. Idempotent.+pub async fn ensure_permanent_store(jan_data_folder: &Path) -> Result<PathBuf, String> {+ let root = permanent_store(jan_data_folder);+ for kind in ["memory", "skills"] {+ tokio::fs::create_dir_all(store_dir(&root, kind))+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ }+ Ok(root)+}++/// Create a thread's sandbox root and return it. Idempotent.+///+/// The directory must exist before any tool runs: `escapes_project`+/// canonicalizes the root, and a missing root is treated as an escape, so every+/// call would otherwise be refused.+pub async fn ensure_thread_workspace(+ jan_data_folder: &Path,+ thread_id: &str,+) -> Result<PathBuf, String> {+ let dir = thread_workspace(jan_data_folder, thread_id)?;+ tokio::fs::create_dir_all(&dir)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ Ok(dir)+}++/// Delete a thread's sandbox. Idempotent: a missing sandbox is Ok.+pub async fn remove_thread_workspace(+ jan_data_folder: &Path,+ thread_id: &str,+) -> Result<(), String> {+ let dir = thread_workspace(jan_data_folder, thread_id)?;+ crate::tools::appcontainer::release(&dir);+ match tokio::fs::remove_dir_all(&dir).await {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(format!("ERROR: {e}")),+ }+}++/// Delete every thread sandbox whose id is not in `keep`, returning how many+/// were removed.+///+/// Sandboxes are ephemeral, but a crash or a thread deleted while the app was+/// closed leaves one behind. Called at startup with the surviving thread ids so+/// leftovers cannot accumulate. An unreadable threads directory is not an error:+/// nothing has been created yet.+pub async fn sweep_thread_workspaces(+ jan_data_folder: &Path,+ keep: &[String],+) -> Result<usize, String> {+ let dir = threads_dir(jan_data_folder);+ let Ok(mut entries) = tokio::fs::read_dir(&dir).await else {+ return Ok(0);+ };+ // Compare against sanitized ids: the directory name is the sanitized form,+ // so a raw id would fail to match its own sandbox and delete a live one.+ let keep: std::collections::HashSet<String> = keep+ .iter()+ .filter_map(|id| thread_segment(id).ok())+ .collect();+ let mut removed = 0;+ while let Ok(Some(entry)) = entries.next_entry().await {+ let Some(name) = entry.file_name().to_str().map(str::to_string) else {+ continue;+ };+ if keep.contains(&name) {+ continue;+ }+ crate::tools::appcontainer::release(&entry.path());+ if tokio::fs::remove_dir_all(entry.path()).await.is_ok() {+ removed += 1;+ }+ }+ Ok(removed)+}++/// Sanitize a caller-supplied thread id into one safe path segment.+///+/// Stricter than [`workspace_filename`] on purpose: a thread id is generated,+/// never typed, so anything outside `[A-Za-z0-9._-]` is a bug or an attack. Dots+/// are allowed inside the id but a dot-only segment is not, which is what would+/// resolve to the threads directory itself or its parent.+pub fn thread_segment(thread_id: &str) -> Result<String, String> {+ let id = thread_id.trim();+ let ok = !id.is_empty()+ && id.len() <= 128+ && id+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))+ && !id.chars().all(|c| c == '.');+ if !ok {+ return Err(format!("ERROR: invalid thread id '{thread_id}'"));+ }+ Ok(id.to_string())+}++/// Sanitize a caller-supplied entry name into a safe `<stem>.md` filename.+/// Rejects path separators and `..` so the result can never escape the+/// store directory. `.md` is appended if absent.+pub fn workspace_filename(name: &str) -> Result<String, String> {+ let trimmed = name.trim();+ let stem = trimmed.strip_suffix(".md").unwrap_or(trimmed);+ // Checked on the stem, not the input: otherwise a bare "." passes and the+ // guard emits "..md", a name it would itself reject as input.+ if stem.is_empty()+ || stem.contains('/')+ || stem.contains('\\')+ || stem.contains("..")+ || stem.chars().all(|c| c == '.')+ {+ return Err(format!("ERROR: invalid name '{name}'"));+ }+ Ok(format!("{stem}.md"))+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};++ static COUNTER: AtomicUsize = AtomicUsize::new(0);++ fn unique_data_folder() -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::SeqCst);+ std::env::temp_dir().join(format!("jan_ws_test_{}_{}", std::process::id(), n))+ }++ #[test]+ fn permanent_store_holds_memory_and_skills() {+ let store = permanent_store(Path::new("/data"));+ assert_eq!(store, Path::new("/data/agent-workspace"));+ assert_eq!(+ store_dir(&store, "memory"),+ Path::new("/data/agent-workspace/memory")+ );+ }++ /// dev's layout: a project keeps its store inside itself.+ #[test]+ fn project_store_is_under_jan_agent() {+ assert_eq!(+ store_dir(&project_store(Path::new("/p")), "memory"),+ Path::new("/p/.jan/agent/memory")+ );+ }++ /// The whole point of the split: a thread sandbox is a sibling of the store,+ /// so no relative path from inside it stays within the sandbox and reaches+ /// memory. `escapes_project` refuses the climb.+ #[test]+ fn thread_workspace_does_not_contain_the_store() {+ let data = Path::new("/data");+ let thread = thread_workspace(data, "abc-123").unwrap();+ assert_eq!(thread, Path::new("/data/agent-workspace/threads/abc-123"));+ assert!(!store_dir(&permanent_store(data), "memory").starts_with(&thread));+ }++ #[test]+ fn thread_segment_rejects_traversal_and_separators() {+ for bad in [+ "", " ", ".", "..", "...", "../x", "a/b", "a\\b", "a b", "a;b", "a$b", "évil",+ ] {+ assert!(+ thread_segment(bad).is_err(),+ "expected {bad:?} to be rejected"+ );+ }+ assert!(thread_segment(&"a".repeat(129)).is_err(), "over-long id");+ }++ #[test]+ fn thread_segment_accepts_generated_ids() {+ for ok in [+ "01H8XGJWBWBAQ",+ "3f2a9c1e-1234-4c9a-9b7e-000000000000",+ "thread_42",+ "v1.2",+ ] {+ assert_eq!(thread_segment(ok).unwrap(), ok);+ }+ assert_eq!(thread_segment(" padded ").unwrap(), "padded");+ }++ #[tokio::test]+ async fn ensure_permanent_store_creates_both_kinds() {+ let data = unique_data_folder();+ let root = ensure_permanent_store(&data).await.unwrap();+ assert!(store_dir(&root, "memory").is_dir());+ assert!(store_dir(&root, "skills").is_dir());+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn thread_workspace_lifecycle_is_idempotent() {+ let data = unique_data_folder();+ let dir = ensure_thread_workspace(&data, "t1").await.unwrap();+ assert!(dir.is_dir());+ ensure_thread_workspace(&data, "t1").await.unwrap();++ remove_thread_workspace(&data, "t1").await.unwrap();+ assert!(!dir.exists());+ remove_thread_workspace(&data, "t1").await.unwrap();+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn sweep_removes_only_unknown_threads() {+ let data = unique_data_folder();+ for id in ["live", "dead", "also-dead"] {+ ensure_thread_workspace(&data, id).await.unwrap();+ }+ let removed = sweep_thread_workspaces(&data, &["live".to_string()])+ .await+ .unwrap();+ assert_eq!(removed, 2);+ assert!(thread_workspace(&data, "live").unwrap().is_dir());+ assert!(!thread_workspace(&data, "dead").unwrap().exists());+ let _ = std::fs::remove_dir_all(&data);+ }++ /// The store sits beside `threads/`, so a sweep must never touch it.+ #[tokio::test]+ async fn sweep_leaves_memory_and_skills_alone() {+ let data = unique_data_folder();+ let store = ensure_permanent_store(&data).await.unwrap();+ ensure_thread_workspace(&data, "dead").await.unwrap();++ sweep_thread_workspaces(&data, &[]).await.unwrap();+ assert!(store_dir(&store, "memory").is_dir());+ assert!(store_dir(&store, "skills").is_dir());+ let _ = std::fs::remove_dir_all(&data);+ }++ #[tokio::test]+ async fn sweep_on_a_fresh_install_is_not_an_error() {+ let data = unique_data_folder();+ assert_eq!(sweep_thread_workspaces(&data, &[]).await.unwrap(), 0);+ }++ #[test]+ fn filename_appends_md_once() {+ assert_eq!(workspace_filename("notes").unwrap(), "notes.md");+ assert_eq!(workspace_filename("notes.md").unwrap(), "notes.md");+ assert_eq!(workspace_filename(" notes ").unwrap(), "notes.md");+ }++ #[test]+ fn filename_rejects_escapes() {+ for bad in ["", " ", "../x", "a/b", "a\\b", "..", "a/../b", "a..b"] {+ assert!(+ workspace_filename(bad).is_err(),+ "expected {bad:?} to be rejected"+ );+ }+ }++ /// Dot-only and empty-stem names are rejected rather than turned into a+ /// hidden file. A bare "." used to yield "..md" -- contained, but a name the+ /// guard would reject as input.+ #[test]+ fn filename_rejects_dot_only_and_empty_stem() {+ for bad in [".", "..", "...", ".md", " .md "] {+ assert!(+ workspace_filename(bad).is_err(),+ "expected {bad:?} to be rejected"+ );+ }+ }+}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/tsconfig.json b/src-tauri/plugins/tauri-plugin-agent-tools/tsconfig.jsonnew file mode 100644index 000000000..059112270--- /dev/null+++ b/src-tauri/plugins/tauri-plugin-agent-tools/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "target": "es2021",+ "module": "esnext",+ "moduleResolution": "bundler",+ "skipLibCheck": true,+ "strict": true,+ "noUnusedLocals": true,+ "noImplicitAny": true,+ "noEmit": true+ },+ "include": ["guest-js/*.ts"],+ "exclude": ["dist-js", "node_modules"]+}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.mdindex b96ca3302..b36b4d85a 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/autogenerated/reference.md@@ -948,6 +948,32 @@ Denies the prioritize_backends command without any pre-configured scope.<tr><td>+`llamacpp:allow-probe-backend-load`++</td>+<td>++Enables the probe_backend_load command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`llamacpp:deny-probe-backend-load`++</td>+<td>++Denies the probe_backend_load command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`llamacpp:allow-read-gguf-metadata`</td>diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.jsonindex 494ee500a..eb6be2a95 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/permissions/schemas/schema.json@@ -702,6 +702,18 @@"const": "deny-prioritize-backends","markdownDescription": "Denies the prioritize_backends command without any pre-configured scope."},+ {+ "description": "Enables the probe_backend_load command without any pre-configured scope.",+ "type": "string",+ "const": "allow-probe-backend-load",+ "markdownDescription": "Enables the probe_backend_load command without any pre-configured scope."+ },+ {+ "description": "Denies the probe_backend_load command without any pre-configured scope.",+ "type": "string",+ "const": "deny-probe-backend-load",+ "markdownDescription": "Denies the probe_backend_load command without any pre-configured scope."+ },{"description": "Enables the read_gguf_metadata command without any pre-configured scope.","type": "string",diff --git a/src-tauri/plugins/yarn.lock b/src-tauri/plugins/yarn.lockindex 29b7f79d1..1a66f5549 100644--- a/src-tauri/plugins/yarn.lock+++ b/src-tauri/plugins/yarn.lock@@ -28,6 +28,18 @@ __metadata:languageName: nodelinkType: hard+"@janhq/tauri-plugin-agent-tools-api@workspace:tauri-plugin-agent-tools":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-agent-tools-api@workspace:tauri-plugin-agent-tools"+ dependencies:+ "@rollup/plugin-typescript": "npm:^12.0.0"+ "@tauri-apps/api": "npm:>=2.0.0-beta.6"+ rollup: "npm:^4.9.6"+ tslib: "npm:^2.6.2"+ typescript: "npm:^5.3.3"+ languageName: unknown+ linkType: soft+"@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@workspace:tauri-plugin-hardware"diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rsindex 385364c50..f5118467d 100644--- a/src-tauri/src/bin/jan.rs+++ b/src-tauri/src/bin/jan.rs@@ -351,6 +351,12 @@ fn make_logo() -> String {#[tokio::main]async fn main() {+ // Exits early if invoked as the Windows sandbox helper for a `bash` tool+ // call: the helper's only job is to spawn the confined shell and wait, so it+ // must run before anything else -- starting the app first would run a second+ // copy per shell command.+ tauri_plugin_agent_tools::run_sandbox_helper_if_requested();+// Pre-scan raw args for --verbose / -v before full parse so we can set// the log level before any logging happens.let verbose = std::env::args().any(|a| a == "--verbose" || a == "-v");@@ -600,7 +606,7 @@ async fn handle_models(cmd: ModelsCommands) {let mut output: Vec<serde_json::Value> = configs.values().filter(|c| app_lib::core::cli::providers::is_cli_reachable(c))- .filter(|c| provider.as_ref().map_or(true, |p| &c.provider == p))+ .filter(|c| provider.as_ref().is_none_or(|p| &c.provider == p)).flat_map(|c| {c.models.iter().map(move |m| {serde_json::json!({diff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rsindex a5e7a84b7..e7721789e 100644--- a/src-tauri/src/core/agent/commands.rs+++ b/src-tauri/src/core/agent/commands.rs@@ -14,15 +14,16 @@ use tokio::sync::{mpsc, oneshot, Mutex};use crate::core::agent::events::StreamEvent;use crate::core::agent::git;-use crate::core::agent::permissions::ToolPermissions;+use tauri_plugin_agent_tools::permissions::ToolPermissions;use crate::core::agent::project::{agent_toml_path, ensure_project, load_agent_config, permissions_from,set_skills_enabled_in_agent_toml,};use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs};use crate::core::agent::skill_hub;-use crate::core::agent::skills::{self, SkillMeta};-use crate::core::agent::tools::gate::PermissionDecision;+use tauri_plugin_agent_tools::skills::{self, SkillMeta};+use tauri_plugin_agent_tools::workspace;+use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use crate::core::app::commands::get_jan_data_folder_path;use crate::core::state::AppState;@@ -171,14 +172,14 @@ fn ui_error(e: String) -> String {#[tauri::command]pub async fn agent_skill_list(project: String) -> Result<Vec<SkillMeta>, String> {let root = std::path::PathBuf::from(&project);- Ok(skills::list_meta(&root))+ Ok(skills::list_meta(&workspace::project_store(&root)))}/// Read one skill's raw SKILL.md (frontmatter included) for the editor.#[tauri::command]pub async fn agent_skill_read(project: String, name: String) -> Result<String, String> {let root = std::path::PathBuf::from(&project);- skills::read_raw(&root, &name).map_err(ui_error)+ skills::read_raw(&workspace::project_store(&root), &name).map_err(ui_error)}/// Create or overwrite a skill. New skills are written as `<name>/SKILL.md`;@@ -191,14 +192,14 @@ pub async fn agent_skill_write() -> Result<(), String> {let root = std::path::PathBuf::from(&project);ensure_project(&root)?;- skills::write(&root, &name, &content).map_err(ui_error)+ skills::write(&workspace::project_store(&root), &name, &content).map_err(ui_error)}/// Delete a skill by name. Idempotent: a missing skill is treated as success.#[tauri::command]pub async fn agent_skill_delete(project: String, name: String) -> Result<(), String> {let root = std::path::PathBuf::from(&project);- skills::delete(&root, &name).map_err(ui_error)+ skills::delete(&workspace::project_store(&root), &name).map_err(ui_error)}/// List the skills available on Anthropic's public skill hub (name + purpose).diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 1b601b2c9..393bc8c8d 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -7,7 +7,7 @@ use std::path::Path;use chrono::Local;use crate::core::agent::git;-use crate::core::agent::skills;+use tauri_plugin_agent_tools::{skills, workspace};/// Default persona used only when no assistant instructions are supplied, so a/// bare project run still opens with a role statement instead of "# Working@@ -80,14 +80,8 @@ const DEFAULT_SKILL_GUIDE: &str = include_str!("default_skill.md");/// Covers folder skills (`<name>/SKILL.md`) and legacy flat `<name>.md`. Returns/// None when no advertisable skill exists.pub(crate) fn load_skills(project_root: &Path) -> Option<String> {- // Honor the project's `[skills].enabled` whitelist (empty = all). Reading the- // config here keeps load_skills self-contained; a missing/malformed config- // falls back to "all skills" rather than erroring.- let enabled = crate::core::agent::project::load_agent_config(project_root)- .ok()- .map(|c| c.skills.enabled)- .unwrap_or_default();- let entries = skills::catalog(project_root, &enabled);+ let enabled = crate::core::agent::project::enabled_skills(project_root);+ let entries = skills::catalog(&workspace::project_store(project_root), &enabled);if entries.is_empty() {return None;}diff --git a/src-tauri/src/core/agent/git.rs b/src-tauri/src/core/agent/git.rsindex 1ffd41b25..6cf5df3d5 100644--- a/src-tauri/src/core/agent/git.rs+++ b/src-tauri/src/core/agent/git.rs@@ -18,7 +18,7 @@//! touched. Shelling out keeps us free of a libgit2 dependency.use std::path::Path;-#[cfg(any(feature = "cli", test))]+#[cfg(feature = "cli")]use std::path::PathBuf;use std::process::Command;diff --git a/src-tauri/src/core/agent/interaction.rs b/src-tauri/src/core/agent/interaction.rsindex b009e14da..4c8b97cd3 100644--- a/src-tauri/src/core/agent/interaction.rs+++ b/src-tauri/src/core/agent/interaction.rs@@ -187,6 +187,9 @@ pub(crate) fn ask_tool_schema() -> Value {})}+// Only the TUI owns an ask registry; the desktop `ask` IPC surface is not wired+// up yet, so these are absent from that build.+#[cfg(any(feature = "cli", test))]pub(crate) fn new_registry() -> AskRegistry {Arc::new(Mutex::new(HashMap::new()))}@@ -213,6 +216,7 @@ pub(crate) async fn respond(.map_err(|_| format!("ask request '{request_id}' is no longer pending"))}+#[cfg(any(feature = "cli", test))]pub(crate) async fn cancel_all(registry: &AskRegistry) {let pending = std::mem::take(&mut *registry.lock().await);for (_, sender) in pending {diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 85b588a2d..d66e70817 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -15,7 +15,7 @@ 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 tauri_plugin_agent_tools::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,@@ -61,7 +61,7 @@ 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 permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,pub project_root: Option<std::path::PathBuf>,pub permission_requests: PermissionRegistry,/// Present only when a client can render and answer structured questions.@@ -191,18 +191,101 @@ struct SubagentContext {struct CompositeToolInvoker {mcp: McpToolInvoker,project_root: std::path::PathBuf,- permissions: crate::core::agent::permissions::ToolPermissions,+ /// Where `memory/` and `skills/` live. Co-located with the project here, so+ /// the on-disk layout is unchanged; the desktop points this at its permanent+ /// store instead.+ store_root: std::path::PathBuf,+ /// `[skills].enabled`, resolved once per run. The toolset owns no config+ /// format, so the whitelist is injected rather than re-read per tool call.+ enabled_skills: Vec<String>,+ /// Whether the sandboxed shell keeps its network namespace. Resolved once+ /// per run from `[tools].allow_network`, falling back to the surface+ /// default when unset.+ allow_network: bool,+ /// Whether the sandboxed shell may read `$HOME`. Resolved once per run+ /// from `[tools].allow_home_read`, falling back to `true` on the CLI.+ allow_home_read: bool,+ permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,events: mpsc::UnboundedSender<StreamEvent>,permission_requests: PermissionRegistry,ask_requests: Option<crate::core::agent::interaction::AskRegistry>,todo_registry: Option<crate::core::agent::todo::TodoRegistry>,- grants: std::sync::Mutex<crate::core::agent::tools::gate::SessionGrants>,+ grants: std::sync::Mutex<tauri_plugin_agent_tools::tools::gate::SessionGrants>,subagents: Option<SubagentContext>,yolo: bool,run_mode: crate::core::agent::plan::RunMode,}+/// Default for the sandboxed shell's network namespace, used when+/// `[tools].allow_network` is unset.+///+/// The CLI agent runs in the user's own terminal against their own project, and+/// every exec is already gated behind an interactive prompt, so the network is+/// not what confines it -- the user is. Before the shell was sandboxed at all it+/// ran fully unconfined, and a coding agent that cannot `curl`, `git fetch`, or+/// install a package is largely useless, so the sandbox keeps the network and+/// relies on the prompt.+///+/// The desktop chat sandbox makes the opposite trade: it is ephemeral, has no+/// prompt, and opts in per call from a user setting (`commands.rs`).+#[cfg(feature = "cli")]+const DEFAULT_ALLOW_NETWORK: bool = true;+#[cfg(not(feature = "cli"))]+const DEFAULT_ALLOW_NETWORK: bool = false;++/// `[tools].allow_network` wins over the surface default when set.+fn resolve_allow_network(configured: Option<bool>) -> bool {+ configured.unwrap_or(DEFAULT_ALLOW_NETWORK)+}++/// Default for whether the sandboxed shell can read `$HOME`, used when+/// `[tools].allow_home_read` is unset.+///+/// The CLI needs it for `git`/`ssh` credential helpers, so its shell binds+/// `$HOME` read-only. The desktop keeps the full isolation and masks the home+/// (the Jan data folder lives inside `$HOME`, so exposing it read-only would+/// leak `settings.json` API keys, thread workspaces, and the memory store).+#[cfg(feature = "cli")]+const DEFAULT_ALLOW_HOME_READ: bool = true;+#[cfg(not(feature = "cli"))]+const DEFAULT_ALLOW_HOME_READ: bool = false;++/// `[tools].allow_home_read` wins over the surface default when set.+fn resolve_allow_home_read(configured: Option<bool>) -> bool {+ configured.unwrap_or(DEFAULT_ALLOW_HOME_READ)+}++/// agent.toml resolved for one run: the skill whitelist, plus the network+/// decision with this surface's default already applied.+struct ResolvedSettings {+ enabled_skills: Vec<String>,+ allow_network: bool,+ allow_home_read: bool,+}++/// Kept out of the invoker's struct literal so it is reachable from a test.+/// Inline, it was silently passing `None` instead of the parsed value, which+/// made `[tools].allow_network` a no-op that nothing detected.+fn resolve_run_settings(project_root: &std::path::Path) -> ResolvedSettings {+ let settings = crate::core::agent::project::run_settings(project_root);+ ResolvedSettings {+ enabled_skills: settings.enabled_skills,+ allow_network: resolve_allow_network(settings.allow_network),+ allow_home_read: resolve_allow_home_read(settings.allow_home_read),+ }+}+impl CompositeToolInvoker {+ fn tool_context(&self) -> tauri_plugin_agent_tools::tools::ToolContext<'_> {+ tauri_plugin_agent_tools::tools::ToolContext::new(+ &self.project_root,+ &self.store_root,+ &self.enabled_skills,+ )+ .with_network(self.allow_network)+ .with_home_readonly(self.allow_home_read)+ }+/// Prompt the user to approve an MCP tool call, mirroring the built-in gate./// A dropped responder (client gone / run cancelled) resolves to Deny.async fn prompt_mcp_permission(&self, tool_name: &str) -> PermissionDecision {@@ -494,10 +577,10 @@ impl ToolInvoker for CompositeToolInvoker {&self,tool_calls: &[serde_json::Value],) -> Result<Vec<ToolOutcome>, String> {- use crate::core::agent::tools::{+ use tauri_plugin_agent_tools::tools::{gate::{resolve_decision, Decision, PromptKind},handlers::{execute_builtin_with_diff, preview_diff},- is_builtin, lookup, Capability,+ is_builtin, lookup, Capability, ToolContext,};let mut out: Vec<ToolOutcome> = Vec::with_capacity(tool_calls.len());let mut mcp_calls: Vec<serde_json::Value> = Vec::new();@@ -641,9 +724,18 @@ impl ToolInvoker for CompositeToolInvoker {if matches!(decision, Decision::Allow)&& matches!(tool.capability, Capability::Read | Capability::Net){+ // The future outlives this borrow of `self`, so it owns its roots+ // and builds the context inside.let root = self.project_root.clone();+ let store = self.store_root.clone();+ let enabled = self.enabled_skills.clone();+ let allow_network = self.allow_network;+ let allow_home_read = self.allow_home_read;read_futures.push(async move {- let (text, diff) = execute_builtin_with_diff(tool, &args, &root).await;+ let ctx = ToolContext::new(&root, &store, &enabled)+ .with_network(allow_network)+ .with_home_readonly(allow_home_read);+ let (text, diff) = execute_builtin_with_diff(tool, &args, &ctx).await;ToolOutcome {id,content: text,@@ -653,7 +745,7 @@ impl ToolInvoker for CompositeToolInvoker {continue;}let (text, diff) = match decision {- Decision::Allow => execute_builtin_with_diff(tool, &args, &self.project_root).await,+ Decision::Allow => execute_builtin_with_diff(tool, &args, &self.tool_context()).await,Decision::HardDeny => (denied_by_policy_msg(name, &self.project_root), None),Decision::Prompt(kind) => {let request_id = next_permission_id();@@ -673,6 +765,7 @@ impl ToolInvoker for CompositeToolInvoker {let prompt_kind = match kind {PromptKind::ReadEscape => "read_escape",PromptKind::Write => "write",+ PromptKind::WriteEscape => "write_escape",PromptKind::Exec => "exec",};let path = tool@@ -685,7 +778,7 @@ impl ToolInvoker for CompositeToolInvoker {.then(|| args.get("command").and_then(|v| v.as_str())).flatten().map(String::from);- let diff = preview_diff(tool, &args, &self.project_root).await;+ let diff = preview_diff(tool, &args, &self.tool_context()).await;let _ = self.events.send(StreamEvent::PermissionRequest {request_id: request_id.clone(),tool_name: name.to_string(),@@ -703,7 +796,7 @@ impl ToolInvoker for CompositeToolInvoker {self.permission_requests.lock().await.remove(&request_id);match decision {PermissionDecision::AllowOnce => {- execute_builtin_with_diff(tool, &args, &self.project_root).await+ execute_builtin_with_diff(tool, &args, &self.tool_context()).await}PermissionDecision::AllowAlways => {// Thread-scoped only; never persisted to agent.toml.@@ -717,7 +810,7 @@ impl ToolInvoker for CompositeToolInvoker {} else {self.grants.lock().unwrap().grant(kind);}- execute_builtin_with_diff(tool, &args, &self.project_root).await+ execute_builtin_with_diff(tool, &args, &self.tool_context()).await}PermissionDecision::Deny => {(format!("ERROR: tool '{name}' denied by user"), None)@@ -771,7 +864,7 @@ 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(),+ permissions: tauri_plugin_agent_tools::permissions::ToolPermissions::allow_all(),project_root: None,permission_requests: Arc::new(Mutex::new(HashMap::new())),ask_requests: None,@@ -836,7 +929,7 @@ fn apply_tool_allowlist(fn retain_advertisable_mcp_tools(openai_tools: &mut Vec<serde_json::Value>,tool_to_server: &mut HashMap<String, String>,- permissions: &crate::core::agent::permissions::ToolPermissions,+ permissions: &tauri_plugin_agent_tools::permissions::ToolPermissions,) {openai_tools.retain(|t| {t.get("function")@@ -1167,7 +1260,7 @@ async fn orchestrate_inner(// 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.- for schema in crate::core::agent::tools::schema::builtin_tool_schemas() {+ for schema in tauri_plugin_agent_tools::tools::schema::builtin_tool_schemas() {let name = schema["function"]["name"].as_str().unwrap_or_default();if permissions.is_denied(name) {continue;@@ -1175,11 +1268,11 @@ async fn orchestrate_inner(// Plan mode advertises only read/net builtins; write/exec are hidden// entirely rather than relying on a prompt or execution-time denial.if run_mode == crate::core::agent::plan::RunMode::Plan- && crate::core::agent::tools::lookup(name).is_some_and(|t| {+ && tauri_plugin_agent_tools::tools::lookup(name).is_some_and(|t| {matches!(t.capability,- crate::core::agent::tools::Capability::Write- | crate::core::agent::tools::Capability::Exec+ tauri_plugin_agent_tools::tools::Capability::Write+ | tauri_plugin_agent_tools::tools::Capability::Exec)}){@@ -1289,15 +1382,20 @@ async fn orchestrate_inner(max_session_tokens,bg: bg.clone(),});+ let settings = resolve_run_settings(root);let tools = CompositeToolInvoker {mcp: mcp_tools,+ store_root: tauri_plugin_agent_tools::workspace::project_store(root),+ enabled_skills: settings.enabled_skills,+ allow_network: settings.allow_network,+ allow_home_read: settings.allow_home_read,project_root: root.clone(),permissions: permissions.clone(),events: events.clone(),permission_requests: permission_requests.clone(),ask_requests: ask_requests.clone(),todo_registry: todo_registry.clone(),- grants: std::sync::Mutex::new(crate::core::agent::tools::gate::SessionGrants::default()),+ grants: std::sync::Mutex::new(tauri_plugin_agent_tools::tools::gate::SessionGrants::default()),subagents,yolo: *yolo,run_mode,@@ -1709,7 +1807,7 @@ async fn run_turn_cycle(// call as failed for display.let is_error = content.starts_with("ERROR")|| (tool_names.get(id.as_str()) == Some(&"bash")- && crate::core::agent::tools::handlers::bash_result_failed(&content));+ && tauri_plugin_agent_tools::tools::handlers::bash_result_failed(&content));let name = tool_names.get(id.as_str()).copied().unwrap_or("");if name == "todo" {todo_touched_this_batch = true;@@ -2545,8 +2643,8 @@ 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 tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};+ use tauri_plugin_agent_tools::tools::gate::{PermissionDecision, SessionGrants};use std::sync::atomic::{AtomicUsize, Ordering};static TEST_ROOT_SEQ: AtomicUsize = AtomicUsize::new(0);@@ -2581,6 +2679,10 @@ mod tests {mcp_servers: Arc::new(Mutex::new(HashMap::new())),mcp_settings: Arc::new(Mutex::new(McpSettings::default())),},+ store_root: tauri_plugin_agent_tools::workspace::project_store(&root),+ enabled_skills: Vec::new(),+ allow_network: DEFAULT_ALLOW_NETWORK,+ allow_home_read: DEFAULT_ALLOW_HOME_READ,project_root: root,// Read-only default => write PROMPTS.permissions: ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),@@ -2595,6 +2697,134 @@ mod tests {}}+ /// The whole point of the setting: what agent.toml says has to survive the+ /// trip into the invoker. This is the assertion that was missing when the+ /// resolution passed `None` and silently ignored the file.+ #[test]+ fn agent_toml_network_setting_reaches_the_invoker() {+ let root = std::env::temp_dir().join(format!(+ "jan_loop_net_{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let agent_dir = root.join(".jan").join("agent");+ std::fs::create_dir_all(&agent_dir).expect("create agent dir");++ let write = |body: &str| {+ std::fs::write(agent_dir.join("agent.toml"), body).expect("write agent.toml")+ };++ write("[tools]\nallow_network = false\n[skills]\nenabled = [\"deploy\"]\n");+ let denied = resolve_run_settings(&root);+ assert!(!denied.allow_network, "explicit false must be honoured");+ assert_eq!(denied.enabled_skills, vec!["deploy".to_string()]);++ write("[tools]\nallow_network = true\n");+ assert!(+ resolve_run_settings(&root).allow_network,+ "explicit true must be honoured"+ );++ write("[tools]\ndefault = \"read-only\"\n");+ assert_eq!(+ resolve_run_settings(&root).allow_network,+ DEFAULT_ALLOW_NETWORK,+ "unset must fall back to the surface default"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ /// An explicit `[tools].allow_network` overrides the surface default in both+ /// directions, so a project can lock the shell down or open it up whichever+ /// way its surface leans.+ #[test]+ fn configured_allow_network_overrides_the_default() {+ assert!(resolve_allow_network(Some(true)));+ assert!(!resolve_allow_network(Some(false)));+ assert_eq!(resolve_allow_network(None), DEFAULT_ALLOW_NETWORK);+ }++ /// `[tools].allow_home_read` likewise overrides the CLI default (on by+ /// default) in both directions, so a project can lock `$HOME` back down.+ #[test]+ fn configured_allow_home_read_overrides_the_default() {+ assert!(resolve_allow_home_read(Some(true)));+ assert!(!resolve_allow_home_read(Some(false)));+ assert_eq!(resolve_allow_home_read(None), DEFAULT_ALLOW_HOME_READ);+ }++ /// The CLI agent's shell keeps its network namespace. Before the sandbox+ /// existed this shell ran fully unconfined, so flipping this to `false`+ /// silently breaks `curl`, `git fetch` and package installs while every+ /// test that does not actually open a socket keeps passing.+ #[test]+ #[cfg(feature = "cli")]+ fn cli_tool_context_allows_network() {+ let root = std::path::PathBuf::from("/tmp/jan-net-check");+ let (tx, _rx) = mpsc::unbounded_channel();+ let invoker = build_prompting_invoker(+ root,+ tx,+ Arc::new(tokio::sync::Mutex::new(HashMap::new())),+ );+ assert!(+ invoker.tool_context().allow_network,+ "CLI shell must keep its network namespace"+ );+ }++ /// The CLI shell reads `$HOME` (so git/ssh credential helpers work) unless+ /// the project explicitly opts out.+ #[test]+ #[cfg(feature = "cli")]+ fn cli_tool_context_reads_home() {+ let root = std::path::PathBuf::from("/tmp/jan-home-check");+ let (tx, _rx) = mpsc::unbounded_channel();+ let invoker = build_prompting_invoker(+ root,+ tx,+ Arc::new(tokio::sync::Mutex::new(HashMap::new())),+ );+ assert!(+ invoker.tool_context().home_readonly,+ "CLI shell must read $HOME"+ );+ }++ /// The desktop keeps the full isolation: the sandbox masks `$HOME` rather+ /// than binding it read-only, so the Jan data folder (which lives inside+ /// `$HOME`) stays unreadable.+ #[test]+ #[cfg(not(feature = "cli"))]+ fn desktop_tool_context_withholds_home() {+ let root = std::path::PathBuf::from("/tmp/jan-home-check");+ let (tx, _rx) = mpsc::unbounded_channel();+ let invoker = build_prompting_invoker(+ root,+ tx,+ Arc::new(tokio::sync::Mutex::new(HashMap::new())),+ );+ assert!(!invoker.tool_context().home_readonly);+ }++ /// The desktop chat sandbox is ephemeral and unprompted, so it opts in per+ /// call from a user setting instead of defaulting on here.+ #[test]+ #[cfg(not(feature = "cli"))]+ fn desktop_tool_context_withholds_network() {+ let root = std::path::PathBuf::from("/tmp/jan-net-check");+ let (tx, _rx) = mpsc::unbounded_channel();+ let invoker = build_prompting_invoker(+ root,+ tx,+ Arc::new(tokio::sync::Mutex::new(HashMap::new())),+ );+ assert!(!invoker.tool_context().allow_network);+ }+async fn respond_once(rx: &mut mpsc::UnboundedReceiver<StreamEvent>,registry: &PermissionRegistry,@@ -3140,7 +3370,7 @@ mod tests {#[test]fn read_only_project_still_advertises_mcp_tools() {- use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};+ use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};let mut tools = vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];let mut map = HashMap::from([("web_search_exa".to_string(), "exa".to_string())]);// The scaffolded CLI project default: read-only, no allow-list.@@ -3154,7 +3384,7 @@ mod tests {#[test]fn denied_mcp_tool_is_not_advertised() {- use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};+ use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};let mut tools = vec![json!({ "type": "function", "function": { "name": "web_search_exa" } }),json!({ "type": "function", "function": { "name": "dangerous_write" } }),@@ -3179,7 +3409,7 @@ mod tests {#[test]fn deny_default_advertises_no_mcp_tools() {- use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};+ use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};let mut tools = vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];let mut map = HashMap::from([("web_search_exa".to_string(), "exa".to_string())]);let perms = ToolPermissions::new(PermissionDefault::Deny, &[], &[], &[]);diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex 43eaa52b3..beaa08539 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -1,5 +1,10 @@//! Shared agent orchestration: the server-side loop and its upstream/provider//! plumbing, consumed by both the API-server proxy and `tauri-plugin-agent`.+//!+//! The toolset the loop drives -- the built-in tools, their capability gate,+//! permissions, and skill storage -- lives in `tauri_plugin_agent_tools`, which+//! builds with or without Tauri so the desktop app and the headless CLI share+//! one implementation. This module owns orchestration only.// Tauri IPC surface for the desktop agent; the CLI drives the loop directly.#[cfg(not(feature = "cli"))]@@ -15,13 +20,10 @@ pub mod global_config;pub mod git;pub mod r#loop;pub mod memory;-pub mod permissions;pub mod plan;pub mod project;pub mod session;pub mod skill_hub;-pub mod skills;pub mod todo;pub mod subagent;-pub mod tools;pub mod upstream;diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex ec975846f..ad176775b 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -4,7 +4,7 @@ use std::path::{Path, PathBuf};use serde::Deserialize;-use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};+use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};/// `[tools]` is always modeled. `[agent]` is only compiled for the CLI (its/// sole consumer, via `jan cli agent run/step/status`); serde still ignores the@@ -93,6 +93,18 @@ pub(crate) struct ToolsSection {pub deny: Vec<String>,#[serde(default)]pub allow_write: Vec<String>,+ /// Whether the sandboxed shell keeps its network namespace. `None` (unset)+ /// leaves the choice to the surface running the loop, which differ: the CLI+ /// prompts before every exec and allows it, the desktop's ephemeral chat+ /// sandbox does not and denies it.+ #[serde(default)]+ pub allow_network: Option<bool>,+ /// Whether the sandboxed shell may read the user's home directory (the+ /// CLI, for `git`/`ssh` credential helpers). `None` (unset) leaves the+ /// choice to the surface: the CLI defaults to true, the desktop masks+ /// `$HOME` entirely. Writes are confined to the workspace either way.+ #[serde(default)]+ pub allow_home_read: Option<bool>,}const AGENT_TOML_TEMPLATE: &str = r#"[agent]@@ -127,6 +139,14 @@ deny = []# Write tools are opt-in only:# allow_write = ["fs.write"]allow_write = []+# Whether the sandboxed shell can reach the network. Unset follows the surface+# running the agent: the CLI allows it (every exec is prompted first), the+# desktop's throwaway chat sandbox does not.+# allow_network = true+# Whether the sandboxed shell can read your home directory (for git/ssh+# credential helpers and ~/.ssh/config). Unset follows the surface: the CLI+# allows it (true), the desktop masks $HOME. Writes stay in the workspace.+# allow_home_read = true[skills]enabled = []@@ -150,6 +170,40 @@ pub(crate) fn load_agent_config(project_root: &Path) -> Result<AgentToml, Stringtoml::from_str(&raw).map_err(|e| format!("Failed to parse {}: {e}", path.display()))}+/// The per-run knobs a `ToolContext` needs from agent.toml.+///+/// The toolset owns no config format, so this is the one place that maps+/// agent.toml onto a `ToolContext`. Resolved once per run rather than per tool+/// call, and in a single parse rather than one per field.+#[derive(Debug, Clone, Default)]+pub(crate) struct RunSettings {+ /// `[skills].enabled` (empty = every skill).+ pub enabled_skills: Vec<String>,+ /// `[tools].allow_network`; `None` when unset, so the caller applies the+ /// default appropriate to its surface.+ pub allow_network: Option<bool>,+ /// `[tools].allow_home_read`; `None` when unset, so the caller applies the+ /// default appropriate to its surface.+ pub allow_home_read: Option<bool>,+}++/// A missing or malformed config yields defaults rather than an error: a project+/// without an agent.toml should still run, advertising all of its skills.+pub(crate) fn run_settings(project_root: &Path) -> RunSettings {+ let Ok(cfg) = load_agent_config(project_root) else {+ return RunSettings::default();+ };+ RunSettings {+ enabled_skills: cfg.skills.enabled,+ allow_network: cfg.tools.allow_network,+ allow_home_read: cfg.tools.allow_home_read,+ }+}++pub(crate) fn enabled_skills(project_root: &Path) -> Vec<String> {+ run_settings(project_root).enabled_skills+}+/// Build a `ToolPermissions` from the parsed `[tools]` section.pub(crate) fn permissions_from(cfg: &AgentToml) -> ToolPermissions {let default = cfg@@ -289,6 +343,76 @@ mod tests {root}+ /// `ensure_project` scaffolds `.jan/agent/{skills,memory}` by hand, while the+ /// toolset resolves those same directories through `workspace::project_store`.+ /// Nothing but this test ties the two together, and if they ever drift a+ /// user's existing skills and memories simply stop being found.+ #[test]+ fn scaffolded_dirs_match_the_toolset_store_layout() {+ use tauri_plugin_agent_tools::workspace;++ let root = unique_root("store_layout");+ ensure_project(&root).expect("scaffold project");++ let store = workspace::project_store(&root);+ assert_eq!(store, root.join(".jan").join("agent"));+ assert!(+ tauri_plugin_agent_tools::skills::skills_dir(&store).is_dir(),+ "skills dir the toolset reads is not the one ensure_project created"+ );+ assert!(+ workspace::store_dir(&store, "memory").is_dir(),+ "memory dir the toolset reads is not the one ensure_project created"+ );++ let _ = std::fs::remove_dir_all(&root);+ }++ fn write_agent_toml(root: &Path, body: &str) {+ let dir = root.join(".jan").join("agent");+ std::fs::create_dir_all(&dir).expect("create agent dir");+ std::fs::write(dir.join("agent.toml"), body).expect("write agent.toml");+ }++ #[test]+ fn run_settings_reads_allow_network_both_ways() {+ let root = unique_root("allow_net");+ write_agent_toml(&root, "[tools]\nallow_network = true\n");+ assert_eq!(run_settings(&root).allow_network, Some(true));++ write_agent_toml(&root, "[tools]\nallow_network = false\n");+ assert_eq!(run_settings(&root).allow_network, Some(false));++ let _ = std::fs::remove_dir_all(&root);+ }++ /// Unset must stay `None` rather than collapsing to `false`, or the caller+ /// cannot tell "explicitly denied" from "not configured" and every CLI+ /// project silently loses the network.+ #[test]+ fn run_settings_leaves_unset_allow_network_undecided() {+ let root = unique_root("allow_net_unset");++ write_agent_toml(&root, "[tools]\ndefault = \"read-only\"\n");+ assert_eq!(run_settings(&root).allow_network, None);++ // A project with no agent.toml at all resolves the same way.+ let bare = unique_root("allow_net_bare");+ assert_eq!(run_settings(&bare).allow_network, None);++ let _ = std::fs::remove_dir_all(&root);+ let _ = std::fs::remove_dir_all(&bare);+ }++ /// The scaffold documents the key, so it has to stay parseable as written.+ #[test]+ fn scaffold_template_parses_with_allow_network_documented() {+ let cfg: AgentToml =+ toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");+ assert_eq!(cfg.tools.allow_network, None);+ assert!(AGENT_TOML_TEMPLATE.contains("allow_network"));+ }+#[test]fn ensure_errors_when_project_dir_missing() {// A mistyped --project (e.g. wrong case) must fail fast, not scaffold adiff --git a/src-tauri/src/core/agent/skill_hub.rs b/src-tauri/src/core/agent/skill_hub.rsindex a6db2e4ac..0f1b64ff9 100644--- a/src-tauri/src/core/agent/skill_hub.rs+++ b/src-tauri/src/core/agent/skill_hub.rs@@ -10,7 +10,7 @@ use std::path::Path;use futures::future::join_all;-use crate::core::agent::skills;+use tauri_plugin_agent_tools::{skills, workspace};const TREE_URL: &str ="https://api.github.com/repos/anthropics/skills/git/trees/main?recursive=1";@@ -152,8 +152,9 @@ pub async fn import(root: &Path, name: &str) -> Result<(), String> {}// Phase 2: replace the destination with the freshly fetched files.- let dest_root = skills::skills_dir(root).join(&stem);- let flat = skills::skills_dir(root).join(format!("{stem}.md"));+ let skills_dir = skills::skills_dir(&workspace::project_store(root));+ let dest_root = skills_dir.join(&stem);+ let flat = skills_dir.join(format!("{stem}.md"));let _ = tokio::fs::remove_dir_all(&dest_root).await;let _ = tokio::fs::remove_file(&flat).await; // drop a legacy flat form, if anyfor (rel, bytes) in fetched {diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex b2f794ce8..6c7a4d27b 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};-use crate::core::agent::permissions::ToolPermissions;+use tauri_plugin_agent_tools::permissions::ToolPermissions;#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]@@ -921,7 +921,7 @@ pub fn subagent_dir_for(#[cfg(test)]mod tests {use super::*;- use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};+ use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};use std::sync::atomic::{AtomicU32, Ordering};static COUNTER: AtomicU32 = AtomicU32::new(0);diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex d5cd56b1c..d7054b3b2 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -368,7 +368,7 @@ use crate::core::agent::project::{use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,};-use crate::core::agent::tools::gate::PermissionDecision;+use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use crate::core::cli::providers::{load_provider_configs, ProviderOverrides};use crate::core::mcp::models::McpSettings;use std::collections::HashMap;@@ -428,6 +428,8 @@ pub fn cli_agent_status("allow": cfg.tools.allow,"deny": cfg.tools.deny,"allow_write": cfg.tools.allow_write,+ "allow_network": cfg.tools.allow_network,+ "allow_home_read": cfg.tools.allow_home_read,},"providers": providers,}))@@ -516,7 +518,7 @@ pub async fn cli_agent_step(#[allow(clippy::too_many_arguments)]fn build_cli_orchestration_args(project_root: PathBuf,- permissions: crate::core::agent::permissions::ToolPermissions,+ permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,provider_configs: HashMap<String, crate::core::state::ProviderConfig>,mcp_servers: crate::core::state::SharedMcpServers,mcp_settings: McpSettings,diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex f2840303d..e85b66506 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -43,7 +43,7 @@ use super::{sort_threads_recent, AgentSession, ResumeTarget};use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};use crate::core::agent::git;use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};-use crate::core::agent::tools::gate::PermissionDecision;+use tauri_plugin_agent_tools::tools::gate::PermissionDecision;#[derive(Debug, PartialEq)]enum Status {@@ -99,7 +99,7 @@ impl Pending {/// sees exactly what a grant covers (`git status && rm foo` -> git AND rm);/// commands that can't be decomposed grant only their exact text.fn always_label(&self) -> String {- use crate::core::agent::tools::cmdscan::{scan_command, CommandScan};+ use tauri_plugin_agent_tools::tools::cmdscan::{scan_command, CommandScan};let Some(command) = self.command.as_deref() else {return "Allow always (this thread)".to_string();};@@ -3056,8 +3056,7 @@ fn assistant_is_awaiting_user_answer(text: &str) -> bool {let Some(last_line) = text.split(['\n', '\r']).map(str::trim)- .filter(|l| !l.is_empty())- .next_back()+ .rfind(|l| !l.is_empty())else {return false;};@@ -3563,6 +3562,9 @@ async fn chat_loop<B: Backend>(}}},+ // `handle_ask_mouse` mutates app state, so it stays in the+ // arm body rather than a match guard that hides the effect.+ #[allow(clippy::collapsible_match)]Ok(Event::Mouse(mouse)) => {if !handle_ask_mouse(app, mouse, ask_requests).await {handle_mouse(app, mouse);@@ -6019,7 +6021,7 @@ fn draw(f: &mut Frame, app: &mut App) {.map(|block| block.detail.clone())});if let Some(detail) = detail {- row_index.extend(std::iter::repeat(Some(i)).take(detail.len()));+ row_index.extend(std::iter::repeat_n(Some(i), detail.len()));lines.extend(detail);}}@@ -7373,7 +7375,7 @@ mod tests {use crate::core::agent::events::{StreamEvent, Usage};use crate::core::cli::updater::{AvailableUpdate, UpdateOutcome};use crate::core::agent::r#loop::PermissionRegistry;- use crate::core::agent::tools::gate::PermissionDecision;+ use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use serde_json::json;use std::collections::HashMap;use std::sync::Arc;diff --git a/src-tauri/src/core/openai_schema.rs b/src-tauri/src/core/openai_schema.rsindex b3ef4fbfb..62997f2ba 100644--- a/src-tauri/src/core/openai_schema.rs+++ b/src-tauri/src/core/openai_schema.rs@@ -139,7 +139,9 @@ pub(crate) fn normalize_openai_tool_parameters_schema(schema: &mut serde_json::V}}-#[cfg(any(not(feature = "cli"), test))]+// Only the desktop proxy calls this, and its tests live in `core::server`, which+// is itself absent from the CLI build.+#[cfg(not(feature = "cli"))]pub(crate) fn normalize_openai_tools_in_chat_body(body: &mut serde_json::Value) {let tools = match body.get_mut("tools") {Some(t) => t,diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rsindex 6377e94c2..7c56b8c7d 100644--- a/src-tauri/src/core/server/proxy.rs+++ b/src-tauri/src/core/server/proxy.rs@@ -702,7 +702,7 @@ async fn proxy_request(} else if !host.is_empty() {log::debug!("CORS preflight: Host is '{host}', trusted hosts: {:?}",- &config.trusted_hosts+ config.trusted_hosts);is_valid_host(host, &config.trusted_hosts)} else {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 5496d1629..7c4dbb9d3 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -198,7 +198,7 @@ async fn handle_graceful_exit<R: tauri::Runtime>(use std::sync::atomic::Ordering;// Reap any still-running agent bash command trees before we tear down, so// no shell (or child it spawned) outlives the app.- crate::core::agent::tools::proc::kill_all();+ tauri_plugin_agent_tools::tools::proc::kill_all();let mut emitted = false;loop {if SHUTTING_DOWN.load(Ordering::SeqCst) {@@ -263,7 +263,8 @@ pub fn run() {.plugin(tauri_plugin_llamacpp::init()).plugin(tauri_plugin_vector_db::init()).plugin(tauri_plugin_rag::init())- .plugin(tauri_plugin_websearch::init());+ .plugin(tauri_plugin_websearch::init())+ .plugin(tauri_plugin_agent_tools::init());#[cfg(feature = "deep-link")]{diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 3de5058cb..52c246af5 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -9,5 +9,8 @@ fn main() {// Exits early if invoked as the out-of-process lddtree helper.tauri_plugin_llamacpp::deps_analyzer::run_deps_analyzer_if_requested();+ // Exits early if invoked as the Windows sandbox helper for a `bash` tool call.+ tauri_plugin_agent_tools::run_sandbox_helper_if_requested();+app_lib::run();}diff --git a/web-app/package.json b/web-app/package.jsonindex 4ed1d76f2..456ae45f8 100644--- a/web-app/package.json+++ b/web-app/package.json@@ -24,6 +24,7 @@"@dnd-kit/sortable": "10.0.0","@janhq/core": "workspace:*","@janhq/interfaces": "0.0.2",+ "@janhq/tauri-plugin-agent-tools-api": "link:../src-tauri/plugins/tauri-plugin-agent-tools","@janhq/tauri-plugin-llamacpp-api": "link:../src-tauri/plugins/tauri-plugin-llamacpp","@janhq/tauri-plugin-websearch-api": "link:../src-tauri/plugins/tauri-plugin-websearch","@radix-ui/react-accordion": "1.2.11",diff --git a/web-app/src/components/FilePickerPopover.tsx b/web-app/src/components/FilePickerPopover.tsxindex a8cd01afe..28862c906 100644--- a/web-app/src/components/FilePickerPopover.tsx+++ b/web-app/src/components/FilePickerPopover.tsx@@ -196,53 +196,3 @@ export function FilePickerPopover({</div>)}--// ─── Expose imperative controls for the parent to forward keyboard events ────-export type FilePickerHandle = {- handleKeyDown: (e: React.KeyboardEvent) => void- activeIndex: number- entries: FilePickerEntry[]-}--export function useFilePickerKeyboard(open: boolean) {- const [activeIndex, setActiveIndex] = useState(0)- const [entries, setEntries] = useState<FilePickerEntry[]>([])-- const handleKeyDown = useCallback(- (e: React.KeyboardEvent) => {- if (!open || entries.length === 0) return-- switch (e.key) {- case 'ArrowDown':- e.preventDefault()- setActiveIndex((prev) => Math.min(prev + 1, entries.length - 1))- break- case 'ArrowUp':- e.preventDefault()- setActiveIndex((prev) => Math.max(prev - 1, 0))- break- case 'Enter':- case 'Tab': {- if (entries[activeIndex]) {- e.preventDefault()- return { selected: entries[activeIndex] } as const- }- break- }- case 'Escape':- e.preventDefault()- return { dismissed: true } as const- }- return undefined- },- [open, entries, activeIndex]- )-- return {- activeIndex,- setActiveIndex,- entries,- setEntries,- handleKeyDown,- }-}diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex 9450dc1b6..59a557a1a 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -11,6 +11,7 @@ export const localStorageKey = {settingLocalApiServer: 'setting-local-api-server',settingProxyConfig: 'setting-proxy-config',settingWebSearch: 'setting-web-search',+ settingAgentTools: 'setting-agent-tools',settingHardware: 'setting-hardware',settingVulkan: 'setting-vulkan',productAnalyticPrompt: 'productAnalyticPrompt',diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex e1e9fbf16..d1df028cc 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -19,6 +19,7 @@ export const route = {mcp_servers: '/settings/mcp-servers',https_proxy: '/settings/https-proxy',web_search: '/settings/web-search',+ agent_tools: '/settings/agent-tools',hardware: '/settings/hardware',assistant: '/settings/assistant',claude_code: '/settings/claude-code',diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex f032531f8..dae421e01 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -32,6 +32,7 @@ import {IconPaperclip,IconLoader2,IconWorldSearch,+ IconFolderCode,IconBrandChrome,} from '@tabler/icons-react'import { generateId } from 'ai'@@ -109,6 +110,7 @@ import {type FilePickerEntry as FileEntry,} from '@/lib/path-references'import { FilePickerPopover } from '@/components/FilePickerPopover'+import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'type ChatInputProps = {className?: string@@ -194,6 +196,10 @@ const ChatInput = memo(function ChatInput({const toggleAgentMode = useAgentMode((state) => state.toggleAgentMode)const webSearchEnabled = useWebSearchConfig((s) => s.webSearchEnabled)const setWebSearchEnabled = useWebSearchConfig((s) => s.setWebSearchEnabled)+ const agentToolsEnabled = useAgentToolsConfig((s) => s.agentToolsEnabled)+ const setAgentToolsEnabled = useAgentToolsConfig(+ (s) => s.setAgentToolsEnabled+ )const [filePickerOpen, setFilePickerOpen] = useState(false)const [filePickerQuery, setFilePickerQuery] = useState('')@@ -240,7 +246,7 @@ const ChatInput = memo(function ChatInput({// @ (the @ must not be glued to a preceding word char, so `user@host`// never opens the picker)const beforeCursor = value.slice(0, cursorIdx)- const atMatch = beforeCursor.match(/(?<![A-Za-z0-9_])@([\w.\/-]*)$/)+ const atMatch = beforeCursor.match(/(?<![A-Za-z0-9_])@([\w./-]*)$/)if (atMatch) {const query = atMatch[1] ?? ''@@ -282,7 +288,7 @@ const ChatInput = memo(function ChatInput({const afterCursor = prompt.slice(filePickerCursorPos.current)// Replace the `@query` with `path/to/file` (the resolved reference)- const textBefore = beforeCursor.replace(/(?<![A-Za-z0-9_])@[\w.\/-]*$/, '')+ const textBefore = beforeCursor.replace(/(?<![A-Za-z0-9_])@[\w./-]*$/, '')const refText = entry.pathconst newPrompt = textBefore + refText + afterCursor@@ -2301,10 +2307,10 @@ const ChatInput = memo(function ChatInput({<TooltipContent><p>{isJanBrowserMCPLoading- ? 'Starting...'+ ? t('common:starting'): janBrowserMCPActive- ? 'Browse (Active)'- : 'Browse'}+ ? t('common:browse') + t('common:activeSuffix')+ : t('common:browse')}</p></TooltipContent></Tooltip>@@ -2444,13 +2450,41 @@ const ChatInput = memo(function ChatInput({<TooltipContent><p>{webSearchEnabled- ? t('common:web_search') + ' (Active)'+ ? t('common:web_search') + t('common:activeSuffix'): t('common:web_search')}</p></TooltipContent></Tooltip>)}+ {!effectiveAgentMode && selectedModel?.capabilities?.includes('tools') && (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon-xs"+ className={cn(agentToolsEnabled && 'text-primary')}+ onClick={() => setAgentToolsEnabled(!agentToolsEnabled)}+ >+ <IconFolderCode+ size={18}+ className={cn(+ 'text-muted-foreground',+ agentToolsEnabled && 'text-primary'+ )}+ />+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <p>+ {agentToolsEnabled+ ? t('common:agent_tools') + t('common:activeSuffix')+ : t('common:agent_tools')}+ </p>+ </TooltipContent>+ </Tooltip>+ )}+{!effectiveAgentMode &&(selectedProvider === 'llamacpp' ||selectedProvider === 'google' ||diff --git a/web-app/src/containers/SettingsMenu.tsx b/web-app/src/containers/SettingsMenu.tsxindex e0a0df5d4..f2c1d0d0c 100644--- a/web-app/src/containers/SettingsMenu.tsx+++ b/web-app/src/containers/SettingsMenu.tsx@@ -16,6 +16,7 @@ import {IconCpu,IconWorld,IconWorldSearch,+ IconFolderCode,IconPaperclip,} from '@tabler/icons-react'import { useMatches, useNavigate } from '@tanstack/react-router'@@ -198,6 +199,11 @@ const SettingsMenu = () => {route: route.settings.web_search,icon: IconWorldSearch,},+ {+ title: 'common:agent_tools',+ route: route.settings.agent_tools,+ icon: IconFolderCode,+ },{title: 'common:keyboardShortcuts',route: route.settings.shortcuts,diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex 1f64e1395..4559aaebe 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -1,5 +1,11 @@import { describe, it, expect, vi, beforeEach } from 'vitest'-import { render, screen, fireEvent, act } from '@testing-library/react'+import {+ render,+ screen,+ fireEvent,+ act,+ waitFor,+} from '@testing-library/react'import '@testing-library/jest-dom'// --- Module mocks (must be declared before component import) ---------------@@ -361,12 +367,14 @@ describe('ChatInput', () => {expect(setPromptMock).toHaveBeenCalledWith('abc')})- it('submits via onSubmit prop when Enter is pressed', () => {+ it('submits via onSubmit prop when Enter is pressed', async () => {promptState = 'hello world'const onSubmit = vi.fn()renderInput({ onSubmit })fireEvent.keyDown(getTextarea(), { key: 'Enter' })- expect(onSubmit).toHaveBeenCalledWith('hello world', undefined)+ await waitFor(() =>+ expect(onSubmit).toHaveBeenCalledWith('hello world', undefined)+ )expect(addToHistoryMock).toHaveBeenCalledWith('hello world')expect(setPromptMock).toHaveBeenCalledWith('')})@@ -379,15 +387,18 @@ describe('ChatInput', () => {expect(onSubmit).not.toHaveBeenCalled()})- it('does nothing when Enter pressed with empty/whitespace prompt', () => {+ it('does nothing when Enter pressed with empty/whitespace prompt', async () => {promptState = ' 'const onSubmit = vi.fn()renderInput({ onSubmit })fireEvent.keyDown(getTextarea(), { key: 'Enter' })+ // submission is async, so flush pending promises before asserting the+ // whitespace guard actually blocked it+ await act(async () => {})expect(onSubmit).not.toHaveBeenCalled()})- it('submits via the send button click', () => {+ it('submits via the send button click', async () => {promptState = 'button submit'const onSubmit = vi.fn()renderInput({ onSubmit })@@ -395,7 +406,9 @@ describe('ChatInput', () => {'[data-test-id="send-message-button"]') as HTMLButtonElementfireEvent.click(btn)- expect(onSubmit).toHaveBeenCalledWith('button submit', undefined)+ await waitFor(() =>+ expect(onSubmit).toHaveBeenCalledWith('button submit', undefined)+ )})it('shows stop button while streaming and hides the send button', () => {@@ -430,15 +443,17 @@ describe('ChatInput', () => {expect(clicked).toBeGreaterThanOrEqual(0) // smoke: no crash})- it('queues the message when streaming with a currentThreadId', () => {+ it('queues the message when streaming with a currentThreadId', async () => {promptState = 'queued msg'const onSubmit = vi.fn()renderInput({ onSubmit, chatStatus: 'streaming' })// During streaming, stop button is shown instead of send; submit path is via Enter on textareafireEvent.keyDown(getTextarea(), { key: 'Enter' })- expect(enqueueMock).toHaveBeenCalledWith(- 'thread-1',- expect.objectContaining({ text: 'queued msg', id: 'gen-id-1' })+ await waitFor(() =>+ expect(enqueueMock).toHaveBeenCalledWith(+ 'thread-1',+ expect.objectContaining({ text: 'queued msg', id: 'gen-id-1' })+ ))// onSubmit should NOT fire when queuedexpect(onSubmit).not.toHaveBeenCalled()@@ -485,7 +500,7 @@ describe('ChatInput', () => {expect(navigateHistoryMock).toHaveBeenCalledWith('down')})- it('adds attached image files to onSubmit payload', () => {+ it('adds attached image files to onSubmit payload', async () => {promptState = 'with image'attachmentsList = [{@@ -497,15 +512,17 @@ describe('ChatInput', () => {const onSubmit = vi.fn()renderInput({ onSubmit })fireEvent.keyDown(getTextarea(), { key: 'Enter' })- expect(onSubmit).toHaveBeenCalledWith(- 'with image',- expect.arrayContaining([- expect.objectContaining({- type: 'file',- mediaType: 'image/png',- url: 'data:image/png;base64,xxx',- }),- ])+ await waitFor(() =>+ expect(onSubmit).toHaveBeenCalledWith(+ 'with image',+ expect.arrayContaining([+ expect.objectContaining({+ type: 'file',+ mediaType: 'image/png',+ url: 'data:image/png;base64,xxx',+ }),+ ])+ ))expect(clearAttachmentsMock).toHaveBeenCalled()})diff --git a/web-app/src/containers/message/AgentToolWidget.tsx b/web-app/src/containers/message/AgentToolWidget.tsxnew file mode 100644index 000000000..1d9971e48--- /dev/null+++ b/web-app/src/containers/message/AgentToolWidget.tsx@@ -0,0 +1,262 @@+import { memo, useMemo } from 'react'+import type { ToolUIPart } from 'ai'+import {+ IconTerminal2,+ IconFile,+ IconFolder,+ IconSearch,+ IconNotebook,+ IconBook,+ IconLock,+ IconFilePencil,+} from '@tabler/icons-react'+import { Shimmer } from '@/components/ai-elements/shimmer'+import { useTranslation } from '@/i18n/react-i18next-compat'+import {+ isToolRunning,+ parseBashOutput,+ type ToolCallBar,+} from '@/lib/toolPresentation'+import { cn } from '@/lib/utils'+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'+import { Caret, ToolBar } from './ToolBar'++const asText = (output: unknown): string =>+ typeof output === 'string'+ ? output+ : typeof (output as { content?: unknown })?.content === 'string'+ ? (output as { content: string }).content+ : ''++const OutputBlock = ({ children }: { children: React.ReactNode }) => (+ <pre className="mt-1.5 max-h-56 overflow-auto whitespace-pre-wrap wrap-break-word rounded-md border bg-card/40 px-2 py-1.5 font-mono text-xs text-muted-foreground">+ {children}+ </pre>+)++/**+ * Tone for one line of a `write`/`edit` diff. The format comes from+ * `render_edit_diff`/`render_write_diff` in Rust: `@@ ... @@` hunk headers, then+ * `-`/`+` lines carrying their own ` N | text` line numbers.+ */+const diffLineTone = (line: string): string => {+ if (line.startsWith('@@')) return 'text-muted-foreground/60'+ if (line.startsWith('+'))+ return 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'+ if (line.startsWith('-')) return 'bg-destructive/10 text-destructive'+ return 'text-muted-foreground'+}++/**+ * A `write`/`edit` diff. Kept out of the model-facing tool output on purpose (it+ * would just repeat the file), so it arrives through the runtime store instead.+ */+const DiffBlock = memo(({ diff }: { diff: string }) => (+ <div className="mt-1.5 max-h-56 overflow-auto rounded-md border bg-card/40 py-1 font-mono text-xs">+ {diff.split('\n').map((line, i) => (+ <div+ key={i}+ className={cn(+ 'whitespace-pre-wrap wrap-break-word px-2',+ diffLineTone(line)+ )}+ >+ {line || ' '}+ </div>+ ))}+ </div>+))++DiffBlock.displayName = 'DiffBlock'++export type TerminalWidgetProps = {+ bar: Extract<ToolCallBar, { variant: 'terminal' }>+ state: ToolUIPart['state']+ output?: ToolUIPart['output']+ errorText?: string+}++/**+ * `bash` rendered as a terminal: the command streams in after a prompt, then its+ * output fills the scrollback below. The trailing `[exit N]` marker becomes a+ * status chip rather than staying in the text.+ *+ * The command streams; the output does not. `execute_tool` is one round trip, so+ * stdout arrives whole when the run finishes. Incremental output would need the+ * Rust side to emit events per chunk.+ */+export const TerminalWidget = memo(+ ({ bar, state, output, errorText }: TerminalWidgetProps) => {+ const { t } = useTranslation()+ const running = isToolRunning(state)+ const result = useMemo(+ () => (output ? parseBashOutput(output) : undefined),+ [output]+ )+ // A non-zero exit is reported in-band, so the body is the failure detail and+ // the chip is the failure signal; there is no separate error banner to show.+ const failed = errorText !== undefined || (result?.exit ?? 0) !== 0+ const body = result?.text || (errorText ? asText(errorText) : '')++ return (+ <div className="overflow-hidden rounded-md border bg-card/60">+ <div className="flex items-center gap-1.5 border-b px-2 py-1 text-xs text-muted-foreground">+ <IconTerminal2 size={14} className="shrink-0" />+ <span className="font-medium">{t('tools:toolCall.terminal')}</span>+ {result?.exit !== undefined && (+ <span+ className={cn(+ 'ml-auto shrink-0 rounded px-1.5 py-0.5 font-mono',+ failed+ ? 'bg-destructive/10 text-destructive'+ : 'bg-primary/10 text-primary'+ )}+ >+ {t('tools:toolCall.exitCode', { code: result.exit })}+ </span>+ )}+ {result?.signaled && (+ <span className="ml-auto shrink-0 rounded bg-destructive/10 px-1.5 py-0.5 text-destructive">+ {t('tools:toolCall.terminated')}+ </span>+ )}+ </div>+ <div className="px-2 py-1.5 font-mono text-xs">+ <div className="flex gap-1.5">+ <span className="shrink-0 select-none text-muted-foreground/70">+ $+ </span>+ <span className="min-w-0 flex-1 whitespace-pre-wrap wrap-break-word text-foreground">+ {bar.jobId && !bar.command+ ? t('tools:toolCall.pollingJob', { id: bar.jobId })+ : bar.command}+ {running && <Caret />}+ </span>+ </div>+ {running && (+ <div className="mt-1">+ {/* The command is already on screen above, so the tool-named+ `running` string would just repeat it. */}+ <Shimmer duration={1}>{t('tools:toolCall.working')}</Shimmer>+ </div>+ )}+ {!running && body && (+ <pre className="mt-1 max-h-56 overflow-auto whitespace-pre-wrap wrap-break-word text-muted-foreground">+ {body}+ </pre>+ )}+ {result?.truncated && (+ <p className="mt-1 text-muted-foreground/70">+ {t('tools:toolCall.outputTruncated')}+ </p>+ )}+ {/* Surfaced rather than dropped: when the sandbox is what failed the+ command, the limits are the actual explanation for the exit code. */}+ {result?.sandboxNote && (+ <p className="mt-1 flex items-start gap-1.5 text-muted-foreground/70">+ <IconLock size={13} className="mt-0.5 shrink-0" />+ <span>{result.sandboxNote}</span>+ </p>+ )}+ </div>+ </div>+ )+ }+)++TerminalWidget.displayName = 'TerminalWidget'++const TOOL_ICONS: Record<string, typeof IconFile> = {+ read: IconFile,+ ls: IconFolder,+ find: IconSearch,+ grep: IconSearch,+ write: IconFilePencil,+ edit: IconFilePencil,+ memory_list: IconNotebook,+ memory_read: IconNotebook,+ memory_write: IconNotebook,+ skill_list: IconBook,+ skill_read: IconBook,+ skill_write: IconBook,+}++/** Tools whose whole call is the verb: there is no argument worth a bar. */+const LISTING_TOOLS = new Set(['memory_list', 'skill_list', 'ls'])++export type AgentToolWidgetProps = {+ bar: Extract<ToolCallBar, { variant: 'workspace' }>+ state: ToolUIPart['state']+ output?: ToolUIPart['output']+ errorText?: string+ /** Needed to look up this call's display-only diff. */+ toolCallId?: string+}++/**+ * The workspace tools rendered as the thing they act on -- a path, a glob, a+ * memory name -- followed by the result, mirroring how the web tools present a+ * query or a URL.+ */+export const AgentToolWidget = memo(+ ({ bar, state, output, errorText, toolCallId }: AgentToolWidgetProps) => {+ const { t } = useTranslation()+ const running = isToolRunning(state)+ const diff = useToolCallRuntime((s) =>+ toolCallId ? s.diffs[toolCallId] : undefined+ )+ const Icon = TOOL_ICONS[bar.tool] ?? IconFile+ const body = asText(output)+ // `ls` with no path lists the workspace root; show that rather than a bar+ // that reads as though an argument failed to stream.+ const value =+ bar.target || (LISTING_TOOLS.has(bar.tool) ? t('tools:toolCall.workspaceRoot') : '')++ return (+ <div className="space-y-1.5">+ <ToolBar+ icon={<Icon size={16} />}+ value={value}+ placeholder={t('tools:toolCall.pathPlaceholder')}+ typing={running}+ mono+ trailing={+ bar.detail ? (+ <span className="shrink-0 font-mono text-xs text-muted-foreground/70">+ {bar.detail}+ </span>+ ) : undefined+ }+ />++ {errorText && (+ <div className="rounded-md bg-destructive/10 px-2 py-1.5 text-sm text-destructive">+ {errorText}+ </div>+ )}++ {running && !errorText && (+ <div className="px-2 text-sm">+ <Shimmer duration={1}>{t('tools:toolCall.reading')}</Shimmer>+ </div>+ )}++ {!running &&+ !errorText &&+ // A diff supersedes the body: `Applied 2 edit(s) to a.txt` says less+ // than the change itself.+ (diff ? (+ <DiffBlock diff={diff} />+ ) : body ? (+ <OutputBlock>{body}</OutputBlock>+ ) : (+ <p className="px-2 text-sm text-muted-foreground/70">+ {t('tools:toolCall.noResults')}+ </p>+ ))}+ </div>+ )+ }+)++AgentToolWidget.displayName = 'AgentToolWidget'diff --git a/web-app/src/containers/message/ToolBar.tsx b/web-app/src/containers/message/ToolBar.tsxindex f1698c84c..ffdd84df7 100644--- a/web-app/src/containers/message/ToolBar.tsx+++ b/web-app/src/containers/message/ToolBar.tsx@@ -1,7 +1,7 @@import { cn } from '@/lib/utils'/** Blinking block that reads as the model typing into the bar. */-const Caret = () => (+export const Caret = () => (<span className="ml-0.5 inline-block h-[1.05em] w-[2px] translate-y-[0.15em] animate-pulse bg-foreground/70" />)diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsxindex 41e06d60a..429f341cc 100644--- a/web-app/src/containers/message/ToolCallCard.tsx+++ b/web-app/src/containers/message/ToolCallCard.tsx@@ -14,6 +14,7 @@ import { describeNativeToolCall } from '@/lib/toolPresentation'import { isToolPart, type MessagePartLike } from './types'import { RagToolWidget } from './RagToolWidget'import { WebToolWidget } from './WebToolWidget'+import { AgentToolWidget, TerminalWidget } from './AgentToolWidget'const identityResolver = (input: string) => Promise.resolve(input)@@ -41,7 +42,9 @@ export const ToolCallCard = memo(? t('tools:toolCall.originWeb'): origin.kind === 'rag'? t('tools:toolCall.originDocuments')- : origin.detail+ : origin.kind === 'agent'+ ? t('tools:toolCall.originWorkspace')+ : origin.detailconst errorText = isError? part.error || part.errorText || t('tools:toolCall.executionFailed')@@ -80,6 +83,21 @@ export const ToolCallCard = memo(messageId={messageId}citationOffset={citationOffset}/>+ ) : bar.variant === 'terminal' ? (+ <TerminalWidget+ bar={bar}+ state={part.state}+ output={part.output}+ errorText={errorText}+ />+ ) : bar.variant === 'workspace' ? (+ <AgentToolWidget+ bar={bar}+ state={part.state}+ output={part.output}+ errorText={errorText}+ toolCallId={part.toolCallId}+ />) : (<WebToolWidgetbar={bar}diff --git a/web-app/src/hooks/__tests__/useAgentToolsConfig.test.ts b/web-app/src/hooks/__tests__/useAgentToolsConfig.test.tsnew file mode 100644index 000000000..9c68743c0--- /dev/null+++ b/web-app/src/hooks/__tests__/useAgentToolsConfig.test.ts@@ -0,0 +1,48 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++// The store persists via backendStorage; stub the persist layer so the import+// is inert and no disk I/O happens in tests.+vi.mock('@/constants/localStorage', () => ({+ localStorageKey: { settingAgentTools: 'setting-agent-tools' },+}))+vi.mock('zustand/middleware', () => ({+ persist: (fn: any) => fn,+ createJSONStorage: () => ({+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ }),+}))++import { useAgentToolsConfig } from '../useAgentToolsConfig'++describe('useAgentToolsConfig', () => {+ beforeEach(() => {+ useAgentToolsConfig.setState({+ agentToolsEnabled: false,+ bashNetworkEnabled: false,+ })+ })++ it('defaults both toggles off', () => {+ expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(false)+ expect(useAgentToolsConfig.getState().bashNetworkEnabled).toBe(false)+ })++ it('toggles the agent tools switch on and off', () => {+ useAgentToolsConfig.getState().setAgentToolsEnabled(true)+ expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(true)++ useAgentToolsConfig.getState().setAgentToolsEnabled(false)+ expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(false)+ })++ it('keeps bash network and agent tools switches independent', () => {+ useAgentToolsConfig.getState().setAgentToolsEnabled(true)+ expect(useAgentToolsConfig.getState().bashNetworkEnabled).toBe(false)++ useAgentToolsConfig.getState().setBashNetworkEnabled(true)+ expect(useAgentToolsConfig.getState().bashNetworkEnabled).toBe(true)+ expect(useAgentToolsConfig.getState().agentToolsEnabled).toBe(true)+ })+})diff --git a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts b/web-app/src/hooks/__tests__/useToolCallRuntime.test.tsindex 9dd905fef..f3e006071 100644--- a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts+++ b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts@@ -134,4 +134,27 @@ describe('useToolCallRuntime', () => {store().markSettled('ghost')expect(store().timings['ghost']).toBeUndefined()})++ // The diff is the whole point of a finished write/edit card, so unlike+ // `progress` it has to outlive the call settling.+ it('keeps a recorded diff after the call settles', () => {+ store().enqueue(['a'])+ store().markRunning('a')+ store().recordDiff('a', '@@ edit 1/1 @@\n+ 1 | A')+ store().markSettled('a')+ expect(store().diffs['a']).toContain('+ 1 | A')+ })++ it("clears diffs on reset so a thread cannot show another thread's diff", () => {+ store().recordDiff('a', 'diff')+ store().reset()+ expect(store().diffs).toEqual({})+ })++ it('records diffs per call without disturbing the others', () => {+ store().recordDiff('a', 'first')+ store().recordDiff('b', 'second')+ store().recordDiff('a', 'first again')+ expect(store().diffs).toEqual({ a: 'first again', b: 'second' })+ })})diff --git a/web-app/src/hooks/useAgentToolsConfig.ts b/web-app/src/hooks/useAgentToolsConfig.tsnew file mode 100644index 000000000..070fbbeba--- /dev/null+++ b/web-app/src/hooks/useAgentToolsConfig.ts@@ -0,0 +1,36 @@+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'+import { localStorageKey } from '@/constants/localStorage'+import { backendStorage } from '@/lib/backendStorage'++type AgentToolsConfigState = {+ agentToolsEnabled: boolean+ setAgentToolsEnabled: (value: boolean) => void+ /** Open the sandboxed shell's network namespace. */+ bashNetworkEnabled: boolean+ setBashNetworkEnabled: (value: boolean) => void+}++/**+ * Off by default: the toolset gives the model filesystem reach (inside the+ * isolated agent workspace) and a persistent memory, so it is opt-in.+ *+ * `bashNetworkEnabled` is separately off, because it is the one setting that+ * lets a command reach off the machine. With it off, the sandbox confines a+ * command to the workspace *and* keeps it from sending anything anywhere.+ */+export const useAgentToolsConfig = create<AgentToolsConfigState>()(+ persist(+ (set) => ({+ agentToolsEnabled: false,+ setAgentToolsEnabled: (agentToolsEnabled) => set({ agentToolsEnabled }),+ bashNetworkEnabled: false,+ setBashNetworkEnabled: (bashNetworkEnabled) => set({ bashNetworkEnabled }),+ }),+ {+ name: localStorageKey.settingAgentTools,+ storage: createJSONStorage(() => backendStorage),+ skipHydration: true,+ }+ )+)diff --git a/web-app/src/hooks/useSkills.ts b/web-app/src/hooks/useSkills.tsindex e5701e21b..82c11b134 100644--- a/web-app/src/hooks/useSkills.ts+++ b/web-app/src/hooks/useSkills.ts@@ -1,9 +1,11 @@import { invoke } from '@tauri-apps/api/core'-import { useCallback, useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { create } from 'zustand'import { toast } from 'sonner'+import * as skillStore from '@/lib/skillStore'+import type { SkillMeta } from '@/lib/skillStore'-export type SkillMeta = { name: string; description: string }+export type { SkillMeta }export type HubSkill = { name: string; description: string }// The `[skills].enabled` whitelist uses three shapes:@@ -43,9 +45,11 @@ const useSkillsVersion = create<{ v: number; bump: () => void }>((set) => ({}))/**- * CRUD over the agent's per-project skills (`<folder>/.jan/agent/skills/*.md`),- * backed by the `agent_skill_*` Tauri commands. All operations are scoped to- * `folder`; with no folder there are no skills to manage.+ * CRUD over the agent's per-project skills (`<folder>/.jan/agent/skills/*.md`).+ * Storage is shared with the settings page's permanent store via `skillStore`;+ * only the root differs. The `[skills].enabled` whitelist and the skill hub stay+ * on their own commands -- both are project concerns with no store equivalent.+ * All operations are scoped to `folder`; with no folder there are no skills.*/export function useSkills(folder: string | null) {const [skills, setSkills] = useState<SkillMeta[]>([])@@ -58,8 +62,13 @@ export function useSkills(folder: string | null) {// an await without depending on (and being recreated by) the state itself.const enabledRef = useRef<string[]>([])+ const scope = useMemo(+ () => (folder ? skillStore.projectScope(folder) : null),+ [folder]+ )+const refresh = useCallback(async () => {- if (!folder) {+ if (!folder || !scope) {setSkills([])setEnabledState([])enabledRef.current = []@@ -68,7 +77,7 @@ export function useSkills(folder: string | null) {setLoading(true)try {const [list, en] = await Promise.all([- invoke<SkillMeta[]>('agent_skill_list', { project: folder }),+ skillStore.listSkills(scope),invoke<string[]>('agent_skill_enabled_get', { project: folder }),])setSkills(list)@@ -77,7 +86,7 @@ export function useSkills(folder: string | null) {} finally {setLoading(false)}- }, [folder])+ }, [folder, scope])// Persist the enabled whitelist (empty = all). Optimistic local update; on a// write failure, roll back so the UI never diverges from the on-disk config.@@ -108,26 +117,33 @@ export function useSkills(folder: string | null) {refresh()}, [refresh, version])+ // Callers reach these only from surfaces that already require a folder; the+ // guard keeps that an explicit failure rather than a silent write to the+ // wrong root.+ const requireScope = useCallback(() => {+ if (!scope) throw new Error('No project folder selected')+ return scope+ }, [scope])+const read = useCallback(- (name: string) =>- invoke<string>('agent_skill_read', { project: folder, name }),- [folder]+ (name: string) => skillStore.readSkill(requireScope(), name),+ [requireScope])const write = useCallback(async (name: string, content: string) => {- await invoke('agent_skill_write', { project: folder, name, content })+ await skillStore.writeSkill(requireScope(), name, content)bump()},- [folder, bump]+ [requireScope, bump])const remove = useCallback(async (name: string) => {- await invoke('agent_skill_delete', { project: folder, name })+ await skillStore.deleteSkill(requireScope(), name)bump()},- [folder, bump]+ [requireScope, bump])// Anthropic skill hub. `hubList` is project-independent; `hubImport` downloadsdiff --git a/web-app/src/hooks/useThreads.ts b/web-app/src/hooks/useThreads.tsindex 1fdc61d9e..7d569a58d 100644--- a/web-app/src/hooks/useThreads.ts+++ b/web-app/src/hooks/useThreads.ts@@ -8,6 +8,7 @@ import { ExtensionManager } from '@/lib/extension'import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'import { useChatSessions } from '@/stores/chat-session-store'import { useAppState } from '@/hooks/useAppState'+import { cleanupThreadWorkspace } from '@/lib/agentTools'type ThreadState = {threads: Record<string, Thread>@@ -58,6 +59,14 @@ const cleanupVectorDB = async (threadId: string) => {}}+// Everything belonging to a thread that lives outside the thread store: its+// vector DB collection and its ephemeral agent sandbox. Fire-and-forget, since+// every caller runs inside a `set` reducer; both log their own failures.+const cleanupThreadArtifacts = (threadId: string) => {+ cleanupVectorDB(threadId)+ cleanupThreadWorkspace(threadId)+}+export const useThreads = create<ThreadState>()((set, get) => ({threads: {},isLoadingThreads: true,@@ -164,7 +173,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({useAgentMode.getState().removeThread(threadId)useChatSessions.getState().removeSession(threadId)useAppState.getState().clearThreadState(threadId)- cleanupVectorDB(threadId)+ cleanupThreadArtifacts(threadId)getServiceHub().threads().deleteThread(threadId)return {@@ -198,9 +207,9 @@ export const useThreads = create<ThreadState>()((set, get) => ({!state.threads[threadId].metadata?.project)- // Delete threads and clean up their vector DB collections+ // Delete threads and clean up their out-of-store artifactsthreadsToDeleteIds.forEach((threadId) => {- cleanupVectorDB(threadId)+ cleanupThreadArtifacts(threadId)getServiceHub().threads().deleteThread(threadId)})@@ -234,7 +243,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({useAgentMode.getState().removeThread(threadId)useChatSessions.getState().removeSession(threadId)useAppState.getState().clearThreadState(threadId)- cleanupVectorDB(threadId)+ cleanupThreadArtifacts(threadId)getServiceHub().threads().deleteThread(threadId)})@@ -260,7 +269,7 @@ export const useThreads = create<ThreadState>()((set, get) => ({threadsToDeleteIds.forEach((threadId) => {useChatSessions.getState().removeSession(threadId)useAppState.getState().clearThreadState(threadId)- cleanupVectorDB(threadId)+ cleanupThreadArtifacts(threadId)getServiceHub().threads().deleteThread(threadId)})diff --git a/web-app/src/hooks/useToolCallRuntime.ts b/web-app/src/hooks/useToolCallRuntime.tsindex baab3d4c5..5bb419bce 100644--- a/web-app/src/hooks/useToolCallRuntime.ts+++ b/web-app/src/hooks/useToolCallRuntime.ts@@ -27,6 +27,13 @@ export type ToolCallRuntimeSnapshot = {timings: Record<string, ToolCallTiming>/** Latest progress update per call, cleared when the call settles. */progress: Record<string, ToolProgressUpdate>+ /**+ * Unified diff per `write`/`edit` call. Display-only: it deliberately never+ * enters the model-facing tool output, so it cannot travel on the message part+ * and needs a side channel. Unlike `progress` it is kept after the call+ * settles, since the diff is the whole point of the finished card.+ */+ diffs: Record<string, string>}type ToolCallRuntimeState = ToolCallRuntimeSnapshot & {@@ -43,6 +50,8 @@ type ToolCallRuntimeState = ToolCallRuntimeSnapshot & {* belong to -- well defined because tools execute one at a time.*/reportProgress: (update: ToolProgressUpdate) => void+ /** Records a display-only diff against the call that produced it. */+ recordDiff: (toolCallId: string, diff: string) => void/** Ends a turn: nothing still queued will run, so stop showing it as waiting. */settleRemaining: () => voidreset: () => void@@ -73,6 +82,7 @@ export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({queue: [],timings: {},progress: {},+ diffs: {},enqueue: (toolCallIds) =>set((s) => {@@ -128,6 +138,9 @@ export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({return running ? { progress: { ...s.progress, [running]: update } } : s}),+ recordDiff: (toolCallId, diff) =>+ set((s) => ({ diffs: { ...s.diffs, [toolCallId]: diff } })),+settleRemaining: () =>set((s) => {if (s.queue.length === 0) return s@@ -139,5 +152,5 @@ export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({return { queue: [], timings }}),- reset: () => set({ queue: [], timings: {}, progress: {} }),+ reset: () => set({ queue: [], timings: {}, progress: {}, diffs: {} }),}))diff --git a/web-app/src/hooks/useToolOrigin.ts b/web-app/src/hooks/useToolOrigin.tsindex eec052be1..9ba27e6f2 100644--- a/web-app/src/hooks/useToolOrigin.ts+++ b/web-app/src/hooks/useToolOrigin.ts@@ -2,6 +2,7 @@ import { useMemo } from 'react'import { useAppState } from '@/hooks/useAppState'import { getProviderMeta, useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { resolveToolOrigin, type ToolOrigin } from '@/lib/toolOrigin'+import { AGENT_TOOL_NAMES } from '@/lib/agentTools'/*** Resolve which family a tool call belongs to. Each selector returns a@@ -13,6 +14,7 @@ export const useToolOrigin = (toolName: string): ToolOrigin | undefined => {(s) => s.tools.find((tool) => tool.name === toolName)?.server)const isRagTool = useAppState((s) => s.ragToolNames.has(toolName))+ const isAgentTool = AGENT_TOOL_NAMES.has(toolName)const webSearchProviderLabel = useWebSearchConfig((s) => getProviderMeta(s.searchProvider).label)@@ -22,8 +24,9 @@ export const useToolOrigin = (toolName: string): ToolOrigin | undefined => {resolveToolOrigin(toolName, {mcpServer,isRagTool,+ isAgentTool,webSearchProviderLabel,}),- [toolName, mcpServer, isRagTool, webSearchProviderLabel]+ [toolName, mcpServer, isRagTool, isAgentTool, webSearchProviderLabel])}diff --git a/web-app/src/i18n/__tests__/keys.test.ts b/web-app/src/i18n/__tests__/keys.test.tsnew file mode 100644index 000000000..fe923e516--- /dev/null+++ b/web-app/src/i18n/__tests__/keys.test.ts@@ -0,0 +1,76 @@+import { describe, it, expect } from 'vitest'+import { readdirSync, readFileSync } from 'node:fs'+import { join, resolve, basename } from 'node:path'++/**+ * The custom `t` returns the key itself when a lookup fails, so a missing entry+ * renders `tools:toolApproval.title` at the user rather than throwing or falling+ * back. That is invisible in review and in every other test, which is how five+ * approval-dialog keys and two toast keys shipped broken.+ *+ * This walks every statically-written `t('ns:key')` in the app and asserts it+ * resolves in the `en` locale, which is also the fallback for every other one.+ */+const SRC = resolve(__dirname, '../..')+const LOCALES = join(SRC, 'locales/en')++const loadEnglish = (): Record<string, unknown> =>+ Object.fromEntries(+ readdirSync(LOCALES)+ .filter((f) => f.endsWith('.json'))+ .map((f) => [+ basename(f, '.json'),+ JSON.parse(readFileSync(join(LOCALES, f), 'utf-8')),+ ])+ )++const sourceFiles = (dir: string): string[] =>+ readdirSync(dir, { withFileTypes: true }).flatMap((e) => {+ const full = join(dir, e.name)+ if (e.isDirectory()) {+ return e.name === '__tests__' || e.name === 'node_modules'+ ? []+ : sourceFiles(full)+ }+ return /\.tsx?$/.test(e.name) && !/\.test\.tsx?$/.test(e.name) ? [full] : []+ })++const resolves = (+ bundle: Record<string, unknown>,+ ns: string,+ key: string+): boolean => {+ let cur: unknown = bundle[ns]+ for (const part of key.split('.')) {+ if (typeof cur !== 'object' || cur === null || !(part in cur)) return false+ cur = (cur as Record<string, unknown>)[part]+ }+ return typeof cur === 'string'+}++// Only literal keys; dynamically-built ones can't be checked statically.+const KEY_CALL = /t\(\s*['"]([a-zA-Z0-9_-]+):([a-zA-Z0-9_.]+)['"]/g++describe('i18n keys', () => {+ it('resolves every statically-referenced key in the en locale', () => {+ const bundle = loadEnglish()+ const missing: string[] = []++ for (const file of sourceFiles(SRC)) {+ const text = readFileSync(file, 'utf-8')+ for (const [, ns, key] of text.matchAll(KEY_CALL)) {+ if (!resolves(bundle, ns, key)) {+ missing.push(`${ns}:${key} (${file.slice(SRC.length + 1)})`)+ }+ }+ }++ expect(missing).toEqual([])+ })++ it('finds the locale bundle it is auditing', () => {+ const bundle = loadEnglish()+ expect(Object.keys(bundle).length).toBeGreaterThan(5)+ expect(resolves(bundle, 'tools', 'toolApproval.title')).toBe(true)+ })+})diff --git a/web-app/src/i18n/setup.ts b/web-app/src/i18n/setup.tsindex 9b4f4621e..2d02734c8 100644--- a/web-app/src/i18n/setup.ts+++ b/web-app/src/i18n/setup.ts@@ -93,10 +93,16 @@ const translate = (key: string, options: Record<string, unknown> = {}): string =translation = getNestedValue(res[fallbackLng]?.[namespace], translationKey)}- // If still not found, return the key itself+ // Callers may supply an inline `defaultValue`, as i18next allows. Honour it+ // before giving up, so a missing key degrades to real copy rather than+ // rendering the key itself at the user.if (translation === undefined) {- console.warn(`Translation missing for key: ${key}`)- return key+ if (typeof options.defaultValue === 'string') {+ translation = options.defaultValue+ } else {+ console.warn(`Translation missing for key: ${key}`)+ return key+ }}// Handle interpolationdiff --git a/web-app/src/lib/__tests__/agentTools.test.ts b/web-app/src/lib/__tests__/agentTools.test.tsnew file mode 100644index 000000000..fc9f919bd--- /dev/null+++ b/web-app/src/lib/__tests__/agentTools.test.ts@@ -0,0 +1,253 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const toolSchemas = vi.fn()+const executeTool = vi.fn()+const threadWorkspaceDelete = vi.fn()+const threadWorkspaceSweep = vi.fn()+const sandboxStatus = vi.fn()+const getJanDataFolder = vi.fn()++vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({+ toolSchemas: () => toolSchemas(),+ executeTool: (...args: unknown[]) => executeTool(...args),+ threadWorkspaceDelete: (...args: unknown[]) => threadWorkspaceDelete(...args),+ threadWorkspaceSweep: (...args: unknown[]) => threadWorkspaceSweep(...args),+ sandboxStatus: () => sandboxStatus(),+}))++vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({ app: () => ({ getJanDataFolder }) }),+}))++const schemaFor = (name: string) => ({+ type: 'function' as const,+ function: { name, description: `${name} desc`, parameters: {} },+})++describe('agentTools', () => {+ beforeEach(() => {+ vi.resetModules()+ toolSchemas.mockReset()+ executeTool.mockReset()+ threadWorkspaceDelete.mockReset().mockResolvedValue(undefined)+ threadWorkspaceSweep.mockReset().mockResolvedValue(0)+ sandboxStatus+ .mockReset()+ .mockResolvedValue({ backend: 'bubblewrap', enforces: true })+ getJanDataFolder.mockReset().mockResolvedValue('/data')+ })++ it('advertises the workspace tools including writes and bash', async () => {+ const { AGENT_TOOL_NAMES } = await import('../agentTools')+ for (const name of ['read', 'ls', 'find', 'grep', 'bash']) {+ expect(AGENT_TOOL_NAMES.has(name)).toBe(true)+ }+ // write/edit can only touch the thread's ephemeral sandbox, so they are+ // allowed there without a prompt -- withholding them while bash can write+ // the same files would be a restriction a sibling tool bypasses.+ for (const name of ['write', 'edit']) {+ expect(AGENT_TOOL_NAMES.has(name)).toBe(true)+ }+ // Already advertised through the websearch plugin.+ for (const name of ['web_search', 'web_fetch']) {+ expect(AGENT_TOOL_NAMES.has(name)).toBe(false)+ }+ })++ it('filters Rust schemas down to the advertised subset', async () => {+ toolSchemas.mockResolvedValue([+ schemaFor('read'),+ schemaFor('write'),+ schemaFor('memory_write'),+ schemaFor('web_search'),+ ])+ const { getAgentToolSchemas } = await import('../agentTools')+ const names = (await getAgentToolSchemas()).map((s) => s.function.name)+ expect(names).toEqual(['read', 'write', 'memory_write'])+ })++ /// The diff must reach the caller so the UI can render it, but stay out of+ /// `content`, which is what gets sent back to the model.+ it('returns the diff alongside content, not inside it', async () => {+ executeTool.mockResolvedValue({+ content: 'Applied 1 edit(s) to a.txt',+ diff: '@@ edit 1/1 @@\n- 1 | a\n+ 1 | A',+ isError: false,+ })+ const { executeAgentTool } = await import('../agentTools')+ const result = await executeAgentTool('edit', { path: 'a.txt' }, 'thread-1')+ expect(result.content).toBe('Applied 1 edit(s) to a.txt')+ expect(result.diff).toContain('+ 1 | A')+ expect(String(result.content)).not.toContain('@@')+ })++ it('omits the diff for tools that produce none', async () => {+ executeTool.mockResolvedValue({+ content: 'a.txt',+ diff: null,+ isError: false,+ })+ const { executeAgentTool } = await import('../agentTools')+ const result = await executeAgentTool('ls', {}, 'thread-1')+ expect(result.diff).toBeUndefined()+ })++ it('offers bash when the sandbox can enforce', async () => {+ toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])+ const { getAgentToolSchemas } = await import('../agentTools')+ const names = (await getAgentToolSchemas()).map((s) => s.function.name)+ expect(names).toEqual(['read', 'bash'])+ })++ // Offering a tool the executor will always refuse wastes a model turn, so an+ // unconfinable host must not see bash at all.+ it('withholds bash when no sandbox backend exists', async () => {+ sandboxStatus.mockResolvedValue({ backend: 'none', enforces: false })+ toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])+ const { getAgentToolSchemas } = await import('../agentTools')+ const names = (await getAgentToolSchemas()).map((s) => s.function.name)+ expect(names).toEqual(['read'])+ })++ it('withholds bash when the sandbox probe itself fails', async () => {+ sandboxStatus.mockRejectedValue(new Error('probe exploded'))+ toolSchemas.mockResolvedValue([schemaFor('read'), schemaFor('bash')])+ const { getAgentToolSchemas, sandboxEnforces } = await import(+ '../agentTools'+ )+ const names = (await getAgentToolSchemas()).map((s) => s.function.name)+ expect(names).toEqual(['read'])+ expect(sandboxEnforces()).toBe(false)+ })++ it('passes the network setting through to the plugin', async () => {+ executeTool.mockResolvedValue({ content: '', diff: null, isError: false })+ const { useAgentToolsConfig } = await import('@/hooks/useAgentToolsConfig')+ const { executeAgentTool } = await import('../agentTools')++ await executeAgentTool('bash', { command: 'ls' }, 'thread-1')+ expect(executeTool).toHaveBeenLastCalledWith(+ '/data',+ 'thread-1',+ 'bash',+ { command: 'ls' },+ undefined,+ undefined,+ false+ )++ useAgentToolsConfig.getState().setBashNetworkEnabled(true)+ await executeAgentTool('bash', { command: 'ls' }, 'thread-1')+ expect(executeTool).toHaveBeenLastCalledWith(+ '/data',+ 'thread-1',+ 'bash',+ { command: 'ls' },+ undefined,+ undefined,+ true+ )+ useAgentToolsConfig.getState().setBashNetworkEnabled(false)+ })++ it('caches the schemas so every turn does not re-cross IPC', async () => {+ toolSchemas.mockResolvedValue([schemaFor('read')])+ const { getAgentToolSchemas } = await import('../agentTools')+ await getAgentToolSchemas()+ await getAgentToolSchemas()+ expect(toolSchemas).toHaveBeenCalledTimes(1)+ })++ /// The thread id scopes the sandbox, so it must reach the plugin on every+ /// call; without it two conversations would share one scratch directory.+ it('scopes execution to the calling thread and passes no project path', async () => {+ executeTool.mockResolvedValue({+ content: 'hello',+ diff: null,+ isError: false,+ })+ const { executeAgentTool } = await import('../agentTools')+ await expect(+ executeAgentTool('read', { path: 'a.txt' }, 'thread-1')+ ).resolves.toEqual({ content: 'hello' })+ expect(executeTool).toHaveBeenCalledWith(+ '/data',+ 'thread-1',+ 'read',+ { path: 'a.txt' },+ undefined,+ undefined,+ false+ )+ })++ it('maps a gate refusal to an error rather than content', async () => {+ executeTool.mockResolvedValue({+ content: "tool 'write' needs user approval",+ diff: null,+ isError: true,+ })+ const { executeAgentTool } = await import('../agentTools')+ await expect(executeAgentTool('write', {}, 'thread-1')).resolves.toEqual({+ error: "tool 'write' needs user approval",+ })+ })++ it('reports a rejected invoke as an error instead of throwing', async () => {+ executeTool.mockRejectedValue({ message: 'denied by policy' })+ const { executeAgentTool } = await import('../agentTools')+ await expect(executeAgentTool('read', {}, 'thread-1')).resolves.toEqual({+ error: 'denied by policy',+ })+ })++ it('errors when the data folder is unavailable', async () => {+ getJanDataFolder.mockResolvedValue(undefined)+ const { executeAgentTool } = await import('../agentTools')+ const result = await executeAgentTool('read', {}, 'thread-1')+ expect(result.error).toBeTruthy()+ expect(executeTool).not.toHaveBeenCalled()+ })++ it('coerces a non-object input to empty args', async () => {+ executeTool.mockResolvedValue({ content: '', diff: null, isError: false })+ const { executeAgentTool } = await import('../agentTools')+ await executeAgentTool('memory_list', undefined, 'thread-1')+ expect(executeTool).toHaveBeenCalledWith(+ '/data',+ 'thread-1',+ 'memory_list',+ {},+ undefined,+ undefined,+ false+ )+ })++ it('deletes one thread sandbox on cleanup', async () => {+ const { cleanupThreadWorkspace } = await import('../agentTools')+ await cleanupThreadWorkspace('thread-1')+ expect(threadWorkspaceDelete).toHaveBeenCalledWith('/data', 'thread-1')+ })++ /// Deleting a thread must not fail loudly over a leftover directory; the next+ /// startup sweep collects it.+ it('swallows a cleanup failure', async () => {+ threadWorkspaceDelete.mockRejectedValue({ message: 'busy' })+ const { cleanupThreadWorkspace } = await import('../agentTools')+ await expect(cleanupThreadWorkspace('thread-1')).resolves.toBeUndefined()+ })++ it('sweeps with the surviving thread ids', async () => {+ threadWorkspaceSweep.mockResolvedValue(3)+ const { sweepThreadWorkspaces } = await import('../agentTools')+ await expect(sweepThreadWorkspaces(['a', 'b'])).resolves.toBe(3)+ expect(threadWorkspaceSweep).toHaveBeenCalledWith('/data', ['a', 'b'])+ })++ it('reports zero swept when the sweep fails', async () => {+ threadWorkspaceSweep.mockRejectedValue(new Error('nope'))+ const { sweepThreadWorkspaces } = await import('../agentTools')+ await expect(sweepThreadWorkspaces(['a'])).resolves.toBe(0)+ })+})diff --git a/web-app/src/lib/__tests__/agentWorkspace.test.ts b/web-app/src/lib/__tests__/agentWorkspace.test.tsnew file mode 100644index 000000000..507557745--- /dev/null+++ b/web-app/src/lib/__tests__/agentWorkspace.test.ts@@ -0,0 +1,89 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++const api = {+ workspacePath: vi.fn(),+ skillList: vi.fn(),+ skillRead: vi.fn(),+ skillWrite: vi.fn(),+ skillDelete: vi.fn(),+ memoryList: vi.fn(),+ memoryRead: vi.fn(),+ memoryWrite: vi.fn(),+ memoryDelete: vi.fn(),+}+const getJanDataFolder = vi.fn()+const revealItemInDir = vi.fn()++vi.mock('@janhq/tauri-plugin-agent-tools-api', () => api)++vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({+ app: () => ({ getJanDataFolder }),+ opener: () => ({ revealItemInDir }),+ }),+}))++describe('agentWorkspace', () => {+ beforeEach(() => {+ vi.resetModules()+ Object.values(api).forEach((fn) => fn.mockReset())+ api.workspacePath.mockResolvedValue('/data/agent-workspace')+ getJanDataFolder.mockReset().mockResolvedValue('/data')+ revealItemInDir.mockReset()+ })++ /// Every call resolves the data folder first; none of them take a project+ /// path, so the settings page always edits the permanent store.+ it('reads and writes the permanent store', async () => {+ api.skillList.mockResolvedValue([{ name: 'deploy', description: 'd' }])+ api.memoryList.mockResolvedValue(['prefs'])+ api.skillRead.mockResolvedValue('body')+ api.memoryRead.mockResolvedValue('note')+ const ws = await import('../agentWorkspace')++ await expect(ws.storePath()).resolves.toBe('/data/agent-workspace')+ await expect(ws.listSkills()).resolves.toEqual([+ { name: 'deploy', description: 'd' },+ ])+ await expect(ws.listMemories()).resolves.toEqual(['prefs'])+ await expect(ws.readSkill('deploy')).resolves.toBe('body')+ await expect(ws.readMemory('prefs')).resolves.toBe('note')++ expect(api.skillList).toHaveBeenCalledWith('/data')+ expect(api.memoryRead).toHaveBeenCalledWith('/data', 'prefs')+ })++ it('writes and deletes by name', async () => {+ const ws = await import('../agentWorkspace')+ await ws.writeSkill('deploy', 'x')+ await ws.deleteSkill('deploy')+ await ws.writeMemory('prefs', 'y')+ await ws.deleteMemory('prefs')++ expect(api.skillWrite).toHaveBeenCalledWith('/data', 'deploy', 'x')+ expect(api.skillDelete).toHaveBeenCalledWith('/data', 'deploy')+ expect(api.memoryWrite).toHaveBeenCalledWith('/data', 'prefs', 'y')+ expect(api.memoryDelete).toHaveBeenCalledWith('/data', 'prefs')+ })++ /// Unlike a tool call, a failed edit has a user waiting on it, so these throw+ /// instead of resolving to an error value the page would have to sniff for.+ it('propagates failures to the caller', async () => {+ api.memoryWrite.mockRejectedValue(new Error("invalid name '..'"))+ const ws = await import('../agentWorkspace')+ await expect(ws.writeMemory('..', 'x')).rejects.toThrow("invalid name '..'")+ })++ it('fails clearly when the data folder is unavailable', async () => {+ getJanDataFolder.mockResolvedValue(undefined)+ const ws = await import('../agentWorkspace')+ await expect(ws.listMemories()).rejects.toThrow('data folder')+ expect(api.memoryList).not.toHaveBeenCalled()+ })++ it('reveals the resolved store path, not the data folder', async () => {+ const ws = await import('../agentWorkspace')+ await ws.revealStore()+ expect(revealItemInDir).toHaveBeenCalledWith('/data/agent-workspace')+ })+})diff --git a/web-app/src/lib/__tests__/codeTurns.test.ts b/web-app/src/lib/__tests__/codeTurns.test.tsnew file mode 100644index 000000000..402ed3859--- /dev/null+++ b/web-app/src/lib/__tests__/codeTurns.test.ts@@ -0,0 +1,104 @@+import { describe, it, expect } from 'vitest'+import { codeTurnsToUIMessages } from '@/lib/codeTurns'+import type { CodeTurn } from '@/hooks/useCodeSessions'++/* eslint-disable @typescript-eslint/no-explicit-any */+const partsOf = (messages: any[], index = 0) => messages[index]?.parts ?? []+const toolPart = (turns: CodeTurn[]) =>+ partsOf(codeTurnsToUIMessages(turns)).find((p: any) =>+ p.type?.startsWith('tool-')+ )++describe('codeTurnsToUIMessages', () => {+ it('starts a new user message and flushes the assistant before it', () => {+ const messages = codeTurnsToUIMessages([+ { role: 'user', content: 'first' },+ { role: 'assistant', content: 'answer' },+ { role: 'user', content: 'second' },+ ])+ expect(messages.map((m) => m.role)).toEqual([+ 'user',+ 'assistant',+ 'user',+ ])+ })++ it('maps a tool turn onto a tool-<name> part carrying its input', () => {+ const part = toolPart([+ {+ role: 'tool',+ content: '',+ callId: 'call-1',+ name: 'edit',+ args: { path: 'a.ts' },+ result: 'ok',+ status: 'done',+ },+ ])+ expect(part.type).toBe('tool-edit')+ expect(part.toolCallId).toBe('call-1')+ expect(part.input).toEqual({ path: 'a.ts' })+ expect(part.state).toBe('output-available')+ expect(part.output).toBe('ok')+ })++ it('leaves a running tool call awaiting output', () => {+ const part = toolPart([+ { role: 'tool', content: '', callId: 'c', name: 'bash', status: 'running' },+ ])+ expect(part.state).toBe('input-available')+ expect(part.output).toBeUndefined()+ expect(part.errorText).toBeUndefined()+ })++ it('routes a failed tool call to errorText, not output', () => {+ const part = toolPart([+ {+ role: 'tool',+ content: '',+ callId: 'c',+ name: 'bash',+ result: 'boom',+ isError: true,+ status: 'done',+ },+ ])+ expect(part.state).toBe('output-error')+ expect(part.errorText).toBe('boom')+ expect(part.output).toBeUndefined()+ })++ // The diff used to be prepended to the output text, which both showed the+ // model a diff it authored and corrupted the output AgentToolWidget parses.+ // It now travels via useToolCallRuntime.diffs instead.+ it('keeps the diff out of the tool output entirely', () => {+ const diff = '@@ edit 1/1 @@\n-old\n+new'+ const part = toolPart([+ {+ role: 'tool',+ content: '',+ callId: 'c',+ name: 'edit',+ result: 'wrote a.ts',+ diff,+ status: 'done',+ },+ ])+ expect(part.output).toBe('wrote a.ts')+ expect(JSON.stringify(part)).not.toContain('+new')+ })++ it('falls back to legacy content when a turn has no result', () => {+ const part = toolPart([+ { role: 'tool', content: 'legacy body', callId: 'c', name: 'read' },+ ])+ expect(part.output).toBe('legacy body')+ })++ it('keeps ids unique across prefixes so committed and live turns can merge', () => {+ const turns: CodeTurn[] = [{ role: 'user', content: 'hi' }]+ const committed = codeTurnsToUIMessages(turns, 'c')+ const live = codeTurnsToUIMessages(turns, 'l')+ expect(committed[0].id).not.toBe(live[0].id)+ })+})diff --git a/web-app/src/lib/__tests__/skillStore.test.ts b/web-app/src/lib/__tests__/skillStore.test.tsnew file mode 100644index 000000000..1c03c60fc--- /dev/null+++ b/web-app/src/lib/__tests__/skillStore.test.ts@@ -0,0 +1,110 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import {+ listSkills,+ readSkill,+ writeSkill,+ deleteSkill,+ projectScope,+ storeScope,+} from '@/lib/skillStore'++// Hoisted: vi.mock factories are lifted above module-level consts, so the spies+// have to be created in the same hoisted scope to be referenceable there.+const { api, invoke, getJanDataFolder } = vi.hoisted(() => ({+ api: {+ skillList: vi.fn(),+ skillRead: vi.fn(),+ skillWrite: vi.fn(),+ skillDelete: vi.fn(),+ },+ invoke: vi.fn(),+ getJanDataFolder: vi.fn(),+}))++vi.mock('@janhq/tauri-plugin-agent-tools-api', () => api)+vi.mock('@tauri-apps/api/core', () => ({ invoke }))+vi.mock('@/hooks/useServiceHub', () => ({+ getServiceHub: () => ({ app: () => ({ getJanDataFolder }) }),+}))++describe('skillStore', () => {+ beforeEach(() => {+ Object.values(api).forEach((fn) => fn.mockReset())+ invoke.mockReset().mockResolvedValue(undefined)+ getJanDataFolder.mockReset().mockResolvedValue('/data')+ })++ describe('store scope', () => {+ it('goes through guest-js against the data folder, with no project', async () => {+ api.skillList.mockResolvedValue([{ name: 'deploy', description: 'd' }])+ api.skillRead.mockResolvedValue('body')++ await expect(listSkills(storeScope)).resolves.toEqual([+ { name: 'deploy', description: 'd' },+ ])+ await expect(readSkill(storeScope, 'deploy')).resolves.toBe('body')+ await writeSkill(storeScope, 'deploy', 'text')+ await deleteSkill(storeScope, 'deploy')++ expect(api.skillList).toHaveBeenCalledWith('/data')+ expect(api.skillRead).toHaveBeenCalledWith('/data', 'deploy')+ expect(api.skillWrite).toHaveBeenCalledWith('/data', 'deploy', 'text')+ expect(api.skillDelete).toHaveBeenCalledWith('/data', 'deploy')+ expect(invoke).not.toHaveBeenCalled()+ })++ it('fails loudly when the data folder is unavailable', async () => {+ getJanDataFolder.mockResolvedValue(null)+ await expect(listSkills(storeScope)).rejects.toThrow(+ 'Jan data folder is unavailable'+ )+ })+ })++ describe('project scope', () => {+ const scope = projectScope('/proj')++ it('routes every operation to the core commands with the project path', async () => {+ invoke.mockResolvedValueOnce([{ name: 'lint', description: 'l' }])+ await expect(listSkills(scope)).resolves.toEqual([+ { name: 'lint', description: 'l' },+ ])+ expect(invoke).toHaveBeenCalledWith('agent_skill_list', {+ project: '/proj',+ })++ invoke.mockResolvedValueOnce('body')+ await expect(readSkill(scope, 'lint')).resolves.toBe('body')+ expect(invoke).toHaveBeenCalledWith('agent_skill_read', {+ project: '/proj',+ name: 'lint',+ })++ await deleteSkill(scope, 'lint')+ expect(invoke).toHaveBeenCalledWith('agent_skill_delete', {+ project: '/proj',+ name: 'lint',+ })+ })++ // agent_skill_write also runs ensure_project, scaffolding agent.toml and+ // AGENT.md. The plugin owns no config format and cannot write them, so+ // routing this through guest-js would silently drop the scaffold.+ it('writes through the core command so the project scaffold is preserved', async () => {+ await writeSkill(scope, 'lint', 'text')+ expect(invoke).toHaveBeenCalledWith('agent_skill_write', {+ project: '/proj',+ name: 'lint',+ content: 'text',+ })+ expect(api.skillWrite).not.toHaveBeenCalled()+ })++ it('never resolves the data folder, so it cannot reach the permanent store', async () => {+ invoke.mockResolvedValueOnce([])+ await listSkills(scope)+ await writeSkill(scope, 'lint', 'text')+ expect(getJanDataFolder).not.toHaveBeenCalled()+ })+ })+})diff --git a/web-app/src/lib/__tests__/toolOrigin.test.ts b/web-app/src/lib/__tests__/toolOrigin.test.tsindex 9642b0f64..8bd45b59f 100644--- a/web-app/src/lib/__tests__/toolOrigin.test.ts+++ b/web-app/src/lib/__tests__/toolOrigin.test.ts@@ -3,6 +3,7 @@ import { resolveToolOrigin } from '../toolOrigin'const context = {isRagTool: false,+ isAgentTool: false,webSearchProviderLabel: 'Exa',}@@ -59,6 +60,24 @@ describe('resolveToolOrigin', () => {).toEqual({ kind: 'rag' })})+ it('recognises a built-in agent tool', () => {+ expect(+ resolveToolOrigin('memory_read', { ...context, isAgentTool: true })+ ).toEqual({ kind: 'agent' })+ })++ // Mirrors the thread route, where agent tools are dispatched before MCP, so a+ // filesystem server exposing `read` does not claim the built-in one's card.+ it('prefers the built-in agent tool over a same-named MCP tool', () => {+ expect(+ resolveToolOrigin('read', {+ ...context,+ isAgentTool: true,+ mcpServer: 'filesystem',+ })+ ).toEqual({ kind: 'agent' })+ })+it('is undefined for an unknown tool', () => {expect(resolveToolOrigin('mystery', context)).toBeUndefined()})diff --git a/web-app/src/lib/__tests__/toolPresentation.test.ts b/web-app/src/lib/__tests__/toolPresentation.test.tsindex 611372375..bce236f19 100644--- a/web-app/src/lib/__tests__/toolPresentation.test.ts+++ b/web-app/src/lib/__tests__/toolPresentation.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from 'vitest'-import { describeNativeToolCall, parseWebFetchOutput } from '../toolPresentation'+import {+ describeNativeToolCall,+ parseBashOutput,+ parseWebFetchOutput,+} from '../toolPresentation'const search = { kind: 'web-search', detail: 'Exa' } as constconst fetchOrigin = { kind: 'web-fetch' } as const@@ -125,3 +129,150 @@ describe('parseWebFetchOutput', () => {expect(parseWebFetchOutput(undefined)).toBeUndefined()})})++const agent = { kind: 'agent' } as const++describe('describeNativeToolCall for agent tools', () => {+ it('builds a terminal from the command', () => {+ expect(describeNativeToolCall(agent, 'bash', { command: 'ls -la' })).toEqual({+ variant: 'terminal',+ command: 'ls -la',+ })+ })++ // The command streams in like any other argument, so a partial one must show.+ it('accepts a partially streamed command', () => {+ expect(describeNativeToolCall(agent, 'bash', { command: 'git pu' })).toEqual({+ variant: 'terminal',+ command: 'git pu',+ })+ })++ // Polling a backgrounded run sends only job_id, so there is no command to show.+ it('marks a job poll', () => {+ expect(describeNativeToolCall(agent, 'bash', { job_id: 'bash-0' })).toEqual({+ variant: 'terminal',+ command: '',+ jobId: 'bash-0',+ })+ })++ it('leads with the pattern for find and grep, path as detail', () => {+ expect(+ describeNativeToolCall(agent, 'grep', { pattern: 'TODO', path: 'src' })+ ).toEqual({ variant: 'workspace', tool: 'grep', target: 'TODO', detail: 'src' })+ expect(describeNativeToolCall(agent, 'find', { pattern: '**/*.rs' })).toEqual({+ variant: 'workspace',+ tool: 'find',+ target: '**/*.rs',+ })+ })++ it('leads with the path for read and ls', () => {+ expect(describeNativeToolCall(agent, 'read', { path: 'a.txt' })).toEqual({+ variant: 'workspace',+ tool: 'read',+ target: 'a.txt',+ })+ expect(describeNativeToolCall(agent, 'ls', {})).toEqual({+ variant: 'workspace',+ tool: 'ls',+ target: '',+ })+ })++ it('leads with the name for memory and skill tools', () => {+ expect(describeNativeToolCall(agent, 'memory_read', { name: 'prefs' })).toEqual({+ variant: 'workspace',+ tool: 'memory_read',+ target: 'prefs',+ })+ })+})++describe('parseBashOutput', () => {+ it('splits the trailing exit marker off the body', () => {+ const r = parseBashOutput('total 0\nfile.txt\n[exit 0]')+ expect(r.text).toBe('total 0\nfile.txt')+ expect(r.exit).toBe(0)+ expect(r.signaled).toBe(false)+ })++ it('keeps a non-zero exit code', () => {+ const r = parseBashOutput('nope: not found\n[exit 127]')+ expect(r.text).toBe('nope: not found')+ expect(r.exit).toBe(127)+ })++ it('recognises a signal termination', () => {+ const r = parseBashOutput('partial\n[terminated by signal]')+ expect(r.text).toBe('partial')+ expect(r.signaled).toBe(true)+ expect(r.exit).toBeUndefined()+ })++ it('flags truncated output', () => {+ const r = parseBashOutput('tail lines\n[output truncated, full output at /tmp/x]\n[exit 0]')+ expect(r.truncated).toBe(true)+ expect(r.exit).toBe(0)+ })++ // The order Rust actually emits: `finish()` appends the exit marker first and+ // the truncation notice after it. Anchoring the exit match to end-of-string+ // lost the code on exactly these runs.+ it('still finds the exit code when a truncation notice follows it', () => {+ const r = parseBashOutput(+ 'tail lines\n[exit 2]\n[output truncated at 100 of 900 bytes; full output ' ++ 'written to /tmp/x. Use the read tool (with offset/limit) on that path]'+ )+ expect(r.exit).toBe(2)+ expect(r.truncated).toBe(true)+ expect(r.text).toBe('tail lines')+ })++ it('surfaces the sandbox hint separately from the body', () => {+ const r = parseBashOutput(+ "touch: cannot touch '/etc/x': Read-only file system\n[exit 1]\n" ++ '[sandbox: writes are limited to the workspace (/data/ws) and files under ' ++ 'your home directory are not readable. Network access is disabled.]'+ )+ expect(r.exit).toBe(1)+ expect(r.text).toBe("touch: cannot touch '/etc/x': Read-only file system")+ expect(r.sandboxNote).toContain('writes are limited to the workspace')+ expect(r.sandboxNote).toContain('Network access is disabled')+ })++ it('has no sandbox note on an ordinary run', () => {+ expect(parseBashOutput('ok\n[exit 0]').sandboxNote).toBeUndefined()+ })++ // A command that prints an exit-marker-shaped line must not shadow the real one.+ it('takes the last exit marker when the output echoes one', () => {+ const r = parseBashOutput('log says [exit 0]\n[exit 3]')+ expect(r.exit).toBe(3)+ expect(r.text).toBe('log says [exit 0]')+ })++ it('strips notices from a signalled run too', () => {+ const r = parseBashOutput(+ 'partial\n[terminated by signal]\n[sandbox: writes are limited to X.]'+ )+ expect(r.signaled).toBe(true)+ expect(r.text).toBe('partial')+ expect(r.sandboxNote).toBe('writes are limited to X.')+ })++ // Mid-run there is no marker yet; the body is whatever has arrived.+ it('leaves an unfinished run without an exit code', () => {+ const r = parseBashOutput('still going')+ expect(r.text).toBe('still going')+ expect(r.exit).toBeUndefined()+ expect(r.signaled).toBe(false)+ })++ it('handles a wrapped content payload and no output at all', () => {+ expect(parseBashOutput({ content: 'hi\n[exit 0]' }).text).toBe('hi')+ expect(parseBashOutput(undefined).text).toBe('')+ expect(parseBashOutput(undefined).exit).toBeUndefined()+ })+})diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsnew file mode 100644index 000000000..9546b4522--- /dev/null+++ b/web-app/src/lib/agentTools.ts@@ -0,0 +1,181 @@+import {+ toolSchemas,+ executeTool,+ sandboxStatus,+ threadWorkspaceDelete,+ threadWorkspaceSweep,+ type SandboxStatus,+ type ToolSchema,+} from '@janhq/tauri-plugin-agent-tools-api'+import { getServiceHub } from '@/hooks/useServiceHub'+import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'++/**+ * The built-in agent tools the desktop can dispatch.+ *+ * `write` and `edit` are included: they can only touch the thread's ephemeral+ * sandbox, which is deleted with the conversation, so `execute_tool` allows them+ * without a prompt. Withholding them while `bash` can write the same files would+ * be a restriction a sibling tool trivially bypasses.+ *+ * `web_search`/`web_fetch` are also built-ins but are already advertised through+ * the websearch plugin (see `webSearchTool.ts`), so they are not duplicated here.+ */+export const AGENT_TOOL_NAMES = new Set([+ 'read',+ 'ls',+ 'find',+ 'grep',+ 'write',+ 'edit',+ 'bash',+ 'memory_list',+ 'memory_read',+ 'memory_write',+ 'skill_list',+ 'skill_read',+ 'skill_write',+])++/**+ * Tools that only run under an enforcing OS sandbox. They stay in+ * `AGENT_TOOL_NAMES` -- the desktop still owns dispatching them -- but are held+ * back from the advertised schemas when no backend can confine them.+ */+const SANDBOX_REQUIRED_TOOLS = new Set(['bash'])++let schemaCache: ToolSchema[] | null = null+let statusCache: Promise<SandboxStatus> | null = null++/**+ * The sandbox backend for this machine, fetched once. A failure is treated as+ * "no sandbox", which withholds `bash` rather than offering something that+ * cannot run.+ */+export function getSandboxStatus(): Promise<SandboxStatus> {+ statusCache ??= sandboxStatus()+ .catch((e) => {+ console.warn('[agentTools] Failed to read sandbox status:', messageOf(e))+ return { backend: 'none', enforces: false }+ })+ .then((s) => {+ enforcesNow = s.enforces+ return s+ })+ return statusCache+}++let enforcesNow = false++/**+ * Synchronous view of the sandbox, for building the system prompt. `false` until+ * the probe resolves, which is safe: the prompt is assembled after+ * `getAgentToolSchemas`, so by then the answer is known.+ */+export function sandboxEnforces(): boolean {+ return enforcesNow+}++/**+ * Schemas for the advertised subset. Rust's `schema.rs` is the only source, and+ * the sandbox decides whether `bash` is among them.+ */+export async function getAgentToolSchemas(): Promise<ToolSchema[]> {+ if (schemaCache) return schemaCache+ const [all, sandbox] = await Promise.all([toolSchemas(), getSandboxStatus()])+ schemaCache = all.filter(+ (s) =>+ AGENT_TOOL_NAMES.has(s.function.name) &&+ (sandbox.enforces || !SANDBOX_REQUIRED_TOOLS.has(s.function.name))+ )+ return schemaCache+}++type AgentToolResult = {+ content?: unknown+ error?: string+ /** Unified diff from `write`/`edit`. Display-only; never sent to the model. */+ diff?: string+}++const messageOf = (e: unknown): string =>+ e && typeof e === 'object' && 'message' in e+ ? String((e as { message: unknown }).message)+ : String(e)++/**+ * Execute one built-in agent tool.+ *+ * The filesystem tools are confined to this thread's own sandbox, so scratch+ * files from one conversation are invisible to the next; memory and skill tools+ * reach the permanent store instead and persist. No project path is passed --+ * the desktop has no project picker yet, so the plugin uses the permanent store+ * in the Jan data folder.+ *+ * `bash` additionally runs under an OS sandbox, whose network access follows the+ * `bashNetworkEnabled` setting. It is read here, per call, rather than captured+ * once, so toggling it takes effect on the next command instead of the next+ * restart.+ */+export async function executeAgentTool(+ toolName: string,+ input: unknown,+ threadId: string+): Promise<AgentToolResult> {+ try {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return { error: 'Jan data folder is unavailable' }+ const args =+ input && typeof input === 'object'+ ? (input as Record<string, unknown>)+ : {}+ const result = await executeTool(+ dataFolder,+ threadId,+ toolName,+ args,+ undefined,+ undefined,+ useAgentToolsConfig.getState().bashNetworkEnabled+ )+ if (result.isError) return { error: result.content }+ return { content: result.content, diff: result.diff ?? undefined }+ } catch (e) {+ return { error: messageOf(e) }+ }+}++/**+ * Delete a thread's sandbox. Best-effort: a failure here leaves a directory+ * behind for the next startup sweep to collect, which is not worth surfacing+ * while the user is deleting a thread.+ */+export async function cleanupThreadWorkspace(threadId: string): Promise<void> {+ try {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return+ await threadWorkspaceDelete(dataFolder, threadId)+ } catch (e) {+ console.warn(+ `[agentTools] Failed to delete workspace for thread ${threadId}:`,+ messageOf(e)+ )+ }+}++/**+ * Delete sandboxes left behind by threads that no longer exist, returning how+ * many were removed. Best-effort, same reasoning as above.+ */+export async function sweepThreadWorkspaces(+ liveThreadIds: string[]+): Promise<number> {+ try {+ const dataFolder = await getServiceHub().app().getJanDataFolder()+ if (!dataFolder) return 0+ return await threadWorkspaceSweep(dataFolder, liveThreadIds)+ } catch (e) {+ console.warn('[agentTools] Failed to sweep thread workspaces:', messageOf(e))+ return 0+ }+}diff --git a/web-app/src/lib/agentWorkspace.ts b/web-app/src/lib/agentWorkspace.tsnew file mode 100644index 000000000..b46f3c493--- /dev/null+++ b/web-app/src/lib/agentWorkspace.ts@@ -0,0 +1,63 @@+import {+ workspacePath,+ memoryList,+ memoryRead,+ memoryWrite,+ memoryDelete,+} from '@janhq/tauri-plugin-agent-tools-api'+import { getServiceHub } from '@/hooks/useServiceHub'+import * as skillStore from '@/lib/skillStore'+import type { SkillMeta } from '@/lib/skillStore'++export type { SkillMeta }++/**+ * The management surface over the agent's permanent store, for the settings UI.+ * Separate from `agentTools.ts`, which is the chat-loop surface: this one edits+ * what the agent remembers, that one executes what the model calls.+ *+ * Errors are thrown rather than swallowed. Unlike a tool call, a failed edit has+ * a user waiting on it, so the page surfaces it.+ */++const dataFolder = async (): Promise<string> => {+ const folder = await getServiceHub().app().getJanDataFolder()+ if (!folder) throw new Error('Jan data folder is unavailable')+ return folder+}++/** Path of the permanent store, created if absent. */+export async function storePath(): Promise<string> {+ return await workspacePath(await dataFolder())+}++// Skill CRUD is shared with the code screen's per-project skills; only the root+// differs. These bind this page to the permanent store.+export const listSkills = () => skillStore.listSkills(skillStore.storeScope)+export const readSkill = (name: string) =>+ skillStore.readSkill(skillStore.storeScope, name)+export const writeSkill = (name: string, content: string) =>+ skillStore.writeSkill(skillStore.storeScope, name, content)+export const deleteSkill = (name: string) =>+ skillStore.deleteSkill(skillStore.storeScope, name)++export async function listMemories(): Promise<string[]> {+ return await memoryList(await dataFolder())+}++export async function readMemory(name: string): Promise<string> {+ return await memoryRead(await dataFolder(), name)+}++export async function writeMemory(name: string, content: string): Promise<void> {+ await memoryWrite(await dataFolder(), name, content)+}++export async function deleteMemory(name: string): Promise<void> {+ await memoryDelete(await dataFolder(), name)+}++/** Open the store in the OS file manager. */+export async function revealStore(): Promise<void> {+ await getServiceHub().opener().revealItemInDir(await storePath())+}diff --git a/web-app/src/lib/codeTurns.ts b/web-app/src/lib/codeTurns.tsindex b42605aec..0f2e2d0ee 100644--- a/web-app/src/lib/codeTurns.ts+++ b/web-app/src/lib/codeTurns.ts@@ -12,8 +12,10 @@ import { reasoningPartsFromText } from '@/lib/messages'* as reasoning/`text` parts, tool calls as `tool-<name>` parts) until the next user turn —* mirroring how one agent turn maps to one assistant message with ordered parts.*- * `diff` has no dedicated slot in the UIMessage tool part, so it is prepended to- * the tool output as text (per the chosen tradeoff — non-colored).+ * `diff` has no slot on a UIMessage tool part, so it does not travel here at all.+ * It is published to `useToolCallRuntime.diffs` by the caller and rendered as a+ * real coloured diff by `AgentToolWidget`, keyed on `toolCallId`. Folding it into+ * the output text would also corrupt the output the widget parses.*/export function codeTurnsToUIMessages(turns: CodeTurn[],@@ -73,9 +75,8 @@ export function codeTurnsToUIMessages(}if (!running) {- // Legacy turns carry only `content`; new turns carry result (+optional diff).- const body = turn.result ?? turn.content ?? ''- const output = turn.diff ? `${turn.diff}\n\n${body}` : body+ // Legacy turns carry only `content`; new turns carry `result`.+ const output = turn.result ?? turn.content ?? ''if (turn.isError) {part.errorText = output} else {diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 1320f414e..8fd82ef3c 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -27,6 +27,8 @@ import {WEB_FETCH_DESCRIPTION,WEB_FETCH_INPUT_SCHEMA,} from '@/lib/webSearchTool'+import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'+import { getAgentToolSchemas, sandboxEnforces } from '@/lib/agentTools'import { useAppState } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'import { ExtensionManager } from '@/lib/extension'@@ -969,6 +971,22 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {inputSchema: jsonSchema(WEB_FETCH_INPUT_SCHEMA as Record<string, unknown>),} as Tool}++ // Built-in agent tools (filesystem reads plus skills/memory), provided by+ // the agent-tools plugin. Schemas come from Rust so they are never+ // re-typed here.+ if (useAgentToolsConfig.getState().agentToolsEnabled) {+ try {+ for (const schema of await getAgentToolSchemas()) {+ toolsRecord[schema.function.name] = {+ description: schema.function.description,+ inputSchema: jsonSchema(schema.function.parameters),+ } as Tool+ }+ } catch (error) {+ console.warn('Failed to load agent tools:', error)+ }+ }}this.tools = toolsRecord@@ -1224,8 +1242,14 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const filesInstruction = this.buildFilesSystemInstruction(messagesToConvert)const webSearchInstruction = this.buildWebSearchSystemInstruction()+ const agentToolsInstruction = this.buildAgentToolsSystemInstruction()const rawSystem =- [this.systemMessage, filesInstruction, webSearchInstruction]+ [+ this.systemMessage,+ filesInstruction,+ webSearchInstruction,+ agentToolsInstruction,+ ].filter((s) => typeof s === 'string' && s.trim().length > 0).join('\n\n') || undefined// Drop whitespace-only system prompts so we don't send a useless system@@ -1629,6 +1653,41 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {].join(' ')}+ /**+ * Static instruction describing the isolated agent workspace the built-in+ * tools operate in. Only added when the toolset is enabled so it doesn't+ * affect prompt caching for users who keep it off.+ */+ buildAgentToolsSystemInstruction(): string {+ if (!useAgentToolsConfig.getState().agentToolsEnabled) return ''+ const parts = [+ '# Workspace',+ 'read, ls, find, grep, write and edit operate on an isolated agent',+ "workspace, not the user's whole filesystem. Paths are relative to that",+ 'workspace root and cannot escape it. The workspace is scratch space for',+ 'this conversation only and is deleted with it, so do not keep anything',+ 'there that should last. Use memory_write to persist facts worth remembering',+ 'across conversations, and memory_list/memory_read to recall them. Skills',+ 'are reusable instructions: list and read them before a task they cover,',+ 'and record a repeatable procedure with skill_write.',+ ]+ // Stating the limits up front is cheaper than letting the model discover+ // them by having a command refused. Only when bash is actually offered.+ if (sandboxEnforces()) {+ parts.push(+ 'bash runs commands in that workspace under an OS sandbox: it starts',+ 'there, can only write there, and cannot read files in the',+ "user's home directory."+ )+ parts.push(+ useAgentToolsConfig.getState().bashNetworkEnabled+ ? 'It has network access.'+ : 'It has no network access, so commands that download or upload will fail.'+ )+ }+ return parts.join(' ')+ }+mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {return messages.map((message) => {if (message.role === 'user') {diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.tsindex f94b309b9..5dfe41bf2 100644--- a/web-app/src/lib/hydrateStores.ts+++ b/web-app/src/lib/hydrateStores.ts@@ -21,6 +21,7 @@ import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'import { useAgentMode } from '@/hooks/useAgentMode'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { useCodeSessions } from '@/hooks/useCodeSessions'+import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'/*** Stores persisted through `backendStorage` set `skipHydration: true` so they@@ -53,6 +54,7 @@ const secondaryStores = [useAgentMode,useWebSearchConfig,useCodeSessions,+ useAgentToolsConfig,] as constexport async function hydrateBackendStores(): Promise<void> {diff --git a/web-app/src/lib/skillStore.ts b/web-app/src/lib/skillStore.tsnew file mode 100644index 000000000..7c73835e4--- /dev/null+++ b/web-app/src/lib/skillStore.ts@@ -0,0 +1,96 @@+import { invoke } from '@tauri-apps/api/core'+import {+ skillList,+ skillRead,+ skillWrite,+ skillDelete,+ type SkillMeta,+} from '@janhq/tauri-plugin-agent-tools-api'+import { getServiceHub } from '@/hooks/useServiceHub'++export type { SkillMeta }++/**+ * Skill CRUD, for both roots a skill can live under.+ *+ * A skill is the same thing on disk either way -- `<root>/skills/<name>/SKILL.md`+ * -- and Rust runs one implementation for both. Only the root differs, so this is+ * the single place that picks one:+ *+ * - `store` -- the desktop's permanent store in the Jan data folder, managed+ * from Settings. Reached through the plugin's guest-js.+ * - `project` -- a project's co-located `<folder>/.jan/agent`, managed from the+ * code screen.+ *+ * The project scope deliberately keeps using the core `agent_skill_*` commands+ * rather than the plugin's. They are not redundant: `agent_skill_write` also runs+ * `ensure_project`, which scaffolds `agent.toml` and `AGENT.md`. That format is+ * owned by `core::agent::project`, and the plugin must not learn to write it --+ * owning no config format is what let the toolset be extracted at all. Routing+ * project writes through guest-js would silently drop the scaffold.+ */+export type SkillScope =+ | { kind: 'store' }+ | { kind: 'project'; folder: string }++export const storeScope: SkillScope = { kind: 'store' }+export const projectScope = (folder: string): SkillScope => ({+ kind: 'project',+ folder,+})++const dataFolder = async (): Promise<string> => {+ const folder = await getServiceHub().app().getJanDataFolder()+ if (!folder) throw new Error('Jan data folder is unavailable')+ return folder+}++export async function listSkills(scope: SkillScope): Promise<SkillMeta[]> {+ if (scope.kind === 'project') {+ return await invoke<SkillMeta[]>('agent_skill_list', {+ project: scope.folder,+ })+ }+ return await skillList(await dataFolder())+}++/** Raw SKILL.md text, frontmatter included. */+export async function readSkill(+ scope: SkillScope,+ name: string+): Promise<string> {+ if (scope.kind === 'project') {+ return await invoke<string>('agent_skill_read', {+ project: scope.folder,+ name,+ })+ }+ return await skillRead(await dataFolder(), name)+}++export async function writeSkill(+ scope: SkillScope,+ name: string,+ content: string+): Promise<void> {+ if (scope.kind === 'project') {+ await invoke('agent_skill_write', {+ project: scope.folder,+ name,+ content,+ })+ return+ }+ await skillWrite(await dataFolder(), name, content)+}++export async function deleteSkill(+ scope: SkillScope,+ name: string+): Promise<void> {+ if (scope.kind === 'project') {+ await invoke('agent_skill_delete', { project: scope.folder, name })+ return+ }+ await skillDelete(await dataFolder(), name)+}diff --git a/web-app/src/lib/toolOrigin.ts b/web-app/src/lib/toolOrigin.tsindex 7ffdf137a..317f404ac 100644--- a/web-app/src/lib/toolOrigin.ts+++ b/web-app/src/lib/toolOrigin.ts@@ -1,18 +1,20 @@/**- * Where a tool call came from. Jan runs three families of tools -- the native- * web tools, the built-in RAG tools, and MCP server tools -- and a collapsed- * card is ambiguous without saying which.+ * Where a tool call came from. Jan runs four families of tools -- the native+ * web tools, the built-in RAG tools, the built-in agent tools, and MCP server+ * tools -- and a collapsed card is ambiguous without saying which.*/export type ToolOrigin =| { kind: 'web-search'; detail: string }| { kind: 'web-fetch' }| { kind: 'rag' }+ | { kind: 'agent' }| { kind: 'mcp'; detail: string }export type ToolOriginContext = {/** MCP server owning this tool, when it is an MCP tool. */mcpServer?: stringisRagTool: boolean+ isAgentTool: boolean/** Display name of the configured web search provider, e.g. "Exa". */webSearchProviderLabel: string}@@ -22,17 +24,19 @@ export const WEB_FETCH_TOOL = 'web_fetch'/*** Resolution order mirrors the execution order in the thread route: native web- * tools win, then RAG, then MCP. RAG names shadowed by an MCP server are- * already dropped from the RAG set upstream, so the two cannot both match.+ * tools win, then agent tools, then RAG, then MCP. RAG names shadowed by an MCP+ * server are already dropped from the RAG set upstream, so the two cannot both+ * match.*/export function resolveToolOrigin(toolName: string,- { mcpServer, isRagTool, webSearchProviderLabel }: ToolOriginContext+ { mcpServer, isRagTool, isAgentTool, webSearchProviderLabel }: ToolOriginContext): ToolOrigin | undefined {if (toolName === WEB_SEARCH_TOOL) {return { kind: 'web-search', detail: webSearchProviderLabel }}if (toolName === WEB_FETCH_TOOL) return { kind: 'web-fetch' }+ if (isAgentTool) return { kind: 'agent' }if (isRagTool) return { kind: 'rag' }if (mcpServer) return { kind: 'mcp', detail: mcpServer }return undefineddiff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.tsindex 2ff2e2dd3..7595e51d5 100644--- a/web-app/src/lib/toolPresentation.ts+++ b/web-app/src/lib/toolPresentation.ts@@ -13,6 +13,14 @@ export type ToolCallBar =| { variant: 'search'; query: string; count?: number }| { variant: 'address'; url: string }| { variant: 'documents'; query: string; count?: number; fileCount?: number }+ /** `bash`, presented as a terminal. `jobId` set = polling a backgrounded run. */+ | { variant: 'terminal'; command: string; jobId?: string }+ /**+ * The workspace tools. `target` is whatever the call is really about -- a path+ * for read/ls, the pattern for find/grep, the entry name for memory/skill --+ * with `detail` carrying the secondary argument when there is one.+ */+ | { variant: 'workspace'; tool: string; target: string; detail?: string }/*** Owned by the RAG extension (extensions/rag-extension/src/tools.ts) and not@@ -53,9 +61,93 @@ export function describeNativeToolCall(fileCount: Array.isArray(args.file_ids) ? args.file_ids.length : undefined,}}+ if (origin.kind === 'agent') {+ if (toolName === 'bash') {+ const jobId = asString(args.job_id)+ return {+ variant: 'terminal',+ command: asString(args.command),+ jobId: jobId || undefined,+ }+ }+ // find/grep are about their pattern, with the directory as context; the+ // others are about the single path or name they act on. `ls` defaults to the+ // workspace root, which the widget shows rather than an empty bar.+ if (toolName === 'find' || toolName === 'grep') {+ return {+ variant: 'workspace',+ tool: toolName,+ target: asString(args.pattern),+ detail: asString(args.path) || undefined,+ }+ }+ return {+ variant: 'workspace',+ tool: toolName,+ target: asString(args.path) || asString(args.name),+ }+ }return undefined}+export type BashOutput = {+ /** Combined stdout/stderr with the status and notice lines removed. */+ text: string+ exit?: number+ /** The run was killed by a signal instead of exiting. */+ signaled: boolean+ /** Output exceeded the cap; only the last lines are present. */+ truncated: boolean+ /** The OS sandbox refused something; explains the limits that applied. */+ sandboxNote?: string+}++/** Global: the exit marker is not always last, so every match is considered. */+const EXIT_LINE = /\n?\[exit (-?\d+)\]/g+const SIGNAL_LINE = /\n?\[terminated by signal\]/+const TRUNCATION_NOTICE = /\n?\[output truncated[^\]]*\]/+const SANDBOX_NOTICE = /\n?\[sandbox: ([^\]]*)\]/++/**+ * Split `bash`'s `[exit N]` / `[terminated by signal]` status and its trailing+ * notices off its output (see the tool description in `schema.rs`), so the+ * terminal can show a status of its own instead of leaving markers in the+ * scrollback. Absent or partial markers are normal: the run may still be going.+ *+ * The exit marker is deliberately not anchored to the end of the string. Rust+ * appends the truncation notice and the sandbox hint *after* it, so anchoring+ * would silently lose the exit code exactly when something went wrong.+ */+export function parseBashOutput(output: unknown): BashOutput {+ const text =+ typeof output === 'string'+ ? output+ : typeof (output as { content?: unknown })?.content === 'string'+ ? (output as { content: string }).content+ : ''++ const truncated = TRUNCATION_NOTICE.test(text)+ const signaled = SIGNAL_LINE.test(text)+ const sandboxNote = text.match(SANDBOX_NOTICE)?.[1]+ // The last marker is the real one: a command can echo `[exit 0]` itself.+ const exits = [...text.matchAll(EXIT_LINE)]+ const exitMatch = exits.at(-1)++ let body = exitMatch ? text.slice(0, exitMatch.index) : text+ body = body+ .replace(SIGNAL_LINE, '')+ .replace(TRUNCATION_NOTICE, '')+ .replace(SANDBOX_NOTICE, '')++ return {+ text: body.replace(/\s+$/, ''),+ exit: exitMatch ? Number(exitMatch[1]) : undefined,+ signaled,+ truncated,+ sandboxNote,+ }+}+export type WebFetchPage = {title?: stringurl?: stringdiff --git a/web-app/src/locales/ca/tool-approval.json b/web-app/src/locales/ca/tool-approval.jsondeleted file mode 100644index eb14d5b7c..000000000--- a/web-app/src/locales/ca/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Sol·licitud d’ús d’una eina",- "description": "L’assistent vol utilitzar l’eina: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Avís de seguretat:</strong> Eines malicioses o contingut de la conversa podrien enganyar l’assistent perquè faci accions perjudicials. Revisa cada sol·licitud amb cura abans d’aprovar-la.",- "deny": "Denega",- "allowOnce": "Permet un cop",- "alwaysAllow": "Permet en aquest fil",- "permissions": "Permisos",- "approve": "Aprova",- "reject": "Rebutja",- "parameters": "Paràmetres de l’eina"-}diff --git a/web-app/src/locales/ca/tools.json b/web-app/src/locales/ca/tools.jsonindex c7808ce44..ca7037883 100644--- a/web-app/src/locales/ca/tools.json+++ b/web-app/src/locales/ca/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Aquesta eina necessita la teva aprovació abans d’executar-se.","deny": "Denega",- "allowOnce": "Permet un cop"+ "allowOnce": "Permet un cop",+ "title": "Sol·licitud d’ús d’una eina",+ "description": "L’assistent vol utilitzar l’eina:",+ "securityNotice": "Avís de seguretat: Eines malicioses o contingut de la conversa podrien enganyar l’assistent perquè faci accions perjudicials. Revisa cada sol·licitud amb cura abans d’aprovar-la."}}diff --git a/web-app/src/locales/cs/tool-approval.json b/web-app/src/locales/cs/tool-approval.jsondeleted file mode 100644index 8e6002bac..000000000--- a/web-app/src/locales/cs/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Žádost o volání nástroje",- "description": "Asistent chce použít nástroj: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Bezpečnostní upozornění:</strong> Škodlivé nástroje nebo obsah konverzace by mohly potenciálně oklamat asistenta k pokusu o škodlivé akce. Před schválením pečlivě zkontrolujte každé volání nástroje.",- "deny": "Zamítnout",- "allowOnce": "Povolit jednou",- "alwaysAllow": "Povolit ve vlákně",- "permissions": "Oprávnění",- "approve": "Schválit",- "reject": "Odmítnout",- "parameters": "Parametry nástroje"-}diff --git a/web-app/src/locales/cs/tools.json b/web-app/src/locales/cs/tools.jsonindex a1fb9aeaa..0931a2859 100644--- a/web-app/src/locales/cs/tools.json+++ b/web-app/src/locales/cs/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Tento nástroj vyžaduje vaše schválení před spuštěním.","deny": "Zamítnout",- "allowOnce": "Povolit jednou"+ "allowOnce": "Povolit jednou",+ "title": "Žádost o volání nástroje",+ "description": "Asistent chce použít nástroj:",+ "securityNotice": "Bezpečnostní upozornění: Škodlivé nástroje nebo obsah konverzace by mohly potenciálně oklamat asistenta k pokusu o škodlivé akce. Před schválením pečlivě zkontrolujte každé volání nástroje."}}diff --git a/web-app/src/locales/de-DE/tool-approval.json b/web-app/src/locales/de-DE/tool-approval.jsondeleted file mode 100644index 8e214f95f..000000000--- a/web-app/src/locales/de-DE/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Werkzeugaufruf angefordert",- "description": "Der Assistent möchte folgendes Werkzeug verwenden: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Sicherheitshinweis:</strong> Schädliche Werkzeuge oder Konversationsinhalte könnten den Assistenten möglicherweise zu schädlichen Aktionen verleiten. Überprüfe jeden Werkzeug-Aufruf sorgfältig, bevor Du ihn genehmigst.",- "deny": "Verweigern",- "allowOnce": "Einmal erlauben",- "alwaysAllow": "Im Thread erlauben",- "permissions": "Berechtigungen",- "approve": "Genehmigen",- "reject": "Ablehnen",- "parameters": "Werkzeug-Parameter"-}diff --git a/web-app/src/locales/de-DE/tools.json b/web-app/src/locales/de-DE/tools.jsonindex 476c52098..f47f9254f 100644--- a/web-app/src/locales/de-DE/tools.json+++ b/web-app/src/locales/de-DE/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Dieses Werkzeug benötigt Ihre Genehmigung, bevor es ausgeführt wird.","deny": "Ablehnen",- "allowOnce": "Einmal erlauben"+ "allowOnce": "Einmal erlauben",+ "title": "Werkzeugaufruf angefordert",+ "description": "Der Assistent möchte folgendes Werkzeug verwenden:",+ "securityNotice": "Sicherheitshinweis: Schädliche Werkzeuge oder Konversationsinhalte könnten den Assistenten möglicherweise zu schädlichen Aktionen verleiten. Überprüfe jeden Werkzeug-Aufruf sorgfältig, bevor Du ihn genehmigst."}}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex e5049a989..f4cd0b136 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -14,6 +14,10 @@"claude_code": "Claude Code","https_proxy": "HTTPS Proxy","web_search": "Web Search",+ "agent_tools": "Agent Tools",+ "browse": "Browse",+ "starting": "Starting...",+ "activeSuffix": " (Active)","extensions": "Extensions","attachments": "Attachments","general": "General",diff --git a/web-app/src/locales/en/hub.json b/web-app/src/locales/en/hub.jsonindex e4d59ee6a..60c2d1965 100644--- a/web-app/src/locales/en/hub.json+++ b/web-app/src/locales/en/hub.json@@ -14,5 +14,6 @@"useModel": "Use this model","downloadModel": "Download model","tools": "Tools",- "searchPlaceholder": "Search for models on Hugging Face..."+ "searchPlaceholder": "Search for models on Hugging Face...",+ "resumeUnavailable": "Cannot resume this download. Please start it again."}diff --git a/web-app/src/locales/en/provider.json b/web-app/src/locales/en/provider.jsonindex 77596c6b0..df88beb56 100644--- a/web-app/src/locales/en/provider.json+++ b/web-app/src/locales/en/provider.json@@ -13,5 +13,6 @@"invalidBaseUrl": "Base URL must be a valid http(s) URL","globalSettings": "Global settings","stripReasoning": "Strip reasoning from context",- "stripReasoningDesc": "Remove prior turns' thinking/reasoning content before resending history, across all providers. Improves KV-cache reuse for local models, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning."+ "stripReasoningDesc": "Remove prior turns' thinking/reasoning content before resending history, across all providers. Improves KV-cache reuse for local models, but some models (e.g. newer Qwen releases) recommend keeping it for better multi-turn reasoning.",+ "providerAlreadyExists": "A provider named {{name}} already exists."}diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 74614c9b6..2232b1cee 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -198,6 +198,34 @@"endpointDesc": "Required. The base URL of your {{provider}} instance, with the JSON API enabled.","endpointPlaceholder": "https://searx.example.com"},+ "agentTools": {+ "title": "Agent Tools",+ "description": "Give models a private scratch workspace for each conversation, plus memories and skills kept permanently in your Jan data folder.",+ "enable": "Enable Agent Tools",+ "enableDesc": "Advertise the built-in workspace, memory and skill tools to models that support tool use. Tools that need approval stay unavailable.",+ "shell": "Shell Commands",+ "shellChecking": "Checking for a sandbox...",+ "shellSandboxed": "Commands run confined by {{backend}}: they can only write inside the conversation workspace, and files in your home folder are not readable.",+ "shellUnavailable": "No sandbox is available on this system, so the bash tool is not offered. Commands are never run unconfined.",+ "network": "Allow Network Access",+ "networkDesc": "Let commands reach the network. Needed for things like installing packages or fetching a repository. Off by default, so a command cannot send anything off your machine.",+ "openFolder": "Open Folder",+ "memories": "Memories",+ "noMemories": "No memories yet. Models add them with the memory_write tool as they learn things worth keeping.",+ "skills": "Skills",+ "noSkills": "No skills yet. A skill is a reusable set of instructions a model can load on demand.",+ "add": "Add",+ "editMemory": "Edit Memory",+ "editMemoryDesc": "One topic per note. Models read these back with the memory_read tool.",+ "editSkill": "Edit Skill",+ "editSkillDesc": "Markdown instructions, optionally with a description in YAML frontmatter. The description is what models see before loading the skill.",+ "namePlaceholder": "Name",+ "contentPlaceholder": "Content",+ "loadFailed": "Could not load the agent workspace",+ "saveFailed": "Could not save",+ "deleteFailed": "Could not delete",+ "revealFailed": "Could not open the folder"+ },"localApiServer": {"title": "Local API Server","description": "Run an OpenAI-compatible server locally.",diff --git a/web-app/src/locales/en/tool-approval.json b/web-app/src/locales/en/tool-approval.jsondeleted file mode 100644index 2d0c8b549..000000000--- a/web-app/src/locales/en/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Tool Call Request",- "description": "The assistant wants to use the tool: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Security Notice:</strong> Malicious tools or conversation content could potentially trick the assistant into attempting harmful actions. Review each tool call carefully before approving.",- "deny": "Deny",- "allowOnce": "Allow Once",- "alwaysAllow": "Allow in thread",- "permissions": "Permissions",- "approve": "Approve",- "reject": "Reject",- "parameters": "Tool Parameters"-}diff --git a/web-app/src/locales/en/tools.json b/web-app/src/locales/en/tools.jsonindex 53b00d40a..7db560584 100644--- a/web-app/src/locales/en/tools.json+++ b/web-app/src/locales/en/tools.json@@ -5,7 +5,12 @@"allowOnce": "Allow Once","allowInThread": "Allow in thread","allowServerAlways": "Always allow {{server}}",- "allowToolAlways": "Always allow {{tool}}"+ "allowToolAlways": "Always allow {{tool}}",+ "title": "Tool Call Request",+ "description": "The assistant wants to use the tool:",+ "securityNotice": "Security Notice: Malicious tools or conversation content could potentially trick the assistant into attempting harmful actions. Review each tool call carefully before approving.",+ "permissionScope": "You can allow it just this once, or every time.",+ "alwaysAllow": "Always allow"},"toolCall": {"awaitingApproval": "Awaiting approval: {{tool}}",@@ -31,6 +36,7 @@"contentTruncated": "Content truncated","originWeb": "Web","originDocuments": "Documents",+ "originWorkspace": "Workspace","viewRaw": "Raw","viewTable": "Table","showMore": "Show more",@@ -42,6 +48,14 @@"summaryBlocks": "{{text}} text, {{other}} attachment(s)","summaryItems": "{{count}} item(s)","summaryFields": "{{count}} field(s): {{fields}}",- "summaryEmpty": "Empty result"+ "summaryEmpty": "Empty result",+ "terminal": "Terminal",+ "exitCode": "exit {{code}}",+ "terminated": "terminated",+ "outputTruncated": "Output was truncated; only the last lines are shown.",+ "pollingJob": "waiting for background job {{id}}",+ "pathPlaceholder": "path",+ "reading": "Reading...",+ "workspaceRoot": "workspace root"}}diff --git a/web-app/src/locales/es/tool-approval.json b/web-app/src/locales/es/tool-approval.jsondeleted file mode 100644index 84b58fea2..000000000--- a/web-app/src/locales/es/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Solicitud de llamada a herramienta",- "description": "El asistente quiere usar la herramienta: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Aviso de seguridad:</strong> Herramientas maliciosas o contenido de conversación podrían engañar al asistente para que intente acciones dañinas. Revisa cada llamada a herramienta cuidadosamente antes de aprobar.",- "deny": "Denegar",- "allowOnce": "Permitir una vez",- "alwaysAllow": "Permitir en el hilo",- "permissions": "Permisos",- "approve": "Aprobar",- "reject": "Rechazar",- "parameters": "Parámetros de la herramienta"-}diff --git a/web-app/src/locales/es/tools.json b/web-app/src/locales/es/tools.jsonindex 83b94f607..adb9c994d 100644--- a/web-app/src/locales/es/tools.json+++ b/web-app/src/locales/es/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Esta herramienta necesita tu aprobación antes de ejecutarse.","deny": "Denegar",- "allowOnce": "Permitir una vez"+ "allowOnce": "Permitir una vez",+ "title": "Solicitud de llamada a herramienta",+ "description": "El asistente quiere usar la herramienta:",+ "securityNotice": "Aviso de seguridad: Herramientas maliciosas o contenido de conversación podrían engañar al asistente para que intente acciones dañinas. Revisa cada llamada a herramienta cuidadosamente antes de aprobar."}}diff --git a/web-app/src/locales/fr/tool-approval.json b/web-app/src/locales/fr/tool-approval.jsondeleted file mode 100644index bb71a8ba1..000000000--- a/web-app/src/locales/fr/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Demande d'appel d'outil",- "description": "L'assistant souhaite utiliser l'outil : <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Avis de sécurité :</strong> Des outils malveillants ou du contenu de conversation pourraient potentiellement tromper l'assistant pour qu'il tente des actions nuisibles. Examinez attentivement chaque appel d'outil avant de l'approuver.",- "deny": "Refuser",- "allowOnce": "Autoriser une fois",- "alwaysAllow": "Autoriser dans la discussion",- "permissions": "Permissions",- "approve": "Approuver",- "reject": "Rejeter",- "parameters": "Paramètres de l'outil"-}diff --git a/web-app/src/locales/fr/tools.json b/web-app/src/locales/fr/tools.jsonindex eaef22255..86b36f5f0 100644--- a/web-app/src/locales/fr/tools.json+++ b/web-app/src/locales/fr/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Cet outil nécessite votre approbation avant de s'exécuter.","deny": "Refuser",- "allowOnce": "Autoriser une fois"+ "allowOnce": "Autoriser une fois",+ "title": "Demande d'appel d'outil",+ "description": "L'assistant souhaite utiliser l'outil :",+ "securityNotice": "Avis de sécurité : Des outils malveillants ou du contenu de conversation pourraient potentiellement tromper l'assistant pour qu'il tente des actions nuisibles. Examinez attentivement chaque appel d'outil avant de l'approuver."}}diff --git a/web-app/src/locales/hi/tool-approval.json b/web-app/src/locales/hi/tool-approval.jsondeleted file mode 100644index ee854d360..000000000--- a/web-app/src/locales/hi/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "टूल कॉल अनुरोध",- "description": "सहायक निम्नलिखित टूल का उपयोग करने का प्रयास कर रहा है: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>सुरक्षा सूचना:</strong> दुर्भावनापूर्ण टूल या वार्तालाप सामग्री सहायक को हानिकारक कार्रवाई करने के लिए धोखा दे सकती है। अनुमति देने से पहले प्रत्येक टूल कॉल को सावधानीपूर्वक जांचें।",- "deny": "अस्वीकार करें",- "allowOnce": "एक बार अनुमति दें",- "alwaysAllow": "थ्रेड में हमेशा अनुमति दें",- "permissions": "अनुमतियाँ",- "approve": "स्वीकृत करें",- "reject": "अस्वीकार करें",- "parameters": "टूल पैरामीटर"-}\ No newline at end of filediff --git a/web-app/src/locales/hi/tools.json b/web-app/src/locales/hi/tools.jsonindex 0b3e01d92..93b883e0f 100644--- a/web-app/src/locales/hi/tools.json+++ b/web-app/src/locales/hi/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "इस टूल को चलने से पहले आपकी अनुमति की आवश्यकता है।","deny": "अस्वीकार करें",- "allowOnce": "एक बार अनुमति दें"+ "allowOnce": "एक बार अनुमति दें",+ "title": "टूल कॉल अनुरोध",+ "description": "सहायक निम्नलिखित टूल का उपयोग करने का प्रयास कर रहा है:",+ "securityNotice": "सुरक्षा सूचना: दुर्भावनापूर्ण टूल या वार्तालाप सामग्री सहायक को हानिकारक कार्रवाई करने के लिए धोखा दे सकती है। अनुमति देने से पहले प्रत्येक टूल कॉल को सावधानीपूर्वक जांचें।"}}diff --git a/web-app/src/locales/id/tool-approval.json b/web-app/src/locales/id/tool-approval.jsondeleted file mode 100644index 6193d97e3..000000000--- a/web-app/src/locales/id/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Permintaan Panggilan Alat",- "description": "Asisten ingin menggunakan alat: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Pemberitahuan Keamanan:</strong> Alat berbahaya atau konten percakapan dapat menipu asisten untuk mencoba melakukan tindakan yang merugikan. Tinjau setiap permintaan penggunaan alat dengan cermat sebelum menyetujui.",- "deny": "Tolak",- "allowOnce": "Izinkan Sekali",- "alwaysAllow": "Izinkan di thread",- "permissions": "Izin",- "approve": "Setujui",- "reject": "Tolak",- "parameters": "Parameter Alat"-}\ No newline at end of filediff --git a/web-app/src/locales/id/tools.json b/web-app/src/locales/id/tools.jsonindex 2e328be03..a14115de2 100644--- a/web-app/src/locales/id/tools.json+++ b/web-app/src/locales/id/tools.json@@ -2,6 +2,9 @@"toolApproval": {"deny": "Tolak","allowOnce": "Izinkan Sekali",- "needsApproval": "Alat ini memerlukan persetujuan Anda sebelum dijalankan."+ "needsApproval": "Alat ini memerlukan persetujuan Anda sebelum dijalankan.",+ "title": "Permintaan Panggilan Alat",+ "description": "Asisten ingin menggunakan alat:",+ "securityNotice": "Pemberitahuan Keamanan: Alat berbahaya atau konten percakapan dapat menipu asisten untuk mencoba melakukan tindakan yang merugikan. Tinjau setiap permintaan penggunaan alat dengan cermat sebelum menyetujui."}}diff --git a/web-app/src/locales/it/tool-approval.json b/web-app/src/locales/it/tool-approval.jsondeleted file mode 100644index fe87356b1..000000000--- a/web-app/src/locales/it/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Richiesta chiamata strumento",- "description": "L'assistente vuole utilizzare lo strumento: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Avviso di sicurezza:</strong> strumenti dannosi o il contenuto della conversazione potrebbero ingannare l'assistente spingendolo a compiere azioni nocive. Verifica attentamente ogni chiamata prima di approvarla.",- "deny": "Rifiuta",- "allowOnce": "Consenti una volta",- "alwaysAllow": "Consenti nella conversazione",- "permissions": "Autorizzazioni",- "approve": "Approva",- "reject": "Rifiuta",- "parameters": "Parametri dello strumento"-}diff --git a/web-app/src/locales/it/tools.json b/web-app/src/locales/it/tools.jsonindex 425146c08..582d59820 100644--- a/web-app/src/locales/it/tools.json+++ b/web-app/src/locales/it/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Questo strumento richiede la tua approvazione prima di essere eseguito.","deny": "Rifiuta",- "allowOnce": "Consenti una volta"+ "allowOnce": "Consenti una volta",+ "title": "Richiesta chiamata strumento",+ "description": "L'assistente vuole utilizzare lo strumento:",+ "securityNotice": "Avviso di sicurezza: strumenti dannosi o il contenuto della conversazione potrebbero ingannare l'assistente spingendolo a compiere azioni nocive. Verifica attentamente ogni chiamata prima di approvarla."}}diff --git a/web-app/src/locales/ja/tool-approval.json b/web-app/src/locales/ja/tool-approval.jsondeleted file mode 100644index 48cecf3fb..000000000--- a/web-app/src/locales/ja/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "ツール呼び出しリクエスト",- "description": "アシスタントは次のツールを使用しようとしています: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>セキュリティに関するお知らせ:</strong> 悪意のあるツールや会話の内容は、アシスタントを騙して有害なアクションを試みさせる可能性があります。承認する前に、各ツール呼び出しを注意深く確認してください。",- "deny": "拒否",- "allowOnce": "一度だけ許可",- "alwaysAllow": "スレッドで許可",- "permissions": "権限",- "approve": "承認",- "reject": "拒否",- "parameters": "ツールパラメータ"-}\ No newline at end of filediff --git a/web-app/src/locales/ja/tools.json b/web-app/src/locales/ja/tools.jsonindex 68a1aaa27..4176fec31 100644--- a/web-app/src/locales/ja/tools.json+++ b/web-app/src/locales/ja/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "このツールを実行するには承認が必要です。","deny": "拒否",- "allowOnce": "一度だけ許可"+ "allowOnce": "一度だけ許可",+ "title": "ツール呼び出しリクエスト",+ "description": "アシスタントは次のツールを使用しようとしています:",+ "securityNotice": "セキュリティに関するお知らせ: 悪意のあるツールや会話の内容は、アシスタントを騙して有害なアクションを試みさせる可能性があります。承認する前に、各ツール呼び出しを注意深く確認してください。"}}diff --git a/web-app/src/locales/ko/tool-approval.json b/web-app/src/locales/ko/tool-approval.jsondeleted file mode 100644index 4ce6bb73d..000000000--- a/web-app/src/locales/ko/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "도구 호출 요청",- "description": "어시스턴트가 다음 도구를 사용하려고 합니다: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>보안 유의사항:</strong> 악성 도구나 대화 내용으로 인해 어시스턴트가 유해한 작업을 시도하도록 유도될 수 있습니다. 승인하기 전에 각 도구 호출을 주의 깊게 검토하세요.",- "deny": "거부",- "allowOnce": "한 번 허용",- "alwaysAllow": "이 대화에서 허용",- "permissions": "권한",- "approve": "승인",- "reject": "거절",- "parameters": "도구 매개변수"-}diff --git a/web-app/src/locales/ko/tools.json b/web-app/src/locales/ko/tools.jsonindex da77aa688..321619fdf 100644--- a/web-app/src/locales/ko/tools.json+++ b/web-app/src/locales/ko/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "이 도구를 실행하기 전에 승인이 필요합니다.","deny": "거부",- "allowOnce": "한 번 허용"+ "allowOnce": "한 번 허용",+ "title": "도구 호출 요청",+ "description": "어시스턴트가 다음 도구를 사용하려고 합니다:",+ "securityNotice": "보안 유의사항: 악성 도구나 대화 내용으로 인해 어시스턴트가 유해한 작업을 시도하도록 유도될 수 있습니다. 승인하기 전에 각 도구 호출을 주의 깊게 검토하세요."}}diff --git a/web-app/src/locales/pl/tool-approval.json b/web-app/src/locales/pl/tool-approval.jsondeleted file mode 100644index 71263cf42..000000000--- a/web-app/src/locales/pl/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Prośba o Użycie Narzędzia",- "description": "Asystent chce użyć narzędzia: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Ostrzeżenie Bezpieczeństwa:</strong> Złośliwe narzędzia lub treści rozmowy mają potencjał nakłonić agenta do szkodliwych działań. Dokładnie przejrzyj każdą prośbę o użycie narzędzia przed wyrażeniem zgody.",- "deny": "Odmów",- "allowOnce": "Pozwól Raz",- "alwaysAllow": "Pozwól w wątku",- "permissions": "Pozwolenia",- "approve": "Zaakceptuj",- "reject": "Odrzuć",- "parameters": "Parametry Narzędzia"-}diff --git a/web-app/src/locales/pl/tools.json b/web-app/src/locales/pl/tools.jsonindex c2139f2fe..c31a7302b 100644--- a/web-app/src/locales/pl/tools.json+++ b/web-app/src/locales/pl/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "To narzędzie wymaga Twojej zgody przed uruchomieniem.","deny": "Odmów",- "allowOnce": "Pozwól Raz"+ "allowOnce": "Pozwól Raz",+ "title": "Prośba o Użycie Narzędzia",+ "description": "Asystent chce użyć narzędzia:",+ "securityNotice": "Ostrzeżenie Bezpieczeństwa: Złośliwe narzędzia lub treści rozmowy mają potencjał nakłonić agenta do szkodliwych działań. Dokładnie przejrzyj każdą prośbę o użycie narzędzia przed wyrażeniem zgody."}}diff --git a/web-app/src/locales/pt-BR/tool-approval.json b/web-app/src/locales/pt-BR/tool-approval.jsondeleted file mode 100644index 0c0678b12..000000000--- a/web-app/src/locales/pt-BR/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Solicitação de Chamada de Ferramenta",- "description": "O assistente quer usar a ferramenta: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Aviso de Segurança:</strong> Ferramentas maliciosas ou conteúdo de conversa podem potencialmente enganar o assistente para tentar ações prejudiciais. Revise cada chamada de ferramenta cuidadosamente antes de aprovar.",- "deny": "Negar",- "allowOnce": "Permitir Uma Vez",- "alwaysAllow": "Permitir na conversa",- "permissions": "Permissões",- "approve": "Aprovar",- "reject": "Rejeitar",- "parameters": "Parâmetros da Ferramenta"-}diff --git a/web-app/src/locales/pt-BR/tools.json b/web-app/src/locales/pt-BR/tools.jsonindex 1fb7acfbe..ebaf02140 100644--- a/web-app/src/locales/pt-BR/tools.json+++ b/web-app/src/locales/pt-BR/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Esta ferramenta precisa da sua aprovação antes de ser executada.","deny": "Negar",- "allowOnce": "Permitir Uma Vez"+ "allowOnce": "Permitir Uma Vez",+ "title": "Solicitação de Chamada de Ferramenta",+ "description": "O assistente quer usar a ferramenta:",+ "securityNotice": "Aviso de Segurança: Ferramentas maliciosas ou conteúdo de conversa podem potencialmente enganar o assistente para tentar ações prejudiciais. Revise cada chamada de ferramenta cuidadosamente antes de aprovar."}}diff --git a/web-app/src/locales/ru/tool-approval.json b/web-app/src/locales/ru/tool-approval.jsondeleted file mode 100644index f544e52f0..000000000--- a/web-app/src/locales/ru/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Запрос вызова инструмента",- "description": "Ассистент хочет использовать инструмент: <strong>{{toolName}}</strong>.",- "securityNotice": "<strong>Предупреждение безопасности:</strong> Вредоносные инструменты или содержимое диалогов могут обмануть ассистента, заставив его попытаться выполнить опасные действия. Внимательно проверяйте каждый вызов инструмента перед его одобрением.",- "deny": "Запретить",- "allowOnce": "Разрешить один раз",- "alwaysAllow": "Разрешить в обсуждении",- "permissions": "Разрешения",- "approve": "Одобрить",- "reject": "Отклонить",- "parameters": "Параметры инструмента"-}diff --git a/web-app/src/locales/ru/tools.json b/web-app/src/locales/ru/tools.jsonindex e6f186621..fdb0767c9 100644--- a/web-app/src/locales/ru/tools.json+++ b/web-app/src/locales/ru/tools.json@@ -2,6 +2,9 @@"toolApproval": {"needsApproval": "Этот инструмент требует вашего одобрения перед запуском.","deny": "Запретить",- "allowOnce": "Разрешить один раз"+ "allowOnce": "Разрешить один раз",+ "title": "Запрос вызова инструмента",+ "description": "Ассистент хочет использовать инструмент:",+ "securityNotice": "Предупреждение безопасности: Вредоносные инструменты или содержимое диалогов могут обмануть ассистента, заставив его попытаться выполнить опасные действия. Внимательно проверяйте каждый вызов инструмента перед его одобрением."}}diff --git a/web-app/src/locales/vn/tool-approval.json b/web-app/src/locales/vn/tool-approval.jsondeleted file mode 100644index 808a5d72f..000000000--- a/web-app/src/locales/vn/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "Yêu cầu gọi công cụ",- "description": "Trợ lý muốn sử dụng công cụ: <strong>{{toolName}}</strong>",- "securityNotice": "<strong>Thông báo bảo mật:</strong> Các công cụ độc hại hoặc nội dung cuộc trò chuyện có khả năng lừa trợ lý thực hiện các hành động có hại. Hãy xem xét kỹ từng lệnh gọi công cụ trước khi phê duyệt.",- "deny": "Từ chối",- "allowOnce": "Cho phép một lần",- "alwaysAllow": "Cho phép trong chuỗi",- "permissions": "Quyền",- "approve": "Phê duyệt",- "reject": "Từ chối",- "parameters": "Tham số công cụ"-}\ No newline at end of filediff --git a/web-app/src/locales/vn/tools.json b/web-app/src/locales/vn/tools.jsonindex b533cc5b6..9bb39cadf 100644--- a/web-app/src/locales/vn/tools.json+++ b/web-app/src/locales/vn/tools.json@@ -2,6 +2,9 @@"toolApproval": {"deny": "Từ chối","allowOnce": "Cho phép một lần",- "needsApproval": "Công cụ này cần sự chấp thuận của bạn trước khi chạy."+ "needsApproval": "Công cụ này cần sự chấp thuận của bạn trước khi chạy.",+ "title": "Yêu cầu gọi công cụ",+ "description": "Trợ lý muốn sử dụng công cụ:",+ "securityNotice": "Thông báo bảo mật: Các công cụ độc hại hoặc nội dung cuộc trò chuyện có khả năng lừa trợ lý thực hiện các hành động có hại. Hãy xem xét kỹ từng lệnh gọi công cụ trước khi phê duyệt."}}diff --git a/web-app/src/locales/zh-CN/tool-approval.json b/web-app/src/locales/zh-CN/tool-approval.jsondeleted file mode 100644index 3bbc6a745..000000000--- a/web-app/src/locales/zh-CN/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "工具调用请求",- "description": "助手想要使用工具:<strong>{{toolName}}</strong>",- "securityNotice": "<strong>安全警告:</strong>恶意的工具或对话内容可能会诱使助手尝试有害操作。在批准之前,请仔细审查每个工具调用。",- "deny": "拒绝",- "allowOnce": "允许一次",- "alwaysAllow": "在线程中允许",- "permissions": "权限",- "approve": "批准",- "reject": "拒绝",- "parameters": "工具参数"-}\ No newline at end of filediff --git a/web-app/src/locales/zh-CN/tools.json b/web-app/src/locales/zh-CN/tools.jsonindex a9af7a571..f95b18f7e 100644--- a/web-app/src/locales/zh-CN/tools.json+++ b/web-app/src/locales/zh-CN/tools.json@@ -2,6 +2,9 @@"toolApproval": {"deny": "拒绝","allowOnce": "允许一次",- "needsApproval": "此工具需要您的批准才能运行。"+ "needsApproval": "此工具需要您的批准才能运行。",+ "title": "工具调用请求",+ "description": "助手想要使用工具:",+ "securityNotice": "安全警告:恶意的工具或对话内容可能会诱使助手尝试有害操作。在批准之前,请仔细审查每个工具调用。"}}diff --git a/web-app/src/locales/zh-TW/tool-approval.json b/web-app/src/locales/zh-TW/tool-approval.jsondeleted file mode 100644index 120a8af15..000000000--- a/web-app/src/locales/zh-TW/tool-approval.json+++ /dev/null@@ -1,12 +0,0 @@-{- "title": "工具呼叫請求",- "description": "助理想要使用工具:<strong>{{toolName}}</strong>",- "securityNotice": "<strong>安全性通知:</strong>惡意的工具或對話內容可能會誘騙助理嘗試有害的操作。在核准之前,請仔細檢閱每個工具呼叫。",- "deny": "拒絕",- "allowOnce": "允許一次",- "alwaysAllow": "在討論串中允許",- "permissions": "權限",- "approve": "核准",- "reject": "拒絕",- "parameters": "工具參數"-}\ No newline at end of filediff --git a/web-app/src/locales/zh-TW/tools.json b/web-app/src/locales/zh-TW/tools.jsonindex 995d21b31..34da28d27 100644--- a/web-app/src/locales/zh-TW/tools.json+++ b/web-app/src/locales/zh-TW/tools.json@@ -2,6 +2,9 @@"toolApproval": {"deny": "拒絕","allowOnce": "允許一次",- "needsApproval": "此工具需要您的核准才能執行。"+ "needsApproval": "此工具需要您的核准才能執行。",+ "title": "工具呼叫請求",+ "description": "助理想要使用工具:",+ "securityNotice": "安全性通知:惡意的工具或對話內容可能會誘騙助理嘗試有害的操作。在核准之前,請仔細檢閱每個工具呼叫。"}}diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsxindex 80695b3d8..3f28585ee 100644--- a/web-app/src/providers/DataProvider.tsx+++ b/web-app/src/providers/DataProvider.tsx@@ -6,7 +6,7 @@ import {HUGGINGFACE_TOKEN_SECRET_KEY,} from '@/hooks/useGeneralSetting'import { useServiceHub } from '@/hooks/useServiceHub'-import { useEffect } from 'react'+import { useEffect, useRef } from 'react'import { useMCPServers, DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'import { useAssistant } from '@/hooks/useAssistant'import { useNavigate } from '@tanstack/react-router'@@ -18,6 +18,7 @@ import { useAppState } from '@/hooks/useAppState'import { AppEvent, events } from '@janhq/core'import { SystemEvent } from '@/types/events'import { isDev } from '@/lib/utils'+import { sweepThreadWorkspaces } from '@/lib/agentTools'import { invoke } from '@tauri-apps/api/core'import { providerHasRemoteApiKeys, providerRemoteApiKeyChain } from '@/lib/provider-api-keys'@@ -186,6 +187,9 @@ export function DataProvider() {const { setAssistants } = useAssistant()const { setThreads } = useThreads()const setThreadsLoading = useThreads((s) => s.setThreadsLoading)+ // The thread fetch re-runs on extension re-registration; the sandbox sweep+ // should not.+ const sweptWorkspaces = useRef(false)const navigate = useNavigate()const serviceHub = useServiceHub()@@ -303,6 +307,15 @@ export function DataProvider() {}setThreads(threads)setThreadsLoading(false)+ // Collect agent sandboxes whose thread is gone (crash, or a thread+ // deleted while the app was closed). Once per session, and only on a+ // non-empty result: sweeping against an empty list would delete live+ // sandboxes if this fetch were still a transient not-ready state.+ // Leftovers then wait for the next startup that does see threads.+ if (!sweptWorkspaces.current && threads.length > 0) {+ sweptWorkspaces.current = true+ sweepThreadWorkspaces(threads.map((t) => t.id))+ }}).catch(() => {if (cancelled) returndiff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.tsindex 1cb42c97c..2dcbb9231 100644--- a/web-app/src/routeTree.gen.ts+++ b/web-app/src/routeTree.gen.ts@@ -28,6 +28,7 @@ import { Route as SettingsExtensionsRouteImport } from './routes/settings/extensimport { Route as SettingsClaudeCodeRouteImport } from './routes/settings/claude-code'import { Route as SettingsAttachmentsRouteImport } from './routes/settings/attachments'import { Route as SettingsAssistantRouteImport } from './routes/settings/assistant'+import { Route as SettingsAgentToolsRouteImport } from './routes/settings/agent-tools'import { Route as ProjectProjectIdRouteImport } from './routes/project/$projectId'import { Route as LocalApiServerLogsRouteImport } from './routes/local-api-server/logs'import { Route as HubModelIdRouteImport } from './routes/hub/$modelId'@@ -129,6 +130,11 @@ const SettingsAssistantRoute = SettingsAssistantRouteImport.update({path: '/settings/assistant',getParentRoute: () => rootRouteImport,} as any)+const SettingsAgentToolsRoute = SettingsAgentToolsRouteImport.update({+ id: '/settings/agent-tools',+ path: '/settings/agent-tools',+ getParentRoute: () => rootRouteImport,+} as any)const ProjectProjectIdRoute = ProjectProjectIdRouteImport.update({id: '/project/$projectId',path: '/project/$projectId',@@ -164,6 +170,7 @@ export interface FileRoutesByFullPath {'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute+ '/settings/agent-tools': typeof SettingsAgentToolsRoute'/settings/assistant': typeof SettingsAssistantRoute'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute@@ -190,6 +197,7 @@ export interface FileRoutesByTo {'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute+ '/settings/agent-tools': typeof SettingsAgentToolsRoute'/settings/assistant': typeof SettingsAssistantRoute'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute@@ -217,6 +225,7 @@ export interface FileRoutesById {'/hub/$modelId': typeof HubModelIdRoute'/local-api-server/logs': typeof LocalApiServerLogsRoute'/project/$projectId': typeof ProjectProjectIdRoute+ '/settings/agent-tools': typeof SettingsAgentToolsRoute'/settings/assistant': typeof SettingsAssistantRoute'/settings/attachments': typeof SettingsAttachmentsRoute'/settings/claude-code': typeof SettingsClaudeCodeRoute@@ -245,6 +254,7 @@ export interface FileRouteTypes {| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'+ | '/settings/agent-tools'| '/settings/assistant'| '/settings/attachments'| '/settings/claude-code'@@ -271,6 +281,7 @@ export interface FileRouteTypes {| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'+ | '/settings/agent-tools'| '/settings/assistant'| '/settings/attachments'| '/settings/claude-code'@@ -297,6 +308,7 @@ export interface FileRouteTypes {| '/hub/$modelId'| '/local-api-server/logs'| '/project/$projectId'+ | '/settings/agent-tools'| '/settings/assistant'| '/settings/attachments'| '/settings/claude-code'@@ -324,6 +336,7 @@ export interface RootRouteChildren {HubModelIdRoute: typeof HubModelIdRouteLocalApiServerLogsRoute: typeof LocalApiServerLogsRouteProjectProjectIdRoute: typeof ProjectProjectIdRoute+ SettingsAgentToolsRoute: typeof SettingsAgentToolsRouteSettingsAssistantRoute: typeof SettingsAssistantRouteSettingsAttachmentsRoute: typeof SettingsAttachmentsRouteSettingsClaudeCodeRoute: typeof SettingsClaudeCodeRoute@@ -478,6 +491,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsAssistantRouteImportparentRoute: typeof rootRouteImport}+ '/settings/agent-tools': {+ id: '/settings/agent-tools'+ path: '/settings/agent-tools'+ fullPath: '/settings/agent-tools'+ preLoaderRoute: typeof SettingsAgentToolsRouteImport+ parentRoute: typeof rootRouteImport+ }'/project/$projectId': {id: '/project/$projectId'path: '/project/$projectId'@@ -524,6 +544,7 @@ const rootRouteChildren: RootRouteChildren = {HubModelIdRoute: HubModelIdRoute,LocalApiServerLogsRoute: LocalApiServerLogsRoute,ProjectProjectIdRoute: ProjectProjectIdRoute,+ SettingsAgentToolsRoute: SettingsAgentToolsRoute,SettingsAssistantRoute: SettingsAssistantRoute,SettingsAttachmentsRoute: SettingsAttachmentsRoute,SettingsClaudeCodeRoute: SettingsClaudeCodeRoute,diff --git a/web-app/src/routes/code.tsx b/web-app/src/routes/code.tsxindex dfbb17c9e..a5b463ddb 100644--- a/web-app/src/routes/code.tsx+++ b/web-app/src/routes/code.tsx@@ -29,6 +29,7 @@ import CodePermissionDialog, {import { MessageItem } from '@/containers/MessageItem'import SkillSelector from '@/containers/SkillSelector'import { codeTurnsToUIMessages } from '@/lib/codeTurns'+import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'import { PromptProgress } from '@/components/PromptProgress'import { useAppState } from '@/hooks/useAppState'import { useAutoScroll } from '@/hooks/useAutoScroll'@@ -204,6 +205,15 @@ function CodePage() {() => codeTurnsToUIMessages(current?.turns ?? [], 'c'),[current?.turns])+ // Sessions persist their diffs, but the runtime diff store is transient, so+ // reopening a session would otherwise render its write/edit cards with no+ // diff at all.+ useEffect(() => {+ const { recordDiff } = useToolCallRuntime.getState()+ for (const turn of current?.turns ?? []) {+ if (turn.callId && turn.diff) recordDiff(turn.callId, turn.diff)+ }+ }, [current?.turns])const liveMessages = useMemo(() => codeTurnsToUIMessages(liveTurns, 'l'),[liveTurns]@@ -480,6 +490,11 @@ function CodePage() {diff: ev.diff,status: 'done',})+ // Kept out of the turn's output text so the model never sees it and+ // the widget's output parsing stays intact.+ if (ev.diff) {+ useToolCallRuntime.getState().recordDiff(ev.id, ev.diff)+ }breakcase 'permission_request':setPendingPerms((prev) => [diff --git a/web-app/src/routes/settings/agent-tools.tsx b/web-app/src/routes/settings/agent-tools.tsxnew file mode 100644index 000000000..bd944151c--- /dev/null+++ b/web-app/src/routes/settings/agent-tools.tsx@@ -0,0 +1,395 @@+import { createFileRoute } from '@tanstack/react-router'+import { useCallback, useEffect, useState } from 'react'+import { route } from '@/constants/routes'+import HeaderPage from '@/containers/HeaderPage'+import SettingsMenu from '@/containers/SettingsMenu'+import { Card, CardItem } from '@/containers/Card'+import { Switch } from '@/components/ui/switch'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Textarea } from '@/components/ui/textarea'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ IconFolderCode,+ IconTrash,+ IconPencil,+ IconLock,+ IconLockOpen,+} from '@tabler/icons-react'+import { toast } from 'sonner'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useAgentToolsConfig } from '@/hooks/useAgentToolsConfig'+import { getSandboxStatus } from '@/lib/agentTools'+import type { SandboxStatus } from '@janhq/tauri-plugin-agent-tools-api'+import {+ storePath,+ revealStore,+ listSkills,+ readSkill,+ writeSkill,+ deleteSkill,+ listMemories,+ readMemory,+ writeMemory,+ deleteMemory,+ type SkillMeta,+} from '@/lib/agentWorkspace'++// eslint-disable-next-line @typescript-eslint/no-explicit-any+export const Route = createFileRoute(route.settings.agent_tools as any)({+ component: AgentToolsContent,+})++type EntryKind = 'memory' | 'skill'++/** An open editor. `original` is unset when creating, which is what unlocks the+ * name field: renaming an existing entry would mean a write plus a delete. */+type Editor = {+ kind: EntryKind+ original?: string+ name: string+ content: string+}++const messageOf = (e: unknown): string =>+ e && typeof e === 'object' && 'message' in e+ ? String((e as { message: unknown }).message)+ : String(e)++const SKILL_TEMPLATE = '---\ndescription: \n---\n\n'++function AgentToolsContent() {+ const { t } = useTranslation()+ const agentToolsEnabled = useAgentToolsConfig((s) => s.agentToolsEnabled)+ const setAgentToolsEnabled = useAgentToolsConfig(+ (s) => s.setAgentToolsEnabled+ )+ const bashNetworkEnabled = useAgentToolsConfig((s) => s.bashNetworkEnabled)+ const setBashNetworkEnabled = useAgentToolsConfig(+ (s) => s.setBashNetworkEnabled+ )+ // `undefined` until the probe answers, so the row reads as "checking" rather+ // than briefly claiming there is no sandbox.+ const [sandbox, setSandbox] = useState<SandboxStatus | undefined>()++ const [path, setPath] = useState('')+ const [skills, setSkills] = useState<SkillMeta[]>([])+ const [memories, setMemories] = useState<string[]>([])+ const [editor, setEditor] = useState<Editor | null>(null)+ const [saving, setSaving] = useState(false)++ const refresh = useCallback(async () => {+ try {+ const [nextPath, nextSkills, nextMemories] = await Promise.all([+ storePath(),+ listSkills(),+ listMemories(),+ ])+ setPath(nextPath)+ setSkills(nextSkills)+ setMemories(nextMemories)+ } catch (e) {+ toast.error(t('settings:agentTools.loadFailed'), {+ description: messageOf(e),+ })+ }+ }, [t])++ useEffect(() => {+ refresh()+ }, [refresh])++ useEffect(() => {+ getSandboxStatus().then(setSandbox)+ }, [])++ const openEditor = async (kind: EntryKind, name?: string) => {+ if (!name) {+ setEditor({+ kind,+ name: '',+ content: kind === 'skill' ? SKILL_TEMPLATE : '',+ })+ return+ }+ try {+ const content =+ kind === 'skill' ? await readSkill(name) : await readMemory(name)+ setEditor({ kind, original: name, name, content })+ } catch (e) {+ toast.error(t('settings:agentTools.loadFailed'), {+ description: messageOf(e),+ })+ }+ }++ const save = async () => {+ if (!editor) return+ const name = editor.name.trim()+ if (!name) return+ setSaving(true)+ try {+ if (editor.kind === 'skill') await writeSkill(name, editor.content)+ else await writeMemory(name, editor.content)+ setEditor(null)+ await refresh()+ } catch (e) {+ toast.error(t('settings:agentTools.saveFailed'), {+ description: messageOf(e),+ })+ } finally {+ setSaving(false)+ }+ }++ const remove = async (kind: EntryKind, name: string) => {+ try {+ if (kind === 'skill') await deleteSkill(name)+ else await deleteMemory(name)+ await refresh()+ } catch (e) {+ toast.error(t('settings:agentTools.deleteFailed'), {+ description: messageOf(e),+ })+ }+ }++ const reveal = async () => {+ try {+ await revealStore()+ } catch (e) {+ toast.error(t('settings:agentTools.revealFailed'), {+ description: messageOf(e),+ })+ }+ }++ const entryRow = (+ kind: EntryKind,+ name: string,+ description?: string+ ) => (+ <CardItem+ key={`${kind}-${name}`}+ title={name}+ description={description}+ actions={+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="icon-xs"+ title={t('common:edit')}+ onClick={() => openEditor(kind, name)}+ >+ <IconPencil size={16} className="text-muted-foreground" />+ </Button>+ <Button+ variant="ghost"+ size="icon-xs"+ title={t('common:delete')}+ onClick={() => remove(kind, name)}+ >+ <IconTrash size={16} className="text-destructive" />+ </Button>+ </div>+ }+ />+ )++ const sectionHeader = (titleKey: string, kind: EntryKind) => (+ <div className="flex items-center justify-between">+ <h1 className="text-foreground font-studio font-medium text-base mb-2">+ {t(titleKey)}+ </h1>+ <Button variant="outline" size="sm" onClick={() => openEditor(kind)}>+ {t('settings:agentTools.add')}+ </Button>+ </div>+ )++ return (+ <div className="flex flex-col h-svh w-full">+ <HeaderPage>+ <div className="flex items-center gap-2 w-full">+ <span className="font-medium text-base font-studio">+ {t('common:settings')}+ </span>+ </div>+ </HeaderPage>+ <div className="flex h-[calc(100%-60px)]">+ <SettingsMenu />+ <div className="p-4 pt-0 w-full overflow-y-auto">+ <div className="flex flex-col justify-between gap-4 gap-y-3 w-full">+ <Card+ header={+ <div className="flex items-start justify-between gap-4 mb-4">+ <div className="space-y-1">+ <h1 className="text-foreground font-studio font-medium text-base">+ {t('settings:agentTools.title')}+ </h1>+ <p className="text-muted-foreground leading-normal">+ {t('settings:agentTools.description')}+ </p>+ </div>+ {/* The path is a tooltip, not a row: it derives from the Jan+ data folder that Settings > General already owns. */}+ <Button+ variant="link"+ size="sm"+ className="shrink-0 gap-1.5"+ title={path}+ onClick={reveal}+ disabled={!path}+ >+ <IconFolderCode size={16} />+ {t('settings:agentTools.openFolder')}+ </Button>+ </div>+ }+ >+ <CardItem+ title={t('settings:agentTools.enable')}+ description={t('settings:agentTools.enableDesc')}+ align="start"+ actions={+ <Switch+ checked={agentToolsEnabled}+ onCheckedChange={setAgentToolsEnabled}+ />+ }+ />+ <CardItem+ title={t('settings:agentTools.shell')}+ align="start"+ description={+ <span className="flex items-start gap-1.5">+ {sandbox?.enforces ? (+ <IconLock size={14} className="mt-0.5 shrink-0" />+ ) : (+ <IconLockOpen+ size={14}+ className="mt-0.5 shrink-0 text-destructive"+ />+ )}+ <span>+ {sandbox === undefined+ ? t('settings:agentTools.shellChecking')+ : sandbox.enforces+ ? t('settings:agentTools.shellSandboxed', {+ backend: sandbox.backend,+ })+ : t('settings:agentTools.shellUnavailable')}+ </span>+ </span>+ }+ />+ {/* Only offered where it can be enforced: with no backend there is+ no shell to give network access to in the first place. */}+ {sandbox?.enforces && (+ <CardItem+ title={t('settings:agentTools.network')}+ description={t('settings:agentTools.networkDesc')}+ align="start"+ actions={+ <Switch+ checked={bashNetworkEnabled}+ onCheckedChange={setBashNetworkEnabled}+ disabled={!agentToolsEnabled}+ />+ }+ />+ )}+ </Card>++ <Card header={sectionHeader('settings:agentTools.memories', 'memory')}>+ {memories.length === 0 ? (+ <CardItem+ description={t('settings:agentTools.noMemories')}+ />+ ) : (+ memories.map((name) => entryRow('memory', name))+ )}+ </Card>++ <Card header={sectionHeader('settings:agentTools.skills', 'skill')}>+ {skills.length === 0 ? (+ <CardItem description={t('settings:agentTools.noSkills')} />+ ) : (+ skills.map((skill) =>+ entryRow('skill', skill.name, skill.description)+ )+ )}+ </Card>+ </div>+ </div>+ </div>++ <Dialog+ open={editor !== null}+ onOpenChange={(open) => !open && setEditor(null)}+ >+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>+ {t(+ editor?.kind === 'skill'+ ? 'settings:agentTools.editSkill'+ : 'settings:agentTools.editMemory'+ )}+ </DialogTitle>+ <DialogDescription>+ {t(+ editor?.kind === 'skill'+ ? 'settings:agentTools.editSkillDesc'+ : 'settings:agentTools.editMemoryDesc'+ )}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-3">+ <Input+ type="text"+ placeholder={t('settings:agentTools.namePlaceholder')}+ value={editor?.name ?? ''}+ // Locked once the entry exists: a new name would create a second+ // entry rather than rename this one.+ disabled={editor?.original !== undefined}+ onChange={(e) =>+ setEditor((prev) =>+ prev ? { ...prev, name: e.target.value } : prev+ )+ }+ />+ <Textarea+ className="min-h-64 font-mono text-xs"+ placeholder={t('settings:agentTools.contentPlaceholder')}+ value={editor?.content ?? ''}+ onChange={(e) =>+ setEditor((prev) =>+ prev ? { ...prev, content: e.target.value } : prev+ )+ }+ />+ </div>+ <DialogFooter>+ <Button variant="link" onClick={() => setEditor(null)}>+ {t('common:cancel')}+ </Button>+ <Button+ onClick={save}+ disabled={saving || !editor?.name.trim()}+ >+ {t('common:save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </div>+ )+}diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex e1c75cb47..124cce54f 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -77,6 +77,7 @@ import { useToolApproval } from '@/hooks/useToolApproval'import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'+import { AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'import DropdownModelProvider from '@/containers/DropdownModelProvider'import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'import { ExtensionManager } from '@/lib/extension'@@ -99,6 +100,17 @@ function serverForTool(toolName: string): string | undefined {?.server}+// Internal tools never prompt: RAG and the native web tools are Jan's own, and+// the built-in agent tools are gated in Rust (execute_tool refuses anything+// needing approval), so only workspace-confined calls ever reach here.+function isAutoAllowedTool(toolName: string): boolean {+ return (+ useAppState.getState().ragToolNames.has(toolName) ||+ WEB_TOOL_NAMES.has(toolName) ||+ AGENT_TOOL_NAMES.has(toolName)+ )+}+// Persist the out-of-context error onto the latest user message so the banner// survives thread switches, mirroring how LlamacppOomListener stamps oom/backend.function stampContextErrorOnThread(@@ -488,9 +500,7 @@ function ThreadDetail() {try {const toolName = toolCall.toolName- // Built-in RAG and native web tools are internal and auto-allowed.- const approved = ragToolNames.has(toolName) ||- WEB_TOOL_NAMES.has(toolName)+ const approved = isAutoAllowedTool(toolName)? true: await (toolApprovalPromises.current.get(toolCall.toolCallId) ??useToolApprovalRequests@@ -521,6 +531,22 @@ function ThreadDetail() {if (WEB_TOOL_NAMES.has(toolName)) {result = await executeWebTool(toolName, toolCall.input)+ } else if (AGENT_TOOL_NAMES.has(toolName)) {+ const agentResult = await executeAgentTool(+ toolName,+ toolCall.input,+ threadId+ )+ // The diff is display-only, so it goes to the runtime store rather+ // than into `result`: anything in `result` reaches the model, and a+ // full diff there would duplicate the file it just wrote.+ const { diff, ...rest } = agentResult+ if (diff) {+ useToolCallRuntime+ .getState()+ .recordDiff(toolCall.toolCallId, diff)+ }+ result = rest} else if (ragToolNames.has(toolName)) {result = await serviceHub.rag().callTool({toolName,@@ -660,13 +686,11 @@ function ThreadDetail() {// right now so the popup appears immediately instead of waiting for the// stream's terminal finish chunk (a stalled stream would otherwise leave// the tool at "Running..." with no popup). Execution itself stays in- // onFinish so the tool result lands on a completed message. RAG tools are- // internal and never prompt.+ // onFinish so the tool result lands on a completed message. Internal tools+ // never prompt (see isAutoAllowedTool).sessionData.tools.push(toolCall)- const ragToolNames = useAppState.getState().ragToolNamesif (- !ragToolNames.has(toolCall.toolName) &&- !WEB_TOOL_NAMES.has(toolCall.toolName) &&+ !isAutoAllowedTool(toolCall.toolName) &&!toolApprovalPromises.current.has(toolCall.toolCallId)) {toolApprovalPromises.current.set(@@ -884,6 +908,11 @@ function ThreadDetail() {toolCallAbortController.current = nullapprovalPromises.clear()useToolApprovalRequests.getState().clearPendingForThread(threadId)+ // Drop per-thread timing/progress/diff state from the shared runtime+ // store. The cards for the thread we leave are unmounting, so a thread a+ // later visit cannot show another thread's diff. (code.tsx re-hydrates+ // its own diffs on mount, so it is unaffected by clearing here.)+ useToolCallRuntime.getState().reset()}}, [threadId])diff --git a/yarn.lock b/yarn.lockindex d89675ce8..2bfe87f45 100644--- a/yarn.lock+++ b/yarn.lock@@ -2889,6 +2889,12 @@ __metadata:languageName: nodelinkType: hard+"@janhq/tauri-plugin-agent-tools-api@link:../src-tauri/plugins/tauri-plugin-agent-tools::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app":+ version: 0.0.0-use.local+ resolution: "@janhq/tauri-plugin-agent-tools-api@link:../src-tauri/plugins/tauri-plugin-agent-tools::locator=%40janhq%2Fweb-app%40workspace%3Aweb-app"+ languageName: node+ linkType: soft+"@janhq/tauri-plugin-hardware-api@link:../../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fllamacpp-extension%40workspace%3Aextensions%2Fllamacpp-extension":version: 0.0.0-use.localresolution: "@janhq/tauri-plugin-hardware-api@link:../../src-tauri/plugins/tauri-plugin-hardware::locator=%40janhq%2Fllamacpp-extension%40workspace%3Aextensions%2Fllamacpp-extension"@@ -2982,6 +2988,7 @@ __metadata:"@eslint/js": "npm:8.57.0""@janhq/core": "workspace:*""@janhq/interfaces": "npm:0.0.2"+ "@janhq/tauri-plugin-agent-tools-api": "link:../src-tauri/plugins/tauri-plugin-agent-tools""@janhq/tauri-plugin-llamacpp-api": "link:../src-tauri/plugins/tauri-plugin-llamacpp""@janhq/tauri-plugin-websearch-api": "link:../src-tauri/plugins/tauri-plugin-websearch""@radix-ui/react-accordion": "npm:1.2.11"