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): monitor tool watches a file and pings the agent per condition match

Akarshan Biswasbbf883cb2b5f
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
index c6e37055a..26a6920ed 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/build.rs
@@ -21,6 +21,10 @@ const COMMANDS: &[&str] = &[
"subagent_result_fill",
"execute_tool",
"execute_tool_streaming",
+ "start_monitor",
+ "stop_monitor",
+ "list_monitors",
+ "stop_session_monitors",
];
fn main() {
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
index 58a7c806a..fa77b7aa6 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/index.ts
@@ -1,6 +1,7 @@
import { invoke, Channel } from '@tauri-apps/api/core'
import {
MemoryCatalogEntry,
+ MonitorUpdate,
SkillMeta,
ToolOutputChunk,
ToolResult,
@@ -10,6 +11,7 @@ import {
export {
MemoryCatalogEntry,
+ MonitorUpdate,
SkillMeta,
ToolOutputChunk,
ToolResult,
@@ -371,3 +373,57 @@ export async function executeToolStreaming(
callId: options?.callId,
})
}
+
+/**
+ * Start a file monitor for a session: condition scripts are evaluated whenever
+ * the watched file changes, and every match is delivered to `onUpdate` (a
+ * callback here; the IPC channel it feeds is built in this layer). Resolves
+ * with the model-facing result string (the monitor id and the ground rules).
+ * Rejects when the args are invalid, the path escapes what the session may
+ * read, or no enforcing OS sandbox is available to run the scripts under.
+ */
+export async function startMonitor(
+ dataFolder: string,
+ threadId: string,
+ args: Record<string, unknown>,
+ onUpdate: (update: MonitorUpdate) => void,
+ options?: {
+ allowNetwork?: boolean
+ readOnlyProject?: string
+ scope?: WorkspaceScope
+ }
+): Promise<string> {
+ const channel = new Channel<MonitorUpdate>()
+ channel.onmessage = onUpdate
+ return await invoke('plugin:agent-tools|start_monitor', {
+ dataFolder,
+ threadId,
+ args,
+ onUpdate: channel,
+ allowNetwork: options?.allowNetwork,
+ readOnlyProject: options?.readOnlyProject,
+ scope: options?.scope,
+ })
+}
+
+/** Stop one monitor. The result string is model-facing (`ERROR: ...` for an
+ * unknown id), matching the `monitor` tool contract. */
+export async function stopMonitor(
+ threadId: string,
+ monitorId: string
+): Promise<string> {
+ return await invoke('plugin:agent-tools|stop_monitor', {
+ threadId,
+ monitorId,
+ })
+}
+
+/** One line per active monitor, for `monitor {op:"list"}`. */
+export async function listMonitors(threadId: string): Promise<string> {
+ return await invoke('plugin:agent-tools|list_monitors', { threadId })
+}
+
+/** Abort every monitor a session still has. Called at run end. */
+export async function stopSessionMonitors(threadId: string): Promise<void> {
+ await invoke('plugin:agent-tools|stop_session_monitors', { threadId })
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
index 8269c2b34..e5bd3a6e7 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts
@@ -47,3 +47,15 @@ export type ToolOutputChunk = {
callId: string | null
text: string
}
+
+/**
+ * One monitor notice, in the two registers a background ping needs: `headline`
+ * for the transcript row, `text` for the `<SYSTEM>` reminder the model gets.
+ * `done` marks the update that also ends the monitor (all met, or timeout).
+ */
+export type MonitorUpdate = {
+ monitorId: string
+ headline: string
+ text: string
+ done: boolean
+}
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
index d886252b8..6439accf1 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/default.toml
@@ -23,4 +23,8 @@ permissions = [
"allow-subagent-result-fill",
"allow-execute-tool",
"allow-execute-tool-streaming",
+ "allow-start-monitor",
+ "allow-stop-monitor",
+ "allow-list-monitors",
+ "allow-stop-session-monitors",
]
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
index 6b2aaa0b8..21cbfd664 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/permissions/schemas/schema.json
@@ -318,6 +318,18 @@
"const": "deny-execute-tool-streaming",
"markdownDescription": "Denies the execute_tool_streaming command without any pre-configured scope."
},
+ {
+ "description": "Enables the list_monitors command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-list-monitors",
+ "markdownDescription": "Enables the list_monitors command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the list_monitors command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-list-monitors",
+ "markdownDescription": "Denies the list_monitors command without any pre-configured scope."
+ },
{
"description": "Enables the memory_catalog command without any pre-configured scope.",
"type": "string",
@@ -474,6 +486,42 @@
"const": "deny-skill-write",
"markdownDescription": "Denies the skill_write command without any pre-configured scope."
},
+ {
+ "description": "Enables the start_monitor command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-start-monitor",
+ "markdownDescription": "Enables the start_monitor command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the start_monitor command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-start-monitor",
+ "markdownDescription": "Denies the start_monitor command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the stop_monitor command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-stop-monitor",
+ "markdownDescription": "Enables the stop_monitor command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the stop_monitor command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-stop-monitor",
+ "markdownDescription": "Denies the stop_monitor command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the stop_session_monitors command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-stop-session-monitors",
+ "markdownDescription": "Enables the stop_session_monitors command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the stop_session_monitors command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-stop-session-monitors",
+ "markdownDescription": "Denies the stop_session_monitors command without any pre-configured scope."
+ },
{
"description": "Enables the subagent_result_fill command without any pre-configured scope.",
"type": "string",
@@ -559,10 +607,10 @@
"markdownDescription": "Denies the workspace_path command without any pre-configured scope."
},
{
- "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`",
+ "description": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`",
"type": "string",
"const": "default",
- "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`"
+ "markdownDescription": "Default permissions for the agent tools plugin: skill/memory management plus built-in tool execution\n#### This default permission set includes:\n\n- `allow-workspace-path`\n- `allow-thread-workspace-path`\n- `allow-thread-workspace-delete`\n- `allow-thread-workspace-sweep`\n- `allow-session-workspace-path`\n- `allow-session-workspace-delete`\n- `allow-session-workspace-sweep`\n- `allow-skill-list`\n- `allow-skill-read`\n- `allow-skill-write`\n- `allow-skill-delete`\n- `allow-memory-list`\n- `allow-memory-read`\n- `allow-memory-write`\n- `allow-memory-catalog`\n- `allow-memory-delete`\n- `allow-tool-schemas`\n- `allow-sandbox-status`\n- `allow-subagent-result-reserve`\n- `allow-subagent-result-fill`\n- `allow-execute-tool`\n- `allow-execute-tool-streaming`\n- `allow-start-monitor`\n- `allow-stop-monitor`\n- `allow-list-monitors`\n- `allow-stop-session-monitors`"
}
]
}
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 a2fc0d6a8..ce6059228 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs
@@ -426,6 +426,138 @@ pub async fn subagent_result_fill(
Ok(())
}
+/// Live monitors per Cowork session, each with the IPC channel its updates are
+/// forwarded over. Process-wide like `bash`'s background jobs: the Cowork loop
+/// runs in the frontend, so nothing host-side scopes a run. The channel slot is
+/// swappable because a session outlives any one run -- each `start_monitor`
+/// installs the current run's channel, and updates always go to the latest.
+struct SessionMonitors {
+ set: std::sync::Arc<crate::tools::monitor::MonitorSet>,
+ channel: MonitorChannelSlot,
+}
+
+type MonitorChannelSlot = std::sync::Arc<
+ std::sync::Mutex<Option<tauri::ipc::Channel<crate::tools::monitor::MonitorUpdate>>>,
+>;
+
+fn session_monitors(
+) -> &'static std::sync::Mutex<std::collections::HashMap<String, SessionMonitors>> {
+ static SETS: std::sync::OnceLock<
+ std::sync::Mutex<std::collections::HashMap<String, SessionMonitors>>,
+ > = std::sync::OnceLock::new();
+ SETS.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
+}
+
+/// Start a file monitor for a Cowork session; updates stream over `on_update`.
+///
+/// Returns the model-facing result string from `MonitorSet::start`. Like
+/// `bash` on this surface, condition scripts run only under an enforcing OS
+/// sandbox -- there is no one to prompt, so unconfined execution is refused
+/// rather than allowed.
+#[tauri::command]
+#[allow(clippy::too_many_arguments)]
+pub async fn start_monitor(
+ data_folder: String,
+ thread_id: String,
+ args: serde_json::Value,
+ allow_network: Option<bool>,
+ read_only_project: Option<String>,
+ scope: Option<WorkspaceScope>,
+ on_update: tauri::ipc::Channel<crate::tools::monitor::MonitorUpdate>,
+) -> Result<String, AgentToolsError> {
+ use crate::tools::monitor;
+ if !jail::backend().enforces() {
+ return Err(AgentToolsError::from(
+ "monitor is unavailable because no OS sandbox could be established on this system"
+ .to_string(),
+ ));
+ }
+ let spec = monitor::parse_start_args(&args).map_err(AgentToolsError::from)?;
+ let root = scope
+ .unwrap_or_default()
+ .ensure(Path::new(&data_folder), &thread_id)
+ .await?;
+ let scratch = workspace::ensure_scratch_dir(&thread_id).await?;
+ let read_roots: Vec<PathBuf> = match read_only_project.as_deref() {
+ Some(path) => vec![workspace::validate_read_root(
+ Path::new(path),
+ &root,
+ Some(Path::new(&data_folder)),
+ )?],
+ None => Vec::new(),
+ };
+ let ctx = monitor::MonitorCtx {
+ project_root: root,
+ scratch_root: Some(scratch),
+ mask_root: Some(PathBuf::from(&data_folder)),
+ read_roots,
+ allow_network: allow_network.unwrap_or(false),
+ home_readonly: false,
+ sandbox: true,
+ };
+ let set = {
+ let mut sets = session_monitors().lock().unwrap();
+ let entry = sets.entry(thread_id).or_insert_with(|| {
+ let slot: MonitorChannelSlot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let subscriber_slot = slot.clone();
+ SessionMonitors {
+ set: std::sync::Arc::new(monitor::MonitorSet::subscribed(std::sync::Arc::new(
+ move |update| {
+ if let Some(channel) = subscriber_slot.lock().unwrap().as_ref() {
+ let _ = channel.send(update);
+ }
+ },
+ ))),
+ channel: slot,
+ }
+ });
+ *entry.channel.lock().unwrap() = Some(on_update);
+ entry.set.clone()
+ };
+ set.start(spec, ctx).map_err(AgentToolsError::from)
+}
+
+/// Stop one monitor. The result string is model-facing, so an unknown id comes
+/// back as an `ERROR:` result rather than a command failure.
+#[tauri::command]
+pub async fn stop_monitor(
+ thread_id: String,
+ monitor_id: String,
+) -> Result<String, AgentToolsError> {
+ let set = session_monitors()
+ .lock()
+ .unwrap()
+ .get(&thread_id)
+ .map(|entry| entry.set.clone());
+ Ok(match set {
+ Some(set) => set.stop(&monitor_id),
+ None => format!("ERROR: unknown or already-stopped monitor '{monitor_id}'"),
+ })
+}
+
+#[tauri::command]
+pub async fn list_monitors(thread_id: String) -> Result<String, AgentToolsError> {
+ let set = session_monitors()
+ .lock()
+ .unwrap()
+ .get(&thread_id)
+ .map(|entry| entry.set.clone());
+ Ok(match set {
+ Some(set) => set.list(),
+ None => "No active monitors.".to_string(),
+ })
+}
+
+/// Abort every monitor a session still has. Called at run end (and session
+/// teardown), the Cowork counterpart of the run-scoped drop on the CLI.
+#[tauri::command]
+pub async fn stop_session_monitors(thread_id: String) -> Result<(), AgentToolsError> {
+ if let Some(entry) = session_monitors().lock().unwrap().remove(&thread_id) {
+ entry.set.stop_all();
+ }
+ Ok(())
+}
+
/// Execute one built-in tool.
///
/// The gate decides, not the caller. `write` and `edit` resolve to `Prompt` and
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
index 98d2bdeb9..49fe8a47e 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/lib.rs
@@ -54,7 +54,11 @@ pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
commands::subagent_result_reserve,
commands::subagent_result_fill,
commands::execute_tool,
- commands::execute_tool_streaming
+ commands::execute_tool_streaming,
+ commands::start_monitor,
+ commands::stop_monitor,
+ commands::list_monitors,
+ commands::stop_session_monitors
])
.build()
}
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 eaa420239..8c37d6205 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
@@ -733,25 +733,21 @@ async fn edit(
}
}
-async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
- let Some(command) = arg_str(args, "command").filter(|command| !command.trim().is_empty())
- else {
- if let Some(job_id) = arg_str(args, "job_id").filter(|job_id| !job_id.trim().is_empty()) {
- return await_bash_job(job_id).await;
- }
- return "ERROR: missing required argument 'command' (or 'job_id' to poll a backgrounded job)"
- .to_string();
- };
- let timeout_secs = arg_u64(args, "timeout").unwrap_or(DEFAULT_BASH_TIMEOUT_SECS);
-
+/// The shell a confined command launches with: the (possibly jail-wrapped)
+/// shell config, the path the sandbox exposes as its temp dir, and the policy
+/// itself (which `denial_hint` reads even when the shell runs unconfined).
+///
+/// With the sandbox off the shell is spawned bare, the way the user's own
+/// terminal would run it: no wrapper, no policy mounts, the real `$HOME` and
+/// `/tmp`. Only a surface that opted in gets that (the CLI's
+/// `--sandbox`/`sandbox` setting); the desktop never does, so an exec there is
+/// still confined or withheld. Shared by `bash` and the `monitor` condition
+/// scripts so a monitored evaluation runs under exactly the policy a `bash`
+/// call would.
+pub(crate) fn confined_shell(
+ ctx: &ToolContext<'_>,
+) -> Result<(proc::ShellConfig, Option<PathBuf>, jail::Policy), String> {
let root = ctx.project_root;
- if !root.is_dir() {
- return format!(
- "ERROR: working directory does not exist: {}",
- root.display()
- );
- }
-
let mut policy =
jail::Policy::new(root, ctx.allow_network).with_home_readonly(ctx.home_readonly);
// While the shell is sandboxed, hide the project's own `.jan` state directory
@@ -770,31 +766,51 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
if !ctx.read_roots.is_empty() {
policy = policy.with_read_roots(ctx.read_roots.to_vec());
}
- // With the sandbox off the shell is spawned bare, the way the user's own
- // terminal would: no wrapper, no policy, the real `$HOME` and `/tmp`. Only
- // a surface that opted in gets here (the CLI's `--sandbox`/`sandbox`
- // setting); the desktop never does, so `bash` there is still confined or
- // withheld. `policy` is still built either way -- it is what
- // `denial_hint` reads, and an unconfined command can still hit a plain
- // filesystem permission error worth explaining.
let shell = if ctx.sandbox {
// No confinement available means no shell: running unsandboxed would give
// the command the whole machine, which is never what the caller asked for.
let Some(wrapped) = jail::wrap(proc::shell(), &policy) else {
- return "ERROR: bash is unavailable because no OS sandbox could be established on \
- this system. Use the read/ls/find/grep tools instead."
- .to_string();
+ return Err(
+ "ERROR: bash is unavailable because no OS sandbox could be established on \
+ this system. Use the read/ls/find/grep tools instead."
+ .to_string(),
+ );
};
wrapped
} else {
proc::shell().clone()
};
-
let sandbox_tmp = if ctx.sandbox {
jail::scratch_env_path(jail::backend(), &policy)
} else {
None
};
+ Ok((shell, sandbox_tmp, policy))
+}
+
+async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
+ let Some(command) = arg_str(args, "command").filter(|command| !command.trim().is_empty())
+ else {
+ if let Some(job_id) = arg_str(args, "job_id").filter(|job_id| !job_id.trim().is_empty()) {
+ return await_bash_job(job_id).await;
+ }
+ return "ERROR: missing required argument 'command' (or 'job_id' to poll a backgrounded job)"
+ .to_string();
+ };
+ let timeout_secs = arg_u64(args, "timeout").unwrap_or(DEFAULT_BASH_TIMEOUT_SECS);
+
+ let root = ctx.project_root;
+ if !root.is_dir() {
+ return format!(
+ "ERROR: working directory does not exist: {}",
+ root.display()
+ );
+ }
+
+ let (shell, sandbox_tmp, policy) = match confined_shell(ctx) {
+ Ok(v) => v,
+ Err(e) => return e,
+ };
let child = match proc::spawn(&shell, command, root, sandbox_tmp.as_deref()).await {
Ok(c) => c,
Err(e) => return format!("ERROR: failed to run command: {e}"),
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 9c34aec94..ecee1569f 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,6 +11,9 @@ pub mod gate;
pub mod handlers;
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;
pub mod proc;
/// Path containment for the filesystem tools. Distinct from [`jail`], which is
/// kernel-level confinement for spawned commands.
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
new file mode 100644
index 000000000..b0784ed53
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -0,0 +1,880 @@
+//! The `monitor` tool: watch a file a long-running job streams into and
+//! evaluate custom condition scripts against it, reporting each match to the
+//! agent as an out-of-band notice.
+//!
+//! A condition is an arbitrary shell script run from the project root under the
+//! same confinement `bash` gets (`handlers::confined_shell`). Exit 0 means the
+//! condition matched, and its stdout is the matched content. Conditions are
+//! evaluated once at start and again whenever the watched file changes; a met
+//! condition is never re-evaluated. The monitor stops itself when every
+//! condition has matched, when it is stopped explicitly, or at its deadline --
+//! the bound that makes it safe for a run to park on an active monitor.
+//!
+//! Delivery is the caller's: a [`MonitorSet`] either queues [`MonitorUpdate`]s
+//! for the agent loop to drain into `<SYSTEM>` reminders (the CLI/desktop run
+//! path), or hands each one to a subscriber callback (the Tauri command layer,
+//! which forwards them to Cowork over an IPC channel).
+
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use crate::tools::{sandbox, ToolContext};
+
+pub const MONITOR_TOOL_NAME: &str = "monitor";
+
+/// Active monitors per set. A run fanning out more watchers than this is
+/// polling, not monitoring, and each one holds a background task.
+pub const MAX_MONITORS: usize = 8;
+/// Conditions per monitor.
+pub const MAX_CONDITIONS: usize = 16;
+pub const DEFAULT_TIMEOUT_SECS: u64 = 1800;
+pub const MAX_TIMEOUT_SECS: u64 = 7200;
+const MIN_TIMEOUT_SECS: u64 = 10;
+/// How often the watched file is re-checked for changes.
+const POLL_INTERVAL: Duration = Duration::from_secs(2);
+/// A condition script that runs longer than this is killed and treated as
+/// unmet; a matcher is a check, not a job of its own.
+const EVAL_TIMEOUT: Duration = Duration::from_secs(60);
+/// Cap on the matched content a notice carries into the conversation.
+const MATCH_MAX_BYTES: usize = 4096;
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonitorCondition {
+ pub name: String,
+ pub script: String,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct MonitorSpec {
+ /// The watched path as the model wrote it; resolved against the project
+ /// root and scratch at start.
+ pub file: String,
+ pub conditions: Vec<MonitorCondition>,
+ pub timeout_secs: u64,
+ /// Poll cadence. Not model-settable; tests shorten it.
+ pub interval: Duration,
+}
+
+/// Owned snapshot of the [`ToolContext`] fields an evaluation needs: the
+/// monitor task outlives the borrowed context of the call that started it.
+#[derive(Debug, Clone)]
+pub struct MonitorCtx {
+ pub project_root: PathBuf,
+ pub scratch_root: Option<PathBuf>,
+ pub mask_root: Option<PathBuf>,
+ pub read_roots: Vec<PathBuf>,
+ pub allow_network: bool,
+ pub home_readonly: bool,
+ pub sandbox: bool,
+}
+
+impl MonitorCtx {
+ pub fn from_tool_context(ctx: &ToolContext<'_>) -> Self {
+ Self {
+ project_root: ctx.project_root.to_path_buf(),
+ scratch_root: ctx.scratch_root.map(Path::to_path_buf),
+ mask_root: ctx.mask_root.map(Path::to_path_buf),
+ read_roots: ctx.read_roots.to_vec(),
+ allow_network: ctx.allow_network,
+ home_readonly: ctx.home_readonly,
+ sandbox: ctx.sandbox,
+ }
+ }
+
+ /// A borrowed context over this snapshot, for the pieces of the bash
+ /// machinery that take one. The store root is never consulted by an exec,
+ /// so the project root stands in for it.
+ fn as_tool_context(&self) -> ToolContext<'_> {
+ let mut ctx = ToolContext::new(&self.project_root, &self.project_root, &[])
+ .with_network(self.allow_network)
+ .with_home_readonly(self.home_readonly)
+ .with_sandbox(self.sandbox)
+ .with_read_roots(&self.read_roots);
+ if let Some(mask) = &self.mask_root {
+ ctx = ctx.with_mask_root(mask);
+ }
+ if let Some(scratch) = &self.scratch_root {
+ ctx = ctx.with_scratch_root(scratch);
+ }
+ ctx
+ }
+}
+
+/// One notice, in the two registers every background ping needs: `headline`
+/// for the transcript row, `text` for the `<SYSTEM>` reminder the model gets.
+/// `done` marks the update that also ends the monitor (all met, or timeout).
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MonitorUpdate {
+ pub monitor_id: String,
+ pub headline: String,
+ pub text: String,
+ pub done: bool,
+}
+
+/// Parse and validate a `monitor {op:"start"}` call.
+pub fn parse_start_args(args: &serde_json::Value) -> Result<MonitorSpec, String> {
+ let file = args
+ .get("file")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .ok_or("start requires 'file': the path the job streams its output to")?
+ .to_string();
+ let raw = args
+ .get("conditions")
+ .and_then(|v| v.as_array())
+ .filter(|a| !a.is_empty())
+ .ok_or("start requires a non-empty 'conditions' array of {name, script}")?;
+ if raw.len() > MAX_CONDITIONS {
+ return Err(format!("at most {MAX_CONDITIONS} conditions per monitor"));
+ }
+ let mut conditions = Vec::with_capacity(raw.len());
+ for c in raw {
+ let name = c
+ .get("name")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .ok_or("every condition needs a non-empty 'name'")?;
+ let script = c
+ .get("script")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.trim().is_empty())
+ .ok_or("every condition needs a non-empty 'script'")?;
+ if conditions
+ .iter()
+ .any(|existing: &MonitorCondition| existing.name == name)
+ {
+ return Err(format!("duplicate condition name '{name}'"));
+ }
+ conditions.push(MonitorCondition {
+ name: name.to_string(),
+ script: script.to_string(),
+ });
+ }
+ let timeout_secs = args
+ .get("timeout")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(DEFAULT_TIMEOUT_SECS)
+ .clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);
+ Ok(MonitorSpec {
+ file,
+ conditions,
+ timeout_secs,
+ interval: POLL_INTERVAL,
+ })
+}
+
+pub fn parse_stop_args(args: &serde_json::Value) -> Result<String, String> {
+ args.get("monitor_id")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+ .ok_or_else(|| "stop requires 'monitor_id'".to_string())
+}
+
+/// Shared, mutable view of one monitor's progress, read by `list` and written
+/// by the monitor's own task.
+struct MonitorStatus {
+ file: String,
+ met: Vec<String>,
+ unmet: Vec<String>,
+}
+
+struct Entry {
+ abort: tokio::task::AbortHandle,
+ status: Arc<Mutex<MonitorStatus>>,
+}
+
+/// How a set delivers updates: queued for the agent loop to drain as
+/// `<SYSTEM>` reminders, or pushed to a subscriber as they happen.
+enum Delivery {
+ Queue,
+ Subscriber(Arc<dyn Fn(MonitorUpdate) + Send + Sync>),
+}
+
+/// Registry of one owner's monitors (a run on the CLI/desktop loop, a Cowork
+/// session on the command layer). Mirrors `BackgroundSubagents`: notices +
+/// wake + an active count whose decrement always follows the notice push, so
+/// "is anything still owed?" can never read false in between.
+pub struct MonitorSet {
+ inner: Mutex<std::collections::HashMap<String, Entry>>,
+ notices: Mutex<Vec<MonitorUpdate>>,
+ wake: tokio::sync::Notify,
+ active: AtomicUsize,
+ seq: AtomicU64,
+ delivery: Delivery,
+}
+
+impl Default for MonitorSet {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl MonitorSet {
+ pub fn new() -> Self {
+ Self::with_delivery(Delivery::Queue)
+ }
+
+ /// Route every update to `subscriber` instead of the queue. The subscriber
+ /// owns ordering and persistence; `take_notices` then never has anything.
+ pub fn subscribed(subscriber: Arc<dyn Fn(MonitorUpdate) + Send + Sync>) -> Self {
+ Self::with_delivery(Delivery::Subscriber(subscriber))
+ }
+
+ fn with_delivery(delivery: Delivery) -> Self {
+ Self {
+ inner: Mutex::new(std::collections::HashMap::new()),
+ notices: Mutex::new(Vec::new()),
+ wake: tokio::sync::Notify::new(),
+ active: AtomicUsize::new(0),
+ seq: AtomicU64::new(1),
+ delivery,
+ }
+ }
+
+ /// Take every queued update, oldest first.
+ pub fn take_notices(&self) -> Vec<MonitorUpdate> {
+ std::mem::take(&mut *self.notices.lock().unwrap())
+ }
+
+ /// Whether anything could still produce an update: an active monitor, or a
+ /// queued update not yet delivered. Safe to park on -- every monitor
+ /// terminates (all met, stopped, or its deadline).
+ pub fn has_pending_work(&self) -> bool {
+ !self.notices.lock().unwrap().is_empty() || self.active.load(Ordering::SeqCst) > 0
+ }
+
+ /// Park until an update is queued, or nothing is left to wait for. The
+ /// waiter registers before the state re-read, so a monitor finishing in
+ /// between wakes this call rather than being missed.
+ pub async fn wait_for_notice(&self) {
+ loop {
+ let waiter = self.wake.notified();
+ tokio::pin!(waiter);
+ waiter.as_mut().enable();
+ if !self.notices.lock().unwrap().is_empty()
+ || self.active.load(Ordering::SeqCst) == 0
+ {
+ return;
+ }
+ waiter.await;
+ }
+ }
+
+ fn push_update(&self, update: MonitorUpdate) {
+ match &self.delivery {
+ Delivery::Queue => {
+ self.notices.lock().unwrap().push(update);
+ }
+ Delivery::Subscriber(subscriber) => subscriber(update),
+ }
+ self.wake.notify_waiters();
+ }
+
+ /// Start a monitor, returning the model-facing result string. The watched
+ /// path must sit where a read may reach (project, scratch, or an attached
+ /// read-only root); the file itself may not exist yet.
+ pub fn start(self: &Arc<Self>, spec: MonitorSpec, ctx: MonitorCtx) -> Result<String, String> {
+ if self.inner.lock().unwrap().len() >= MAX_MONITORS {
+ return Err(format!(
+ "at most {MAX_MONITORS} monitors may be active; stop one first"
+ ));
+ }
+ let scratch = ctx.scratch_root.as_deref();
+ match sandbox::escapes_read_roots(&ctx.project_root, scratch, &ctx.read_roots, &spec.file)
+ {
+ Ok(false) => {}
+ Ok(true) => {
+ return Err(format!(
+ "'{}' is outside the project; a monitor can only watch files the run can read",
+ spec.file
+ ))
+ }
+ Err(e) => return Err(format!("cannot resolve '{}': {e}", spec.file)),
+ }
+ let watch_path = sandbox::resolve_path(&ctx.project_root, scratch, &spec.file);
+ let monitor_id = format!("mon-{}", self.seq.fetch_add(1, Ordering::Relaxed));
+
+ let status = Arc::new(Mutex::new(MonitorStatus {
+ file: spec.file.clone(),
+ met: Vec::new(),
+ unmet: spec.conditions.iter().map(|c| c.name.clone()).collect(),
+ }));
+ let condition_count = spec.conditions.len();
+ let timeout_secs = spec.timeout_secs;
+ let file = spec.file.clone();
+
+ self.active.fetch_add(1, Ordering::SeqCst);
+ let set = self.clone();
+ let id_task = monitor_id.clone();
+ let status_task = status.clone();
+ let handle = tokio::spawn(async move {
+ run_monitor(&set, &id_task, spec, ctx, watch_path, status_task).await;
+ // The terminal update (queued inside run_monitor) precedes both the
+ // entry removal and the count release.
+ set.inner.lock().unwrap().remove(&id_task);
+ set.active.fetch_sub(1, Ordering::SeqCst);
+ set.wake.notify_waiters();
+ });
+ self.inner.lock().unwrap().insert(
+ monitor_id.clone(),
+ Entry {
+ abort: handle.abort_handle(),
+ status,
+ },
+ );
+ let plural = if condition_count == 1 { "" } else { "s" };
+ Ok(format!(
+ "Monitor started (monitor_id={monitor_id}) watching {file} with {condition_count} \
+ condition{plural}. Conditions are checked now and whenever the file changes; each \
+ match arrives as a <SYSTEM> note carrying the matched content. The monitor stops \
+ when every condition has matched, when you stop it, or after {timeout_secs}s. Keep \
+ working meanwhile."
+ ))
+ }
+
+ /// Stop one monitor. Its own tool result reports the state; no notice is
+ /// queued, since the model asked for the stop itself.
+ pub fn stop(&self, monitor_id: &str) -> String {
+ let entry = self.inner.lock().unwrap().remove(monitor_id);
+ let Some(entry) = entry else {
+ return format!("ERROR: unknown or already-stopped monitor '{monitor_id}'");
+ };
+ entry.abort.abort();
+ self.active.fetch_sub(1, Ordering::SeqCst);
+ self.wake.notify_waiters();
+ let status = entry.status.lock().unwrap();
+ format!(
+ "Monitor {monitor_id} stopped. Conditions met: {}; unmet: {}.",
+ name_list(&status.met),
+ name_list(&status.unmet)
+ )
+ }
+
+ /// One line per active monitor, for `monitor {op:"list"}`.
+ pub fn list(&self) -> String {
+ let inner = self.inner.lock().unwrap();
+ if inner.is_empty() {
+ return "No active monitors.".to_string();
+ }
+ let mut ids: Vec<&String> = inner.keys().collect();
+ ids.sort();
+ let mut out = String::new();
+ for id in ids {
+ let status = inner[id].status.lock().unwrap();
+ out.push_str(&format!(
+ "{id}: watching {} (met: {}; unmet: {})\n",
+ status.file,
+ name_list(&status.met),
+ name_list(&status.unmet)
+ ));
+ }
+ out.trim_end().to_string()
+ }
+
+ /// Abort and forget every monitor. Called at owner teardown; nothing is
+ /// queued, since no turn is left to read it.
+ pub fn stop_all(&self) {
+ let mut inner = self.inner.lock().unwrap();
+ for (_, entry) in inner.drain() {
+ entry.abort.abort();
+ self.active.fetch_sub(1, Ordering::SeqCst);
+ }
+ self.notices.lock().unwrap().clear();
+ self.wake.notify_waiters();
+ }
+}
+
+impl Drop for MonitorSet {
+ fn drop(&mut self) {
+ // Abort without touching the counters: the set is going away with its
+ // owner, and a waiter cannot outlive it.
+ for (_, entry) in self.inner.lock().unwrap().drain() {
+ entry.abort.abort();
+ }
+ }
+}
+
+fn name_list(names: &[String]) -> String {
+ if names.is_empty() {
+ "none".to_string()
+ } else {
+ names.join(", ")
+ }
+}
+
+/// The change signature polling keys off. Length plus mtime rather than either
+/// alone: an append changes the length, an in-place rewrite the mtime.
+fn file_signature(meta: &std::fs::Metadata) -> (u64, Option<std::time::SystemTime>) {
+ (meta.len(), meta.modified().ok())
+}
+
+async fn run_monitor(
+ set: &Arc<MonitorSet>,
+ monitor_id: &str,
+ spec: MonitorSpec,
+ ctx: MonitorCtx,
+ watch_path: PathBuf,
+ status: Arc<Mutex<MonitorStatus>>,
+) {
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(spec.timeout_secs);
+ let mut unmet = spec.conditions;
+ // `None` until the file exists; the first sighting triggers an evaluation,
+ // as does a start over a file that already has content.
+ let mut last_sig: Option<(u64, Option<std::time::SystemTime>)> = None;
+ let mut first_pass = true;
+ loop {
+ let sig = tokio::fs::metadata(&watch_path)
+ .await
+ .ok()
+ .map(|m| file_signature(&m));
+ // The very first pass evaluates even with no file yet: a condition
+ // script need not read the watched file at all.
+ let changed = (sig.is_some() && sig != last_sig) || first_pass;
+ first_pass = false;
+ if changed {
+ last_sig = sig;
+ let mut still_unmet = Vec::with_capacity(unmet.len());
+ let mut met_now: Vec<(String, String)> = Vec::new();
+ for cond in unmet {
+ match eval_condition(&ctx, &cond.script).await {
+ Some(content) => met_now.push((cond.name, content)),
+ None => still_unmet.push(cond),
+ }
+ }
+ unmet = still_unmet;
+ let total = met_now.len();
+ for (i, (name, content)) in met_now.into_iter().enumerate() {
+ {
+ let mut s = status.lock().unwrap();
+ s.unmet.retain(|n| n != &name);
+ s.met.push(name.clone());
+ }
+ let last = unmet.is_empty() && i + 1 == total;
+ set.push_update(match_update(monitor_id, &spec.file, &name, &content, last));
+ }
+ if unmet.is_empty() {
+ return;
+ }
+ }
+ let now = tokio::time::Instant::now();
+ if now >= deadline {
+ let names: Vec<String> = unmet.iter().map(|c| c.name.clone()).collect();
+ set.push_update(MonitorUpdate {
+ monitor_id: monitor_id.to_string(),
+ headline: format!("Monitor {monitor_id}: timed out"),
+ text: format!(
+ "Monitor '{monitor_id}' timed out after {}s watching {}. Unmet conditions: \
+ {}. It has stopped.",
+ spec.timeout_secs,
+ spec.file,
+ name_list(&names)
+ ),
+ done: true,
+ });
+ return;
+ }
+ tokio::time::sleep(spec.interval.min(deadline - now)).await;
+ }
+}
+
+fn match_update(
+ monitor_id: &str,
+ file: &str,
+ name: &str,
+ content: &str,
+ last: bool,
+) -> MonitorUpdate {
+ let body = if content.is_empty() {
+ "(the condition script matched with no output)".to_string()
+ } else {
+ format!(":\n{content}")
+ };
+ let mut text = format!("Monitor '{monitor_id}' condition '{name}' matched on {file}{body}");
+ let headline = if last {
+ text.push_str("\n\nAll conditions for this monitor have now matched; it has stopped.");
+ format!("Monitor {monitor_id}: condition '{name}' matched; all conditions met")
+ } else {
+ format!("Monitor {monitor_id}: condition '{name}' matched")
+ };
+ MonitorUpdate {
+ monitor_id: monitor_id.to_string(),
+ headline,
+ text,
+ done: last,
+ }
+}
+
+/// Run one condition script under the same confinement `bash` gets.
+/// `Some(content)` when it exits 0 (its stdout, bounded); `None` for a nonzero
+/// exit, a spawn failure, or a script that outran [`EVAL_TIMEOUT`] -- all of
+/// which read as "not matched yet" and are retried on the next change.
+async fn eval_condition(ctx: &MonitorCtx, script: &str) -> Option<String> {
+ let tool_ctx = ctx.as_tool_context();
+ let (shell, sandbox_tmp, _policy) =
+ crate::tools::handlers::confined_shell(&tool_ctx).ok()?;
+ let mut child = crate::tools::proc::spawn(
+ &shell,
+ script,
+ &ctx.project_root,
+ sandbox_tmp.as_deref(),
+ )
+ .await
+ .ok()?;
+ let pid = child.id();
+ let result = tokio::time::timeout(EVAL_TIMEOUT, async {
+ let stdout = child.stdout.take();
+ // Drained so a chatty script cannot block on a full pipe, discarded
+ // because only stdout is the matched content.
+ let stderr = child.stderr.take();
+ 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 = MATCH_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(pid);
+ }
+ match result {
+ Ok((Ok(exit), head)) if exit.success() => {
+ Some(String::from_utf8_lossy(&head).trim().to_string())
+ }
+ Ok(_) => None,
+ Err(_) => {
+ // Timed out: reap the whole tree, or a wedged matcher leaks.
+ if let Some(pid) = pid {
+ crate::tools::proc::kill_tree(pid);
+ }
+ None
+ }
+ }
+}
+
+/// OpenAI function schema for the `monitor` tool. Mirrored verbatim by
+/// Cowork's client-side tool table, like `task`/`todo`.
+pub fn monitor_tool_schema() -> serde_json::Value {
+ serde_json::json!({
+ "type": "function",
+ "function": {
+ "name": MONITOR_TOOL_NAME,
+ "description": "Watch a file a long-running job streams output into (e.g. a backgrounded bash job redirecting to a log) and evaluate condition scripts against it. Each condition is a shell script run from the project root whenever the file changes; exit 0 means the condition matched and its stdout is the matched content. You get a <SYSTEM> note per match, so start the monitor and keep working. The monitor stops when every condition has matched, on stop, or at its timeout. A met condition is never re-checked.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "op": { "type": "string", "enum": ["start", "stop", "list"] },
+ "file": { "type": "string", "description": "For start: the file to watch, relative to the project root (or under /tmp). It may not exist yet." },
+ "conditions": {
+ "type": "array",
+ "description": "For start: the conditions to watch for. Scripts should be cheap checks (e.g. grep -m1 'BUILD FAILED' build.log), not jobs.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": { "type": "string", "description": "Short unique label, quoted back to you when it matches." },
+ "script": { "type": "string", "description": "Shell script; exit 0 = matched, stdout = the matched content." }
+ },
+ "required": ["name", "script"]
+ }
+ },
+ "timeout": { "type": "integer", "description": "For start: seconds before the monitor gives up and reports its unmet conditions (default 1800, max 7200)." },
+ "monitor_id": { "type": "string", "description": "For stop: the id returned by start." }
+ },
+ "required": ["op"]
+ }
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// A fresh directory under the OS temp dir (the plugin has no tempfile
+ /// dev-dependency; same pattern as the handlers tests).
+ fn unique_root() -> PathBuf {
+ static N: AtomicUsize = AtomicUsize::new(0);
+ let n = N.fetch_add(1, Ordering::SeqCst);
+ let root =
+ std::env::temp_dir().join(format!("jan_monitor_test_{}_{}", std::process::id(), n));
+ std::fs::create_dir_all(&root).unwrap();
+ root
+ }
+
+ fn ctx_for(root: &Path) -> MonitorCtx {
+ MonitorCtx {
+ project_root: root.to_path_buf(),
+ scratch_root: None,
+ mask_root: None,
+ read_roots: Vec::new(),
+ allow_network: false,
+ home_readonly: false,
+ // Bare shell: these tests exercise the monitor loop, not the jail.
+ sandbox: false,
+ }
+ }
+
+ fn spec(file: &str, conditions: &[(&str, &str)], timeout_secs: u64) -> MonitorSpec {
+ MonitorSpec {
+ file: file.to_string(),
+ conditions: conditions
+ .iter()
+ .map(|(name, script)| MonitorCondition {
+ name: name.to_string(),
+ script: script.to_string(),
+ })
+ .collect(),
+ timeout_secs,
+ interval: Duration::from_millis(25),
+ }
+ }
+
+ async fn next_notice(set: &Arc<MonitorSet>) -> MonitorUpdate {
+ for _ in 0..200 {
+ if let Some(update) = set.take_notices().into_iter().next() {
+ return update;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ panic!("no monitor update arrived");
+ }
+
+ #[test]
+ fn parse_rejects_a_call_with_no_conditions() {
+ assert!(parse_start_args(&serde_json::json!({"op": "start", "file": "a.log"})).is_err());
+ assert!(parse_start_args(
+ &serde_json::json!({"op": "start", "file": "a.log", "conditions": []})
+ )
+ .is_err());
+ assert!(parse_start_args(&serde_json::json!({
+ "op": "start", "conditions": [{"name": "x", "script": "true"}]
+ }))
+ .is_err());
+ assert!(parse_start_args(&serde_json::json!({
+ "op": "start", "file": "a.log",
+ "conditions": [{"name": "x", "script": "true"}, {"name": "x", "script": "false"}]
+ }))
+ .is_err());
+ }
+
+ #[test]
+ fn parse_clamps_the_timeout_and_defaults_it() {
+ let base = serde_json::json!({
+ "op": "start", "file": "a.log",
+ "conditions": [{"name": "x", "script": "true"}]
+ });
+ assert_eq!(
+ parse_start_args(&base).unwrap().timeout_secs,
+ DEFAULT_TIMEOUT_SECS
+ );
+ let mut low = base.clone();
+ low["timeout"] = serde_json::json!(1);
+ assert_eq!(parse_start_args(&low).unwrap().timeout_secs, MIN_TIMEOUT_SECS);
+ let mut high = base;
+ high["timeout"] = serde_json::json!(1_000_000);
+ assert_eq!(
+ parse_start_args(&high).unwrap().timeout_secs,
+ MAX_TIMEOUT_SECS
+ );
+ }
+
+ #[tokio::test]
+ async fn a_condition_matching_at_start_reports_its_content_and_stops() {
+ let dir = unique_root();
+ std::fs::write(dir.join("build.log"), "warm up\nBUILD OK line\n").unwrap();
+ let set = Arc::new(MonitorSet::new());
+ let result = set
+ .start(
+ spec("build.log", &[("ok", "grep 'BUILD OK' build.log")], 30),
+ ctx_for(&dir),
+ )
+ .unwrap();
+ assert!(result.contains("monitor_id=mon-1"), "{result}");
+ let update = next_notice(&set).await;
+ assert!(update.done, "single condition: the match ends the monitor");
+ assert!(update.text.contains("BUILD OK line"), "{}", update.text);
+ assert!(update.text.contains("all conditions") || update.text.contains("All conditions"));
+ for _ in 0..100 {
+ if !set.has_pending_work() {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ panic!("the set still reports pending work after the final match");
+ }
+
+ #[tokio::test]
+ async fn a_later_append_meets_the_second_condition() {
+ let dir = unique_root();
+ let log = dir.join("job.log");
+ std::fs::write(&log, "phase one done\n").unwrap();
+ let set = Arc::new(MonitorSet::new());
+ set.start(
+ spec(
+ "job.log",
+ &[
+ ("one", "grep 'phase one' job.log"),
+ ("two", "grep 'phase two' job.log"),
+ ],
+ 30,
+ ),
+ ctx_for(&dir),
+ )
+ .unwrap();
+ let first = next_notice(&set).await;
+ assert!(first.text.contains("'one'"), "{}", first.text);
+ assert!(!first.done);
+ assert!(set.has_pending_work(), "condition 'two' is still owed");
+ assert!(set.list().contains("met: one; unmet: two"), "{}", set.list());
+
+ let mut content = std::fs::read_to_string(&log).unwrap();
+ content.push_str("phase two done\n");
+ std::fs::write(&log, content).unwrap();
+ let second = next_notice(&set).await;
+ assert!(second.text.contains("'two'"), "{}", second.text);
+ assert!(second.text.contains("phase two done"));
+ assert!(second.done);
+ }
+
+ #[tokio::test]
+ async fn an_unmet_monitor_times_out_and_names_its_conditions() {
+ let dir = unique_root();
+ let set = Arc::new(MonitorSet::new());
+ // Timeout of zero: the deadline has passed by the first re-check, so
+ // the test never waits out a real timeout.
+ set.start(
+ spec("never.log", &[("ghost", "grep ghost never.log")], 0),
+ ctx_for(&dir),
+ )
+ .unwrap();
+ let update = next_notice(&set).await;
+ assert!(update.done);
+ assert!(update.text.contains("timed out"), "{}", update.text);
+ assert!(update.text.contains("ghost"), "{}", update.text);
+ }
+
+ #[tokio::test]
+ async fn stop_reports_progress_and_frees_the_slot() {
+ let dir = unique_root();
+ let set = Arc::new(MonitorSet::new());
+ let result = set
+ .start(
+ spec("never.log", &[("ghost", "false")], 3600),
+ ctx_for(&dir),
+ )
+ .unwrap();
+ assert!(result.contains("mon-1"));
+ assert!(set.has_pending_work());
+ let stopped = set.stop("mon-1");
+ assert!(stopped.contains("unmet: ghost"), "{stopped}");
+ assert!(!set.has_pending_work());
+ assert!(set.stop("mon-1").starts_with("ERROR"));
+ assert_eq!(set.list(), "No active monitors.");
+ }
+
+ #[tokio::test]
+ async fn a_watched_path_outside_the_project_is_refused() {
+ let dir = unique_root();
+ let set = Arc::new(MonitorSet::new());
+ let err = set
+ .start(
+ spec("/etc/passwd", &[("x", "true")], 30),
+ ctx_for(&dir),
+ )
+ .unwrap_err();
+ assert!(err.contains("outside the project"), "{err}");
+ assert!(!set.has_pending_work());
+ }
+
+ #[tokio::test]
+ async fn the_monitor_cap_is_enforced() {
+ let dir = unique_root();
+ let set = Arc::new(MonitorSet::new());
+ for _ in 0..MAX_MONITORS {
+ set.start(spec("a.log", &[("x", "false")], 3600), ctx_for(&dir))
+ .unwrap();
+ }
+ let err = set
+ .start(spec("a.log", &[("x", "false")], 3600), ctx_for(&dir))
+ .unwrap_err();
+ assert!(err.contains("at most"), "{err}");
+ set.stop_all();
+ assert!(!set.has_pending_work());
+ }
+
+ #[tokio::test]
+ async fn wait_for_notice_wakes_on_a_match() {
+ let dir = unique_root();
+ let log = dir.join("late.log");
+ let set = Arc::new(MonitorSet::new());
+ set.start(
+ spec("late.log", &[("hit", "grep hit late.log")], 30),
+ ctx_for(&dir),
+ )
+ .unwrap();
+ let waiter = {
+ let set = set.clone();
+ tokio::spawn(async move {
+ set.wait_for_notice().await;
+ set.take_notices()
+ })
+ };
+ tokio::time::sleep(Duration::from_millis(60)).await;
+ std::fs::write(&log, "a hit at last\n").unwrap();
+ let notices = tokio::time::timeout(Duration::from_secs(5), waiter)
+ .await
+ .expect("wait_for_notice never woke")
+ .unwrap();
+ assert_eq!(notices.len(), 1);
+ assert!(notices[0].text.contains("a hit at last"));
+ }
+
+ #[tokio::test]
+ async fn a_subscriber_gets_updates_instead_of_the_queue() {
+ let dir = unique_root();
+ std::fs::write(dir.join("s.log"), "hit\n").unwrap();
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+ let set = Arc::new(MonitorSet::subscribed(Arc::new(move |u| {
+ let _ = tx.send(u);
+ })));
+ set.start(
+ spec("s.log", &[("hit", "grep hit s.log")], 30),
+ ctx_for(&dir),
+ )
+ .unwrap();
+ let update = tokio::time::timeout(Duration::from_secs(5), rx.recv())
+ .await
+ .expect("no subscriber update")
+ .unwrap();
+ assert!(update.done);
+ assert!(set.take_notices().is_empty(), "queue must stay empty");
+ }
+}
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index ddd6c37ba..55d1451d6 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -114,6 +114,12 @@ pub enum StreamEvent {
name: String,
event: Box<StreamEvent>,
},
+ /// The user-facing headline of a background ping the loop just delivered to
+ /// the model as a `<SYSTEM>` reminder (today: a `monitor` condition
+ /// matching). Emitted at delivery, not when the ping is queued, so the
+ /// transcript reads in the order the model saw things. Display-only and
+ /// transient, like notes: it is never journaled.
+ Notice { text: String },
/// The loop's compaction reduced the conversation while retrying a
/// context overflow. The client should replace its session history with
/// `messages` for subsequent turns.
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 8846024b7..5da2689bd 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -142,14 +142,25 @@ impl ToolOutcome {
}
}
+/// One background ping. `text` is what reaches the model as a `<SYSTEM>`
+/// reminder; `headline`, when set, is shown to the user at delivery as
+/// [`StreamEvent::Notice`]. Subagent completions carry no headline -- their
+/// `SubagentEnd` row already reported the fact -- while a monitor match has no
+/// other on-screen account.
+pub(crate) struct BackgroundNotice {
+ pub headline: Option<String>,
+ pub text: String,
+}
+
#[async_trait]
pub(crate) trait ToolInvoker: Send + Sync {
async fn invoke(&self, tool_calls: &[serde_json::Value]) -> Result<Vec<ToolOutcome>, String>;
/// Pings raised by work the model started and is no longer blocked on (a
- /// backgrounded subagent finishing), oldest first. Folded into the
- /// conversation as `<SYSTEM>` reminders at the top of the next turn.
- fn background_notices(&self) -> Vec<String> {
+ /// backgrounded subagent finishing, a monitor condition matching), oldest
+ /// first. Folded into the conversation as `<SYSTEM>` reminders at the top
+ /// of the next turn.
+ fn background_notices(&self) -> Vec<BackgroundNotice> {
Vec::new()
}
@@ -303,6 +314,11 @@ struct CompositeToolInvoker {
todo_registry: Option<crate::core::agent::todo::TodoRegistry>,
grants: std::sync::Mutex<tauri_plugin_agent_tools::tools::gate::SessionGrants>,
subagents: Option<SubagentContext>,
+ /// This run's file monitors. Scoped to the run like `subagents`: dropping
+ /// the invoker aborts every watcher, and an active monitor keeps the run
+ /// parked via `background_pending` (bounded, since every monitor has a
+ /// deadline).
+ monitors: std::sync::Arc<tauri_plugin_agent_tools::tools::monitor::MonitorSet>,
auto_approve: bool,
run_mode: crate::core::agent::plan::RunMode,
}
@@ -649,6 +665,78 @@ impl CompositeToolInvoker {
}
}
+ /// Prompt the user to approve starting a monitor: its condition scripts are
+ /// arbitrary shell commands the watcher will run repeatedly, so starting one
+ /// is an exec-class action even though each later evaluation is unattended.
+ async fn prompt_monitor_start(
+ &self,
+ spec: &tauri_plugin_agent_tools::tools::monitor::MonitorSpec,
+ ) -> PermissionDecision {
+ let request_id = next_permission_id();
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ self.permission_requests
+ .lock()
+ .await
+ .insert(request_id.clone(), tx);
+ // The prompt's detail shows `command` INSTEAD of `path`, so the watched
+ // file has to ride along here or the user approves scripts with no idea
+ // what triggers them. A shell comment keeps the `$ ` preview honest.
+ let scripts = std::iter::once(format!("# watches {}", spec.file))
+ .chain(
+ spec.conditions
+ .iter()
+ .map(|c| format!("{}: {}", c.name, c.script)),
+ )
+ .collect::<Vec<_>>()
+ .join("\n");
+ let _ = self.events.send(StreamEvent::PermissionRequest {
+ request_id: request_id.clone(),
+ tool_name: tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME.to_string(),
+ capability: "run".to_string(),
+ path: Some(spec.file.clone()),
+ command: Some(scripts),
+ diff: None,
+ prompt_kind: "monitor".to_string(),
+ offers_always: false,
+ });
+ let decision = rx.await.unwrap_or(PermissionDecision::Deny);
+ self.permission_requests.lock().await.remove(&request_id);
+ decision
+ }
+
+ /// Execute one `monitor` tool call. `start` is gated (it schedules shell
+ /// scripts); `stop` and `list` only touch this run's own registry.
+ async fn handle_monitor_tool(&self, args: &serde_json::Value) -> String {
+ use tauri_plugin_agent_tools::tools::monitor;
+ match args.get("op").and_then(|v| v.as_str()).unwrap_or("") {
+ "start" => {
+ let spec = match monitor::parse_start_args(args) {
+ Ok(spec) => spec,
+ Err(e) => return format!("ERROR: {e}"),
+ };
+ if !self.auto_approve {
+ match self.prompt_monitor_start(&spec).await {
+ PermissionDecision::AllowOnce | PermissionDecision::AllowAlways => {}
+ PermissionDecision::Deny => {
+ return "ERROR: monitor start denied by user".to_string()
+ }
+ }
+ }
+ let ctx = monitor::MonitorCtx::from_tool_context(&self.tool_context());
+ match self.monitors.start(spec, ctx) {
+ Ok(msg) => msg,
+ Err(e) => format!("ERROR: {e}"),
+ }
+ }
+ "stop" => match monitor::parse_stop_args(args) {
+ Ok(id) => self.monitors.stop(&id),
+ Err(e) => format!("ERROR: {e}"),
+ },
+ "list" => self.monitors.list(),
+ other => format!("ERROR: unknown monitor op '{other}'"),
+ }
+ }
+
async fn handle_ask_tool(&self, args: &serde_json::Value) -> String {
use crate::core::agent::interaction::{register, AskError, AskRequest};
@@ -860,22 +948,57 @@ fn plan_mode_read_only_msg(name: &str) -> String {
#[async_trait]
impl ToolInvoker for CompositeToolInvoker {
- fn background_notices(&self) -> Vec<String> {
- self.subagents
+ fn background_notices(&self) -> Vec<BackgroundNotice> {
+ let mut out: Vec<BackgroundNotice> = self
+ .subagents
.as_ref()
.map(|ctx| ctx.bg.take_notices())
.unwrap_or_default()
+ .into_iter()
+ .map(|text| BackgroundNotice {
+ headline: None,
+ text,
+ })
+ .collect();
+ out.extend(
+ self.monitors
+ .take_notices()
+ .into_iter()
+ .map(|u| BackgroundNotice {
+ headline: Some(u.headline),
+ text: u.text,
+ }),
+ );
+ out
}
fn background_pending(&self) -> bool {
self.subagents
.as_ref()
.is_some_and(|ctx| ctx.bg.has_pending_work())
+ || self.monitors.has_pending_work()
}
async fn await_background(&self) {
- if let Some(ctx) = &self.subagents {
- ctx.bg.wait_for_notice().await;
+ // 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
+ // instantly every time and starve the side actually being waited on.
+ // The re-check between iterations is what `run_turn_cycle` does anyway.
+ let sub_pending = self
+ .subagents
+ .as_ref()
+ .is_some_and(|ctx| ctx.bg.has_pending_work());
+ let mon_pending = self.monitors.has_pending_work();
+ match (self.subagents.as_ref(), sub_pending, mon_pending) {
+ (Some(ctx), true, true) => {
+ tokio::select! {
+ _ = ctx.bg.wait_for_notice() => {}
+ _ = self.monitors.wait_for_notice() => {}
+ }
+ }
+ (Some(ctx), true, false) => ctx.bg.wait_for_notice().await,
+ (_, _, true) => self.monitors.wait_for_notice().await,
+ _ => {}
}
}
@@ -955,6 +1078,31 @@ impl ToolInvoker for CompositeToolInvoker {
out.push(ToolOutcome::plain(id, content));
continue;
}
+ // The monitor tool schedules shell scripts and owns per-run state,
+ // so like the subagent tools it is handled ahead of the fs/exec
+ // gate (its own prompt gates `start`).
+ if name == tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME {
+ let id = tc
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ // Not advertised in Plan; hard-denied here as defense in depth
+ // (a started monitor runs exec-class scripts).
+ if self.run_mode == crate::core::agent::plan::RunMode::Plan {
+ out.push(ToolOutcome::plain(id, plan_mode_read_only_msg(name)));
+ 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 content = self.handle_monitor_tool(&args).await;
+ out.push(ToolOutcome::plain(id, content));
+ continue;
+ }
if !is_builtin(name) {
let id = tc
.get("id")
@@ -1396,6 +1544,16 @@ fn advertise_local_tools(
}
}
}
+ // The monitor tool watches project files and runs exec-class condition
+ // scripts, so it needs a project and is hidden in read-only Plan mode.
+ if !planning {
+ let name = tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME;
+ if !permissions.is_denied(name)
+ && allowed_names.is_none_or(|allowed| allowed.contains(name))
+ {
+ openai_tools.push(tauri_plugin_agent_tools::tools::monitor::monitor_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
@@ -1920,6 +2078,9 @@ async fn orchestrate_inner(
tauri_plugin_agent_tools::tools::gate::SessionGrants::default(),
),
subagents,
+ monitors: std::sync::Arc::new(
+ tauri_plugin_agent_tools::tools::monitor::MonitorSet::new(),
+ ),
auto_approve: *auto_approve,
run_mode,
};
@@ -2254,7 +2415,15 @@ async fn run_turn_cycle(
let notices = tools.background_notices();
if !notices.is_empty() {
for notice in &notices {
- crate::core::agent::reminder::attach(&mut conversation_messages, notice);
+ crate::core::agent::reminder::attach(&mut conversation_messages, &notice.text);
+ // The headline is shown at delivery, not when the ping was
+ // queued, so the transcript reads in the order the model saw
+ // things (matching Cowork's inbox drain).
+ if let Some(headline) = &notice.headline {
+ let _ = events.send(StreamEvent::Notice {
+ text: headline.clone(),
+ });
+ }
}
let _ = events.send(StreamEvent::MessagesUpdated {
messages: conversation_messages.clone(),
@@ -3811,8 +3980,14 @@ mod tests {
) -> Result<Vec<ToolOutcome>, String> {
Ok(Vec::new())
}
- fn background_notices(&self) -> Vec<String> {
+ fn background_notices(&self) -> Vec<BackgroundNotice> {
std::mem::take(&mut *self.ready.lock().unwrap())
+ .into_iter()
+ .map(|text| BackgroundNotice {
+ headline: None,
+ text,
+ })
+ .collect()
}
fn background_pending(&self) -> bool {
!self.ready.lock().unwrap().is_empty() || !self.pending.lock().unwrap().is_empty()
@@ -3927,6 +4102,90 @@ mod tests {
);
}
+ /// A tool invoker whose one queued ping carries a headline, standing in for
+ /// a monitor match. The headline must surface as `StreamEvent::Notice` at
+ /// delivery; the text must reach the model as a `<SYSTEM>` reminder.
+ struct HeadlinedTool {
+ // The match "lands" only once the cycle parks (await_background), so
+ // the ping resumes a stopped run rather than riding the first turn.
+ armed: StdMutex<bool>,
+ delivered: StdMutex<bool>,
+ }
+ #[async_trait]
+ impl ToolInvoker for HeadlinedTool {
+ async fn invoke(
+ &self,
+ _tool_calls: &[serde_json::Value],
+ ) -> Result<Vec<ToolOutcome>, String> {
+ Ok(Vec::new())
+ }
+ fn background_notices(&self) -> Vec<BackgroundNotice> {
+ if !*self.armed.lock().unwrap() {
+ return Vec::new();
+ }
+ let mut delivered = self.delivered.lock().unwrap();
+ if *delivered {
+ return Vec::new();
+ }
+ *delivered = true;
+ vec![BackgroundNotice {
+ headline: Some("Monitor mon-1: condition 'ok' matched".to_string()),
+ text: "Monitor 'mon-1' condition 'ok' matched on build.log:\nBUILD OK".to_string(),
+ }]
+ }
+ fn background_pending(&self) -> bool {
+ !*self.delivered.lock().unwrap()
+ }
+ async fn await_background(&self) {
+ *self.armed.lock().unwrap() = true;
+ }
+ }
+
+ /// A monitor match is delivered in both registers: the model gets the
+ /// `<SYSTEM>` reminder, the user gets the headline as a `Notice` event.
+ #[tokio::test]
+ async fn a_monitor_match_pings_the_model_and_shows_its_headline() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let model = MockModel::new(vec![final_answer("watching"), final_answer("reacted")]);
+ let tool = HeadlinedTool {
+ armed: StdMutex::new(false),
+ delivered: StdMutex::new(false),
+ };
+ let mut budget = SessionBudget::new(None);
+
+ run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ vec![json!({ "role": "user", "content": "watch the build" })],
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let requests = model.requests.lock().unwrap();
+ let sent = requests[1]["messages"].as_array().unwrap();
+ let last = sent.last().unwrap();
+ assert!(crate::core::agent::reminder::is_reminder_only(&last["content"]));
+ assert!(last["content"].as_str().unwrap().contains("BUILD OK"));
+
+ let mut saw_notice = false;
+ while let Ok(event) = rx.try_recv() {
+ if let StreamEvent::Notice { text } = event {
+ assert_eq!(text, "Monitor mon-1: condition 'ok' matched");
+ saw_notice = true;
+ }
+ }
+ assert!(saw_notice, "the headline must be emitted as a Notice event");
+ }
+
struct FixedTool {
content: String,
}
@@ -4715,6 +4974,9 @@ mod tests {
todo_registry: None,
grants: std::sync::Mutex::new(SessionGrants::default()),
subagents: None,
+ monitors: std::sync::Arc::new(
+ tauri_plugin_agent_tools::tools::monitor::MonitorSet::new(),
+ ),
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
}
@@ -5610,6 +5872,132 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ fn monitor_call(id: &str, args: serde_json::Value) -> serde_json::Value {
+ json!({
+ "id": id,
+ "type": "function",
+ "function": { "name": "monitor", "arguments": args.to_string() }
+ })
+ }
+
+ /// Starting a monitor schedules shell scripts, so it prompts like an exec
+ /// and a deny refuses without starting anything.
+ #[tokio::test]
+ async fn monitor_start_prompts_and_a_deny_refuses() {
+ let root = unique_project_root();
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let invoker = Arc::new(build_prompting_invoker(root.clone(), tx, registry.clone()));
+
+ let responder = {
+ let registry = registry.clone();
+ tokio::spawn(async move {
+ let (request_id, prompt_kind, command) = loop {
+ match rx.recv().await {
+ Some(StreamEvent::PermissionRequest {
+ request_id,
+ prompt_kind,
+ command,
+ ..
+ }) => break (request_id, prompt_kind, command),
+ Some(_) => continue,
+ None => panic!("no permission prompt for monitor start"),
+ }
+ };
+ assert_eq!(prompt_kind, "monitor");
+ let shown = command.as_deref().unwrap_or("");
+ assert!(
+ shown.contains("grep READY"),
+ "the prompt must show the scripts it approves: {command:?}"
+ );
+ assert!(
+ shown.contains("# watches boot.log"),
+ "the prompt shows command INSTEAD of path, so the watched \
+ file must ride along: {command:?}"
+ );
+ let tx = registry.lock().await.remove(&request_id).unwrap();
+ let _ = tx.send(PermissionDecision::Deny);
+ })
+ };
+
+ let out = invoker
+ .invoke(&[monitor_call(
+ "m1",
+ json!({
+ "op": "start",
+ "file": "boot.log",
+ "conditions": [{ "name": "ready", "script": "grep READY boot.log" }]
+ }),
+ )])
+ .await
+ .unwrap();
+ responder.await.unwrap();
+ assert!(out[0].content.contains("denied"), "got: {}", out[0].content);
+ assert!(!invoker.background_pending(), "nothing may have started");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ /// End to end through the invoker: an auto-approved start whose condition
+ /// already holds delivers a merged background notice carrying a headline
+ /// and the matched content, and the pending flag clears once all conditions
+ /// are met.
+ #[tokio::test]
+ async fn monitor_match_arrives_as_a_headlined_background_notice() {
+ let root = unique_project_root();
+ std::fs::write(root.join("boot.log"), "starting\nREADY on port 1337\n").unwrap();
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));
+ let mut invoker = build_prompting_invoker(root.clone(), tx, registry);
+ invoker.auto_approve = true;
+ // Bare shell: this exercises the loop wiring, not the jail.
+ invoker.sandbox = false;
+
+ let out = invoker
+ .invoke(&[monitor_call(
+ "m1",
+ json!({
+ "op": "start",
+ "file": "boot.log",
+ "conditions": [{ "name": "ready", "script": "grep READY boot.log" }]
+ }),
+ )])
+ .await
+ .unwrap();
+ assert!(
+ out[0].content.contains("monitor_id=mon-1"),
+ "got: {}",
+ out[0].content
+ );
+ assert!(invoker.background_pending());
+
+ let mut notices = Vec::new();
+ for _ in 0..200 {
+ notices = invoker.background_notices();
+ if !notices.is_empty() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ assert_eq!(notices.len(), 1, "one match, one ping");
+ assert!(
+ notices[0].headline.as_deref().unwrap_or("").contains("'ready' matched"),
+ "{:?}",
+ notices[0].headline
+ );
+ assert!(notices[0].text.contains("READY on port 1337"));
+ for _ in 0..200 {
+ if !invoker.background_pending() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ assert!(
+ !invoker.background_pending(),
+ "all conditions met, so the run must not stay parked"
+ );
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[tokio::test]
async fn auto_approve_writes_without_prompting() {
let root = unique_project_root();
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 637b87a16..075d71a98 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1384,6 +1384,9 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
Some(e) => eprintln!("\x1b[2m[subagent:{name}] failed: {e}\x1b[0m"),
None => eprintln!("\x1b[2m[subagent:{name}] finished\x1b[0m"),
},
+ StreamEvent::Notice { text } => {
+ eprintln!("\x1b[2m[notice] {text}\x1b[0m")
+ }
StreamEvent::Subagent { name, event, .. } => {
if let StreamEvent::ToolCall { name: tool, args, .. } = *event {
eprintln!(
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 0538b296b..d5d8c35ca 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -4837,6 +4837,14 @@ impl App {
};
self.push_subagent_summary(&name, calls, outcome);
}
+ // A background ping's headline (a monitor condition matching),
+ // emitted as the loop delivers the `<SYSTEM>` text to the model.
+ // Transient like every other note: not journaled.
+ StreamEvent::Notice { text } => {
+ self.finalize_tool_group();
+ self.flush_assistant();
+ self.note(&text);
+ }
StreamEvent::Subagent {
run_id,
name,
@@ -6147,11 +6155,42 @@ fn tool_activity(name: &str, args: &serde_json::Value) -> String {
}
"ask" => "Asking a question".to_string(),
"todo" => format!("{} {}", todo_op_verb(args, false), todo_target_label(args)),
+ "monitor" => monitor_activity(args, false),
// Skill/memory tools already produce active labels ("Updating memory: X").
_ => describe_tool_call(name, args),
}
}
+/// Present/past-tense label for a `monitor` tool call, keyed on its `op`.
+/// Without this the row falls through to the raw-JSON fallback, and a start's
+/// condition scripts make that a paragraph, not a label.
+fn monitor_activity(args: &serde_json::Value, past: bool) -> String {
+ let s = |k: &str| args.get(k).and_then(|v| v.as_str()).unwrap_or("");
+ match (s("op"), past) {
+ ("start", _) => {
+ let file = s("file");
+ let n = args
+ .get("conditions")
+ .and_then(|v| v.as_array())
+ .map(Vec::len)
+ .unwrap_or(0);
+ let verb = if past { "Started" } else { "Starting" };
+ let conditions = format!("({n} condition{})", if n == 1 { "" } else { "s" });
+ if file.is_empty() {
+ format!("{verb} a monitor {conditions}")
+ } else {
+ format!("{verb} a monitor on {file} {conditions}")
+ }
+ }
+ ("stop", false) => format!("Stopping monitor {}", s("monitor_id")),
+ ("stop", true) => format!("Stopped monitor {}", s("monitor_id")),
+ ("list", false) => "Listing monitors".to_string(),
+ ("list", true) => "Listed monitors".to_string(),
+ (_, false) => "Updating monitors".to_string(),
+ (_, true) => "Updated monitors".to_string(),
+ }
+}
+
/// Present/past-tense verb for a `todo` tool call, keyed on its `op` argument.
fn todo_op_verb(args: &serde_json::Value, past: bool) -> &'static str {
match (args.get("op").and_then(|v| v.as_str()).unwrap_or(""), past) {
@@ -6279,6 +6318,7 @@ fn tool_finished(name: &str, args: &serde_json::Value) -> String {
}
"ask" => "Asked a question".to_string(),
"todo" => format!("{} {}", todo_op_verb(args, true), todo_target_label(args)),
+ "monitor" => monitor_activity(args, true),
_ => describe_tool_call(name, args),
}
}
@@ -18977,6 +19017,37 @@ mod tests {
);
}
+ /// A `monitor` call must never fall through to the raw-JSON fallback: a
+ /// start's condition scripts make that a paragraph, not a label.
+ #[test]
+ fn monitor_calls_get_readable_labels() {
+ let start = json!({
+ "op": "start",
+ "file": "build.log",
+ "conditions": [
+ { "name": "ok", "script": "grep OK build.log" },
+ { "name": "fail", "script": "grep FAILED build.log" }
+ ]
+ });
+ assert_eq!(
+ tool_activity("monitor", &start),
+ "Starting a monitor on build.log (2 conditions)"
+ );
+ assert_eq!(
+ tool_finished("monitor", &start),
+ "Started a monitor on build.log (2 conditions)"
+ );
+ assert_eq!(
+ tool_activity("monitor", &json!({ "op": "stop", "monitor_id": "mon-2" })),
+ "Stopping monitor mon-2"
+ );
+ assert_eq!(
+ tool_finished("monitor", &json!({ "op": "stop", "monitor_id": "mon-2" })),
+ "Stopped monitor mon-2"
+ );
+ assert_eq!(tool_activity("monitor", &json!({ "op": "list" })), "Listing monitors");
+ }
+
#[test]
fn tool_finished_is_concise_past_tense() {
assert_eq!(