Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): hide .jan from the agent, and promote /init in the TUI (#8643)
Akarshan Biswas089c0623645c
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex 6c612359d..3bf03ee1a 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -292,7 +292,14 @@ pub async fn execute_tool(&SessionGrants::default(),) {Decision::Allow => {}- Decision::HardDeny => {+ Decision::HardDeny(gate::DenyReason::Hidden) => {+ return Err(format!(+ "tool '{name}' is denied: {} is the agent's own state directory and is hidden",+ crate::tools::sandbox::JAN_DIR+ )+ .into());+ }+ Decision::HardDeny(gate::DenyReason::Policy) => {return Err(format!("tool '{name}' is denied by policy").into());}// An exec prompt asks the user to vouch for a command that could reach@@ -812,7 +819,7 @@ mod tests {.await.expect_err("agent config must be hard-denied");assert!(- err.message.contains("denied by policy"),+ err.message.contains("is hidden"),"unexpected: {}",err.message);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rsindex 09616094c..94ab39976 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/gate.rs@@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};use crate::permissions::ToolPermissions;use crate::tools::cmdscan::{normalize, scan_command, CommandScan};use crate::tools::sandbox::{- command_touches_restricted_agent_path, escapes_project, is_restricted_agent_path,+ command_touches_hidden_jan_path, escapes_project, is_hidden_jan_path,};use crate::tools::{BuiltinTool, Capability};@@ -105,10 +105,22 @@ impl SessionGrants {}}+/// Why a call was refused outright. The reason reaches the model, and the two+/// cases need different wording: a policy deny is something the user can edit in+/// `agent.toml`, while a hidden path is structural -- telling the model to check+/// a deny list would send it reading a file that is itself hidden.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DenyReason {+ /// `[tools] deny` in agent.toml names this tool.+ Policy,+ /// The call reaches `<project>/.jan`, which is hidden from every tool.+ Hidden,+}+#[derive(Debug, PartialEq, Eq)]pub enum Decision {Allow,- HardDeny,+ HardDeny(DenyReason),Prompt(PromptKind),}@@ -127,25 +139,25 @@ pub fn resolve_decision(grants: &SessionGrants,) -> Decision {if perms.is_denied(tool.name) {- return Decision::HardDeny;+ return Decision::HardDeny(DenyReason::Policy);}- // Nothing under .jan/agent/ is reachable: skills/memory only through their- // dedicated tools, agent.toml and the dir listing not at all. Checked ahead- // of allow rules so an allowed tool name cannot bypass it.- let hits_restricted = tool.path_args.iter().any(|key| {+ // Nothing under .jan is reachable: skills/memory only through their+ // dedicated tools, config, threads and the dir listing not at all. Checked+ // ahead of allow rules so an allowed tool name cannot bypass it.+ let hits_hidden = tool.path_args.iter().any(|key| {args.get(key).and_then(|v| v.as_str())- .map(|p| is_restricted_agent_path(project_root, p))+ .map(|p| is_hidden_jan_path(project_root, p)).unwrap_or(false)});- let exec_hits_restricted = tool.capability == Capability::Exec+ let exec_hits_hidden = tool.capability == Capability::Exec&& args.get("command").and_then(|v| v.as_str())- .map(|c| command_touches_restricted_agent_path(project_root, c))+ .map(|c| command_touches_hidden_jan_path(project_root, c)).unwrap_or(false);- if hits_restricted || exec_hits_restricted {- return Decision::HardDeny;+ if hits_hidden || exec_hits_hidden {+ return Decision::HardDeny(DenyReason::Hidden);}if perms.is_allowed(tool.name) {return Decision::Allow;@@ -306,7 +318,11 @@ mod tests {&perms,&grants,);- assert_eq!(d, Decision::HardDeny, "deny in agent.toml must win for web tools");+ assert_eq!(+ d,+ Decision::HardDeny(DenyReason::Policy),+ "deny in agent.toml must win for web tools"+ );let _ = std::fs::remove_dir_all(&root);}@@ -326,7 +342,11 @@ mod tests {&perms,&grants,);- assert_eq!(d, Decision::HardDeny, "{tool} on agent.toml must be denied");+ assert_eq!(+ d,+ Decision::HardDeny(DenyReason::Hidden),+ "{tool} on agent.toml must be denied"+ );}// bash referencing it is denied too.let d = resolve_decision(@@ -336,7 +356,7 @@ mod tests {&perms,&grants,);- assert_eq!(d, Decision::HardDeny);+ assert_eq!(d, Decision::HardDeny(DenyReason::Hidden));// The instructions file is an ordinary project file at the root.std::fs::write(root.join("JAN.md"), b"x").unwrap();let d = resolve_decision(@@ -531,7 +551,11 @@ mod tests {&perms,&grants,);- assert_eq!(d, Decision::HardDeny, "{tool} on {path} must be denied");+ assert_eq!(+ d,+ Decision::HardDeny(DenyReason::Hidden),+ "{tool} on {path} must be denied"+ );}}let _ = std::fs::remove_dir_all(&root);@@ -561,7 +585,7 @@ mod tests {&denied,&grants,);- assert_eq!(d, Decision::HardDeny);+ assert_eq!(d, Decision::HardDeny(DenyReason::Policy));let _ = std::fs::remove_dir_all(&root);}@@ -577,7 +601,7 @@ mod tests {&perms,&grants,);- assert_eq!(d, Decision::HardDeny);+ assert_eq!(d, Decision::HardDeny(DenyReason::Policy));let _ = std::fs::remove_dir_all(&root);}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.rsindex 460eb0103..3ea2e6906 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@@ -15,7 +15,7 @@ use crate::memory;use crate::skills;use crate::tools::jail;use crate::tools::proc;-use crate::tools::sandbox::{escapes_project, is_restricted_agent_path};+use crate::tools::sandbox::{escapes_project, is_hidden_jan_path};use crate::tools::{BuiltinTool, ToolContext};const MAX_BYTES: usize = 64 * 1024;@@ -523,6 +523,11 @@ async fn ls(args: &serde_json::Value, root: &Path) -> String {loop {match entries.next_entry().await {Ok(Some(entry)) => {+ // Hidden state is omitted, not reported-then-denied: an entry the+ // agent can never open is only an invitation to try.+ if is_hidden_jan_path(root, &entry.path().to_string_lossy()) {+ continue;+ }let mut name = entry.file_name().to_string_lossy().into_owned();if entry.file_type().await.map(|t| t.is_dir()).unwrap_or(false) {name.push('/');@@ -647,7 +652,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// No confinement available means no shell: running unsandboxed would give the// command the whole machine, which is never what the caller asked for.- let mut policy = jail::Policy::new(root, ctx.allow_network).with_home_readonly(ctx.home_readonly);+ let mut policy = jail::Policy::new(root, ctx.allow_network)+ .with_home_readonly(ctx.home_readonly)+ .with_hide_root(&root.join(crate::tools::sandbox::JAN_DIR));if let Some(mask) = ctx.mask_root {policy = policy.with_mask_root(mask);}@@ -974,7 +981,7 @@ async fn find(args: &serde_json::Value, root: &Path) -> String {if entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {continue;}- if is_restricted_agent_path(&root_owned, &entry.path().to_string_lossy()) {+ if is_hidden_jan_path(&root_owned, &entry.path().to_string_lossy()) {continue;}let rel = rel_to(&base, entry.path());@@ -1094,7 +1101,7 @@ async fn grep(args: &serde_json::Value, root: &Path) -> String {if entry.file_type().map(|t| t.is_dir()).unwrap_or(true) {continue;}- if is_restricted_agent_path(&root_owned, &entry.path().to_string_lossy()) {+ if is_hidden_jan_path(&root_owned, &entry.path().to_string_lossy()) {continue;}if !search_file(entry.path(), &base) {@@ -1686,6 +1693,21 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// Hidden means absent from the listing, not present-but-unopenable: an+ /// entry the agent can never read is only an invitation to try.+ #[tokio::test]+ async fn ls_omits_the_hidden_jan_dir() {+ let root = unique_root();+ std::fs::create_dir_all(root.join(".jan/agent")).unwrap();+ std::fs::write(root.join("src.rs"), b"x").unwrap();+ std::fs::write(root.join("JAN.md"), b"x").unwrap();+ let out = execute_builtin(lookup("ls").unwrap(), &json!({}), &root).await;+ assert!(out.contains("src.rs"), "unexpected: {out}");+ assert!(out.contains("JAN.md"), "unexpected: {out}");+ assert!(!out.contains(".jan/"), "must not list the agent state dir: {out}");+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn find_glob_respects_gitignore() {let root = unique_root();@@ -1709,11 +1731,13 @@ mod tests {}#[tokio::test]- async fn find_does_not_leak_restricted_agent_tree() {+ async fn find_does_not_leak_the_hidden_jan_tree() {let root = unique_root();std::fs::create_dir_all(root.join(".jan/agent/threads/t1")).unwrap();std::fs::write(root.join(".jan/agent/threads/t1/thread.json"), b"{}").unwrap();std::fs::write(root.join(".jan/agent/agent.toml"), b"[tools]\n").unwrap();+ // Directly under `.jan`, outside `agent/`: hidden by the same rule.+ std::fs::write(root.join(".jan/stray.txt"), b"x").unwrap();std::fs::write(root.join("JAN.md"), b"instructions").unwrap();std::fs::write(root.join("README.md"), b"x").unwrap();let out =@@ -1734,11 +1758,15 @@ mod tests {!out.contains("agent.toml"),"must not leak agent config: {out}");+ assert!(+ !out.contains("stray.txt"),+ "the whole .jan dir is hidden, not just agent/: {out}"+ );let _ = std::fs::remove_dir_all(&root);}#[tokio::test]- async fn grep_does_not_leak_restricted_agent_contents() {+ async fn grep_does_not_leak_hidden_jan_contents() {let root = unique_root();std::fs::create_dir_all(root.join(".jan/agent/threads/t1")).unwrap();std::fs::write(diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rsindex 75571e447..0a0272efe 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs@@ -13,6 +13,9 @@//! interpreter, loader, and libraries.//! - writes: the thread workspace and a private temp dir, nothing else.//! - network: denied unless explicitly allowed.+//! - the agent's own `<workspace>/.jan` state directory is hidden even though it+//! sits inside the workspace ([`Policy::hide_root`]); AppContainer is the one+//! backend that cannot express it.//!//! AppContainer is stricter than that on reads: it can only read what grants//! `ALL APPLICATION PACKAGES`, which covers the system directories a process@@ -72,6 +75,11 @@ pub struct Policy {/// masking it would hide the very files the agent works on.pub mask_root: Option<PathBuf>,pub allow_network: bool,+ /// A path *inside* the workspace to hide from the shell: the agent's own+ /// `<project>/.jan` state directory. The workspace bind/allow makes the whole+ /// project reachable, so hiding it needs a rule layered on top -- see+ /// [`Policy::with_hide_root`].+ pub hide_root: Option<PathBuf>,/// Expose `$HOME` to the sandboxed shell read-only instead of hiding it./// The CLI turns this on so helpers that read the user's home (`git`/`ssh`/// credential helpers, `~/.ssh/config`, `~/.netrc`) work, while writes stay@@ -87,6 +95,7 @@ impl Policy {workspace: workspace.to_path_buf(),mask_root: None,allow_network,+ hide_root: None,home_readonly: false,}}@@ -100,6 +109,18 @@ impl Policy {self}+ /// Hide `hide_root` from the sandboxed shell. Applied after the workspace is+ /// bound/allowed, so it wins over it: the gate's token scan of the command+ /// string is best-effort, and this is what makes `.jan` unreachable to the+ /// spellings a scan cannot see (`cd .jan`, `$(echo ...)`, a script the shell+ /// writes and runs). Not enforced on AppContainer, where the workspace is+ /// granted by an ACE and carving a subpath back out would mean writing a deny+ /// ACE onto the user's directory; there the scan stands alone.+ pub fn with_hide_root(mut self, hide_root: &Path) -> Self {+ self.hide_root = Some(hide_root.to_path_buf());+ self+ }+/// Expose `$HOME` read-only instead of masking it. See [`Policy::home_readonly`].pub fn with_home_readonly(mut self, home_readonly: bool) -> Self {self.home_readonly = home_readonly;@@ -299,6 +320,14 @@ pub fn bwrap_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {}push(&mut args, &["--bind", &ws, &ws]);+ // After the workspace bind, so it is not shadowed by it: an empty tmpfs where+ // the agent's own state directory sits. Mounted unconditionally rather than+ // only when the directory exists, so a `.jan` created while the sandbox runs+ // cannot be read back by the next command in the same shell. Writes into it+ // are discarded with the sandbox (and hard-denied at the tool layer anyway).+ if let Some(hide) = &policy.hide_root {+ push(&mut args, &["--tmpfs", &hide.to_string_lossy()]);+ }push(&mut args, &["--chdir", &ws]);// Drops the network, pid, ipc, uts and cgroup namespaces along with the@@ -376,6 +405,14 @@ pub fn seatbelt_policy(policy: &Policy) -> String {(allow file-write* (subpath (param \"TMPDIR\")))\n\(allow file-write* (subpath \"/private/tmp\"))\n",);+ // Last, so it wins over the workspace allow above: the agent's own state+ // directory is neither readable nor writable, however the command spells it.+ if policy.hide_root.is_some() {+ p.push_str(+ "(deny file-read* (subpath (param \"HIDE_ROOT\")))\n\+ (deny file-write* (subpath (param \"HIDE_ROOT\")))\n",+ );+ }if policy.allow_network {p.push_str("(allow network*)\n\@@ -406,6 +443,9 @@ pub fn seatbelt_args(policy: &Policy, cfg: &ShellConfig) -> Vec<String> {if let Some(mask) = &policy.mask_root {args.push(format!("-DMASK_ROOT={}", mask.to_string_lossy()));}+ if let Some(hide) = &policy.hide_root {+ args.push(format!("-DHIDE_ROOT={}", hide.to_string_lossy()));+ }args.push(format!("-DTMPDIR={}",std::env::temp_dir().to_string_lossy()@@ -529,6 +569,42 @@ mod tests {assert!(ro.contains(&ro_bind), "{ro}");}+ /// The workspace bind makes the whole project reachable, so the mask must be+ /// layered on after it or it would be shadowed and silently do nothing.+ #[test]+ fn bwrap_hides_the_agent_state_dir_after_binding_the_workspace() {+ let ws = "/data/agent-workspace/threads/t1";+ let hide = format!("{ws}/.jan");+ let text = joined(&bwrap_args(+ &policy().with_hide_root(Path::new(&hide)),+ &cfg(),+ ));+ let bind = text.find(&format!("--bind {ws} {ws}")).expect("bind");+ let tmpfs = text.find(&format!("--tmpfs {hide}")).expect("hide tmpfs");+ assert!(bind < tmpfs, "the mask must follow the workspace bind: {text}");+ // Unset by default, so nothing is hidden where no state dir is named.+ assert!(!joined(&bwrap_args(&policy(), &cfg())).contains(".jan"));+ }++ #[test]+ fn seatbelt_denies_the_agent_state_dir_last() {+ let hide = "/data/agent-workspace/threads/t1/.jan";+ let p = policy().with_hide_root(Path::new(hide));+ let profile = seatbelt_policy(&p);+ let allow = profile+ .find("(allow file-read* (subpath (param \"WORKSPACE\")))")+ .expect("workspace allow");+ let deny = profile+ .find("(deny file-read* (subpath (param \"HIDE_ROOT\")))")+ .expect("hide deny");+ assert!(allow < deny, "later rules win, so the deny must come last");+ assert!(profile.contains("(deny file-write* (subpath (param \"HIDE_ROOT\")))"));+ // The path travels as a -D parameter, never interpolated into the profile.+ assert!(!profile.contains(hide), "{profile}");+ assert!(joined(&seatbelt_args(&p, &cfg())).contains(&format!("-DHIDE_ROOT={hide}")));+ assert!(!seatbelt_policy(&policy()).contains("HIDE_ROOT"));+ }+#[test]fn bwrap_denies_network_unless_allowed() {let denied = joined(&bwrap_args(&policy(), &cfg()));diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex 0039810d1..a94013e85 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -18,13 +18,19 @@ pub fn escapes_project(project_root: &Path, raw: &str) -> Result<bool, String> {Ok(!resolved.starts_with(&root))}-/// True iff `raw` resolves inside `<project_root>/.jan/agent/`. The `skills/`-/// and `memory/` workspaces are reachable only through the dedicated-/// skill_*/memory_* tools, never general read/write/edit/ls/find/grep/bash;-/// agent.toml and any other config are fully off-limits. The project-/// instructions file is `<project_root>/JAN.md`, an ordinary project file, so-/// the whole agent dir is opaque to the general filesystem tools.-pub fn is_restricted_agent_path(project_root: &Path, raw: &str) -> bool {+/// The agent's own state directory inside a project. Hidden wholesale rather+/// than per-subdirectory: it holds `agent.toml`, the skills/memory workspaces+/// (reachable only through the dedicated skill_*/memory_* tools), and the thread+/// store with the conversation's own transcripts. None of it is project source,+/// so a listing that shows it is noise at best and a self-referential read at+/// worst -- and anything added under it later is hidden by construction.+pub const JAN_DIR: &str = ".jan";++/// True iff `raw` resolves inside `<project_root>/.jan`. Hidden paths are not+/// merely denied: `ls`/`find`/`grep` omit them from their output, so the agent+/// never sees the directory exists. The project instructions file is+/// `<project_root>/JAN.md`, an ordinary project file, and is unaffected.+pub fn is_hidden_jan_path(project_root: &Path, raw: &str) -> bool {let Ok(root) = project_root.canonicalize() else {return false;};@@ -36,17 +42,20 @@ pub fn is_restricted_agent_path(project_root: &Path, raw: &str) -> bool {let Ok(resolved) = canonicalize_lenient(&abs) else {return false;};- resolved.starts_with(root.join(".jan").join("agent"))+ resolved.starts_with(root.join(JAN_DIR))}-/// True iff a shell command references a restricted agent path (best-effort token-/// scan). Splits on whitespace and shell metacharacters and checks each token so+/// True iff a shell command references a hidden path (best-effort token scan).+/// Splits on whitespace and shell metacharacters and checks each token so/// `cat .jan/agent/agent.toml` and its quoted/redirected variants are caught.-pub fn command_touches_restricted_agent_path(project_root: &Path, command: &str) -> bool {+/// Best-effort is enough only because the OS sandbox masks the directory too+/// (see [`super::jail::Policy::hide_root`]); this check exists to turn an+/// evasion-free attempt into a clear error instead of an empty directory.+pub fn command_touches_hidden_jan_path(project_root: &Path, command: &str) -> bool {command.split(|c: char| c.is_whitespace() || ";|&><()\"'`".contains(c)).filter(|t| !t.is_empty())- .any(|t| is_restricted_agent_path(project_root, t))+ .any(|t| is_hidden_jan_path(project_root, t))}/// Canonicalize a path that may not fully exist: canonicalize the deepest@@ -153,54 +162,59 @@ mod tests {#[test]- fn restricted_agent_path_covers_the_whole_agent_dir() {+ fn hidden_path_covers_the_whole_jan_dir() {let root = unique_root();std::fs::create_dir_all(root.join(".jan/agent/skills")).unwrap();std::fs::create_dir_all(root.join(".jan/agent/memory")).unwrap();+ std::fs::create_dir_all(root.join(".jan/agent/threads/t1")).unwrap();std::fs::write(root.join(".jan/agent/agent.toml"), b"x").unwrap();- // Restricted: agent.toml, the agent dir listing, unknown config files.- assert!(is_restricted_agent_path(&root, ".jan/agent/agent.toml"));- assert!(is_restricted_agent_path(&root, "./.jan/agent/agent.toml"));- assert!(is_restricted_agent_path(+ // Config, the agent dir listing, unknown config files.+ assert!(is_hidden_jan_path(&root, ".jan/agent/agent.toml"));+ assert!(is_hidden_jan_path(&root, "./.jan/agent/agent.toml"));+ assert!(is_hidden_jan_path(&root,root.join(".jan/agent/agent.toml").to_str().unwrap()));- assert!(is_restricted_agent_path(&root, ".jan/agent"));- assert!(is_restricted_agent_path(&root, ".jan/agent/secrets.env"));+ assert!(is_hidden_jan_path(&root, ".jan/agent"));+ assert!(is_hidden_jan_path(&root, ".jan/agent/secrets.env"));// skills/ and memory/ are reachable only via the dedicated tools, so they- // are restricted from the general filesystem tools too.- assert!(is_restricted_agent_path(&root, ".jan/agent/skills/deploy.md"));- assert!(is_restricted_agent_path(&root, ".jan/agent/memory/notes.md"));- // Nothing under .jan/agent/ is reachable; the instructions file now- // lives at the project root as JAN.md, an ordinary project file.- assert!(is_restricted_agent_path(&root, ".jan/agent/AGENT.md"));- assert!(!is_restricted_agent_path(&root, "JAN.md"));- assert!(!is_restricted_agent_path(&root, "src/main.rs"));- // The `.jan` dir itself is not restricted: threads and other project- // state outside `agent/` were never part of this carve-out.- assert!(!is_restricted_agent_path(&root, ".jan"));+ // are hidden from the general filesystem tools too.+ assert!(is_hidden_jan_path(&root, ".jan/agent/skills/deploy.md"));+ assert!(is_hidden_jan_path(&root, ".jan/agent/memory/notes.md"));+ assert!(is_hidden_jan_path(&root, ".jan/agent/AGENT.md"));+ // The whole `.jan` dir is hidden, not just `agent/`: the thread store+ // holds the running conversation's own transcripts, and future state+ // added beside it is covered without another carve-out.+ assert!(is_hidden_jan_path(&root, ".jan"));+ assert!(is_hidden_jan_path(&root, ".jan/agent/threads/t1"));+ // Ordinary project files, including the instructions file, are untouched.+ assert!(!is_hidden_jan_path(&root, "JAN.md"));+ assert!(!is_hidden_jan_path(&root, "src/main.rs"));+ // A sibling whose name merely starts with `.jan` is not inside it.+ assert!(!is_hidden_jan_path(&root, ".janitor"));let _ = std::fs::remove_dir_all(&root);}#[test]- fn command_scan_flags_restricted_agent_paths() {+ fn command_scan_flags_hidden_paths() {let root = unique_root();std::fs::create_dir_all(root.join(".jan/agent")).unwrap();std::fs::write(root.join(".jan/agent/agent.toml"), b"x").unwrap();- assert!(command_touches_restricted_agent_path(+ assert!(command_touches_hidden_jan_path(&root,"cat .jan/agent/agent.toml"));- assert!(command_touches_restricted_agent_path(+ assert!(command_touches_hidden_jan_path(&root,"grep foo < .jan/agent/agent.toml"));- assert!(command_touches_restricted_agent_path(+ assert!(command_touches_hidden_jan_path(&root,"cat .jan/agent/AGENT.md"));- assert!(!command_touches_restricted_agent_path(&root, "cat JAN.md"));- assert!(!command_touches_restricted_agent_path(&root, "ls -la src"));+ assert!(command_touches_hidden_jan_path(&root, "ls -la .jan"));+ assert!(!command_touches_hidden_jan_path(&root, "cat JAN.md"));+ assert!(!command_touches_hidden_jan_path(&root, "ls -la src"));let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 383dd582c..1056ec417 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -66,6 +66,15 @@ pub(crate) fn load_context_files(project_root: &Path) -> Option<String> {Some(block)}+/// Whether this project has usable instructions, by the same rule the system+/// prompt uses: a non-empty `JAN.md` at the root or in any ancestor. Drives the+/// `/init` invitation on the CLI splash, so an ancestor's file (a monorepo root)+/// correctly counts as already onboarded.+#[cfg(feature = "cli")]+pub(crate) fn has_context_file(project_root: &Path) -> bool {+ load_context_files(project_root).is_some()+}+/// Built-in guide teaching the model the skills/memory file conventions. Always/// injected for project runs so the model can read and maintain both without/// prior knowledge. Embedded in the binary at compile time.diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex dd88a735a..1934919ab 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -15,7 +15,7 @@ use tokio::sync::{mpsc, Mutex};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::session::SessionBudget;-use tauri_plugin_agent_tools::tools::gate::PermissionDecision;+use tauri_plugin_agent_tools::tools::gate::{DenyReason, PermissionDecision};use crate::core::agent::upstream::{collect_mcp_openai_tools, copy_optional_chat_params, execute_mcp_tool_calls,extract_choice_message, extract_tool_calls, load_assistant_config, parse_openai_messages,@@ -566,6 +566,25 @@ fn denied_by_policy_msg(name: &str, project_root: &std::path::Path) -> String {)}+/// Message for a call that reached the hidden agent state directory. Says the+/// path does not exist *for the agent* and that retrying is pointless: pointing+/// at a deny list would send the model reading a file that is hidden too.+fn hidden_path_msg(name: &str) -> String {+ format!(+ "ERROR: tool '{name}' refused: '{}' is the agent's own state directory and is not part of \+ the project. It is hidden from every tool -- do not try to reach it another way. Skills \+ and memory are available through the skill_*/memory_* tools.",+ tauri_plugin_agent_tools::tools::sandbox::JAN_DIR+ )+}++fn hard_deny_msg(name: &str, reason: DenyReason, project_root: &std::path::Path) -> String {+ match reason {+ DenyReason::Policy => denied_by_policy_msg(name, project_root),+ DenyReason::Hidden => hidden_path_msg(name),+ }+}+/// Rejection message for a mutation-capable tool call attempted in/// `RunMode::Plan`. Authoritative: the tool never actually runs.fn plan_mode_read_only_msg(name: &str) -> String {@@ -714,8 +733,8 @@ impl ToolInvoker for CompositeToolInvoker {&snapshot,);// Auto-approval suppresses every prompt (sandbox escape, write, exec) but- // still honors HardDeny, so the `.jan/agent` restricted-path invariant- // and explicit agent.toml denies hold.+ // still honors HardDeny, so the hidden `.jan` invariant and explicit+ // agent.toml denies hold.let decision = match decision {Decision::Prompt(_) if self.auto_approve => Decision::Allow,other => other,@@ -747,7 +766,9 @@ impl ToolInvoker for CompositeToolInvoker {}let (text, diff) = match decision {Decision::Allow => execute_builtin_with_diff(tool, &args, &self.tool_context()).await,- Decision::HardDeny => (denied_by_policy_msg(name, &self.project_root), None),+ Decision::HardDeny(reason) => {+ (hard_deny_msg(name, reason, &self.project_root), None)+ }Decision::Prompt(kind) => {let request_id = next_permission_id();let (tx, rx) = tokio::sync::oneshot::channel();diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 9c69267de..d3ff4c348 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -530,6 +530,7 @@ const BANNER_INDENT: u16 = 2;/// behind `/help` (see `SLASH_COMMANDS`).const BANNER_HINTS: &[(&str, &str)] = &[("/help", "commands"),+ ("/init", "onboard this project"),("/model", "switch model"),("/resume", "reopen a session"),("Ctrl-D", "quit"),@@ -2194,6 +2195,20 @@ impl App {}fn submit_user(&mut self, text: String) {+ self.submit_user_text(text, true)+ }++ /// Start a user turn whose text the model sees but the transcript never+ /// shows. For commands that expand into a long canned prompt (`/init`): the+ /// command's own note already says what is happening, and pasting the+ /// prompt body into the transcript is noise. Hidden turns leave+ /// `pending_images` staged for the user's next real message rather than+ /// attaching them to a prompt they did not write.+ fn submit_user_hidden(&mut self, text: String) {+ self.submit_user_text(text, false)+ }++ fn submit_user_text(&mut self, text: String, display: bool) {if self.model.is_empty() {self.note("not signed in — run /login to sign in to Tokamak first");return;@@ -2205,7 +2220,11 @@ impl App {return;}self.ensure_base_snapshot();- let images = std::mem::take(&mut self.pending_images);+ let images = if display {+ std::mem::take(&mut self.pending_images)+ } else {+ Vec::new()+ };let names: Vec<String> = images.iter().map(|i| i.name.clone()).collect();// Resolve @path file references before sendinglet (clean_text, injected_contents) =@@ -2216,13 +2235,15 @@ impl App {format!("{clean_text}\n\n---\nReferenced file contents:\n\n{injected_contents}")};self.history.push(build_user_message(&final_text, &images));- self.push_user_line(&text, &names);- // The typed text, not `final_text`: `@path` expansions are context for- // the model, and the row never showed them.- self.display_log.push(DisplayEntry::User {- text: text.clone(),- images: names,- });+ if display {+ self.push_user_line(&text, &names);+ // The typed text, not `final_text`: `@path` expansions are context+ // for the model, and the row never showed them.+ self.display_log.push(DisplayEntry::User {+ text: text.clone(),+ images: names,+ });+ }self.begin_turn();// A fresh user turn is new context: allow the next boundary to remind// again even if the open work is unchanged (dedup is "twice in a row"),@@ -4366,6 +4387,11 @@ pub async fn run(if app.model.is_empty() {app.note("not signed in — run /login to sign in to Tokamak, or `jan config set` to configure a provider manually");}+ // Only when there is nothing to load: a project that already has JAN.md needs+ // no invitation, and the splash hint covers re-running /init deliberately.+ if !crate::core::agent::context::has_context_file(&app.project_root) {+ app.note("no JAN.md here — run /init to study this project and write one");+ }// A failed resume is not fatal: the note explains why and the blank session// the user already has stays usable.if let Some(target) = &resume {@@ -5698,22 +5724,23 @@ multi-step recipe exists. Do not invent skills to fill space.\n\n\true beyond this session and not already stated in the code.\n\n\Then report what you wrote and why, briefly.";-/// `/init`: hand the model the onboarding task as an ordinary user turn, so it-/// runs with the normal toolset, permission gate, and transcript. Idle-only,-/// like the other commands that start a turn -- queueing it behind a running-/// turn would have it survey a project mid-change.+/// `/init`: hand the model the onboarding task as a user turn, so it runs with+/// the normal toolset, permission gate, and transcript. The prompt body itself+/// is hidden -- the note below is what the user asked for, the canned text is+/// not. Idle-only, like the other commands that start a turn -- queueing it+/// behind a running turn would have it survey a project mid-change.fn init_command(app: &mut App) {if app.status != Status::Idle {app.note("/init is only available while idle");return;}- let existing = app.project_root.join("JAN.md").exists();+ let existing = crate::core::agent::context::has_context_file(&app.project_root);app.note(if existing {"◈ init · reviewing JAN.md, skills, and memory for this project"} else {"◈ init · studying the project to write JAN.md, skills, and memory"});- app.submit_user(INIT_PROMPT.to_string());+ app.submit_user_hidden(INIT_PROMPT.to_string());}/// Manually compact the conversation: summarize older turns, keeping the recent@@ -10923,6 +10950,33 @@ mod tests {let _ = std::fs::remove_dir_all(&app.agent_dir);}+ /// The canned prompt is plumbing: the note announces `/init`, and neither+ /// the transcript nor the replayable journal carries the prompt body.+ #[test]+ fn init_keeps_the_prompt_out_of_the_transcript() {+ let mut app = test_app();+ app.pending_images.push(super::PendingImage {+ name: "shot.png".into(),+ data_url: "data:image/png;base64,AA".into(),+ });+ super::init_command(&mut app);+ let text: String = row_lines(&app.transcript)+ .iter()+ .flat_map(|l| l.spans.clone())+ .map(|s| s.content.to_string())+ .collect();+ assert!(!text.contains("Onboard yourself"), "{text}");+ assert!(text.contains("init ·"), "{text}");+ assert!(+ !app.display_log+ .iter()+ .any(|e| matches!(e, DisplayEntry::User { .. })),+ "a hidden turn must not journal a user row"+ );+ assert_eq!(app.pending_images.len(), 1, "staged images stay staged");+ let _ = std::fs::remove_dir_all(&app.agent_dir);+ }+/// Surveying a project while a turn is mid-change would onboard against a/// moving target, so the command declines rather than queueing.#[test]@@ -15698,6 +15752,33 @@ mod tests {);}+ /// `/init` is the first thing a new project wants and is invisible unless+ /// promoted, so the splash lists it beside `/help`.+ #[test]+ fn banner_promotes_init() {+ let mut app = test_app();+ app.push_banner("--safe", true);+ let joined = banner_text(&app, 90).join("\n");+ assert!(joined.contains("/init"), "{joined}");+ assert!(joined.contains("onboard this project"), "{joined}");+ }++ /// The invitation is conditional on the same rule the system prompt uses, so+ /// an already-onboarded project (its own JAN.md, or an ancestor's) is quiet.+ #[test]+ fn init_invitation_tracks_whether_the_project_has_instructions() {+ let root = std::env::temp_dir().join(format!("jan_init_invite_{}", std::process::id()));+ let nested = root.join("pkg");+ std::fs::create_dir_all(&nested).unwrap();+ assert!(!crate::core::agent::context::has_context_file(&nested));+ std::fs::write(root.join("JAN.md"), "ROOT_RULES").unwrap();+ assert!(+ crate::core::agent::context::has_context_file(&nested),+ "an ancestor's JAN.md already onboards this project"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn a_seeded_session_is_not_invited_to_type() {let mut app = test_app();