Skip to content

armgit / jan

Public Imported from GitHub
0

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

feat(agent): lifecycle hooks and plugin-declared tools (#8989)

Akarshan Biswasaf0ddc39012b
diff --git a/docs/src/pages/docs/agent/_meta.json b/docs/src/pages/docs/agent/_meta.json
index 7b7039bef..1871f77ae 100644
--- a/docs/src/pages/docs/agent/_meta.json
+++ b/docs/src/pages/docs/agent/_meta.json
@@ -23,6 +23,7 @@
"contributing-providers": "Contributing a Provider",
"project-config": "Project Config",
"permissions": "Tool Permissions",
+ "hooks": "Hooks",
"mcp": "MCP",
"reference-separator": { "title": "Reference", "type": "separator" },
"cli": "CLI"
diff --git a/docs/src/pages/docs/agent/hooks.mdx b/docs/src/pages/docs/agent/hooks.mdx
new file mode 100644
index 000000000..eae56805e
--- /dev/null
+++ b/docs/src/pages/docs/agent/hooks.mdx
@@ -0,0 +1,334 @@
+---
+title: Hooks
+description: Shell commands the agent runs at fixed points of a run, to enforce a policy the model cannot ignore.
+keywords: [Jan, Jan Agent, hooks, lifecycle, PreToolUse, PostToolUse, policy, audit, plugin tools]
+---
+
+import { Callout } from 'nextra/components'
+
+# Hooks
+
+A hook is a shell command Jan runs at a fixed point of a run: before a tool call, after it, when a
+prompt is submitted, when a session starts or ends, and before a compaction. The payload arrives on
+stdin as JSON and the command's stdout is its answer.
+
+The point is to make a team policy enforceable rather than merely requested. "Run `cargo fmt` after
+every `edit`", "never let `bash` touch `infra/`", "log every tool call to our audit sink" used to
+have only one lever - a line in the system prompt, which the model is free to ignore. A hook is not
+advice. A `PreToolUse` hook that answers `deny` stops the call.
+
+A hook is a shell command, not a plugin runtime. It runs through the same confinement `bash` gets,
+so nothing here is a new execution primitive.
+
+## A first hook
+
+`.jan/agent/agent.toml`:
+
+```toml
+[[hooks]]
+event = "PostToolUse"
+matcher = "edit"
+command = "cargo fmt --quiet"
+```
+
+Every `edit` the model makes is now followed by a format pass, for everyone who checks the project
+out. `event` and `command` are the only required fields, so the smallest useful hook is two lines.
+
+## Events
+
+| Event | Fires |
+| --- | --- |
+| `PreToolUse` | Before a tool call executes. The only event whose `deny` is honored |
+| `PostToolUse` | After a tool call returns, with its result text in the payload |
+| `UserPromptSubmit` | A user prompt was submitted, before the turn starts |
+| `SessionStart` | A session began, before the first model call |
+| `SessionEnd` | A session ended, after the last one. Fires on failure and on cancellation too |
+| `PreCompact` | Before the conversation is compacted, whether by the automatic overflow retry or `/compact` |
+
+Names are case-sensitive: they are a wire contract shared with plugin `hooks.json`, and quietly
+accepting `pretooluse` would make a typo in one file behave differently from the same typo in
+another. An unrecognized name is dropped at load with a notice.
+
+`PreToolUse` and `PostToolUse` are inert in [Plan mode](/docs/agent/run-modes). Plan mode withholds
+every write- and exec-capable tool from the model, so running an arbitrary shell command around one
+would reintroduce exactly the capability that mode exists to remove - and with the tool withheld
+there is nothing left to wrap. The four lifecycle events stay live: a run still starts, still ends,
+still takes a prompt and still compacts while planning, and none of those is a mutation Plan mode
+is meant to stop.
+
+## Where hooks come from
+
+Three sources, merged least specific first:
+
+1. an installed plugin's `<plugin>/hooks/hooks.json` - shipped by a third party
+2. `~/.jan/config.toml` `[[hooks]]` - this user, every project
+3. `<project>/.jan/agent/agent.toml` `[[hooks]]` - this project
+
+They all run. Merge order is run order, so the project's hook runs last and its `context` answer
+lands nearest the call. The set is resolved once per run, so a hook file edited mid-run cannot
+change what a call already in flight is judged by.
+
+A deny is not a precedence question. `PreToolUse` stops at the **first** hook that denies and the
+hooks behind it are never run, so any layer can veto a call and no later layer can overturn it. A
+veto a more specific file could quietly undo would not be a policy. It does mean a plugin's hook can
+deny a call the project's own hooks never see; `[plugins] hooks = false` is the way out.
+
+A missing or malformed source contributes nothing rather than failing the run. One bad line in a
+shared config does not take the other hooks down with it - it is dropped, with a notice.
+
+### Plugin hooks
+
+`hooks/hooks.json` in a plugin is a bare JSON array of the same entries:
+
+```json
+[
+ { "event": "PreToolUse", "matcher": "bash", "command": "./hooks/audit.sh", "timeout_secs": 10 },
+ { "event": "SessionEnd", "command": "./hooks/report.sh" }
+]
+```
+
+### Global hooks
+
+`~/.jan/config.toml` takes the same `[[hooks]]` array and applies it to every project you work on:
+
+```toml
+[[hooks]]
+event = "SessionEnd"
+command = "logger -t jan 'agent session finished'"
+```
+
+## Fields
+
+| Field | Meaning |
+| --- | --- |
+| `event` | One of the six names above. Required |
+| `matcher` | Glob over the tool name. Defaults to `*` (every tool) |
+| `command` | The shell command to run. Required; a blank one is dropped |
+| `timeout_secs` | Seconds before the hook is killed. Defaults to 60 |
+
+`matcher` is only consulted for the two tool events - a session-lifecycle hook has no tool name to
+match and always fires. It is an ordinary glob, so `*write*` catches `write`, `memory_write` and
+`skill_write`, while `edit` catches only `edit`. An invalid glob is dropped at load with a notice
+rather than kept: a pattern that cannot parse can only ever answer "no", which reads exactly like a
+hook written for a tool that was never called.
+
+## The payload
+
+One JSON object on stdin. `event` and `project_root` are always present; the rest appear when the
+event has them:
+
+```json
+{
+ "event": "PreToolUse",
+ "project_root": "/home/you/code/app",
+ "tool_name": "bash",
+ "tool_input": { "command": "rm -rf infra/" },
+ "session_id": "01J9...",
+ "message_count": 24
+}
+```
+
+| Key | Present for |
+| --- | --- |
+| `event`, `project_root` | Always |
+| `tool_name`, `tool_input` | `PreToolUse`, `PostToolUse` |
+| `tool_result` | `PostToolUse` - the result text the tool produced |
+| `prompt` | `UserPromptSubmit` |
+| `session_id` | `SessionStart`, `SessionEnd`, `UserPromptSubmit` |
+| `message_count` | `SessionStart`, `UserPromptSubmit`, `PreCompact` |
+
+## The answer
+
+Whatever the command writes to stdout, up to 64KB.
+
+| Stdout | Effect |
+| --- | --- |
+| Empty | Proceed unchanged. The common case |
+| `{"decision":"deny","reason":"..."}` | Block the call. Honored for `PreToolUse` only |
+| `{"context":"..."}` | The text is folded into the next turn as a `<SYSTEM>` reminder |
+
+Anything that is not a JSON object is an error, not consent: a hook that meant to deny and mistyped
+its JSON must never be read as approval. Stderr is drained and discarded - only stdout is the
+protocol.
+
+A hook can only tighten policy, never grant. `"decision":"allow"` does nothing; a tool the
+[permission gate](/docs/agent/permissions) would have withheld stays withheld. A `deny` from any
+event other than `PreToolUse` is ignored, because the call has already happened and there is nothing
+left to stop.
+
+When a `PreToolUse` hook denies, the model sees the same refusal shape every other denial uses, with
+the hook's reason attached:
+
+```
+ERROR: tool 'bash' denied: infra/ is managed by terraform, not by the agent
+```
+
+A worked example - refuse shell commands that touch a protected directory:
+
+```toml
+[[hooks]]
+event = "PreToolUse"
+matcher = "bash"
+command = "jq -e '.tool_input.command | test(\"infra/\") | not' >/dev/null || echo '{\"decision\":\"deny\",\"reason\":\"infra/ is managed by terraform, not by the agent\"}'"
+```
+
+And one that feeds the model a fact at the start of every turn:
+
+```bash
+#!/usr/bin/env bash
+# .jan/agent/hooks/branch.sh
+printf '{"context":"current branch: %s"}' "$(git rev-parse --abbrev-ref HEAD)"
+```
+
+```toml
+[[hooks]]
+event = "UserPromptSubmit"
+command = "./.jan/agent/hooks/branch.sh"
+```
+
+`context` from `PreCompact` and `SessionEnd` is logged rather than delivered: a compaction is not a
+turn, and after `SessionEnd` there is no turn left to attach a reminder to.
+
+## When a hook misbehaves
+
+Failure is never fatal. A hook that exits nonzero, outruns its `timeout_secs`, cannot be started, or
+writes unparseable stdout produces one notice and the run carries on:
+
+```
+Hook PreToolUse ('./hooks/audit.sh') exited 3
+Hook PostToolUse ('cargo fmt --quiet') timed out after 60s
+Hook PreToolUse ('./hooks/check.sh') emitted stdout that is not a JSON object
+```
+
+The notice is logged, shown to you, and handed to the model as a reminder. A hook must not be able
+to wedge a session, and a silent skip would be worse than a visible complaint - a user who believes
+their policy is in force deserves to know it is not. A timed-out hook has its whole process tree
+killed and reaped.
+
+Entries dropped while loading - a bad event name, a blank command, an invalid matcher glob - are
+reported the same way, once per run, before anything fires.
+
+<Callout type="info">
+Hooks run confined exactly the way `bash` does. Under a sandboxed run a hook is sandboxed; on the
+CLI, where the sandbox is off by default, a hook runs with your own access. The shell environment is
+the same minimal one, so a hook does not see your secrets unless `[tools] env_passthrough` or
+`[tools] env_set` names them. See [Tool Permissions](/docs/agent/permissions#the-shell-environment).
+</Callout>
+
+## Which surfaces fire hooks
+
+All of them. The `jan` CLI and the interactive TUI, the OpenAI-compatible API server, subagent runs,
+and the desktop app share one resolution path, so a hook you configure cannot silently be live on one
+surface and dead on another.
+
+- `jan` CLI and TUI: the project's three layers, resolved from the project root
+- API server: the same, for the project a request runs against
+- [Subagents](/docs/agent/subagents): a subagent run resolves the same hooks as its parent, so a
+ `PreToolUse` veto cannot be escaped by delegating the call
+- Desktop app: the app installs the resolver at startup, so tool calls driven from the webview fire
+ hooks too. A desktop chat thread has no project root, so it gets the `~/.jan/config.toml` layer -
+ the one that is about the user rather than the checkout
+
+## Plugin-declared tools
+
+A plugin can declare tools as well as hooks. A `[[tools]]` entry in its `plugin.toml` names a
+description, a JSON Schema and a command:
+
+```toml
+name = "release-tools"
+
+[[tools]]
+name = "changelog"
+description = "Render the changelog between two tags"
+command = "./bin/changelog.sh"
+timeout_secs = 180
+
+[tools.parameters]
+type = "object"
+required = ["from"]
+
+[tools.parameters.properties.from]
+type = "string"
+description = "Start tag"
+
+[tools.parameters.properties.to]
+type = "string"
+description = "End tag, defaults to HEAD"
+```
+
+The model sees it as `plugin__release-tools__changelog`. The `plugin__<plugin>__<tool>` form is
+mandatory so a plugin cannot shadow a built-in like `bash` or `edit`, or collide with an MCP tool.
+Names are ASCII alphanumerics, `_` and `-`, may not contain `__`, and the whole qualified name must
+be 64 characters or shorter - several providers reject a longer function name, and reject the entire
+request rather than the one tool. An entry that breaks a rule is dropped; where two plugins declare
+the same qualified name, the first wins.
+
+Arguments arrive on the command's stdin as one JSON object and its stdout becomes the tool result.
+Stderr is appended under a `[stderr]` marker rather than discarded, so a tool that explains a failure
+there has the explanation reach the model. Output is capped at 128KB with a truncation note, a
+nonzero exit becomes an `ERROR: plugin tool '...' exited ...` result, and the default timeout is 120
+seconds (longer than a hook's: this is the call the model is waiting on, not a check beside it).
+Omit `[tools.parameters]` and the tool is advertised as taking no arguments.
+
+Plugin tools are gated exactly like opaque MCP tools, because their capability is just as
+unknowable from the outside: they are prompted rather than auto-approved, they honor `[tools] deny`,
+and they are withheld entirely in read-only Plan mode. Their calls fire `PreToolUse` and
+`PostToolUse` like any other, so a hook policy covers them too.
+
+## Turning a plugin's hooks and tools off
+
+Both default to on - a plugin that ships hooks is usually installed for them - and both switch off in
+`agent.toml` without uninstalling the plugin and losing its skills, commands and agents:
+
+```toml
+[plugins]
+hooks = false # ignore every installed plugin's hooks/hooks.json
+tools = false # withhold every plugin-declared tool from the model
+```
+
+<Callout type="warning">
+Installing a plugin that ships hooks means a third party's commands run on your tool calls, on every
+session, with whatever access the run has. On the CLI, where the sandbox is off by default, that is
+your own access. Read a plugin's `hooks/hooks.json` and its `[[tools]]` before you install it, or
+set `hooks = false` and `tools = false` and keep only its skills.
+</Callout>
+
+## Debugging
+
+`jan cli agent status` lists every resolved hook, in merge order, with the file it came from:
+
+```bash
+jan cli agent status --project ~/code/app
+```
+
+```json
+"hooks": [
+ {
+ "event": "PreToolUse",
+ "matcher": "bash",
+ "command": "./hooks/audit.sh",
+ "timeout_secs": 10,
+ "source": "/home/you/code/app/.jan/agent/plugins/auditor/hooks/hooks.json"
+ },
+ {
+ "event": "PostToolUse",
+ "matcher": "edit",
+ "command": "cargo fmt --quiet",
+ "timeout_secs": 60,
+ "source": "/home/you/code/app/.jan/agent/agent.toml"
+ }
+],
+"plugin_tools": [
+ {
+ "name": "plugin__release-tools__changelog",
+ "plugin": "release-tools",
+ "description": "Render the changelog between two tags",
+ "command": "./bin/changelog.sh",
+ "source": "/home/you/code/app/.jan/agent/plugins/release-tools"
+ }
+]
+```
+
+A hook missing from that list was dropped at load; the reason was printed as a notice when the run
+started. A hook present but apparently not firing is usually a `matcher` that does not match the tool
+name, or a tool event in Plan mode.
diff --git a/docs/src/pages/docs/agent/plugins.mdx b/docs/src/pages/docs/agent/plugins.mdx
index f97899290..6334755be 100644
--- a/docs/src/pages/docs/agent/plugins.mdx
+++ b/docs/src/pages/docs/agent/plugins.mdx
@@ -10,8 +10,9 @@ import { Callout } from 'nextra/components'
A plugin is a set of [skills](/docs/agent/skills) installed from a git repository. Any repo that
looks like a skill collection - or is a single skill - can be installed with one command, without
-copying files by hand or trusting a download step. Installing a plugin never runs its code: a
-plugin carries instructions plus optional metadata, nothing executable.
+copying files by hand or trusting a download step. Installing a plugin never runs its code: the
+install step only clones and moves files. A plugin that declares [tools or hooks](/docs/agent/hooks)
+runs commands later, once a session uses it.
## Where they live
@@ -34,6 +35,7 @@ A plugin's payload is discovered conventionally, so a repo needs no manifest to
- `SKILL.md` at the repo root - a repo that is itself one skill
- `commands/` - slash-invocable prompt templates (`<name>.md`, nested directories included)
- `agents/` - dispatchable subagent definitions (`<name>.md`, nested directories included)
+- `hooks/hooks.json` - optional [lifecycle hooks](/docs/agent/hooks)
- `plugin.toml` or `.claude-plugin/plugin.json` - optional metadata: `name`, `description`, `version`,
and `repo`. The directory name is the plugin's identity; the manifest's `name` is what
`plugin list` shows when present.
@@ -164,6 +166,33 @@ jan plugin search prepare --project ~/code/app
Removal is a directory delete under the same name guard as everything else in the agent: a name
can never escape the plugins directory.
+## Plugin tools and hooks
+
+Beyond instructions, a plugin can carry two executable payloads. Both are covered in full on the
+[hooks](/docs/agent/hooks) page; the short form:
+
+- `[[tools]]` in `plugin.toml` declares a tool. Each entry names a `description`, a JSON Schema in
+ `[tools.parameters]`, and a `command`. The model calls it as `plugin__<plugin>__<tool>`, the
+ arguments arrive on the command's stdin as JSON, and its stdout becomes the tool result. Plugin
+ tools are gated like MCP tools: prompted rather than auto-approved, and withheld in Plan mode.
+- `hooks/hooks.json` declares [lifecycle hooks](/docs/agent/hooks) - commands that run before and
+ after tool calls, at prompt submit, at session start and end, and before a compaction. A
+ `PreToolUse` hook can deny a call outright.
+
+Both are on by default and both switch off in `agent.toml` without uninstalling the plugin:
+
+```toml
+[plugins]
+hooks = false
+tools = false
+```
+
+<Callout type="warning">
+Installing a plugin that ships hooks means a third party's commands run on your tool calls, with
+whatever access the run has. Read its `hooks/hooks.json` and `[[tools]]` before installing, or turn
+them off and keep only its skills.
+</Callout>
+
## Marketplace
Point `[plugins] marketplace` in `agent.toml` at a JSON index to install by name and search:
diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rs
index 15a959916..82b1304f5 100644
--- a/src-tauri/jan-cli/src/main.rs
+++ b/src-tauri/jan-cli/src/main.rs
@@ -741,19 +741,37 @@ fn format_plugin_list(plugins: &[InstalledPlugin]) -> String {
.max()
.unwrap_or(0)
.max("AGENTS".len());
+ let tools_width = plugins
+ .iter()
+ .map(|plugin| plugin.tools.to_string().len())
+ .max()
+ .unwrap_or(0)
+ .max("TOOLS".len());
+ let hooks_width = plugins
+ .iter()
+ .map(|plugin| plugin.hooks.to_string().len())
+ .max()
+ .unwrap_or(0)
+ .max("HOOKS".len());
let mut output = String::new();
writeln!(
output,
- "{:<name_width$} {:<version_width$} {:>skills_width$} {:>commands_width$} {:>agents_width$}",
- "PLUGIN", "VERSION", "SKILLS", "COMMANDS", "AGENTS"
+ "{:<name_width$} {:<version_width$} {:>skills_width$} {:>commands_width$} {:>agents_width$} {:>tools_width$} {:>hooks_width$}",
+ "PLUGIN", "VERSION", "SKILLS", "COMMANDS", "AGENTS", "TOOLS", "HOOKS"
)
.unwrap();
for plugin in plugins {
writeln!(
output,
- "{:<name_width$} {:<version_width$} {:>skills_width$} {:>commands_width$} {:>agents_width$}",
- plugin.name, plugin.version, plugin.skills, plugin.commands, plugin.agents
+ "{:<name_width$} {:<version_width$} {:>skills_width$} {:>commands_width$} {:>agents_width$} {:>tools_width$} {:>hooks_width$}",
+ plugin.name,
+ plugin.version,
+ plugin.skills,
+ plugin.commands,
+ plugin.agents,
+ plugin.tools,
+ plugin.hooks
)
.unwrap();
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
index 00d549aa5..b7b4b0bf5 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -845,11 +845,13 @@ async fn execute_tool_inner(
// store. (Equivalent to the old `resolve_store(.., None)`, which is what every
// caller passed.)
let store = workspace::permanent_store(Path::new(&data_folder));
- let skill_project: Option<PathBuf> = project
+ let project_dir: Option<PathBuf> = project
.as_deref()
.map(str::trim)
.filter(|p| !p.is_empty())
- .map(|p| workspace::project_store(Path::new(p)));
+ .map(PathBuf::from);
+ let skill_project: Option<PathBuf> =
+ project_dir.as_deref().map(workspace::project_store);
// Plural from the outset so attaching a second folder later is not another
// signature change.
let attached: Vec<PathBuf> = match read_only_project.as_deref() {
@@ -956,7 +958,18 @@ async fn execute_tool_inner(
}
let enabled = enabled_skills.unwrap_or_default();
+ // The hooks that apply to this call, resolved through the app-installed
+ // resolver (`hooks::set_resolver`): this command is handed one tool call
+ // with no run around it, so unlike the CLI loop it has no run-start
+ // snapshot to carry. Without this the desktop would be the one surface a
+ // user's `[[hooks]]` silently did not reach.
+ //
+ // `project` is the attached folder Cowork passes, which is the only project
+ // this surface knows about; chat has none and gets the user's global hooks
+ // alone.
+ let hooks = crate::tools::hooks::resolve_for(project_dir.as_deref());
let mut ctx = ToolContext::new(&root, &store, &enabled)
+ .with_hooks(&hooks, false, None)
.with_network(allow_network.unwrap_or(false))
.with_confined_writes(true)
.with_mask_root(Path::new(&data_folder))
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
index a75d6ec91..ead6ab6ba 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs
@@ -121,10 +121,58 @@ fn collapse_carriage_returns(s: &str) -> String {
/// an image file, the base64 `image_url` content parts the model needs to see
/// the image. Errors are returned as a String STARTING WITH "ERROR" rather than
/// as Err.
+///
+/// The run's `PreToolUse` and `PostToolUse` hooks wrap this function rather
+/// than the caller's invoker. The invoker sits above it, so a surface that
+/// builds its own -- the desktop IPC command today, an out-of-process caller
+/// tomorrow -- would otherwise bypass every hook, including a `PreToolUse`
+/// deny. A denial returns here in the ERROR form the gate's denials take, so
+/// the model and the transcript cannot tell the two apart.
pub async fn execute_builtin(
tool: &BuiltinTool,
args: &serde_json::Value,
ctx: &ToolContext<'_>,
+) -> (String, Option<Vec<ImageContentPart>>) {
+ let payload = crate::tools::hooks::HookPayload {
+ tool_name: Some(tool.name.to_string()),
+ tool_input: Some(args.clone()),
+ ..Default::default()
+ };
+ if let Some(reason) = crate::tools::hooks::fire_from_context(
+ crate::tools::hooks::HookEvent::PreToolUse,
+ &payload,
+ ctx,
+ )
+ .await
+ {
+ return (
+ format!("ERROR: tool '{}' denied: {reason}", tool.name),
+ None,
+ );
+ }
+ let (content, images) = execute_builtin_unhooked(tool, args, ctx).await;
+ let post = crate::tools::hooks::HookPayload {
+ tool_result: Some(content.clone()),
+ ..payload
+ };
+ // A PostToolUse deny is meaningless -- the call already happened -- so the
+ // return is dropped here; `run_hooks` only honors a deny for PreToolUse.
+ let _ = crate::tools::hooks::fire_from_context(
+ crate::tools::hooks::HookEvent::PostToolUse,
+ &post,
+ ctx,
+ )
+ .await;
+ (content, images)
+}
+
+/// The tool dispatch itself, without the hook wrapping. Split out so
+/// [`execute_builtin`] can name the un-hooked call once instead of duplicating
+/// the `read`-plus-images shape inside its own hook bracket.
+async fn execute_builtin_unhooked(
+ tool: &BuiltinTool,
+ args: &serde_json::Value,
+ ctx: &ToolContext<'_>,
) -> (String, Option<Vec<ImageContentPart>>) {
let project_root = ctx.project_root;
let scratch = ctx.scratch_root;
@@ -2977,7 +3025,7 @@ mod tests {
.await;
assert!(!out.starts_with("ERROR"), "unexpected: {out}");
assert!(out.contains("still running in the background"), "{out}");
- assert!(out.contains("output will be written to"), "{out}");
+ assert!(out.contains("result will be written to"), "{out}");
let _ = std::fs::remove_dir_all(&root);
}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs
new file mode 100644
index 000000000..d35f3dd69
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/hooks.rs
@@ -0,0 +1,1256 @@
+//! Declarative lifecycle hooks: user-supplied shell commands the agent runs at
+//! fixed points of a run (before and after a tool call, at prompt submit, at
+//! session start and end, before a compaction).
+//!
+//! The point is to make a team policy enforceable rather than merely requested.
+//! "Run `cargo fmt` after every `edit`", "never let `bash` touch `infra/`",
+//! "log every tool call to our audit sink" had no home before this: the only
+//! lever was the system prompt, which the model is free to ignore.
+//!
+//! A hook is a shell command, not a plugin runtime. It runs through
+//! [`crate::tools::handlers::confined_shell`] -- the very policy `bash` and the
+//! `monitor` condition scripts already get -- so nothing here is a new
+//! execution primitive, and a hook under a sandboxed run is confined exactly as
+//! the shell the model drives is. That is also why this module lives in the
+//! toolset crate and not in `core/agent/`: `confined_shell` is `pub(crate)`.
+//!
+//! Protocol: the event payload arrives on stdin as one JSON object; the answer
+//! is whatever the command writes to stdout. Empty stdout (or output that is
+//! not a JSON object) means "proceed unchanged". A JSON object may carry
+//! `{"decision":"deny","reason":"..."}` -- honored for `PreToolUse` only -- or
+//! `{"context":"..."}`, which the caller folds into the next turn as a
+//! `<SYSTEM>` reminder.
+//!
+//! Failure is never fatal. A hook that exits nonzero, hangs past its timeout,
+//! or writes unparseable stdout produces one [`HookNotice`] and the run carries
+//! on; a hook must not be able to wedge a session, and a silent skip would be
+//! worse than a visible complaint.
+
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, OnceLock};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+
+use crate::tools::ToolContext;
+
+/// Resolves the hooks that apply to a run in the given project (`None` for a
+/// surface with no project, which still gets the user's global ones).
+///
+/// The config formats live in the app crate, not here, so this crate cannot
+/// read them itself. A surface that owns a run resolves them directly; the IPC
+/// command cannot, because it is handed one tool call with no run around it.
+/// Hence this injection point: the app installs its resolver once at startup
+/// and every invoker, including the desktop's, inherits the same hooks.
+pub type HookResolver = Arc<dyn Fn(Option<&Path>) -> HookSet + Send + Sync>;
+
+static RESOLVER: OnceLock<HookResolver> = OnceLock::new();
+
+/// Install the process-wide hook resolver. First call wins; later ones are
+/// ignored, so a second plugin init cannot swap a run's policy out from under
+/// it.
+pub fn set_resolver(resolver: HookResolver) {
+ let _ = RESOLVER.set(resolver);
+}
+
+/// The hooks that apply to `project`, or an empty set when no resolver was
+/// installed (the toolset used standalone, as the tests use it).
+pub fn resolve_for(project: Option<&Path>) -> HookSet {
+ RESOLVER
+ .get()
+ .map(|resolve| resolve(project))
+ .unwrap_or_default()
+}
+
+/// Per-hook wall clock. Matches the monitor's condition-script overrun
+/// (`monitor::EVAL_TIMEOUT`): a hook is the same kind of short side command,
+/// and a run must not stall on one that never returns.
+pub const DEFAULT_TIMEOUT_SECS: u64 = 60;
+
+/// Upper bound on a hook's stdout that is parsed. A hook answers with a small
+/// JSON object; anything past this is a runaway and is truncated rather than
+/// buffered without limit.
+const OUTPUT_MAX_BYTES: usize = 64 * 1024;
+
+/// How long a killed child is waited on before it is given up as unreapable.
+/// SIGKILL on a healthy process is near-instant; the bound only exists so a
+/// child stuck in uninterruptible state cannot turn the timeout path into a
+/// second hang.
+const REAP_GRACE: Duration = Duration::from_secs(2);
+
+/// The lifecycle points a hook can attach to.
+///
+/// Deliberately the set the tree can already express -- there is a real call
+/// site for each, and no event is advertised that nothing fires.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum HookEvent {
+ /// Before a tool call executes. The only event whose `deny` is honored.
+ PreToolUse,
+ /// After a tool call returns, with its result text in the payload.
+ PostToolUse,
+ /// A user prompt was submitted, before the turn starts.
+ UserPromptSubmit,
+ /// A session began.
+ SessionStart,
+ /// A session ended.
+ SessionEnd,
+ /// Before the conversation is compacted.
+ PreCompact,
+}
+
+impl HookEvent {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ HookEvent::PreToolUse => "PreToolUse",
+ HookEvent::PostToolUse => "PostToolUse",
+ HookEvent::UserPromptSubmit => "UserPromptSubmit",
+ HookEvent::SessionStart => "SessionStart",
+ HookEvent::SessionEnd => "SessionEnd",
+ HookEvent::PreCompact => "PreCompact",
+ }
+ }
+
+ /// Parse an event name. Case-sensitive: the names are a wire contract
+ /// shared with `hooks.json`, and quietly accepting `pretooluse` would make
+ /// a typo in one file behave differently from the same typo in another.
+ pub fn parse(name: &str) -> Option<Self> {
+ match name {
+ "PreToolUse" => Some(HookEvent::PreToolUse),
+ "PostToolUse" => Some(HookEvent::PostToolUse),
+ "UserPromptSubmit" => Some(HookEvent::UserPromptSubmit),
+ "SessionStart" => Some(HookEvent::SessionStart),
+ "SessionEnd" => Some(HookEvent::SessionEnd),
+ "PreCompact" => Some(HookEvent::PreCompact),
+ _ => None,
+ }
+ }
+
+ /// Whether this event is suppressed in read-only Plan mode.
+ ///
+ /// Only the two tool events are. Plan mode withholds every write/exec-
+ /// capable tool from the model, so running an arbitrary shell command
+ /// around one would reintroduce exactly the capability that mode exists to
+ /// remove -- and with the tool withheld there is nothing left to wrap.
+ ///
+ /// The lifecycle events stay live. None of them is attached to a tool
+ /// call: a run still starts, still ends, still takes a prompt and still
+ /// compacts in Plan mode, and a `UserPromptSubmit` hook that injects
+ /// context is if anything *more* useful while planning. They are not a
+ /// mutation the mode is meant to stop.
+ pub fn inert_in_plan_mode(self) -> bool {
+ matches!(self, HookEvent::PreToolUse | HookEvent::PostToolUse)
+ }
+}
+
+/// One configured hook: an event, a tool-name glob, and the command to run.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct Hook {
+ pub event: HookEvent,
+ /// Tool-name glob (`*` = any). Only consulted for the tool events; a
+ /// session-lifecycle hook has no tool name to match and always fires.
+ pub matcher: String,
+ pub command: String,
+ /// Seconds before the hook is killed. Defaults to [`DEFAULT_TIMEOUT_SECS`].
+ pub timeout_secs: u64,
+ /// The file this hook was read from, for `jan cli agent status`. A user
+ /// looking at surprising behavior needs to know which of the three layers
+ /// put it there.
+ pub source: PathBuf,
+}
+
+impl Hook {
+ /// Whether this hook applies to `tool_name`. A hook with no meaningful
+ /// matcher (`*` or empty) applies to every tool.
+ pub fn matches(&self, tool_name: &str) -> bool {
+ if self.matcher.is_empty() || self.matcher == "*" {
+ return true;
+ }
+ // An unparseable matcher cannot reach here: `HookSet::extend_from`
+ // drops such an entry with a notice rather than letting it match
+ // nothing forever.
+ glob::Pattern::new(&self.matcher)
+ .map(|p| p.matches(tool_name))
+ .unwrap_or(false)
+ }
+}
+
+/// The raw `[[hooks]]` / `hooks.json` entry, before defaults are applied and
+/// the event name is validated. `event` and `command` are the only required
+/// fields, so the smallest useful hook is two lines.
+///
+/// `Serialize` as well as `Deserialize` because `~/.jan/config.toml` is
+/// round-tripped through its typed struct on every write; without it, saving a
+/// provider would silently drop the user's hooks.
+#[derive(Debug, Clone, Deserialize, Serialize)]
+pub struct HookEntry {
+ pub event: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub matcher: Option<String>,
+ pub command: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub timeout_secs: Option<u64>,
+}
+
+/// Every hook a run may fire, in the order they were merged: least specific
+/// source first, so a project file's hook runs after the user's global one and
+/// a plugin's runs before both.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
+pub struct HookSet {
+ hooks: Vec<Hook>,
+ /// One line per entry dropped while loading: a bad event name, a blank
+ /// command, an unparseable matcher. Reported once per run rather than
+ /// swallowed, because a hook that silently does not fire is worse than one
+ /// that complains -- the user believes their policy is in force.
+ load_notices: Vec<String>,
+}
+
+impl HookSet {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.hooks.is_empty()
+ }
+
+ pub fn len(&self) -> usize {
+ self.hooks.len()
+ }
+
+ pub fn all(&self) -> &[Hook] {
+ &self.hooks
+ }
+
+ /// Entries that were dropped at load time, each already a full sentence.
+ /// See [`Self::load_notices`].
+ pub fn load_notices(&self) -> &[String] {
+ &self.load_notices
+ }
+
+ /// Append entries from one source, skipping any whose event name is not
+ /// recognized, whose command is blank, or whose matcher is not a valid
+ /// glob. A malformed entry is dropped rather than failing the load: one bad
+ /// line in a shared config must not take every other hook down with it. Each
+ /// drop leaves a line in [`Self::load_notices`], so "dropped" never means
+ /// "unnoticed".
+ pub fn extend_from(&mut self, entries: Vec<HookEntry>, source: &Path) {
+ let where_ = source.display();
+ for entry in entries {
+ let Some(event) = HookEvent::parse(entry.event.trim()) else {
+ self.load_notices.push(format!(
+ "Hook in {where_} ignored: '{}' is not a hook event",
+ entry.event.trim()
+ ));
+ continue;
+ };
+ let command = entry.command.trim().to_string();
+ if command.is_empty() {
+ self.load_notices.push(format!(
+ "Hook {} in {where_} ignored: its command is empty",
+ event.as_str()
+ ));
+ continue;
+ }
+ let matcher = entry
+ .matcher
+ .unwrap_or_else(|| "*".to_string())
+ .trim()
+ .to_string();
+ // Checked here, not at match time: `matches` can only answer
+ // "no" for a bad pattern, which reads exactly like a hook the user
+ // wrote for a tool that was never called.
+ if !matcher.is_empty() && matcher != "*" && glob::Pattern::new(&matcher).is_err() {
+ self.load_notices.push(format!(
+ "Hook {} in {where_} ignored: matcher '{matcher}' is not a valid glob",
+ event.as_str()
+ ));
+ continue;
+ }
+ self.hooks.push(Hook {
+ event,
+ matcher,
+ command,
+ timeout_secs: entry.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS),
+ source: source.to_path_buf(),
+ });
+ }
+ }
+
+ /// Hooks that fire for `event` and (for the tool events) `tool_name`, in
+ /// merge order.
+ pub fn matching(&self, event: HookEvent, tool_name: Option<&str>) -> Vec<&Hook> {
+ self.hooks
+ .iter()
+ .filter(|h| h.event == event)
+ .filter(|h| match tool_name {
+ Some(name) => h.matches(name),
+ None => true,
+ })
+ .collect()
+ }
+}
+
+/// Read an installed plugin's `hooks/hooks.json`: a bare JSON array of entries.
+/// Missing or malformed yields nothing, like every other optional plugin
+/// payload -- installing a plugin must not be able to break a run.
+pub fn plugin_hook_entries(plugin_dir: &Path) -> (Vec<HookEntry>, PathBuf) {
+ let path = plugin_dir.join("hooks").join("hooks.json");
+ let entries = std::fs::read_to_string(&path)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<Vec<HookEntry>>(&raw).ok())
+ .unwrap_or_default();
+ (entries, path)
+}
+
+/// What a hook's stdout asked the run to do.
+#[derive(Debug, Clone, Default, Deserialize)]
+pub struct HookResponse {
+ /// `"deny"` blocks the call (PreToolUse only). Any other value is ignored,
+ /// so a hook cannot *grant* a permission the gate would have withheld --
+ /// hooks tighten policy, they never loosen it.
+ #[serde(default)]
+ pub decision: Option<String>,
+ #[serde(default)]
+ pub reason: Option<String>,
+ /// Text folded into the next turn as a `<SYSTEM>` reminder.
+ #[serde(default)]
+ pub context: Option<String>,
+}
+
+impl HookResponse {
+ pub fn denies(&self) -> bool {
+ self.decision.as_deref() == Some("deny")
+ }
+}
+
+/// A hook misbehaved: nonzero exit, timeout, spawn failure or unparseable
+/// stdout. Surfaced to the user once; never fails the run.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct HookNotice {
+ pub event: HookEvent,
+ pub command: String,
+ pub detail: String,
+}
+
+impl HookNotice {
+ pub fn message(&self) -> String {
+ format!(
+ "Hook {} ('{}') {}",
+ self.event.as_str(),
+ self.command,
+ self.detail
+ )
+ }
+}
+
+/// The aggregate answer of every hook that fired for one event.
+#[derive(Debug, Clone, Default)]
+pub struct HookOutcome {
+ /// Set by the first `PreToolUse` hook that denied, with its reason. Later
+ /// hooks for the same call are not run: the decision is already made and a
+ /// hook that expects the call to have happened would be misled.
+ pub denied: Option<String>,
+ /// `context` strings, in hook order, for the caller to attach as reminders.
+ pub context: Vec<String>,
+ /// One entry per hook that failed.
+ pub notices: Vec<HookNotice>,
+}
+
+/// What a fired event has to tell the run, for a [`crate::tools::HookSink`].
+/// Separated from [`HookOutcome`] because a deny is answered synchronously by
+/// the dispatcher while these two are folded into a later turn.
+#[derive(Debug, Clone, Default)]
+pub struct HookReport {
+ pub context: Vec<String>,
+ pub notices: Vec<HookNotice>,
+}
+
+impl HookReport {
+ pub fn is_empty(&self) -> bool {
+ self.context.is_empty() && self.notices.is_empty()
+ }
+}
+
+/// The run-scoped facts a hook payload carries beyond the event itself.
+#[derive(Debug, Clone, Default)]
+pub struct HookPayload {
+ pub tool_name: Option<String>,
+ pub tool_input: Option<serde_json::Value>,
+ pub tool_result: Option<String>,
+ pub prompt: Option<String>,
+ pub session_id: Option<String>,
+ pub message_count: Option<usize>,
+}
+
+impl HookPayload {
+ fn to_json(&self, event: HookEvent, project_root: &Path) -> serde_json::Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("event".into(), serde_json::json!(event.as_str()));
+ obj.insert(
+ "project_root".into(),
+ serde_json::json!(project_root.to_string_lossy()),
+ );
+ if let Some(name) = &self.tool_name {
+ obj.insert("tool_name".into(), serde_json::json!(name));
+ }
+ if let Some(input) = &self.tool_input {
+ obj.insert("tool_input".into(), input.clone());
+ }
+ if let Some(result) = &self.tool_result {
+ obj.insert("tool_result".into(), serde_json::json!(result));
+ }
+ if let Some(prompt) = &self.prompt {
+ obj.insert("prompt".into(), serde_json::json!(prompt));
+ }
+ if let Some(session) = &self.session_id {
+ obj.insert("session_id".into(), serde_json::json!(session));
+ }
+ if let Some(count) = self.message_count {
+ obj.insert("message_count".into(), serde_json::json!(count));
+ }
+ serde_json::Value::Object(obj)
+ }
+}
+
+/// Fire every hook registered for `event`, in merge order, and fold their
+/// answers together.
+///
+/// `plan_mode` suppresses the tool and prompt events entirely (see
+/// [`HookEvent::inert_in_plan_mode`]). A `PreToolUse` deny short-circuits the
+/// rest.
+pub async fn run_hooks(
+ set: &HookSet,
+ event: HookEvent,
+ payload: &HookPayload,
+ ctx: &ToolContext<'_>,
+ plan_mode: bool,
+) -> HookOutcome {
+ let mut outcome = HookOutcome::default();
+ if plan_mode && event.inert_in_plan_mode() {
+ return outcome;
+ }
+ let hooks = set.matching(event, payload.tool_name.as_deref());
+ if hooks.is_empty() {
+ return outcome;
+ }
+ let body = serde_json::to_string(&payload.to_json(event, ctx.project_root))
+ .unwrap_or_else(|_| "{}".to_string());
+ for hook in hooks {
+ match run_one(hook, &body, ctx).await {
+ Ok(mut response) => {
+ if let Some(context) = response.context.take().filter(|c| !c.trim().is_empty()) {
+ outcome.context.push(context);
+ }
+ // Only PreToolUse can deny: there is nothing left to stop once
+ // a tool has run, and the other events do not sit on a decision.
+ if event == HookEvent::PreToolUse && response.denies() {
+ outcome.denied = Some(
+ response
+ .reason
+ .filter(|r| !r.trim().is_empty())
+ .unwrap_or_else(|| "denied by a PreToolUse hook".to_string()),
+ );
+ return outcome;
+ }
+ }
+ Err(detail) => outcome.notices.push(HookNotice {
+ event,
+ command: hook.command.clone(),
+ detail,
+ }),
+ }
+ }
+ outcome
+}
+
+/// Run one hook command to completion. `Err` carries the one-line detail a
+/// [`HookNotice`] reports; it never propagates as a run failure.
+async fn run_one(hook: &Hook, body: &str, ctx: &ToolContext<'_>) -> Result<HookResponse, String> {
+ let (shell, sandbox_tmp, _policy) = crate::tools::handlers::confined_shell(ctx)
+ .map_err(|e| format!("could not start: {}", e.trim_start_matches("ERROR: ")))?;
+ // A hook child is short-lived and belongs to the run rather than to a
+ // cancellable tool call, so it registers in the process-wide bucket the
+ // monitor poll children use.
+ let mut child = crate::tools::proc::spawn_with_stdin(
+ &shell,
+ &hook.command,
+ ctx.project_root,
+ sandbox_tmp.as_deref(),
+ ctx.shell_env(),
+ None,
+ Some(body),
+ )
+ .await
+ .map_err(|e| format!("could not start: {e}"))?;
+ let pid = child.id();
+ let timeout = Duration::from_secs(hook.timeout_secs.max(1));
+ let collected = tokio::time::timeout(timeout, async {
+ let stdout = child.stdout.take();
+ let stderr = child.stderr.take();
+ // stderr is drained and discarded: only stdout is the protocol, but an
+ // undrained pipe would block a chatty hook forever.
+ let drain = async {
+ if let Some(mut stderr) = stderr {
+ let mut sink = tokio::io::sink();
+ let _ = tokio::io::copy(&mut stderr, &mut sink).await;
+ }
+ };
+ let read = async {
+ let mut head = Vec::new();
+ if let Some(mut stdout) = stdout {
+ use tokio::io::AsyncReadExt;
+ let mut buf = [0u8; 8192];
+ loop {
+ match stdout.read(&mut buf).await {
+ Ok(0) | Err(_) => break,
+ Ok(n) => {
+ let room = OUTPUT_MAX_BYTES.saturating_sub(head.len());
+ head.extend_from_slice(&buf[..n.min(room)]);
+ // Keep draining past the cap so the child never
+ // blocks on a full pipe.
+ }
+ }
+ }
+ }
+ head
+ };
+ let (head, ()) = tokio::join!(read, drain);
+ (child.wait().await, head)
+ })
+ .await;
+ if let Some(pid) = pid {
+ crate::tools::proc::unregister(None, pid);
+ }
+ let (status, head) = match collected {
+ Ok(pair) => pair,
+ Err(_) => {
+ // Timed out: reap the whole tree, or a wedged hook leaks children.
+ if let Some(pid) = pid {
+ crate::tools::proc::kill_tree(pid);
+ }
+ // Killing is not reaping: without a `wait` the killed child stays a
+ // zombie for the life of the process. Bounded, because a child
+ // wedged in uninterruptible state would otherwise trade one hang
+ // for another.
+ let _ = tokio::time::timeout(REAP_GRACE, child.wait()).await;
+ return Err(format!("timed out after {}s", hook.timeout_secs));
+ }
+ };
+ let status = status.map_err(|e| format!("could not be waited on: {e}"))?;
+ if !status.success() {
+ let code = status
+ .code()
+ .map(|c| c.to_string())
+ .unwrap_or_else(|| "signal".to_string());
+ return Err(format!("exited {code}"));
+ }
+ parse_response(&String::from_utf8_lossy(&head))
+}
+
+/// Fire `event`'s hooks using the hook set, plan-mode flag and sink a
+/// [`ToolContext`] carries, reporting context and notices through that sink.
+/// `Some(reason)` is a `PreToolUse` deny.
+///
+/// This is what wraps [`crate::tools::handlers::execute_builtin`], so every
+/// caller of the toolset -- the CLI loop, the desktop IPC command, and any
+/// out-of-process caller added later -- goes through the same hooks without
+/// having to remember to.
+pub async fn fire_from_context(
+ event: HookEvent,
+ payload: &HookPayload,
+ ctx: &ToolContext<'_>,
+) -> Option<String> {
+ let set = ctx.hooks?;
+ if set.is_empty() {
+ return None;
+ }
+ let outcome = run_hooks(set, event, payload, ctx, ctx.plan_mode).await;
+ if let Some(sink) = &ctx.hook_sink {
+ let report = HookReport {
+ context: outcome.context,
+ notices: outcome.notices,
+ };
+ if !report.is_empty() {
+ sink(report);
+ }
+ }
+ outcome.denied
+}
+
+/// Interpret a hook's stdout. Empty (or whitespace) is the common case and
+/// means "proceed unchanged". Anything that is not a JSON object is an error
+/// the caller reports, because a hook that meant to deny and mistyped its JSON
+/// must not be read as consent.
+fn parse_response(stdout: &str) -> Result<HookResponse, String> {
+ let trimmed = stdout.trim();
+ if trimmed.is_empty() {
+ return Ok(HookResponse::default());
+ }
+ serde_json::from_str::<HookResponse>(trimmed)
+ .map_err(|_| "emitted stdout that is not a JSON object".to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(event: &str, matcher: Option<&str>, command: &str) -> HookEntry {
+ HookEntry {
+ event: event.to_string(),
+ matcher: matcher.map(str::to_string),
+ command: command.to_string(),
+ timeout_secs: None,
+ }
+ }
+
+ fn unique_root(tag: &str) -> PathBuf {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ static COUNTER: AtomicU32 = AtomicU32::new(0);
+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let dir = std::env::temp_dir().join(format!("jan-hooks-{tag}-{}-{n}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ /// Unconfined so the test does not need an OS sandbox backend; every hook
+ /// test only runs `echo`/`exit`.
+ fn ctx<'a>(root: &'a Path, store: &'a Path, empty: &'a [String]) -> ToolContext<'a> {
+ ToolContext::new(root, store, empty).with_sandbox(false)
+ }
+
+ #[test]
+ fn every_event_name_round_trips() {
+ for event in [
+ HookEvent::PreToolUse,
+ HookEvent::PostToolUse,
+ HookEvent::UserPromptSubmit,
+ HookEvent::SessionStart,
+ HookEvent::SessionEnd,
+ HookEvent::PreCompact,
+ ] {
+ assert_eq!(HookEvent::parse(event.as_str()), Some(event));
+ }
+ assert_eq!(HookEvent::parse("pretooluse"), None);
+ assert_eq!(HookEvent::parse("Nope"), None);
+ }
+
+ #[test]
+ fn entries_with_an_unknown_event_or_blank_command_are_dropped() {
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PreToolUse", None, "true"),
+ entry("NotAnEvent", None, "true"),
+ entry("PostToolUse", None, " "),
+ ],
+ Path::new("/tmp/agent.toml"),
+ );
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.all()[0].event, HookEvent::PreToolUse);
+ }
+
+ #[test]
+ fn a_missing_matcher_defaults_to_every_tool() {
+ let mut set = HookSet::new();
+ set.extend_from(vec![entry("PreToolUse", None, "true")], Path::new("x"));
+ assert_eq!(set.all()[0].matcher, "*");
+ assert!(set.all()[0].matches("bash"));
+ assert!(set.all()[0].matches("edit"));
+ }
+
+ #[test]
+ fn a_matcher_glob_selects_tools() {
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PreToolUse", Some("edit"), "a"),
+ entry("PreToolUse", Some("*write*"), "b"),
+ entry("PostToolUse", Some("edit"), "c"),
+ ],
+ Path::new("x"),
+ );
+ let matched = set.matching(HookEvent::PreToolUse, Some("edit"));
+ assert_eq!(matched.len(), 1);
+ assert_eq!(matched[0].command, "a");
+ let matched = set.matching(HookEvent::PreToolUse, Some("memory_write"));
+ assert_eq!(matched.len(), 1);
+ assert_eq!(matched[0].command, "b");
+ }
+
+ #[test]
+ fn merge_order_is_the_order_sources_were_added() {
+ let mut set = HookSet::new();
+ set.extend_from(vec![entry("SessionStart", None, "plugin")], Path::new("p"));
+ set.extend_from(vec![entry("SessionStart", None, "global")], Path::new("g"));
+ set.extend_from(vec![entry("SessionStart", None, "project")], Path::new("a"));
+ let commands: Vec<&str> = set
+ .matching(HookEvent::SessionStart, None)
+ .iter()
+ .map(|h| h.command.as_str())
+ .collect();
+ assert_eq!(commands, vec!["plugin", "global", "project"]);
+ }
+
+ #[test]
+ fn each_hook_records_the_file_it_came_from() {
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry("SessionEnd", None, "true")],
+ Path::new("/home/u/.jan/config.toml"),
+ );
+ assert_eq!(
+ set.all()[0].source,
+ PathBuf::from("/home/u/.jan/config.toml")
+ );
+ }
+
+ #[test]
+ fn only_the_tool_events_are_inert_in_plan_mode() {
+ assert!(HookEvent::PreToolUse.inert_in_plan_mode());
+ assert!(HookEvent::PostToolUse.inert_in_plan_mode());
+ assert!(!HookEvent::UserPromptSubmit.inert_in_plan_mode());
+ assert!(!HookEvent::SessionStart.inert_in_plan_mode());
+ assert!(!HookEvent::SessionEnd.inert_in_plan_mode());
+ assert!(!HookEvent::PreCompact.inert_in_plan_mode());
+ }
+
+ #[test]
+ fn empty_stdout_proceeds_unchanged() {
+ let response = parse_response(" \n ").unwrap();
+ assert!(!response.denies());
+ assert!(response.context.is_none());
+ }
+
+ #[test]
+ fn unparseable_stdout_is_an_error_not_consent() {
+ assert!(parse_response("yes please").is_err());
+ assert!(parse_response("{\"decision\":").is_err());
+ }
+
+ #[test]
+ fn only_a_deny_decision_blocks() {
+ assert!(parse_response(r#"{"decision":"deny"}"#).unwrap().denies());
+ assert!(!parse_response(r#"{"decision":"allow"}"#).unwrap().denies());
+ assert!(!parse_response(r#"{"context":"hi"}"#).unwrap().denies());
+ }
+
+ #[tokio::test]
+ async fn a_pretooluse_deny_stops_the_call_and_carries_its_reason() {
+ let root = unique_root("deny");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry(
+ "PreToolUse",
+ Some("bash"),
+ r#"echo '{"decision":"deny","reason":"infra is off limits"}'"#,
+ )],
+ Path::new("x"),
+ );
+ let payload = HookPayload {
+ tool_name: Some("bash".to_string()),
+ ..Default::default()
+ };
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PreToolUse,
+ &payload,
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert_eq!(outcome.denied.as_deref(), Some("infra is off limits"));
+ assert!(outcome.notices.is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_deny_short_circuits_the_hooks_behind_it() {
+ let root = unique_root("shortcircuit");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let marker = root.join("second-ran");
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PreToolUse", None, r#"echo '{"decision":"deny"}'"#),
+ entry(
+ "PreToolUse",
+ None,
+ &format!("touch {}", marker.to_string_lossy()),
+ ),
+ ],
+ Path::new("x"),
+ );
+ let payload = HookPayload {
+ tool_name: Some("bash".to_string()),
+ ..Default::default()
+ };
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PreToolUse,
+ &payload,
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert!(outcome.denied.is_some());
+ assert!(!marker.exists(), "the hook behind a deny must not run");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_deny_from_a_non_pretooluse_event_is_ignored() {
+ let root = unique_root("denyignored");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry("PostToolUse", None, r#"echo '{"decision":"deny"}'"#)],
+ Path::new("x"),
+ );
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PostToolUse,
+ &HookPayload {
+ tool_name: Some("edit".to_string()),
+ ..Default::default()
+ },
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert!(outcome.denied.is_none());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_context_answer_is_collected_for_the_caller_to_attach() {
+ let root = unique_root("context");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry(
+ "UserPromptSubmit",
+ None,
+ r#"echo '{"context":"the build is red"}'"#,
+ )],
+ Path::new("x"),
+ );
+ let outcome = run_hooks(
+ &set,
+ HookEvent::UserPromptSubmit,
+ &HookPayload::default(),
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert_eq!(outcome.context, vec!["the build is red".to_string()]);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn the_payload_reaches_the_hook_on_stdin() {
+ let root = unique_root("payload");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let out = root.join("stdin.json");
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry(
+ "PreToolUse",
+ None,
+ &format!("cat > {}", out.to_string_lossy()),
+ )],
+ Path::new("x"),
+ );
+ let payload = HookPayload {
+ tool_name: Some("edit".to_string()),
+ tool_input: Some(serde_json::json!({"path": "a.rs"})),
+ ..Default::default()
+ };
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PreToolUse,
+ &payload,
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert!(outcome.notices.is_empty(), "{:?}", outcome.notices);
+ let written: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap();
+ assert_eq!(written["event"], "PreToolUse");
+ assert_eq!(written["tool_name"], "edit");
+ assert_eq!(written["tool_input"]["path"], "a.rs");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_failing_hook_emits_one_notice_and_does_not_deny() {
+ let root = unique_root("failing");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PreToolUse", None, "exit 3"),
+ entry("PreToolUse", None, "echo not-json"),
+ ],
+ Path::new("x"),
+ );
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PreToolUse,
+ &HookPayload {
+ tool_name: Some("bash".to_string()),
+ ..Default::default()
+ },
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert!(outcome.denied.is_none());
+ assert_eq!(outcome.notices.len(), 2);
+ assert!(outcome.notices[0].detail.contains("exited 3"));
+ assert!(outcome.notices[1].detail.contains("not a JSON object"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_hook_that_outruns_its_timeout_is_a_notice_not_a_hang() {
+ let root = unique_root("timeout");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![HookEntry {
+ event: "PreToolUse".to_string(),
+ matcher: None,
+ command: "sleep 30".to_string(),
+ timeout_secs: Some(1),
+ }],
+ Path::new("x"),
+ );
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PreToolUse,
+ &HookPayload {
+ tool_name: Some("bash".to_string()),
+ ..Default::default()
+ },
+ &ctx(&root, &store, &empty),
+ false,
+ )
+ .await;
+ assert!(outcome.denied.is_none());
+ assert_eq!(outcome.notices.len(), 1);
+ assert!(outcome.notices[0].detail.contains("timed out"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The regression the detached stdin write exists for. A PostToolUse hook
+ /// carries the whole tool result; a hook that never drains stdin used to
+ /// block the parent in `write_all` once the pipe buffer filled, outside the
+ /// timeout and with no kill path. The payload here is far past any pipe
+ /// buffer, and the hook reads none of it.
+ #[tokio::test]
+ async fn a_hook_that_never_reads_a_large_payload_still_times_out() {
+ let root = unique_root("stdinwedge");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![HookEntry {
+ event: "PostToolUse".to_string(),
+ matcher: None,
+ command: "sleep 30".to_string(),
+ timeout_secs: Some(1),
+ }],
+ Path::new("x"),
+ );
+ let outcome = tokio::time::timeout(
+ Duration::from_secs(15),
+ run_hooks(
+ &set,
+ HookEvent::PostToolUse,
+ &HookPayload {
+ tool_name: Some("bash".to_string()),
+ tool_result: Some("x".repeat(4 * 1024 * 1024)),
+ ..Default::default()
+ },
+ &ctx(&root, &store, &empty),
+ false,
+ ),
+ )
+ .await
+ .expect("the write blocked the parent past the hook's own timeout");
+ assert_eq!(outcome.notices.len(), 1);
+ assert!(outcome.notices[0].detail.contains("timed out"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A matcher that cannot compile would otherwise match nothing forever,
+ /// which reads exactly like a hook written for a tool that is never called.
+ #[test]
+ fn an_invalid_matcher_is_dropped_with_a_notice() {
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PreToolUse", Some("ba[sh"), "true"),
+ entry("PreToolUse", Some("ba*"), "true"),
+ ],
+ Path::new("/tmp/agent.toml"),
+ );
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.load_notices().len(), 1);
+ let notice = &set.load_notices()[0];
+ assert!(notice.contains("ba[sh"), "{notice}");
+ assert!(notice.contains("/tmp/agent.toml"), "{notice}");
+ }
+
+ /// Every other drop is reported too, for the same reason.
+ #[test]
+ fn an_unknown_event_or_blank_command_is_dropped_with_a_notice() {
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PreToolUsage", None, "true"),
+ entry("PreToolUse", None, " "),
+ ],
+ Path::new("/tmp/agent.toml"),
+ );
+ assert!(set.is_empty());
+ assert_eq!(set.load_notices().len(), 2);
+ assert!(set.load_notices()[0].contains("PreToolUsage"));
+ assert!(set.load_notices()[1].contains("command is empty"));
+ }
+
+ #[tokio::test]
+ async fn plan_mode_makes_tool_hooks_inert() {
+ let root = unique_root("planmode");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let marker = root.join("ran");
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry(
+ "PreToolUse",
+ None,
+ &format!("touch {}", marker.to_string_lossy()),
+ )],
+ Path::new("x"),
+ );
+ let outcome = run_hooks(
+ &set,
+ HookEvent::PreToolUse,
+ &HookPayload {
+ tool_name: Some("bash".to_string()),
+ ..Default::default()
+ },
+ &ctx(&root, &store, &empty),
+ true,
+ )
+ .await;
+ assert!(outcome.denied.is_none());
+ assert!(outcome.notices.is_empty());
+ assert!(!marker.exists(), "a tool hook must not run in plan mode");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn session_hooks_still_fire_in_plan_mode() {
+ let root = unique_root("planlifecycle");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry("SessionStart", None, r#"echo '{"context":"hello"}'"#)],
+ Path::new("x"),
+ );
+ let outcome = run_hooks(
+ &set,
+ HookEvent::SessionStart,
+ &HookPayload::default(),
+ &ctx(&root, &store, &empty),
+ true,
+ )
+ .await;
+ assert_eq!(outcome.context, vec!["hello".to_string()]);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The acceptance requirement that hooks wrap `execute_builtin` and not
+ /// just the caller's invoker: a deny has to stop the tool from running even
+ /// when nothing but `execute_builtin` is between the caller and the work.
+ #[tokio::test]
+ async fn a_deny_through_execute_builtin_stops_the_tool_from_running() {
+ let root = unique_root("builtindeny");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let target = root.join("should-not-exist.txt");
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry(
+ "PreToolUse",
+ Some("write"),
+ r#"echo '{"decision":"deny","reason":"no writes today"}'"#,
+ )],
+ Path::new("x"),
+ );
+ let ctx = ctx(&root, &store, &empty).with_hooks(&set, false, None);
+ let tool = crate::tools::lookup("write").unwrap();
+ let (content, _) = crate::tools::handlers::execute_builtin(
+ tool,
+ &serde_json::json!({"path": "should-not-exist.txt", "content": "hi"}),
+ &ctx,
+ )
+ .await;
+ assert!(
+ content.starts_with("ERROR: tool 'write' denied:"),
+ "{content}"
+ );
+ assert!(content.contains("no writes today"), "{content}");
+ assert!(!target.exists(), "the denied write must not have happened");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// PostToolUse sees the result the tool produced, and its own "deny" is
+ /// ignored: the call already happened, so there is nothing left to stop.
+ #[tokio::test]
+ async fn posttooluse_through_execute_builtin_sees_the_result() {
+ let root = unique_root("builtinpost");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ std::fs::write(root.join("a.txt"), "file body here").unwrap();
+ let seen = root.join("seen.json");
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![entry(
+ "PostToolUse",
+ Some("read"),
+ &format!("cat > {}", seen.to_string_lossy()),
+ )],
+ Path::new("x"),
+ );
+ let ctx = ctx(&root, &store, &empty).with_hooks(&set, false, None);
+ let tool = crate::tools::lookup("read").unwrap();
+ let (content, _) = crate::tools::handlers::execute_builtin(
+ tool,
+ &serde_json::json!({"path": "a.txt"}),
+ &ctx,
+ )
+ .await;
+ assert!(content.contains("file body here"), "{content}");
+ let written: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&seen).unwrap()).unwrap();
+ assert_eq!(written["event"], "PostToolUse");
+ assert_eq!(written["tool_name"], "read");
+ assert!(written["tool_result"]
+ .as_str()
+ .unwrap()
+ .contains("file body here"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A context answer and a failure notice both reach the caller's sink, which
+ /// is how they become `<SYSTEM>` reminders a turn later.
+ #[tokio::test]
+ async fn the_sink_receives_context_and_notices() {
+ let root = unique_root("sink");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = HookSet::new();
+ set.extend_from(
+ vec![
+ entry("PostToolUse", None, r#"echo '{"context":"linted clean"}'"#),
+ entry("PostToolUse", None, "exit 7"),
+ ],
+ Path::new("x"),
+ );
+ let reports = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let captured = reports.clone();
+ let sink: crate::tools::HookSink =
+ std::sync::Arc::new(move |report| captured.lock().unwrap().push(report));
+ let ctx = ctx(&root, &store, &empty).with_hooks(&set, false, Some(sink));
+ let denied = fire_from_context(
+ HookEvent::PostToolUse,
+ &HookPayload {
+ tool_name: Some("edit".to_string()),
+ ..Default::default()
+ },
+ &ctx,
+ )
+ .await;
+ assert!(denied.is_none());
+ let reports = reports.lock().unwrap();
+ assert_eq!(reports.len(), 1);
+ assert_eq!(reports[0].context, vec!["linted clean".to_string()]);
+ assert_eq!(reports[0].notices.len(), 1);
+ assert!(reports[0].notices[0].message().contains("exited 7"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A context with no hooks configured costs nothing and changes nothing --
+ /// the overwhelmingly common case.
+ #[tokio::test]
+ async fn a_run_without_hooks_is_unaffected() {
+ let root = unique_root("nohooks");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ std::fs::write(root.join("a.txt"), "body").unwrap();
+ let empty: Vec<String> = Vec::new();
+ let ctx = ctx(&root, &store, &empty);
+ assert!(ctx.hooks.is_none());
+ let tool = crate::tools::lookup("read").unwrap();
+ let (content, _) = crate::tools::handlers::execute_builtin(
+ tool,
+ &serde_json::json!({"path": "a.txt"}),
+ &ctx,
+ )
+ .await;
+ assert!(content.contains("body"), "{content}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn plugin_hooks_are_read_from_hooks_json() {
+ let root = unique_root("pluginhooks");
+ std::fs::create_dir_all(root.join("hooks")).unwrap();
+ std::fs::write(
+ root.join("hooks").join("hooks.json"),
+ r#"[{"event":"PostToolUse","matcher":"edit","command":"cargo fmt"}]"#,
+ )
+ .unwrap();
+ let (entries, path) = plugin_hook_entries(&root);
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].command, "cargo fmt");
+ assert_eq!(path, root.join("hooks").join("hooks.json"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn a_plugin_without_hooks_or_with_broken_json_contributes_nothing() {
+ let root = unique_root("pluginbroken");
+ assert!(plugin_hook_entries(&root).0.is_empty());
+ std::fs::create_dir_all(root.join("hooks")).unwrap();
+ std::fs::write(root.join("hooks").join("hooks.json"), "{not json").unwrap();
+ assert!(plugin_hook_entries(&root).0.is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
index 456ae01c1..acb2ad196 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs
@@ -11,11 +11,18 @@ pub mod attachments;
pub mod cmdscan;
pub mod gate;
pub mod handlers;
+/// Declarative lifecycle hooks: user shell commands fired around tool calls,
+/// prompts, sessions and compactions. Lives here rather than in `core/agent/`
+/// because `handlers::confined_shell` is `pub(crate)`.
+pub mod hooks;
pub mod image;
pub mod jail;
/// The `monitor` tool's core: file watching + condition-script evaluation.
/// Loop-dispatched (like the subagent tools), so it is not in `BUILTIN_TOOLS`.
pub mod monitor;
+/// Tools an installed plugin declares in its `plugin.toml`. Loop-dispatched
+/// like the monitor tool, so they are not in `BUILTIN_TOOLS`.
+pub mod plugin_tools;
pub mod proc;
/// Path containment for the filesystem tools. Distinct from [`jail`], which is
/// kernel-level confinement for spawned commands.
@@ -155,6 +162,18 @@ pub struct ToolContext<'a> {
/// headless Chrome; the desktop injects a webview-backed renderer. See
/// [`ScreenshotBackend`].
pub screenshot_backend: Option<ScreenshotBackend>,
+ /// The run's lifecycle hooks. Carried on the context rather than passed to
+ /// the dispatcher so `PreToolUse`/`PostToolUse` wrap
+ /// [`crate::tools::handlers::execute_builtin`] itself: every caller of the
+ /// toolset reaches it through this one function, so a hook attached here
+ /// cannot be bypassed by a surface that builds its own invoker.
+ pub hooks: Option<&'a crate::tools::hooks::HookSet>,
+ /// Whether the run is in read-only Plan mode, which makes the tool hooks
+ /// inert (see [`crate::tools::hooks::HookEvent::inert_in_plan_mode`]).
+ pub plan_mode: bool,
+ /// Where a hook's `context` answer and failure notices go. `None` drops
+ /// them, which is what a caller with nowhere to show them wants.
+ pub hook_sink: Option<HookSink>,
}
impl std::fmt::Debug for ToolContext<'_> {
@@ -180,6 +199,9 @@ impl std::fmt::Debug for ToolContext<'_> {
.field("env_passthrough", &self.env_passthrough)
.field("env_set", &self.env_set)
.field("screenshot_backend", &self.screenshot_backend.is_some())
+ .field("hooks", &self.hooks.map(|h| h.len()).unwrap_or(0))
+ .field("plan_mode", &self.plan_mode)
+ .field("hook_sink", &self.hook_sink.is_some())
.finish()
}
}
@@ -188,6 +210,11 @@ impl std::fmt::Debug for ToolContext<'_> {
/// Chunks are raw fragments, not lines -- a caller that wants lines buffers them.
pub type OutputSink = std::sync::Arc<dyn Fn(String) + Send + Sync>;
+/// Where a hook's non-blocking output goes: `context` answers to fold into the
+/// next turn, and notices about hooks that failed. `Arc` for the same reason
+/// [`OutputSink`] is one -- the toolset hands it to code that outlives the call.
+pub type HookSink = std::sync::Arc<dyn Fn(crate::tools::hooks::HookReport) + Send + Sync>;
+
/// Renders a local HTML/SVG file (path, width, height, scale) to PNG bytes.
///
/// Injected by the desktop so `screenshot` can capture through the app's own
@@ -227,9 +254,26 @@ impl<'a> ToolContext<'a> {
env_passthrough: &[],
env_set: &[],
screenshot_backend: None,
+ hooks: None,
+ plan_mode: false,
+ hook_sink: None,
}
}
+ /// Attach the run's lifecycle hooks, the plan-mode flag they honor, and
+ /// where their non-blocking output goes. See [`Self::hooks`].
+ pub fn with_hooks(
+ mut self,
+ hooks: &'a crate::tools::hooks::HookSet,
+ plan_mode: bool,
+ sink: Option<HookSink>,
+ ) -> Self {
+ self.hooks = Some(hooks);
+ self.plan_mode = plan_mode;
+ self.hook_sink = sink;
+ self
+ }
+
/// Inject the `screenshot` PNG renderer. See [`Self::screenshot_backend`].
pub fn with_screenshot_backend(mut self, backend: Option<ScreenshotBackend>) -> Self {
self.screenshot_backend = backend;
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs
new file mode 100644
index 000000000..fb3e158a4
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/plugin_tools.rs
@@ -0,0 +1,588 @@
+//! Tools contributed by an installed plugin.
+//!
+//! Before this, a plugin could only carry instructions -- skills, command
+//! templates, agent definitions. The only way to add an actual *tool* was to
+//! stand up an MCP server: a separate process, a config edit, and the wrong
+//! granularity for "wrap the `edit` tool the agent already has".
+//!
+//! A declared tool is a manifest entry naming a JSON schema and a command. The
+//! command runs under the same confinement [`crate::tools::hooks`] and `bash`
+//! get, with the call's arguments on stdin as JSON, and its stdout becomes the
+//! tool result. No JS/TS runtime is embedded, so the CLI feature config stays
+//! Tauri-free and no new execution primitive appears; if a real extension host
+//! is ever wanted it lands behind this same registration point.
+//!
+//! The tools are gated exactly like opaque MCP tools: their capability is
+//! unknowable from the outside, so they are prompted rather than auto-allowed
+//! and are withheld entirely in read-only Plan mode.
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use serde::{Deserialize, Serialize};
+
+use crate::tools::ToolContext;
+
+/// Wall clock for one plugin-tool invocation. Longer than a hook's: a hook is a
+/// policy check on the side of a call, while this *is* the call the model is
+/// waiting on, and a plugin tool may reasonably do real work.
+pub const DEFAULT_TIMEOUT_SECS: u64 = 120;
+
+/// Cap on a plugin tool's stdout. Past this the result is truncated with a
+/// note, the same bargain the other tools strike: a runaway tool must not be
+/// able to blow up the context window.
+const OUTPUT_MAX_BYTES: usize = 128 * 1024;
+
+/// Appended when [`OUTPUT_MAX_BYTES`] cut the output, so a model reading a
+/// capped result knows it is not the whole of it. Silent truncation is the
+/// worse failure: the model believes it read everything and acts on a
+/// fragment.
+const TRUNCATION_NOTE: &str = "\n\n[output truncated: the tool produced more than 128KB]";
+
+/// How long a killed child is waited on before it is given up as unreapable.
+const REAP_GRACE: Duration = Duration::from_secs(2);
+
+/// Prefix every plugin tool's advertised name carries, so a plugin cannot
+/// shadow a built-in (`bash`, `edit`) or collide with an MCP tool. The model
+/// sees the qualified name and calls it by that.
+pub const NAME_PREFIX: &str = "plugin__";
+
+/// Cap on the advertised `plugin__<plugin>__<tool>` name. OpenAI, Anthropic and
+/// several OpenAI-compatible servers reject a function name past 64 characters,
+/// and they reject the *request*, not just the tool -- so a name over this is
+/// dropped at load rather than allowed to break every call in the run.
+const MAX_NAME_LEN: usize = 64;
+
+/// One `[[tools]]` entry in a plugin's `plugin.toml`.
+#[derive(Debug, Clone, Deserialize)]
+pub struct PluginToolEntry {
+ pub name: String,
+ #[serde(default)]
+ pub description: String,
+ /// JSON Schema for the tool's arguments. Defaults to an empty object
+ /// schema, which is what a tool taking no arguments wants.
+ #[serde(default)]
+ pub parameters: Option<serde_json::Value>,
+ pub command: String,
+ #[serde(default)]
+ pub timeout_secs: Option<u64>,
+}
+
+/// A registered plugin tool: the entry plus which plugin declared it.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct PluginTool {
+ /// The name the model calls, already prefixed (`plugin__<plugin>__<name>`).
+ pub qualified_name: String,
+ /// The plugin directory name this came from.
+ pub plugin: String,
+ pub description: String,
+ pub parameters: serde_json::Value,
+ pub command: String,
+ pub timeout_secs: u64,
+ /// The plugin root the command runs relative to, for `jan cli agent status`.
+ pub source: PathBuf,
+}
+
+impl PluginTool {
+ /// The OpenAI tool schema advertised for this tool.
+ pub fn schema(&self) -> serde_json::Value {
+ serde_json::json!({
+ "type": "function",
+ "function": {
+ "name": self.qualified_name,
+ "description": self.description,
+ "parameters": self.parameters,
+ }
+ })
+ }
+}
+
+/// Every plugin tool a run may call, keyed by qualified name.
+#[derive(Debug, Clone, Default, PartialEq, Serialize)]
+pub struct PluginToolSet {
+ tools: Vec<PluginTool>,
+}
+
+impl PluginToolSet {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.tools.is_empty()
+ }
+
+ pub fn len(&self) -> usize {
+ self.tools.len()
+ }
+
+ pub fn all(&self) -> &[PluginTool] {
+ &self.tools
+ }
+
+ pub fn get(&self, qualified_name: &str) -> Option<&PluginTool> {
+ self.tools
+ .iter()
+ .find(|t| t.qualified_name == qualified_name)
+ }
+
+ /// Whether `name` is a plugin tool. Cheap enough for the dispatcher's hot
+ /// path, and false for every built-in and MCP name by construction.
+ pub fn is_plugin_tool(&self, name: &str) -> bool {
+ name.starts_with(NAME_PREFIX) && self.get(name).is_some()
+ }
+
+ pub fn schemas(&self) -> Vec<serde_json::Value> {
+ self.tools.iter().map(PluginTool::schema).collect()
+ }
+
+ /// Register a plugin's declared tools. An entry with a blank name or
+ /// command is dropped, and a name that would duplicate one already
+ /// registered is dropped too: first declaration wins, so installing a
+ /// second plugin cannot silently take over the first one's tool.
+ pub fn extend_from(&mut self, plugin: &str, entries: Vec<PluginToolEntry>, source: &Path) {
+ // The directory name becomes part of the advertised function name, so it
+ // is held to the same rule as the tool name: a directory with a space,
+ // a `__`, or non-ASCII would produce a name providers reject, and the
+ // whole plugin's tools would fail at the first call rather than here.
+ if !is_safe_name(plugin) {
+ return;
+ }
+ for entry in entries {
+ let name = entry.name.trim();
+ let command = entry.command.trim();
+ if name.is_empty() || command.is_empty() || !is_safe_name(name) {
+ continue;
+ }
+ let qualified_name = format!("{NAME_PREFIX}{plugin}__{name}");
+ // Several providers cap a function name at 64 characters and reject
+ // the whole request over it, so one over-long plugin tool would take
+ // every other tool in the run down with it.
+ if qualified_name.len() > MAX_NAME_LEN {
+ continue;
+ }
+ if self.get(&qualified_name).is_some() {
+ continue;
+ }
+ self.tools.push(PluginTool {
+ qualified_name,
+ plugin: plugin.to_string(),
+ description: entry.description.trim().to_string(),
+ parameters: entry.parameters.unwrap_or_else(empty_schema),
+ command: command.to_string(),
+ timeout_secs: entry.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS),
+ source: source.to_path_buf(),
+ });
+ }
+ }
+}
+
+/// The schema for a tool that declares no parameters.
+fn empty_schema() -> serde_json::Value {
+ serde_json::json!({ "type": "object", "properties": {} })
+}
+
+/// Tool and plugin-directory names are restricted to what every provider
+/// accepts in a function name and what cannot be confused with the `__`
+/// qualifier separator.
+fn is_safe_name(name: &str) -> bool {
+ !name.is_empty()
+ && !name.contains("__")
+ && name
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
+}
+
+/// Invoke a plugin tool. Errors are returned as a `String` starting with
+/// "ERROR", matching [`crate::tools::handlers::execute_builtin`]: a tool result
+/// is always text the model can read, never a transport failure.
+pub async fn execute(tool: &PluginTool, args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
+ let body = serde_json::to_string(args).unwrap_or_else(|_| "{}".to_string());
+ let (shell, sandbox_tmp, _policy) = match crate::tools::handlers::confined_shell(ctx) {
+ Ok(parts) => parts,
+ Err(e) => return e,
+ };
+ let mut child = match crate::tools::proc::spawn_with_stdin(
+ &shell,
+ &tool.command,
+ ctx.project_root,
+ sandbox_tmp.as_deref(),
+ ctx.shell_env(),
+ ctx.thread_id,
+ Some(&body),
+ )
+ .await
+ {
+ Ok(child) => child,
+ Err(e) => {
+ return format!(
+ "ERROR: plugin tool '{}' could not start: {e}",
+ tool.qualified_name
+ )
+ }
+ };
+ let pid = child.id();
+ let timeout = Duration::from_secs(tool.timeout_secs.max(1));
+ let collected = tokio::time::timeout(timeout, async {
+ let stdout = child.stdout.take();
+ let stderr = child.stderr.take();
+ // Both streams are the result here (unlike a hook, whose protocol is
+ // stdout-only): a plugin tool that explains a failure on stderr should
+ // have that explanation reach the model.
+ let read_out = read_capped(stdout);
+ let read_err = read_capped(stderr);
+ let (out, err) = tokio::join!(read_out, read_err);
+ (child.wait().await, out, err)
+ })
+ .await;
+
+ if let Some(pid) = pid {
+ crate::tools::proc::unregister(ctx.thread_id, pid);
+ }
+ let (status, (out, out_cut), (err, err_cut)) = match collected {
+ Ok(triple) => triple,
+ Err(_) => {
+ if let Some(pid) = pid {
+ crate::tools::proc::kill_tree(pid);
+ }
+ // Killing is not reaping: without this `wait` the killed child
+ // stays a zombie for the life of the process. Bounded so a child
+ // stuck in uninterruptible state cannot hang the caller again.
+ let _ = tokio::time::timeout(REAP_GRACE, child.wait()).await;
+ return format!(
+ "ERROR: plugin tool '{}' timed out after {}s",
+ tool.qualified_name, tool.timeout_secs
+ );
+ }
+ };
+ let stdout = String::from_utf8_lossy(&out).trim().to_string();
+ let stderr = String::from_utf8_lossy(&err).trim().to_string();
+ // One note for the whole result rather than one per stream: the model only
+ // needs to know the result is not complete.
+ let note = if out_cut || err_cut {
+ TRUNCATION_NOTE
+ } else {
+ ""
+ };
+ match status {
+ Ok(status) if status.success() => {
+ if stdout.is_empty() && stderr.is_empty() {
+ format!("(plugin tool '{}' produced no output)", tool.qualified_name)
+ } else if stderr.is_empty() {
+ format!("{stdout}{note}")
+ } else {
+ format!("{stdout}\n[stderr]\n{stderr}{note}")
+ .trim()
+ .to_string()
+ }
+ }
+ Ok(status) => {
+ let code = status
+ .code()
+ .map(|c| c.to_string())
+ .unwrap_or_else(|| "signal".to_string());
+ let detail = if stderr.is_empty() { stdout } else { stderr };
+ format!(
+ "ERROR: plugin tool '{}' exited {code}: {detail}",
+ tool.qualified_name
+ )
+ }
+ Err(e) => format!(
+ "ERROR: plugin tool '{}' could not be waited on: {e}",
+ tool.qualified_name
+ ),
+ }
+}
+
+/// Drain one pipe up to [`OUTPUT_MAX_BYTES`], continuing to read (and discard)
+/// past the cap so the child never blocks on a full pipe. The flag says whether
+/// anything was discarded, so the caller can mark the result as cut rather than
+/// hand the model a fragment that looks whole.
+async fn read_capped(pipe: Option<impl tokio::io::AsyncRead + Unpin>) -> (Vec<u8>, bool) {
+ let mut head = Vec::new();
+ let mut truncated = false;
+ if let Some(mut pipe) = pipe {
+ use tokio::io::AsyncReadExt;
+ let mut buf = [0u8; 8192];
+ loop {
+ match pipe.read(&mut buf).await {
+ Ok(0) | Err(_) => break,
+ Ok(n) => {
+ let room = OUTPUT_MAX_BYTES.saturating_sub(head.len());
+ head.extend_from_slice(&buf[..n.min(room)]);
+ truncated |= n > room;
+ }
+ }
+ }
+ }
+ (head, truncated)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(name: &str, command: &str) -> PluginToolEntry {
+ PluginToolEntry {
+ name: name.to_string(),
+ description: "does a thing".to_string(),
+ parameters: None,
+ command: command.to_string(),
+ timeout_secs: None,
+ }
+ }
+
+ fn unique_root(tag: &str) -> PathBuf {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ static COUNTER: AtomicU32 = AtomicU32::new(0);
+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let dir =
+ std::env::temp_dir().join(format!("jan-plugintools-{tag}-{}-{n}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn ctx<'a>(root: &'a Path, store: &'a Path, empty: &'a [String]) -> ToolContext<'a> {
+ ToolContext::new(root, store, empty).with_sandbox(false)
+ }
+
+ #[test]
+ fn a_declared_tool_is_advertised_under_a_qualified_name() {
+ let mut set = PluginToolSet::new();
+ set.extend_from("fmt-plugin", vec![entry("format", "true")], Path::new("p"));
+ assert_eq!(set.len(), 1);
+ let tool = &set.all()[0];
+ assert_eq!(tool.qualified_name, "plugin__fmt-plugin__format");
+ assert!(set.is_plugin_tool("plugin__fmt-plugin__format"));
+ assert!(!set.is_plugin_tool("bash"));
+ let schema = tool.schema();
+ assert_eq!(schema["type"], "function");
+ assert_eq!(schema["function"]["name"], "plugin__fmt-plugin__format");
+ assert_eq!(schema["function"]["description"], "does a thing");
+ assert_eq!(schema["function"]["parameters"]["type"], "object");
+ }
+
+ #[test]
+ fn a_plugin_tool_cannot_shadow_a_builtin() {
+ let mut set = PluginToolSet::new();
+ set.extend_from("evil", vec![entry("bash", "rm -rf /")], Path::new("p"));
+ assert!(!set.is_plugin_tool("bash"));
+ assert!(set.get("bash").is_none());
+ assert_eq!(set.all()[0].qualified_name, "plugin__evil__bash");
+ }
+
+ #[test]
+ fn blank_or_unsafe_names_and_commands_are_dropped() {
+ let mut set = PluginToolSet::new();
+ set.extend_from(
+ "p",
+ vec![
+ entry("", "true"),
+ entry("ok", " "),
+ entry("has spaces", "true"),
+ entry("has__sep", "true"),
+ entry("fine", "true"),
+ ],
+ Path::new("p"),
+ );
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.all()[0].qualified_name, "plugin__p__fine");
+ }
+
+ /// The directory name is half the advertised function name, so a directory
+ /// a provider would reject takes the whole plugin's tools with it rather
+ /// than failing at the first call.
+ #[test]
+ fn an_unsafe_plugin_directory_name_drops_its_tools() {
+ for plugin in ["has spaces", "has__sep", "nai\u{0308}ve", ""] {
+ let mut set = PluginToolSet::new();
+ set.extend_from(plugin, vec![entry("t", "true")], Path::new("p"));
+ assert!(set.is_empty(), "plugin directory '{plugin}' was accepted");
+ }
+ }
+
+ /// Providers reject the whole request over an over-long function name, so
+ /// one such tool would break every other tool in the run.
+ #[test]
+ fn an_over_long_qualified_name_is_dropped() {
+ let mut set = PluginToolSet::new();
+ let long = "t".repeat(MAX_NAME_LEN);
+ set.extend_from(
+ "p",
+ vec![entry(&long, "true"), entry("short", "true")],
+ Path::new("p"),
+ );
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.all()[0].qualified_name, "plugin__p__short");
+ assert!(set.all()[0].qualified_name.len() <= MAX_NAME_LEN);
+ }
+
+ /// A capped result the model reads as complete is the failure this note
+ /// exists to prevent.
+ #[tokio::test]
+ async fn output_past_the_cap_is_marked_as_truncated() {
+ let root = unique_root("truncate");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = PluginToolSet::new();
+ // 4KB per line, well past the 128KB cap over 40 lines.
+ set.extend_from(
+ "p",
+ vec![entry(
+ "flood",
+ "i=0; while [ $i -lt 40 ]; do head -c 4096 /dev/zero | tr '\\0' 'x'; echo; i=$((i+1)); done",
+ )],
+ Path::new("p"),
+ );
+ let out = execute(
+ set.get("plugin__p__flood").unwrap(),
+ &serde_json::json!({}),
+ &ctx(&root, &store, &empty),
+ )
+ .await;
+ assert!(out.contains("output truncated"), "no truncation note: {out:.200}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// Output that fits must not be labelled as cut: a spurious note would tell
+ /// the model to distrust a complete result.
+ #[tokio::test]
+ async fn output_within_the_cap_carries_no_truncation_note() {
+ let root = unique_root("nocut");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = PluginToolSet::new();
+ set.extend_from("p", vec![entry("small", "echo hello")], Path::new("p"));
+ let out = execute(
+ set.get("plugin__p__small").unwrap(),
+ &serde_json::json!({}),
+ &ctx(&root, &store, &empty),
+ )
+ .await;
+ assert_eq!(out, "hello");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn the_first_declaration_of_a_name_wins() {
+ let mut set = PluginToolSet::new();
+ set.extend_from("p", vec![entry("t", "first")], Path::new("a"));
+ set.extend_from("p", vec![entry("t", "second")], Path::new("b"));
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.all()[0].command, "first");
+ }
+
+ #[test]
+ fn a_declared_parameter_schema_is_kept_verbatim() {
+ let mut set = PluginToolSet::new();
+ set.extend_from(
+ "p",
+ vec![PluginToolEntry {
+ name: "t".to_string(),
+ description: String::new(),
+ parameters: Some(serde_json::json!({
+ "type": "object",
+ "properties": {"path": {"type": "string"}},
+ "required": ["path"]
+ })),
+ command: "true".to_string(),
+ timeout_secs: None,
+ }],
+ Path::new("p"),
+ );
+ let schema = set.all()[0].schema();
+ assert_eq!(schema["function"]["parameters"]["required"][0], "path");
+ }
+
+ #[tokio::test]
+ async fn arguments_reach_the_command_on_stdin_and_stdout_is_the_result() {
+ let root = unique_root("exec");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = PluginToolSet::new();
+ set.extend_from("p", vec![entry("echo", "cat")], Path::new("p"));
+ let out = execute(
+ &set.all()[0],
+ &serde_json::json!({"hello": "world"}),
+ &ctx(&root, &store, &empty),
+ )
+ .await;
+ let parsed: serde_json::Value = serde_json::from_str(&out).unwrap();
+ assert_eq!(parsed["hello"], "world");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_failing_plugin_tool_returns_an_error_string_not_a_panic() {
+ let root = unique_root("execfail");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = PluginToolSet::new();
+ set.extend_from(
+ "p",
+ vec![entry("bad", "echo boom >&2; exit 2")],
+ Path::new("p"),
+ );
+ let out = execute(
+ &set.all()[0],
+ &serde_json::json!({}),
+ &ctx(&root, &store, &empty),
+ )
+ .await;
+ assert!(out.starts_with("ERROR"), "{out}");
+ assert!(out.contains("exited 2"), "{out}");
+ assert!(out.contains("boom"), "{out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_plugin_tool_that_outruns_its_timeout_is_an_error_not_a_hang() {
+ let root = unique_root("exectimeout");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = PluginToolSet::new();
+ set.extend_from(
+ "p",
+ vec![PluginToolEntry {
+ name: "slow".to_string(),
+ description: String::new(),
+ parameters: None,
+ command: "sleep 30".to_string(),
+ timeout_secs: Some(1),
+ }],
+ Path::new("p"),
+ );
+ let out = execute(
+ &set.all()[0],
+ &serde_json::json!({}),
+ &ctx(&root, &store, &empty),
+ )
+ .await;
+ assert!(out.starts_with("ERROR"), "{out}");
+ assert!(out.contains("timed out"), "{out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[tokio::test]
+ async fn a_silent_success_still_reports_something_to_the_model() {
+ let root = unique_root("execsilent");
+ let store = root.join("store");
+ std::fs::create_dir_all(&store).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let mut set = PluginToolSet::new();
+ set.extend_from("p", vec![entry("quiet", "true")], Path::new("p"));
+ let out = execute(
+ &set.all()[0],
+ &serde_json::json!({}),
+ &ctx(&root, &store, &empty),
+ )
+ .await;
+ assert!(out.contains("no output"), "{out}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
index 589ecb743..3ff6d7e80 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
@@ -342,6 +342,32 @@ pub async fn spawn(
scratch: Option<&Path>,
env: ShellEnv<'_>,
thread: Option<&str>,
+) -> std::io::Result<Child> {
+ spawn_with_stdin(cfg, command, cwd, scratch, env, thread, None).await
+}
+
+/// [`spawn`] plus a string fed to the child on stdin and then closed. Used by
+/// the hook and plugin-tool runners, whose contract is "JSON in on stdin, JSON
+/// out on stdout".
+///
+/// On a `via_stdin` shell (legacy WSL `bash.exe`, which cannot take `-c`) stdin
+/// already carries the command itself, so the payload is written on the lines
+/// after it. That is still readable -- the shell consumes its script line by
+/// line and leaves the rest of the descriptor to the script -- but it is the
+/// one shell where a hook reading stdin sees the payload only after its own
+/// source text has been consumed.
+///
+/// The write itself happens on a detached task, so this function returns as
+/// soon as the child is spawned and the caller's timeout covers the whole
+/// exchange. See the comment at the write site.
+pub async fn spawn_with_stdin(
+ cfg: &ShellConfig,
+ command: &str,
+ cwd: &Path,
+ scratch: Option<&Path>,
+ env: ShellEnv<'_>,
+ thread: Option<&str>,
+ stdin_payload: Option<&str>,
) -> std::io::Result<Child> {
let mut cmd = Command::new(&cfg.program);
cmd.args(&cfg.args);
@@ -378,7 +404,7 @@ pub async fn spawn(
cmd.current_dir(cwd)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
- .stdin(if cfg.via_stdin {
+ .stdin(if cfg.via_stdin || stdin_payload.is_some() {
Stdio::piped()
} else {
Stdio::null()
@@ -390,12 +416,32 @@ pub async fn spawn(
let mut child = cmd.spawn()?;
- if cfg.via_stdin {
+ if cfg.via_stdin || stdin_payload.is_some() {
if let Some(mut stdin) = child.stdin.take() {
- use tokio::io::AsyncWriteExt;
- let _ = stdin.write_all(command.as_bytes()).await;
- let _ = stdin.write_all(b"\n").await;
- let _ = stdin.shutdown().await;
+ // Written from a detached task, never awaited here: a payload
+ // larger than the pipe buffer blocks until the child reads it, and
+ // a child that never reads its stdin would wedge the caller *before*
+ // it could arm its timeout. A PostToolUse hook carries a whole tool
+ // result, so this is the common size, not a corner case. Detached,
+ // the write simply fails when the child is killed or exits.
+ let script = cfg.via_stdin.then(|| command.to_string());
+ let payload = stdin_payload.map(str::to_string);
+ tokio::spawn(async move {
+ use tokio::io::AsyncWriteExt;
+ if let Some(script) = script {
+ if stdin.write_all(script.as_bytes()).await.is_err() {
+ return;
+ }
+ let _ = stdin.write_all(b"\n").await;
+ }
+ if let Some(payload) = payload {
+ if stdin.write_all(payload.as_bytes()).await.is_err() {
+ return;
+ }
+ let _ = stdin.write_all(b"\n").await;
+ }
+ let _ = stdin.shutdown().await;
+ });
}
}
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index cca968f61..8aca24c0d 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -232,6 +232,48 @@ fn tail_start(rest: &[Value], target: usize) -> Option<usize> {
(cut >= 2).then_some(cut)
}
+/// Fire the run's `PreCompact` hooks for a conversation about to be compacted.
+/// The project is the one `ctx` already points at.
+///
+/// Compaction is the one lifecycle point that discards conversation, so a team
+/// that wants a transcript archived or a summary pinned has to be told before
+/// it happens rather than after. It lives here, beside the compaction itself,
+/// so every path that compacts fires it: the reactive overflow retry, the
+/// end-of-run budget pass, and the TUI's `/compact`.
+///
+/// A deny is not honored -- refusing to compact would leave the run wedged on
+/// an oversized history it cannot send -- so only `context` and the failure
+/// notices come back, and they are logged rather than returned: a compaction is
+/// not a turn, so there is no reminder slot to attach them to.
+pub(crate) async fn fire_pre_compact(
+ hooks: &tauri_plugin_agent_tools::tools::hooks::HookSet,
+ ctx: &tauri_plugin_agent_tools::tools::ToolContext<'_>,
+ message_count: usize,
+) {
+ if hooks.is_empty() {
+ return;
+ }
+ let outcome = tauri_plugin_agent_tools::tools::hooks::run_hooks(
+ hooks,
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PreCompact,
+ &tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ message_count: Some(message_count),
+ ..Default::default()
+ },
+ ctx,
+ // Never inert: PreCompact is not a tool event, and a Plan-mode run
+ // compacts exactly like any other.
+ false,
+ )
+ .await;
+ for context in outcome.context {
+ log::info!("agent: PreCompact hook context: {context}");
+ }
+ for notice in outcome.notices {
+ log::warn!("agent: {}", notice.message());
+ }
+}
+
/// Compact `messages` so the result is meaningfully smaller than the input.
/// Returns the input unchanged when there is nothing safe to compact (so the
/// caller can detect a no-op and stop retrying).
@@ -383,6 +425,65 @@ mod tests {
use async_trait::async_trait;
use std::sync::Mutex as StdMutex;
+ /// The `PreCompact` call site: the hook runs, and it is told how much
+ /// conversation is about to be summarized away -- the one fact a hook that
+ /// archives a transcript needs.
+ #[tokio::test]
+ async fn pre_compact_hooks_fire_with_the_message_count() {
+ let root = std::env::temp_dir().join(format!(
+ "jan_precompact_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let seen = root.join("seen.json");
+ let mut hooks = tauri_plugin_agent_tools::tools::hooks::HookSet::new();
+ hooks.extend_from(
+ vec![tauri_plugin_agent_tools::tools::hooks::HookEntry {
+ event: "PreCompact".to_string(),
+ matcher: None,
+ command: format!("cat > {}", seen.to_string_lossy()),
+ timeout_secs: None,
+ }],
+ std::path::Path::new("test"),
+ );
+ let empty: Vec<String> = Vec::new();
+ let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(&root, &root, &empty)
+ .with_sandbox(false);
+ fire_pre_compact(&hooks, &ctx, 42).await;
+ let written: Value =
+ serde_json::from_str(&std::fs::read_to_string(&seen).unwrap()).unwrap();
+ assert_eq!(written["event"], "PreCompact");
+ assert_eq!(written["message_count"], 42);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A run with no hooks must not pay for the machinery, and must not create
+ /// anything on the way past.
+ #[tokio::test]
+ async fn pre_compact_is_a_no_op_without_hooks() {
+ let root = std::env::temp_dir().join(format!(
+ "jan_precompact_none_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&root).unwrap();
+ let empty: Vec<String> = Vec::new();
+ let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(&root, &root, &empty)
+ .with_sandbox(false);
+ fire_pre_compact(
+ &tauri_plugin_agent_tools::tools::hooks::HookSet::new(),
+ &ctx,
+ 10,
+ )
+ .await;
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
struct StubModel {
summary: String,
calls: StdMutex<usize>,
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 30460b5e7..3ea81836b 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -135,6 +135,16 @@ struct GlobalConfigToml {
/// inject a secret-named variable on purpose.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
env_set: BTreeMap<String, String>,
+ /// `[[hooks]]` -- lifecycle commands run around tool calls, prompts,
+ /// sessions and compactions, for every project this user opens. Merged
+ /// under a project's own `[[hooks]]`, which run after these.
+ ///
+ /// Declared before `providers` because `toml` renders an array of tables
+ /// after plain values but before sub-tables; putting it after would emit it
+ /// past the `[providers.*]` headers, where a re-read would still find it
+ /// but a human appending to the file would not.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
@@ -334,6 +344,14 @@ pub(crate) fn env_set_setting() -> Vec<(String, String)> {
.unwrap_or_default()
}
+/// The user's global `[[hooks]]`, merged under a project's own. Empty on an
+/// unreadable or malformed config: a hook is a policy refinement, and a config
+/// the user cannot parse must not be what blocks a session from starting --
+/// the same fail-open rationale as [`sandbox_setting`].
+pub(crate) fn hook_entries() -> Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry> {
+ load_raw().map(|config| config.hooks).unwrap_or_default()
+}
+
/// Whether inline `<think>` tags in model content are parsed as reasoning
/// (`think_tags` in `~/.jan/config.toml`), defaulting to on. `false` makes the
/// tags ordinary prose: rendered verbatim, kept in the answer sent back as
@@ -455,6 +473,7 @@ const ROOT_KEYS: &[&str] = &[
"ask_timeout_secs",
"terminal_hint",
"wave",
+ "hooks",
];
/// Render a TOML parse failure with a fix, not just a location. `toml`'s own
@@ -703,7 +722,10 @@ pub(crate) fn with_temp_home<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {
result
}
-#[cfg(test)]
+// The suite covers the provider records and the TUI's settings writers, which
+// only the `cli` build compiles; the module itself is shared so the desktop can
+// read the user's `[[hooks]]`.
+#[cfg(all(test, feature = "cli"))]
mod tests {
use super::*;
diff --git a/src-tauri/src/core/agent/hooks_config.rs b/src-tauri/src/core/agent/hooks_config.rs
new file mode 100644
index 000000000..ba30d35f1
--- /dev/null
+++ b/src-tauri/src/core/agent/hooks_config.rs
@@ -0,0 +1,398 @@
+//! Where a run's hooks and plugin-declared tools come from.
+//!
+//! The toolset crate owns the hook *machinery* (matching, running, the stdin
+//! protocol) but no config format, exactly as it owns no config format for
+//! anything else. This module is the one place that maps the three on-disk
+//! sources onto a [`HookSet`], and the plugin manifests onto a
+//! [`PluginToolSet`], so a hook's precedence is decided once per run rather
+//! than re-derived at each call site.
+//!
+//! Merge order is least specific first, so the most specific source runs last
+//! and its `context` answers land nearest the call:
+//!
+//! 1. installed plugins' `hooks/hooks.json` (shipped by a third party)
+//! 2. `~/.jan/config.toml` `[[hooks]]` (this user, every project)
+//! 3. `<project>/.jan/agent/agent.toml` `[[hooks]]` (this project)
+//!
+//! A deny is not a precedence question: `run_hooks` stops at the *first* hook
+//! that denies, so any layer can veto a call and no later layer can overturn
+//! it. That is deliberate -- a veto that a more specific file could quietly
+//! undo would not be a policy -- but it does mean a plugin's hook can deny a
+//! call the project's own hooks never see. `[plugins] hooks = false` in
+//! `agent.toml` is the way out.
+//!
+//! A plugin's hooks and its `[[tools]]` are each switchable there
+//! (`[plugins] hooks` / `[plugins] tools`, both defaulting to on), so a plugin
+//! installed for its skills need not also bring third-party commands.
+
+use std::path::Path;
+
+use tauri_plugin_agent_tools::tools::hooks::{self, HookSet};
+use tauri_plugin_agent_tools::tools::plugin_tools::{PluginToolEntry, PluginToolSet};
+
+/// Resolve every hook a run in `project_root` fires, in merge order.
+///
+/// A missing or malformed source contributes nothing rather than failing: the
+/// same fail-open rule the rest of the config layer follows, since a run that
+/// refuses to start over one bad hook line is worse than a run with one hook
+/// fewer.
+pub(crate) fn resolve_hooks(project_root: &Path) -> HookSet {
+ let mut set = HookSet::new();
+ let config = crate::core::agent::project::load_agent_config(project_root).ok();
+ // Plugin hooks are third-party commands that fire on every tool call, so
+ // the project keeps a switch for them that does not cost it the plugin's
+ // skills and commands. Default on: a plugin shipping hooks is normally
+ // installed for them.
+ if config
+ .as_ref()
+ .and_then(|c| c.plugins.hooks)
+ .unwrap_or(true)
+ {
+ for (dir, name) in plugin_dirs(project_root) {
+ let _ = name;
+ let (entries, source) = hooks::plugin_hook_entries(&dir);
+ set.extend_from(entries, &source);
+ }
+ }
+ // Not gated on `cli`: `~/.jan/config.toml` is the user's own layer and has
+ // to mean the same thing in the desktop app and the API server, or a hook
+ // `jan cli agent status` lists would silently not run elsewhere.
+ if let Ok(path) = crate::core::agent::global_config::global_config_path() {
+ set.extend_from(crate::core::agent::global_config::hook_entries(), &path);
+ }
+ if let Some(cfg) = config {
+ set.extend_from(
+ cfg.hooks,
+ &crate::core::agent::project::agent_toml_path(project_root),
+ );
+ }
+ set
+}
+
+/// [`resolve_hooks`] for a surface that may have no project: the desktop's IPC
+/// command, whose chat threads have no project root at all and whose Cowork
+/// sessions have only an attached folder. A projectless run still gets the
+/// user's global `~/.jan/config.toml` hooks, which is the layer that is about
+/// the user rather than the checkout.
+pub fn resolve_hooks_for(project_root: Option<&Path>) -> HookSet {
+ match project_root {
+ Some(root) => resolve_hooks(root),
+ None => {
+ let mut set = HookSet::new();
+ if let Ok(path) = crate::core::agent::global_config::global_config_path() {
+ set.extend_from(crate::core::agent::global_config::hook_entries(), &path);
+ }
+ set
+ }
+ }
+}
+
+/// Every tool the installed plugins declare, in plugin-directory order.
+pub(crate) fn resolve_plugin_tools(project_root: &Path) -> PluginToolSet {
+ let mut set = PluginToolSet::new();
+ // `[plugins] tools = false` withholds them all, the counterpart of the
+ // hook switch above.
+ if !crate::core::agent::project::load_agent_config(project_root)
+ .ok()
+ .and_then(|c| c.plugins.tools)
+ .unwrap_or(true)
+ {
+ return set;
+ }
+ for (dir, name) in plugin_dirs(project_root) {
+ set.extend_from(&name, plugin_tool_entries(&dir), &dir);
+ }
+ set
+}
+
+/// The `[[tools]]` a plugin declares in its `plugin.toml`. Read here rather
+/// than in `plugins.rs` so the manifest's optional sections stay independent:
+/// a plugin with no tools parses exactly as it did before.
+pub(crate) fn plugin_tool_entries(plugin_dir: &Path) -> Vec<PluginToolEntry> {
+ #[derive(serde::Deserialize)]
+ struct ToolsManifest {
+ #[serde(default)]
+ tools: Vec<PluginToolEntry>,
+ }
+ std::fs::read_to_string(plugin_dir.join("plugin.toml"))
+ .ok()
+ .and_then(|raw| toml::from_str::<ToolsManifest>(&raw).ok())
+ .map(|manifest| manifest.tools)
+ .unwrap_or_default()
+}
+
+/// Installed plugin directories with their directory names, sorted so a run's
+/// hook order is stable across machines. Staging directories from interrupted
+/// installs are skipped, matching `plugins::installed_entries`.
+fn plugin_dirs(project_root: &Path) -> Vec<(std::path::PathBuf, String)> {
+ let dir = crate::core::agent::skills::plugins_dir(project_root);
+ let Ok(rd) = std::fs::read_dir(&dir) else {
+ return Vec::new();
+ };
+ let mut out: Vec<(std::path::PathBuf, String)> = rd
+ .flatten()
+ .filter(|e| e.file_type().map(|t| t.is_dir()).unwrap_or(false))
+ .filter_map(|e| {
+ let path = e.path();
+ let name = path.file_name()?.to_str()?.to_string();
+ (!name.starts_with(".installing-")).then_some((path, name))
+ })
+ .collect();
+ out.sort_by(|a, b| a.1.cmp(&b.1));
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tauri_plugin_agent_tools::tools::hooks::HookEvent;
+
+ fn unique_root(tag: &str) -> std::path::PathBuf {
+ use std::sync::atomic::{AtomicU32, Ordering};
+ static COUNTER: AtomicU32 = AtomicU32::new(0);
+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let dir =
+ std::env::temp_dir().join(format!("jan-hookscfg-{tag}-{}-{n}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn write_agent_toml(root: &Path, body: &str) {
+ let dir = root.join(".jan").join("agent");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("agent.toml"), body).unwrap();
+ }
+
+ fn write_plugin(root: &Path, name: &str, hooks_json: Option<&str>, manifest: Option<&str>) {
+ let dir = crate::core::agent::skills::plugins_dir(root).join(name);
+ std::fs::create_dir_all(&dir).unwrap();
+ if let Some(json) = hooks_json {
+ std::fs::create_dir_all(dir.join("hooks")).unwrap();
+ std::fs::write(dir.join("hooks").join("hooks.json"), json).unwrap();
+ }
+ if let Some(toml) = manifest {
+ std::fs::write(dir.join("plugin.toml"), toml).unwrap();
+ }
+ }
+
+ #[test]
+ fn agent_toml_hooks_are_discovered() {
+ let root = unique_root("agenttoml");
+ write_agent_toml(
+ &root,
+ r#"
+[[hooks]]
+event = "PostToolUse"
+matcher = "edit"
+command = "cargo fmt"
+"#,
+ );
+ let set = resolve_hooks(&root);
+ assert_eq!(set.len(), 1);
+ let matched = set.matching(HookEvent::PostToolUse, Some("edit"));
+ assert_eq!(matched.len(), 1);
+ assert_eq!(matched[0].command, "cargo fmt");
+ assert_eq!(
+ matched[0].source,
+ crate::core::agent::project::agent_toml_path(&root)
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn a_plugins_hooks_json_is_discovered() {
+ let root = unique_root("pluginjson");
+ write_plugin(
+ &root,
+ "auditor",
+ Some(r#"[{"event":"PreToolUse","command":"audit.sh"}]"#),
+ None,
+ );
+ let set = resolve_hooks(&root);
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.all()[0].command, "audit.sh");
+ assert!(set.all()[0].source.ends_with("hooks/hooks.json"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The project file is merged last, so its hook runs last and gets the
+ /// final say on a call a plugin hook already looked at.
+ #[test]
+ fn a_projects_hooks_are_merged_after_a_plugins() {
+ let root = unique_root("mergeorder");
+ write_plugin(
+ &root,
+ "auditor",
+ Some(r#"[{"event":"PreToolUse","command":"from-plugin"}]"#),
+ None,
+ );
+ write_agent_toml(
+ &root,
+ r#"
+[[hooks]]
+event = "PreToolUse"
+command = "from-project"
+"#,
+ );
+ let set = resolve_hooks(&root);
+ let commands: Vec<&str> = set
+ .matching(HookEvent::PreToolUse, Some("bash"))
+ .iter()
+ .map(|h| h.command.as_str())
+ .collect();
+ assert_eq!(commands, vec!["from-plugin", "from-project"]);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn a_project_with_no_config_at_all_resolves_to_no_hooks() {
+ let root = unique_root("empty");
+ assert!(resolve_hooks(&root).is_empty());
+ assert!(resolve_plugin_tools(&root).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A plugin's hooks are third-party commands that fire on every tool call,
+ /// so a project must be able to refuse them without also losing the
+ /// plugin's skills and commands.
+ #[test]
+ fn a_project_can_switch_off_plugin_hooks_without_uninstalling() {
+ let root = unique_root("pluginhooksoff");
+ write_plugin(
+ &root,
+ "auditor",
+ Some(r#"[{"event":"PreToolUse","command":"audit.sh"}]"#),
+ None,
+ );
+ write_agent_toml(
+ &root,
+ r#"
+[plugins]
+hooks = false
+
+[[hooks]]
+event = "PreToolUse"
+command = "mine"
+"#,
+ );
+ let set = resolve_hooks(&root);
+ // The project's own hook is untouched: only the plugin layer is off.
+ assert_eq!(set.len(), 1);
+ assert_eq!(set.all()[0].command, "mine");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The same switch for the other half of what a plugin can contribute.
+ #[test]
+ fn a_project_can_switch_off_plugin_tools_without_uninstalling() {
+ let root = unique_root("plugintoolsoff");
+ write_plugin(
+ &root,
+ "fmt",
+ None,
+ Some("name = \"fmt\"\n\n[[tools]]\nname = \"format\"\ncommand = \"cargo fmt\"\n"),
+ );
+ assert_eq!(resolve_plugin_tools(&root).len(), 1, "on by default");
+ write_agent_toml(&root, "[plugins]\ntools = false\n");
+ assert!(resolve_plugin_tools(&root).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// Absent config means on: a plugin that ships hooks is normally installed
+ /// for them, so the switch is an opt-out and not an opt-in.
+ #[test]
+ fn plugin_hooks_and_tools_default_to_on() {
+ let root = unique_root("plugindefault");
+ write_plugin(
+ &root,
+ "auditor",
+ Some(r#"[{"event":"PreToolUse","command":"audit.sh"}]"#),
+ Some("name = \"auditor\"\n\n[[tools]]\nname = \"t\"\ncommand = \"true\"\n"),
+ );
+ write_agent_toml(&root, "[plugins]\nmarketplace = \"https://example.com\"\n");
+ assert_eq!(resolve_hooks(&root).len(), 1);
+ assert_eq!(resolve_plugin_tools(&root).len(), 1);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The desktop's IPC command has no project for a chat thread, but the
+ /// user's own global layer still applies: it is about the user, not the
+ /// checkout.
+ #[test]
+ fn a_projectless_surface_still_resolves_the_global_layer() {
+ // Only the shape is asserted: the global file is the real `~/.jan`,
+ // which this test must not write to.
+ let set = resolve_hooks_for(None);
+ for hook in set.all() {
+ assert!(
+ hook.source.ends_with("config.toml"),
+ "a projectless resolve must contribute only the global file, got {:?}",
+ hook.source
+ );
+ }
+ }
+
+ #[test]
+ fn a_malformed_agent_toml_contributes_no_hooks_instead_of_failing() {
+ let root = unique_root("malformed");
+ write_agent_toml(&root, "this is not = = toml");
+ assert!(resolve_hooks(&root).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn a_plugin_can_declare_a_tool_in_its_manifest() {
+ let root = unique_root("plugintool");
+ write_plugin(
+ &root,
+ "fmt",
+ None,
+ Some(
+ r#"
+name = "fmt"
+
+[[tools]]
+name = "format"
+description = "Format the tree"
+command = "cargo fmt"
+"#,
+ ),
+ );
+ let set = resolve_plugin_tools(&root);
+ assert_eq!(set.len(), 1);
+ let tool = &set.all()[0];
+ assert_eq!(tool.qualified_name, "plugin__fmt__format");
+ assert_eq!(tool.plugin, "fmt");
+ assert_eq!(tool.command, "cargo fmt");
+ assert!(set.is_plugin_tool("plugin__fmt__format"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A manifest without a `[[tools]]` section is the common case and must
+ /// keep parsing exactly as it did before plugin tools existed.
+ #[test]
+ fn a_manifest_without_tools_declares_none() {
+ let root = unique_root("notools");
+ write_plugin(
+ &root,
+ "p",
+ None,
+ Some("name = \"p\"\nversion = \"1.0.0\"\n"),
+ );
+ assert!(resolve_plugin_tools(&root).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn staging_directories_from_an_interrupted_install_are_skipped() {
+ let root = unique_root("staging");
+ write_plugin(
+ &root,
+ ".installing-halfdone",
+ Some(r#"[{"event":"SessionStart","command":"nope"}]"#),
+ None,
+ );
+ assert!(resolve_hooks(&root).is_empty());
+ let _ = std::fs::remove_dir_all(&root);
+ }
+}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 71bea227b..9b23b746f 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -195,6 +195,15 @@ pub(crate) trait ToolInvoker: Send + Sync {
fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {
Vec::new()
}
+
+ /// Fire the run's `PreCompact` hooks, just before `message_count` messages
+ /// are summarized away.
+ ///
+ /// On the invoker rather than passed into `compact_conversation` because
+ /// the invoker is what holds the run's resolved hooks and its tool context;
+ /// the default does nothing, which is right for every invoker that has no
+ /// project and therefore no hook files to read.
+ async fn pre_compact(&self, _message_count: usize) {}
}
/// Emit [`StreamEvent::Monitors`] when the set differs from what was last
@@ -368,6 +377,19 @@ struct CompositeToolInvoker {
monitors_outlive_run: bool,
auto_approve: bool,
run_mode: crate::core::agent::plan::RunMode,
+ /// The run's resolved lifecycle hooks (`hooks_config::resolve_hooks`),
+ /// snapshotted once per run like every other config-derived field: a hook
+ /// edited mid-run must not change what a call in flight is judged by.
+ hooks: tauri_plugin_agent_tools::tools::hooks::HookSet,
+ /// Tools the installed plugins declare. Dispatched here rather than through
+ /// `execute_builtin`: they are not built-ins, and like MCP tools their
+ /// capability is unknowable, so they are prompted and hidden in Plan mode.
+ plugin_tools: tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet,
+ /// `context` answers and failure notices raised by hooks during this run,
+ /// drained into `<SYSTEM>` reminders alongside the monitor's. `Arc` because
+ /// the tool-event hooks fire inside the toolset and report through a sink
+ /// that outlives the call (see [`CompositeToolInvoker::hook_sink`]).
+ hook_notices_queue: std::sync::Arc<std::sync::Mutex<Vec<BackgroundNotice>>>,
}
/// Default for the sandboxed shell's network namespace, used when
@@ -639,6 +661,41 @@ impl CompositeToolInvoker {
.with_scratch_root(&self.scratch_root)
.with_env_passthrough(&self.env_passthrough)
.with_env_set(&self.env_set)
+ .with_hooks(
+ &self.hooks,
+ self.run_mode == crate::core::agent::plan::RunMode::Plan,
+ Some(self.hook_sink()),
+ )
+ }
+
+ /// Where the `PreToolUse`/`PostToolUse` hooks fired inside
+ /// [`tauri_plugin_agent_tools::tools::handlers::execute_builtin`] send their
+ /// context answers and failure notices: the same queue `fire_hooks` uses,
+ /// drained into `<SYSTEM>` reminders at the top of the next turn.
+ fn hook_sink(&self) -> tauri_plugin_agent_tools::tools::HookSink {
+ // The queue is shared rather than borrowed because the sink outlives
+ // the call that created it, the way an output sink does.
+ let queue = self.hook_notices_queue.clone();
+ std::sync::Arc::new(
+ move |report: tauri_plugin_agent_tools::tools::hooks::HookReport| {
+ let mut queued = Vec::new();
+ for context in report.context {
+ queued.push(BackgroundNotice {
+ headline: None,
+ text: context,
+ });
+ }
+ for notice in report.notices {
+ let message = notice.message();
+ log::warn!("agent: {message}");
+ queued.push(BackgroundNotice {
+ headline: Some(message.clone()),
+ text: message,
+ });
+ }
+ queue.lock().unwrap().extend(queued);
+ },
+ )
}
/// A tool context whose output streams to the run's event channel as
@@ -653,6 +710,52 @@ impl CompositeToolInvoker {
.with_output_sink(output_sink(&self.events, id))
}
+ /// Fire the hooks for `event` and fold their answers into the run: a
+ /// `context` answer and every failure notice become `<SYSTEM>` reminders
+ /// queued alongside the monitor's, and the deny (if any) is returned for
+ /// the caller to act on.
+ ///
+ /// Hooks see this run's plan mode, so a `PreToolUse` command is inert in
+ /// Plan for the same reason the write tools are withheld there.
+ async fn fire_hooks(
+ &self,
+ event: tauri_plugin_agent_tools::tools::hooks::HookEvent,
+ payload: tauri_plugin_agent_tools::tools::hooks::HookPayload,
+ ) -> Option<String> {
+ if self.hooks.is_empty() {
+ return None;
+ }
+ let outcome = tauri_plugin_agent_tools::tools::hooks::run_hooks(
+ &self.hooks,
+ event,
+ &payload,
+ &self.tool_context(),
+ self.run_mode == crate::core::agent::plan::RunMode::Plan,
+ )
+ .await;
+ let mut queued = Vec::new();
+ for context in outcome.context {
+ queued.push(BackgroundNotice {
+ // No headline: a hook's context is guidance for the model, not
+ // an event the user needs announced, unlike a monitor match.
+ headline: None,
+ text: context,
+ });
+ }
+ for notice in outcome.notices {
+ let message = notice.message();
+ log::warn!("agent: {message}");
+ queued.push(BackgroundNotice {
+ headline: Some(message.clone()),
+ text: message,
+ });
+ }
+ if !queued.is_empty() {
+ self.hook_notices_queue.lock().unwrap().extend(queued);
+ }
+ outcome.denied
+ }
+
/// 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 {
@@ -1082,6 +1185,18 @@ fn hard_deny_msg(name: &str, reason: DenyReason, project_root: &std::path::Path)
/// Rejection message for a mutation-capable tool call attempted in
/// `RunMode::Plan`. Authoritative: the tool never actually runs.
+/// A `PreToolUse` hook refused the call.
+///
+/// Deliberately the same `ERROR: tool '<name>' denied ...` shape every other
+/// refusal uses (see [`denied_by_policy_msg`] and the user-deny arm in
+/// `invoke`), so the model reads a hook denial as the ordinary denial it is
+/// and the TUI renders it in the same row -- there is no second refusal shape
+/// to teach either of them. The hook's reason is what distinguishes it, which
+/// is the part the user wrote to be read.
+fn hook_denied_msg(name: &str, reason: &str) -> String {
+ format!("ERROR: tool '{name}' denied: {reason}")
+}
+
fn plan_mode_read_only_msg(name: &str) -> String {
format!("ERROR: tool '{name}' unavailable in plan_mode_read_only (plan mode is read-only)")
}
@@ -1109,6 +1224,12 @@ impl ToolInvoker for CompositeToolInvoker {
text: u.text,
}),
);
+ // Hook output rides the same channel: a `context` answer has to reach
+ // the model as a reminder, and a hook that failed has to be visible
+ // rather than silently skipped.
+ out.extend(std::mem::take(
+ &mut *self.hook_notices_queue.lock().unwrap(),
+ ));
out
}
@@ -1117,12 +1238,24 @@ impl ToolInvoker for CompositeToolInvoker {
.as_ref()
.is_some_and(|ctx| ctx.bg.has_pending_work())
|| self.monitors_owed()
+ // A queued hook answer is owed to the model the same way a monitor
+ // match is: the turn that would end must deliver it first.
+ || !self.hook_notices_queue.lock().unwrap().is_empty()
}
fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {
self.monitors.snapshot()
}
+ async fn pre_compact(&self, message_count: usize) {
+ crate::core::agent::compaction::fire_pre_compact(
+ &self.hooks,
+ &self.tool_context(),
+ message_count,
+ )
+ .await;
+ }
+
async fn await_background(&self) {
// Each wait returns on a notice OR when its own side has nothing left,
// so an exhausted side must not be selected over: it would win
@@ -1156,6 +1289,9 @@ impl ToolInvoker for CompositeToolInvoker {
};
let mut out: Vec<ToolOutcome> = Vec::with_capacity(tool_calls.len());
let mut mcp_calls: Vec<serde_json::Value> = Vec::new();
+ // id -> (tool name, arguments) for the MCP calls that passed the gate,
+ // so their PostToolUse hooks can be fired once the batch returns.
+ let mut mcp_hook_inputs: HashMap<String, (String, serde_json::Value)> = HashMap::new();
// Auto-allowed read-only built-ins (no prompt, no filesystem mutation)
// are deferred and executed concurrently after the gating pass. Anything
// that prompts, writes, execs, or dispatches stays sequential so
@@ -1249,6 +1385,90 @@ impl ToolInvoker for CompositeToolInvoker {
out.push(ToolOutcome::plain(id, content));
continue;
}
+ // Plugin-declared tools are dispatched ahead of the MCP fallback:
+ // they are neither built-ins nor MCP, but their capability is just
+ // as opaque, so they get the MCP treatment -- prompted rather than
+ // auto-allowed, and withheld entirely in read-only Plan mode.
+ if self.plugin_tools.is_plugin_tool(name) {
+ let id = tc
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ if self.run_mode == crate::core::agent::plan::RunMode::Plan {
+ out.push(ToolOutcome::plain(id, plan_mode_read_only_msg(name)));
+ continue;
+ }
+ if self.permissions.is_denied(name) {
+ out.push(ToolOutcome::plain(
+ id,
+ denied_by_policy_msg(name, &self.project_root),
+ ));
+ continue;
+ }
+ let args: serde_json::Value = tc
+ .get("function")
+ .and_then(|f| f.get("arguments"))
+ .and_then(|v| v.as_str())
+ .and_then(|s| serde_json::from_str(s).ok())
+ .unwrap_or(serde_json::Value::Object(Default::default()));
+ let approved = self.auto_approve
+ || self.grants.lock().unwrap().covers_mcp(name)
+ || match self.prompt_mcp_permission(name).await {
+ PermissionDecision::AllowOnce => true,
+ PermissionDecision::AllowAlways => {
+ self.grants.lock().unwrap().grant_mcp(name);
+ true
+ }
+ PermissionDecision::Deny => false,
+ };
+ if !approved {
+ out.push(ToolOutcome::plain(
+ id,
+ format!("ERROR: tool '{name}' denied by user"),
+ ));
+ continue;
+ }
+ // `execute_builtin`'s hook bracket does not cover this path, so
+ // the tool events are fired here -- a plugin tool is still a
+ // tool call, and a PreToolUse policy that cannot see it would
+ // have a hole exactly where a third party's code runs.
+ let payload = tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ tool_name: Some(name.to_string()),
+ tool_input: Some(args.clone()),
+ ..Default::default()
+ };
+ if let Some(reason) = self
+ .fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PreToolUse,
+ payload.clone(),
+ )
+ .await
+ {
+ out.push(ToolOutcome::plain(id, hook_denied_msg(name, &reason)));
+ continue;
+ }
+ let tool = self
+ .plugin_tools
+ .get(name)
+ .expect("is_plugin_tool implies get");
+ let content = tauri_plugin_agent_tools::tools::plugin_tools::execute(
+ tool,
+ &args,
+ &self.streaming_tool_context(&id),
+ )
+ .await;
+ self.fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PostToolUse,
+ tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ tool_result: Some(content.clone()),
+ ..payload
+ },
+ )
+ .await;
+ out.push(ToolOutcome::plain(id, content));
+ continue;
+ }
if !is_builtin(name) {
let id = tc
.get("id")
@@ -1270,21 +1490,54 @@ impl ToolInvoker for CompositeToolInvoker {
));
continue;
}
- if self.auto_approve || self.grants.lock().unwrap().covers_mcp(name) {
- mcp_calls.push(tc.clone());
+ let args: serde_json::Value = tc
+ .get("function")
+ .and_then(|f| f.get("arguments"))
+ .and_then(|v| v.as_str())
+ .and_then(|s| serde_json::from_str(s).ok())
+ .unwrap_or(serde_json::Value::Object(Default::default()));
+ // An MCP tool is a tool call like any other, so it gets the same
+ // bracket the built-ins and plugin tools get: a PreToolUse
+ // policy that could not see `mcp__*` would have its hole exactly
+ // where a third party's server runs. Fired before the permission
+ // prompt (unlike the built-in path, whose bracket lives inside
+ // `execute_builtin`), so a hook deny does not first cost the
+ // user an answer.
+ if let Some(reason) = self
+ .fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PreToolUse,
+ tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ tool_name: Some(name.to_string()),
+ tool_input: Some(args.clone()),
+ ..Default::default()
+ },
+ )
+ .await
+ {
+ out.push(ToolOutcome::plain(id, hook_denied_msg(name, &reason)));
continue;
}
- match self.prompt_mcp_permission(name).await {
- PermissionDecision::AllowOnce => mcp_calls.push(tc.clone()),
- PermissionDecision::AllowAlways => {
- self.grants.lock().unwrap().grant_mcp(name);
- mcp_calls.push(tc.clone());
- }
- PermissionDecision::Deny => out.push(ToolOutcome::plain(
+ let approved = self.auto_approve
+ || self.grants.lock().unwrap().covers_mcp(name)
+ || match self.prompt_mcp_permission(name).await {
+ PermissionDecision::AllowOnce => true,
+ PermissionDecision::AllowAlways => {
+ self.grants.lock().unwrap().grant_mcp(name);
+ true
+ }
+ PermissionDecision::Deny => false,
+ };
+ if !approved {
+ out.push(ToolOutcome::plain(
id,
format!("ERROR: tool '{name}' denied by user"),
- )),
+ ));
+ continue;
}
+ // Kept alongside the call so PostToolUse can name the tool and
+ // carry its result: the batch `invoke` answers by id only.
+ mcp_hook_inputs.insert(id, (name.to_string(), args));
+ mcp_calls.push(tc.clone());
continue;
}
let id = tc
@@ -1346,12 +1599,19 @@ impl ToolInvoker for CompositeToolInvoker {
let allow_home_read = self.allow_home_read;
let sandbox = self.sandbox;
let scratch = self.scratch_root.clone();
+ // Hooks come along: a read is still a tool call, and a
+ // PreToolUse policy that stopped applying to whatever happened
+ // to be batched concurrently would be no policy at all.
+ let hooks = self.hooks.clone();
+ let planning = self.run_mode == crate::core::agent::plan::RunMode::Plan;
+ let hook_sink = self.hook_sink();
read_futures.push(async move {
let ctx = ToolContext::new(&root, &store, &enabled)
.with_network(allow_network)
.with_home_readonly(allow_home_read)
.with_sandbox(sandbox)
- .with_scratch_root(&scratch);
+ .with_scratch_root(&scratch)
+ .with_hooks(&hooks, planning, Some(hook_sink));
let (text, diff, images) = execute_builtin_with_diff(tool, &args, &ctx).await;
ToolOutcome {
id,
@@ -1461,7 +1721,23 @@ impl ToolInvoker for CompositeToolInvoker {
out.extend(futures::future::join_all(read_futures).await);
}
if !mcp_calls.is_empty() {
- out.extend(self.mcp.invoke(&mcp_calls).await?);
+ let results = self.mcp.invoke(&mcp_calls).await?;
+ for outcome in &results {
+ let Some((name, args)) = mcp_hook_inputs.get(&outcome.id) else {
+ continue;
+ };
+ self.fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::PostToolUse,
+ tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ tool_name: Some(name.clone()),
+ tool_input: Some(args.clone()),
+ tool_result: Some(outcome.content.clone()),
+ ..Default::default()
+ },
+ )
+ .await;
+ }
+ out.extend(results);
}
let order: HashMap<&str, usize> = tool_calls
.iter()
@@ -1712,6 +1988,24 @@ fn advertise_local_tools(
openai_tools.push(tauri_plugin_agent_tools::tools::monitor::monitor_tool_schema());
}
}
+ // Plugin-declared tools run a third party's command, so they are
+ // advertised on exactly the terms opaque MCP tools are: never in
+ // read-only Plan mode, and subject to the same deny list.
+ if !planning {
+ if let Some(root) = project_root {
+ for tool in crate::core::agent::hooks_config::resolve_plugin_tools(root).all() {
+ if permissions.is_denied(&tool.qualified_name) {
+ continue;
+ }
+ if let Some(allow) = allowed_names {
+ if !allow.contains(&tool.qualified_name) {
+ continue;
+ }
+ }
+ openai_tools.push(tool.schema());
+ }
+ }
+ }
}
// The `ask` tool needs no project (it's an interactive question, not
// filesystem access), so it's advertised independent of the project_root
@@ -2239,7 +2533,80 @@ async fn orchestrate_inner(
monitors_outlive_run: session_monitors.is_some(),
auto_approve: *auto_approve,
run_mode,
+ // Resolved once per run, like every other config-derived field: a
+ // hook file edited mid-run must not change what a call already in
+ // flight is judged by.
+ hooks: crate::core::agent::hooks_config::resolve_hooks(root),
+ plugin_tools: crate::core::agent::hooks_config::resolve_plugin_tools(root),
+ hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
+ };
+ // Entries dropped while loading the hook files are reported once here,
+ // before anything fires: a user whose matcher is a bad glob otherwise
+ // watches a hook never run and has nothing to tell them why.
+ {
+ let dropped: Vec<BackgroundNotice> = tools
+ .hooks
+ .load_notices()
+ .iter()
+ .map(|message| {
+ log::warn!("agent: {message}");
+ BackgroundNotice {
+ headline: Some(message.clone()),
+ text: message.clone(),
+ }
+ })
+ .collect();
+ if !dropped.is_empty() {
+ tools.hook_notices_queue.lock().unwrap().extend(dropped);
+ }
+ }
+ // Cancellation aborts this future at its next await point, so the
+ // SessionEnd call below is simply never reached -- a hole exactly for
+ // the "log every session" hooks SessionEnd exists for. The guard closes
+ // it: dropped without being disarmed, it fires the event from a detached
+ // task. Disarmed on the normal path, so the event still fires there
+ // inline and in order.
+ let mut session_end = SessionEndGuard {
+ hooks: tools.hooks.clone(),
+ project_root: root.clone(),
+ store_root: tools.store_root.clone(),
+ sandbox: tools.sandbox,
+ session_id: session_id.clone(),
+ armed: true,
};
+ // SessionStart before the first model call and SessionEnd after the
+ // last, so a hook brackets exactly the work the run did. A context
+ // answer from SessionStart is queued here and drained into the first
+ // turn's reminders, which is why it fires before `run_turn_cycle`.
+ tools
+ .fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::SessionStart,
+ tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ session_id: session_id.clone(),
+ message_count: Some(conversation_messages.len()),
+ ..Default::default()
+ },
+ )
+ .await;
+ // UserPromptSubmit fires here rather than in each surface's submit
+ // handler: the TUI, the headless run and the stream-json duplex all
+ // funnel through this one function, and a hook wired to three call
+ // sites would inevitably grow a fourth it was never added to. `deny` is
+ // not honored -- there is no tool call to stop -- but `context` is,
+ // which is what a prompt hook is for.
+ if let Some(prompt) = latest_user_text(&conversation_messages) {
+ tools
+ .fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::UserPromptSubmit,
+ tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ prompt: Some(prompt),
+ session_id: session_id.clone(),
+ message_count: Some(conversation_messages.len()),
+ ..Default::default()
+ },
+ )
+ .await;
+ }
let result = run_turn_cycle(
events,
json_body,
@@ -2263,6 +2630,21 @@ async fn orchestrate_inner(
if result.is_ok() {
bg.join_all().await;
}
+ // Fired on failure too: a SessionEnd hook that only ran on the happy
+ // path could not be used for the cleanup or audit it exists for. Its
+ // answers cannot reach the model (the run is over) and are logged by
+ // `fire_hooks` instead. Disarm first: this inline call is the ordered
+ // one, and the guard is only the cancellation fallback.
+ session_end.armed = false;
+ tools
+ .fire_hooks(
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::SessionEnd,
+ tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ session_id: session_id.clone(),
+ ..Default::default()
+ },
+ )
+ .await;
if index_memory {
if let Ok(completion) = &result {
if let Some(answer) = extract_choice_message(completion).and_then(|m| {
@@ -2366,6 +2748,65 @@ fn build_completion_request(
serde_json::Value::Object(completion_map)
}
+/// Fires `SessionEnd` if the run is cancelled before it reaches its own call.
+///
+/// A cancelled future is dropped, not unwound past an await, so the only way to
+/// run anything after it is a `Drop` impl. Hooks are async and `Drop` is not,
+/// hence the detached task; it owns everything it needs so nothing borrowed from
+/// the dying run outlives it. Best-effort by construction: on process exit the
+/// task may not get to run, which is the honest limit of the guarantee.
+struct SessionEndGuard {
+ hooks: tauri_plugin_agent_tools::tools::hooks::HookSet,
+ project_root: std::path::PathBuf,
+ store_root: std::path::PathBuf,
+ sandbox: bool,
+ session_id: Option<String>,
+ /// Cleared by the normal path, which fires the event itself and in order.
+ armed: bool,
+}
+
+impl Drop for SessionEndGuard {
+ fn drop(&mut self) {
+ if !self.armed || self.hooks.is_empty() {
+ return;
+ }
+ let hooks = std::mem::take(&mut self.hooks);
+ let project_root = std::mem::take(&mut self.project_root);
+ let store_root = std::mem::take(&mut self.store_root);
+ let sandbox = self.sandbox;
+ let session_id = self.session_id.take();
+ // `spawn` rather than `block_on`: this drop can run on the runtime's own
+ // worker, where blocking would deadlock it.
+ if let Ok(handle) = tokio::runtime::Handle::try_current() {
+ handle.spawn(async move {
+ let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(
+ &project_root,
+ &store_root,
+ &[],
+ )
+ .with_sandbox(sandbox)
+ .with_hooks(&hooks, false, None);
+ let outcome = tauri_plugin_agent_tools::tools::hooks::run_hooks(
+ &hooks,
+ tauri_plugin_agent_tools::tools::hooks::HookEvent::SessionEnd,
+ &tauri_plugin_agent_tools::tools::hooks::HookPayload {
+ session_id,
+ ..Default::default()
+ },
+ &ctx,
+ false,
+ )
+ .await;
+ // Logged, not queued: the run is gone, so there is no turn left
+ // to fold a context answer or a notice into.
+ for notice in outcome.notices {
+ log::warn!("agent: {}", notice.message());
+ }
+ });
+ }
+ }
+}
+
/// Manually compact `messages` for the given model, resolving the upstream from
/// `args` and reusing the same summarization path as the reactive loop. Used by
/// the TUI `/compact` command, which holds `OrchestrationArgs` + a model id but
@@ -2377,6 +2818,18 @@ pub(crate) async fn compact_history(
messages: &[serde_json::Value],
keep_recent: usize,
) -> Result<Vec<serde_json::Value>, String> {
+ // `/compact` discards conversation exactly as the in-loop overflow retry
+ // does, so it owes PreCompact the same warning. This path has no invoker to
+ // hang the hooks off (it holds args and a model id, nothing more), so they
+ // are resolved here.
+ if let Some(root) = args.project_root.as_deref() {
+ let hooks = crate::core::agent::hooks_config::resolve_hooks(root);
+ let store = tauri_plugin_agent_tools::workspace::project_store(root);
+ let ctx = tauri_plugin_agent_tools::tools::ToolContext::new(root, &store, &[])
+ .with_sandbox(effective_sandbox(root))
+ .with_hooks(&hooks, false, None);
+ crate::core::agent::compaction::fire_pre_compact(&hooks, &ctx, messages.len()).await;
+ }
let (upstream_url, api_keys) = resolve_upstream_for_model(
model_id,
args.provider_configs.clone(),
@@ -2672,6 +3125,7 @@ async fn run_turn_cycle(
if crate::core::agent::upstream::is_context_overflow_error(&e)
&& attempts < MAX_COMPACTION_ATTEMPTS =>
{
+ tools.pre_compact(conversation_messages.len()).await;
let compacted = crate::core::agent::compaction::compact_conversation(
&conversation_messages,
model_id,
@@ -2827,6 +3281,7 @@ async fn run_turn_cycle(
// input untouched when there is too little to drop, and publishing
// an unchanged history would spend a summarizer call for nothing.
if budget.exhausted() {
+ tools.pre_compact(conversation_messages.len()).await;
match crate::core::agent::compaction::compact_conversation(
&conversation_messages,
model_id,
@@ -5527,9 +5982,466 @@ mod tests {
monitors_outlive_run: false,
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
+ hooks: tauri_plugin_agent_tools::tools::hooks::HookSet::new(),
+ plugin_tools: tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet::new(),
+ hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
+ }
+ }
+
+ fn hooks_root(tag: &str) -> std::path::PathBuf {
+ let root = std::env::temp_dir().join(format!(
+ "jan_loop_hooks_{tag}_{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&root).expect("create root");
+ root
+ }
+
+ fn invoker_with_hooks(
+ root: std::path::PathBuf,
+ hooks: tauri_plugin_agent_tools::tools::hooks::HookSet,
+ plugin_tools: tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet,
+ run_mode: crate::core::agent::plan::RunMode,
+ ) -> CompositeToolInvoker {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let mut invoker = build_prompting_invoker(root, tx, PermissionRegistry::default());
+ // Unconfined and auto-approved so the assertions are about the hook and
+ // plugin-tool wiring, not about a sandbox backend or a prompt that has
+ // no one to answer it.
+ invoker.sandbox = false;
+ invoker.auto_approve = true;
+ invoker.hooks = hooks;
+ invoker.plugin_tools = plugin_tools;
+ invoker.run_mode = run_mode;
+ invoker
+ }
+
+ fn hooked_tool_call(name: &str, arguments: &str) -> serde_json::Value {
+ json!({
+ "id": "c1",
+ "type": "function",
+ "function": { "name": name, "arguments": arguments }
+ })
+ }
+
+ fn hook_set(
+ entries: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,
+ ) -> tauri_plugin_agent_tools::tools::hooks::HookSet {
+ let mut set = tauri_plugin_agent_tools::tools::hooks::HookSet::new();
+ set.extend_from(entries, std::path::Path::new("test"));
+ set
+ }
+
+ fn hook_entry(
+ event: &str,
+ matcher: Option<&str>,
+ command: &str,
+ ) -> tauri_plugin_agent_tools::tools::hooks::HookEntry {
+ tauri_plugin_agent_tools::tools::hooks::HookEntry {
+ event: event.to_string(),
+ matcher: matcher.map(str::to_string),
+ command: command.to_string(),
+ timeout_secs: None,
+ }
+ }
+
+ fn plugin_tool_set(
+ entries: Vec<tauri_plugin_agent_tools::tools::plugin_tools::PluginToolEntry>,
+ ) -> tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet {
+ let mut set = tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet::new();
+ set.extend_from("p", entries, std::path::Path::new("test"));
+ set
+ }
+
+ fn plugin_tool_entry(
+ name: &str,
+ command: &str,
+ ) -> tauri_plugin_agent_tools::tools::plugin_tools::PluginToolEntry {
+ tauri_plugin_agent_tools::tools::plugin_tools::PluginToolEntry {
+ name: name.to_string(),
+ description: "a plugin tool".to_string(),
+ parameters: None,
+ command: command.to_string(),
+ timeout_secs: None,
}
}
+ /// The acceptance requirement that a hook denial is indistinguishable from
+ /// a gate denial in the transcript: same `ERROR: tool '<name>' denied`
+ /// prefix, carried back as an ordinary tool result rather than a run error.
+ #[tokio::test]
+ async fn a_hook_denial_reaches_the_model_as_an_ordinary_denial() {
+ let root = hooks_root("deny");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry(
+ "PreToolUse",
+ Some("write"),
+ r#"echo '{"decision":"deny","reason":"writes are frozen"}'"#,
+ )]),
+ Default::default(),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ let out = invoker.invoke(&[write_call()]).await.unwrap();
+ assert_eq!(out.len(), 1);
+ assert!(
+ out[0].content.starts_with("ERROR: tool 'write' denied"),
+ "{}",
+ out[0].content
+ );
+ assert!(out[0].content.contains("writes are frozen"));
+ assert!(
+ !root.join("out.txt").exists(),
+ "the denied write must not have happened"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A `context` answer becomes a background notice, which is what
+ /// `run_turn_cycle` turns into a `<SYSTEM>` reminder via `reminder::attach`.
+ #[tokio::test]
+ async fn a_hook_context_answer_is_queued_as_a_background_notice() {
+ let root = hooks_root("context");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry(
+ "PostToolUse",
+ Some("write"),
+ r#"echo '{"context":"remember to update the changelog"}'"#,
+ )]),
+ Default::default(),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ assert!(!invoker.background_pending());
+ let out = invoker.invoke(&[write_call()]).await.unwrap();
+ assert!(!out[0].content.starts_with("ERROR"), "{}", out[0].content);
+ assert!(
+ invoker.background_pending(),
+ "the answer is owed to the model"
+ );
+ let notices = invoker.background_notices();
+ assert_eq!(notices.len(), 1);
+ assert_eq!(notices[0].text, "remember to update the changelog");
+ assert!(
+ notices[0].headline.is_none(),
+ "hook guidance is for the model, not an announcement"
+ );
+ assert!(
+ !invoker.background_pending(),
+ "draining must clear the queue"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A hook that fails is reported once and the tool call still succeeds:
+ /// a broken hook must never be able to wedge a run.
+ #[tokio::test]
+ async fn a_failing_hook_notices_but_does_not_stop_the_call() {
+ let root = hooks_root("failing");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry("PreToolUse", None, "exit 9")]),
+ Default::default(),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ let out = invoker.invoke(&[write_call()]).await.unwrap();
+ assert!(!out[0].content.starts_with("ERROR"), "{}", out[0].content);
+ assert!(
+ root.join("out.txt").exists(),
+ "the write must have happened"
+ );
+ let notices = invoker.background_notices();
+ assert_eq!(notices.len(), 1);
+ assert!(notices[0].text.contains("exited 9"), "{}", notices[0].text);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// Plan mode withholds write tools, so the hooks bracketing them have
+ /// nothing to bracket and must not run either.
+ #[tokio::test]
+ async fn tool_hooks_are_inert_in_plan_mode() {
+ let root = hooks_root("plan");
+ let marker = root.join("hook-ran");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry(
+ "PreToolUse",
+ None,
+ &format!("touch {}", marker.to_string_lossy()),
+ )]),
+ Default::default(),
+ crate::core::agent::plan::RunMode::Plan,
+ );
+ let out = invoker.invoke(&[write_call()]).await.unwrap();
+ assert!(
+ out[0].content.contains("plan_mode_read_only"),
+ "{}",
+ out[0].content
+ );
+ assert!(!marker.exists(), "a tool hook must not run in plan mode");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// Phase 2: a plugin-declared tool is dispatched, runs its command with the
+ /// call's arguments on stdin, and returns its stdout as the tool result.
+ #[tokio::test]
+ async fn a_plugin_declared_tool_is_dispatched_and_returns_its_output() {
+ let root = hooks_root("plugintool");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ Default::default(),
+ plugin_tool_set(vec![plugin_tool_entry("echo", "cat")]),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ let out = invoker
+ .invoke(&[hooked_tool_call("plugin__p__echo", r#"{"value":42}"#)])
+ .await
+ .unwrap();
+ assert_eq!(out.len(), 1);
+ let parsed: serde_json::Value = serde_json::from_str(&out[0].content).unwrap();
+ assert_eq!(parsed["value"], 42);
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A plugin tool's capability is as opaque as an MCP tool's, so Plan mode
+ /// hard-denies it the same way.
+ #[tokio::test]
+ async fn a_plugin_tool_is_withheld_in_plan_mode() {
+ let root = hooks_root("plugintoolplan");
+ let marker = root.join("tool-ran");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ Default::default(),
+ plugin_tool_set(vec![plugin_tool_entry(
+ "touch",
+ &format!("touch {}", marker.to_string_lossy()),
+ )]),
+ crate::core::agent::plan::RunMode::Plan,
+ );
+ let out = invoker
+ .invoke(&[hooked_tool_call("plugin__p__touch", "{}")])
+ .await
+ .unwrap();
+ assert!(
+ out[0].content.contains("plan_mode_read_only"),
+ "{}",
+ out[0].content
+ );
+ assert!(!marker.exists(), "a plugin tool must not run in plan mode");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The hooks cover plugin tools too: a third party's command is exactly
+ /// where a PreToolUse policy most needs to apply.
+ #[tokio::test]
+ async fn a_hook_can_deny_a_plugin_tool() {
+ let root = hooks_root("plugintooldeny");
+ let marker = root.join("tool-ran");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry(
+ "PreToolUse",
+ Some("plugin__*"),
+ r#"echo '{"decision":"deny","reason":"third-party tools are off"}'"#,
+ )]),
+ plugin_tool_set(vec![plugin_tool_entry(
+ "touch",
+ &format!("touch {}", marker.to_string_lossy()),
+ )]),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ let out = invoker
+ .invoke(&[hooked_tool_call("plugin__p__touch", "{}")])
+ .await
+ .unwrap();
+ assert!(
+ out[0]
+ .content
+ .starts_with("ERROR: tool 'plugin__p__touch' denied"),
+ "{}",
+ out[0].content
+ );
+ assert!(out[0].content.contains("third-party tools are off"));
+ assert!(!marker.exists(), "the denied plugin tool must not have run");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The bypass this closes: an MCP call went straight to `mcp.invoke_tool`,
+ /// so a deny hook stopped `bash` and `plugin__*` but never `mcp__*` -- a
+ /// hole exactly where a third party's server runs.
+ #[tokio::test]
+ async fn a_hook_can_deny_an_mcp_tool() {
+ let root = hooks_root("mcpdeny");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry(
+ "PreToolUse",
+ Some("mcp__*"),
+ r#"echo '{"decision":"deny","reason":"no mcp today"}'"#,
+ )]),
+ Default::default(),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ // The invoker's MCP registry is empty, so reaching the call at all
+ // would surface as a transport error rather than this deny message:
+ // the assertion distinguishes "stopped by the hook" from "failed".
+ let out = invoker
+ .invoke(&[hooked_tool_call("mcp__srv__doit", "{}")])
+ .await
+ .unwrap();
+ assert!(
+ out[0]
+ .content
+ .starts_with("ERROR: tool 'mcp__srv__doit' denied"),
+ "{}",
+ out[0].content
+ );
+ assert!(out[0].content.contains("no mcp today"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A hook that does not deny leaves the MCP call alone, and its input
+ /// reaches the hook: a PreToolUse audit hook is useless if it cannot see
+ /// what was asked for.
+ #[tokio::test]
+ async fn an_mcp_pretooluse_hook_sees_the_call_and_may_let_it_through() {
+ let root = hooks_root("mcpallow");
+ let seen = root.join("seen.json");
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![hook_entry(
+ "PreToolUse",
+ Some("mcp__*"),
+ &format!("cat > {}", seen.to_string_lossy()),
+ )]),
+ Default::default(),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ // The call goes on to the empty MCP registry and fails there, which is
+ // the point: the hook did not stop it.
+ let _ = invoker
+ .invoke(&[hooked_tool_call(
+ "mcp__srv__doit",
+ r#"{"path":"a.rs"}"#,
+ )])
+ .await;
+ let written: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(&seen).expect("hook ran")).unwrap();
+ assert_eq!(written["event"], "PreToolUse");
+ assert_eq!(written["tool_name"], "mcp__srv__doit");
+ assert_eq!(written["tool_input"]["path"], "a.rs");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// A deny-listed plugin tool is refused by the same policy path an MCP
+ /// tool's deny takes.
+ #[tokio::test]
+ async fn a_denied_plugin_tool_is_refused_by_policy() {
+ let root = hooks_root("plugintoolpolicy");
+ let mut invoker = invoker_with_hooks(
+ root.clone(),
+ Default::default(),
+ plugin_tool_set(vec![plugin_tool_entry("echo", "cat")]),
+ crate::core::agent::plan::RunMode::Normal,
+ );
+ invoker.permissions = ToolPermissions::new(
+ PermissionDefault::ReadOnly,
+ &[],
+ &["plugin__p__echo".to_string()],
+ &[],
+ );
+ let out = invoker
+ .invoke(&[hooked_tool_call("plugin__p__echo", "{}")])
+ .await
+ .unwrap();
+ assert!(
+ out[0].content.contains("denied by project policy"),
+ "{}",
+ out[0].content
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// The three session-lifecycle events go through `fire_hooks` rather than
+ /// the toolset's `execute_builtin` bracket, so they are pinned here: each
+ /// fires, each receives its payload, and each is still live in Plan mode
+ /// (unlike the tool events above).
+ #[tokio::test]
+ async fn session_and_prompt_hooks_fire_with_their_payloads() {
+ let root = hooks_root("lifecycle");
+ let seen = root.join("seen");
+ std::fs::create_dir_all(&seen).unwrap();
+ let invoker = invoker_with_hooks(
+ root.clone(),
+ hook_set(vec![
+ hook_entry(
+ "SessionStart",
+ None,
+ &format!("cat > {}/start.json", seen.to_string_lossy()),
+ ),
+ hook_entry(
+ "UserPromptSubmit",
+ None,
+ &format!("cat > {}/prompt.json", seen.to_string_lossy()),
+ ),
+ hook_entry(
+ "SessionEnd",
+ None,
+ &format!("cat > {}/end.json", seen.to_string_lossy()),
+ ),
+ ]),
+ Default::default(),
+ // Plan mode on purpose: a lifecycle hook is not a tool call, so it
+ // must still fire where the tool hooks go inert.
+ crate::core::agent::plan::RunMode::Plan,
+ );
+ use tauri_plugin_agent_tools::tools::hooks::{HookEvent, HookPayload};
+ invoker
+ .fire_hooks(
+ HookEvent::SessionStart,
+ HookPayload {
+ session_id: Some("s1".to_string()),
+ message_count: Some(3),
+ ..Default::default()
+ },
+ )
+ .await;
+ invoker
+ .fire_hooks(
+ HookEvent::UserPromptSubmit,
+ HookPayload {
+ prompt: Some("ship it".to_string()),
+ ..Default::default()
+ },
+ )
+ .await;
+ invoker
+ .fire_hooks(
+ HookEvent::SessionEnd,
+ HookPayload {
+ session_id: Some("s1".to_string()),
+ ..Default::default()
+ },
+ )
+ .await;
+
+ let read = |name: &str| -> serde_json::Value {
+ serde_json::from_str(&std::fs::read_to_string(seen.join(name)).unwrap()).unwrap()
+ };
+ let start = read("start.json");
+ assert_eq!(start["event"], "SessionStart");
+ assert_eq!(start["session_id"], "s1");
+ assert_eq!(start["message_count"], 3);
+ let prompt = read("prompt.json");
+ assert_eq!(prompt["event"], "UserPromptSubmit");
+ assert_eq!(prompt["prompt"], "ship it");
+ assert_eq!(read("end.json")["event"], "SessionEnd");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
/// 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.
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 500fcaa1e..6f44c1cad 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -14,10 +14,16 @@ pub mod context;
pub mod events;
pub mod genai_bridge;
pub mod git;
-#[cfg(feature = "cli")]
+// Not cli-gated: `~/.jan/config.toml` is the user's own layer, and its
+// `[[hooks]]` have to mean the same thing in the desktop app and the API
+// server as they do in the CLI. The rest of the module (provider records, the
+// TUI's settings writers) has no consumer outside the CLI, hence the allow
+// rather than a second gate per item.
+#[cfg_attr(not(feature = "cli"), allow(dead_code))]
pub mod global_config;
#[cfg(feature = "cli")]
pub mod goal;
+pub mod hooks_config;
pub mod interaction;
pub mod r#loop;
pub mod memory;
diff --git a/src-tauri/src/core/agent/plugins.rs b/src-tauri/src/core/agent/plugins.rs
index 68f8be6ae..87996df34 100644
--- a/src-tauri/src/core/agent/plugins.rs
+++ b/src-tauri/src/core/agent/plugins.rs
@@ -11,7 +11,14 @@
//! the same layout as project skills
//! - `SKILL.md` at the plugin root — a repo that is itself one skill
//! - `plugin.toml` — optional metadata: `name`, `description`, `version`,
-//! `repo` (the canonical source URL, recorded at install for provenance)
+//! `repo` (the canonical source URL, recorded at install for provenance),
+//! plus optional `[[tools]]` entries the plugin contributes
+//! - `hooks/hooks.json` — optional lifecycle hooks (see
+//! `tauri_plugin_agent_tools::tools::hooks`)
+//!
+//! Installing still executes nothing: a declared tool or hook is a command
+//! recorded on disk, run only when the model calls it or its event fires, and
+//! then under the same confinement `bash` gets.
//!
//! `[plugins] marketplace` in `agent.toml` points at a JSON index of community
//! plugins: `[{ "name", "description", "repo", "ref"? }]`. `install <name>`
@@ -100,6 +107,13 @@ pub struct InstalledPlugin {
pub commands: usize,
/// Number of agent definitions (`agents/**/*.md`).
pub agents: usize,
+ /// Number of tools the plugin declares in `[[tools]]` of its `plugin.toml`.
+ /// Unlike the three counts above these are not markdown: they are commands
+ /// the model can call, which is why the count is worth reporting separately
+ /// rather than folded into the others.
+ pub tools: usize,
+ /// Number of lifecycle hooks the plugin ships in `hooks/hooks.json`.
+ pub hooks: usize,
}
/// A plugin available on the configured marketplace: JSON index entry.
@@ -202,6 +216,10 @@ fn installed_entries(root: &Path) -> Vec<(String, InstalledPlugin)> {
skills: plugin_skills,
commands: plugin_commands,
agents: plugin_agents,
+ tools: crate::core::agent::hooks_config::plugin_tool_entries(&path).len(),
+ hooks: tauri_plugin_agent_tools::tools::hooks::plugin_hook_entries(&path)
+ .0
+ .len(),
},
));
}
@@ -713,6 +731,10 @@ fn install_payload_dir(
.filter(|e| e.plugin == stem)
.count();
let agents_count = crate::core::agent::subagent::count_plugin_agents(root, &stem);
+ let tools_count = crate::core::agent::hooks_config::plugin_tool_entries(&target).len();
+ let hooks_count = tauri_plugin_agent_tools::tools::hooks::plugin_hook_entries(&target)
+ .0
+ .len();
Ok(PayloadOutcome::Installed(InstalledPlugin {
name: stem,
description: manifest.description.unwrap_or_default(),
@@ -721,6 +743,8 @@ fn install_payload_dir(
skills: skills_count,
commands: commands_count,
agents: agents_count,
+ tools: tools_count,
+ hooks: hooks_count,
}))
}
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index d14d37fb9..6df61cf4d 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -26,6 +26,11 @@ pub(crate) struct AgentToml {
pub skills: SkillsSection,
#[serde(default)]
pub plugins: PluginsSection,
+ /// `[[hooks]]` -- lifecycle commands this project runs around tool calls,
+ /// prompts, sessions and compactions. An array of tables rather than a
+ /// `[hooks]` map because several hooks may share one event.
+ #[serde(default)]
+ pub hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,
}
/// `[plugins]` — plugin installs and marketplace. Installed plugins live in
@@ -36,6 +41,17 @@ pub(crate) struct PluginsSection {
/// Unset disables name-based installs; direct git URLs still work.
#[serde(default)]
pub marketplace: Option<String>,
+ /// Whether an installed plugin's `hooks/hooks.json` is honored. On by
+ /// default -- a plugin that ships hooks is usually installed *for* them --
+ /// but a plugin's hooks are third-party commands that fire on every tool
+ /// call, so `hooks = false` must be able to switch them off without
+ /// uninstalling the plugin and losing its skills and commands.
+ #[serde(default)]
+ pub hooks: Option<bool>,
+ /// Whether an installed plugin's `[[tools]]` are advertised to the model.
+ /// Same default and same rationale as [`Self::hooks`].
+ #[serde(default)]
+ pub tools: Option<bool>,
}
/// `[provider]` — project-local override of a single provider's config,
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 17f4e6052..93499f48d 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -787,6 +787,35 @@ pub fn cli_agent_status(
.collect();
providers.sort_by(|a, b| a["provider"].as_str().cmp(&b["provider"].as_str()));
+ let hooks: Vec<serde_json::Value> =
+ crate::core::agent::hooks_config::resolve_hooks(&project_root)
+ .all()
+ .iter()
+ .map(|hook| {
+ serde_json::json!({
+ "event": hook.event.as_str(),
+ "matcher": hook.matcher,
+ "command": hook.command,
+ "timeout_secs": hook.timeout_secs,
+ "source": hook.source.to_string_lossy(),
+ })
+ })
+ .collect();
+ let plugin_tools: Vec<serde_json::Value> =
+ crate::core::agent::hooks_config::resolve_plugin_tools(&project_root)
+ .all()
+ .iter()
+ .map(|tool| {
+ serde_json::json!({
+ "name": tool.qualified_name,
+ "plugin": tool.plugin,
+ "description": tool.description,
+ "command": tool.command,
+ "source": tool.source.to_string_lossy(),
+ })
+ })
+ .collect();
+
Ok(serde_json::json!({
"project": project_root.to_string_lossy(),
"data_folder": resolve_jan_data_folder().to_string_lossy(),
@@ -810,6 +839,11 @@ pub fn cli_agent_status(
"enabled": crate::core::agent::r#loop::effective_sandbox(&project_root),
"backend": tauri_plugin_agent_tools::tools::jail::backend().as_str(),
},
+ // The resolved hook set in merge order, each with the file it came
+ // from: a hook that surprises the user is worth nothing to debug
+ // unless they can tell which of the three layers installed it.
+ "hooks": hooks,
+ "plugin_tools": plugin_tools,
"providers": providers,
}))
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 731451c6e..64fb7c11a 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -8709,9 +8709,32 @@ fn finish_plugin_install(
}
for p in plugins {
app.note(&format!(
- "installed plugin '{}' ({} skills)",
- p.name, p.skills
+ "installed plugin '{}' ({} skills, {} commands, {} agents, {} tools, {} hooks)",
+ p.name, p.skills, p.commands, p.agents, p.tools, p.hooks
));
+ // Named, not just counted: a hook runs a third party's command
+ // on every matching tool call from here on, so the user is told
+ // exactly what was installed and how to switch it off.
+ if p.hooks > 0 || p.tools > 0 {
+ let dir =
+ crate::core::agent::skills::plugins_dir(&app.project_root).join(&p.name);
+ for hook in
+ tauri_plugin_agent_tools::tools::hooks::plugin_hook_entries(&dir).0
+ {
+ app.note(&format!(
+ " hook {} ({}): {}",
+ hook.event,
+ hook.matcher.as_deref().unwrap_or("*"),
+ hook.command
+ ));
+ }
+ for tool in crate::core::agent::hooks_config::plugin_tool_entries(&dir) {
+ app.note(&format!(" tool {}: {}", tool.name, tool.command));
+ }
+ app.note(
+ " disable with [plugins] hooks = false / tools = false in agent.toml",
+ );
+ }
}
}
Ok(GitInstall::Collection(candidates)) => {
@@ -13504,6 +13527,23 @@ async fn plugin_command(app: &mut App, arg: &str) {
if p.agents == 1 { "" } else { "s" }
));
}
+ // Tools and hooks are listed even though the three counts above are
+ // markdown: these are commands a third party gets to run on this
+ // machine, so "what did I just install" has to answer for them.
+ if p.tools > 0 {
+ bits.push(format!(
+ "{} tool{}",
+ p.tools,
+ if p.tools == 1 { "" } else { "s" }
+ ));
+ }
+ if p.hooks > 0 {
+ bits.push(format!(
+ "{} hook{}",
+ p.hooks,
+ if p.hooks == 1 { "" } else { "s" }
+ ));
+ }
if bits.is_empty() {
bits.push("no payload".into());
}
@@ -35242,6 +35282,51 @@ mod tests {
let _ = std::fs::remove_dir_all(&repo);
}
+ /// Installing a plugin that ships hooks and tools means a third party's
+ /// commands run on this machine from then on, so the install note names
+ /// each one and says how to switch them off. A count alone would let the
+ /// most consequential thing a plugin can carry arrive unannounced.
+ #[tokio::test]
+ async fn installing_a_plugin_lists_the_hooks_and_tools_it_brings() {
+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");
+ let dir = crate::core::agent::skills::plugins_dir(&app.project_root).join("auditor");
+ std::fs::create_dir_all(dir.join("hooks")).unwrap();
+ std::fs::write(
+ dir.join("hooks").join("hooks.json"),
+ r#"[{"event":"PreToolUse","matcher":"bash","command":"./audit.sh"}]"#,
+ )
+ .unwrap();
+ std::fs::write(
+ dir.join("plugin.toml"),
+ "name = \"auditor\"\n\n[[tools]]\nname = \"scan\"\ncommand = \"./scan.sh\"\n",
+ )
+ .unwrap();
+
+ finish_plugin_install(
+ &mut app,
+ None,
+ Ok(crate::core::agent::plugins::GitInstall::Installed(vec![
+ crate::core::agent::plugins::InstalledPlugin {
+ name: "auditor".to_string(),
+ description: String::new(),
+ version: "1.0.0".to_string(),
+ repo: String::new(),
+ skills: 0,
+ commands: 0,
+ agents: 0,
+ tools: 1,
+ hooks: 1,
+ },
+ ])),
+ );
+ let text = transcript_text(&app);
+ assert!(text.contains("1 tools, 1 hooks"), "{text}");
+ assert!(text.contains("hook PreToolUse (bash): ./audit.sh"), "{text}");
+ assert!(text.contains("tool scan: ./scan.sh"), "{text}");
+ assert!(text.contains("[plugins] hooks = false"), "{text}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
/// Drive `PickerKind::PluginSelect` end to end: open it via a collection
/// listing, toggle a row with Space (an already-installed row is a no-op),
/// cancel clears the stashed source URL, and a fresh open + Enter hands
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 6e8494fe7..49c5ee8a2 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -257,6 +257,15 @@ async fn handle_graceful_exit<R: tauri::Runtime>(
tauri::mobile_entry_point
)]
pub fn run() {
+ // Installed before any plugin: the toolset crate owns no config format, so
+ // the `execute_tool` IPC command can only reach a user's `[[hooks]]`
+ // through a resolver the app hands it. Without this the desktop is the one
+ // surface where a configured hook silently never fires, since the webview
+ // drives its own tool loop and never builds the CLI's invoker.
+ tauri_plugin_agent_tools::tools::hooks::set_resolver(std::sync::Arc::new(|project| {
+ crate::core::agent::hooks_config::resolve_hooks_for(project)
+ }));
+
let builder = tauri::Builder::default();
// Shadowed rather than mutated: under `e2e` the plugin below is the only
// thing that touched `builder`, and a `mut` binding would then be unused --