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): configurable shell env pass-through on top of the deny-by-default base

Akarshan Biswas846d8f084e70
diff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdx
index f8ae2b1b6..f4b19c303 100644
--- a/docs/src/pages/docs/agent/permissions.mdx
+++ b/docs/src/pages/docs/agent/permissions.mdx
@@ -141,6 +141,35 @@ permanently would leave no way to run a single command without it.
`backend` is the confinement that *would* be used. `none` means none is available on this machine -
with `enabled: true` that combination is what withholds `bash` entirely.
+### The shell environment
+
+The shell does **not** inherit your full environment. Jan starts it from a minimal base -
+`PATH`, `HOME`, `TMPDIR`, locale, and the Windows system keys - so a secret in your environment
+(`OPENAI_API_KEY`, `SSH_AUTH_SOCK`, and the like) never reaches a command the model runs, whether or
+not the sandbox is on. This is deliberate, but it also means a command that needs a variable you
+rely on (a proxy setting, `git` config, a toolchain home) will not see it.
+
+Two keys widen it, without giving up the default:
+
+```toml
+# .jan/agent/agent.toml (per project) or ~/.jan/config.toml (all projects)
+[tools]
+# Host variables the shell may inherit. Exact names or a "*" wildcard.
+env_passthrough = ["SSH_AUTH_SOCK", "GIT_*", "http_proxy", "https_proxy"]
+
+# Explicit values, set regardless of your environment.
+[tools.env_set]
+RUST_LOG = "info"
+```
+
+- `env_passthrough` copies the named host variables in if they are set. The two scopes merge: the
+ global list and the project list both apply.
+- A **secret-looking** name (containing `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `PASSWD`, or
+ `CREDENTIAL`, case-insensitive) is never copied by a wildcard - so a broad `GIT_*` cannot leak a
+ `GIT_TOKEN`. To pass one deliberately, name it in `env_set`, which is not filtered.
+- `env_set` wins over `env_passthrough` and over the global value for the same key. Under the
+ sandbox, `TMPDIR`/`TMP`/`TEMP` are always pointed at the run's scratch directory regardless.
+
## Network access
Network access is a property of the sandbox, so it applies when the sandbox is on. Unconfined, a
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index 4a8fdab0e..c27138b26 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -84,6 +84,9 @@ allow = []
deny = []
allow_write = []
# sandbox = true
+# env_passthrough = ["SSH_AUTH_SOCK", "GIT_*"]
+# [tools.env_set]
+# RUST_LOG = "info"
[skills]
enabled = []
@@ -123,6 +126,11 @@ See [Tool permissions](/docs/agent/permissions#project-policy). `sandbox` is how
[shell confinement](/docs/agent/permissions#the-shell-sandbox) for everyone who checks it out; it is
off by default on the CLI.
+| Key | Default | Description |
+| --- | --- | --- |
+| `env_passthrough` | `[]` | Host environment variables the shell may inherit beyond the minimal base (exact names or a `*` wildcard). Merged with `~/.jan/config.toml`. A secret-looking name is never copied by a wildcard - see [The shell environment](/docs/agent/permissions#the-shell-environment) |
+| `env_set` | `{}` | Explicit `key = "value"` pairs for the shell env, as a `[tools.env_set]` table. Wins over `env_passthrough` and the global value; the way to inject a secret-named variable on purpose |
+
### `[skills]`
See [Skills](/docs/agent/skills#controlling-which-are-active).
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 5b532bba1..e53d6a876 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
@@ -835,7 +835,8 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {
Ok(v) => v,
Err(e) => return e,
};
- let child = match proc::spawn(&shell, command, root, sandbox_tmp.as_deref()).await {
+ let child = match proc::spawn(&shell, command, root, sandbox_tmp.as_deref(), ctx.shell_env()).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/jail.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/jail.rs
index 2ee6f1def..b957dc692 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
@@ -1197,9 +1197,15 @@ mod enforcement_tests {
let wrapped = wrap(super::super::proc::shell(), &policy).expect("backend");
// Mirrors the bash handler: the temp env follows what the backend mounts.
let tmp = scratch_env_path(backend(), &policy);
- let child = super::super::proc::spawn(&wrapped, command, ws, tmp.as_deref())
- .await
- .expect("spawn");
+ let child = super::super::proc::spawn(
+ &wrapped,
+ command,
+ ws,
+ tmp.as_deref(),
+ super::super::proc::ShellEnv::default(),
+ )
+ .await
+ .expect("spawn");
let pid = child.id();
let out = child.wait_with_output().await.expect("wait");
if let Some(pid) = pid {
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 4a1f23995..2070b9191 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
@@ -123,6 +123,15 @@ pub struct ToolContext<'a> {
/// frontend's tool-call id) rather than inside `bash`, so the sink can carry
/// it from the first chunk.
pub call_id: Option<&'a str>,
+ /// Host env-var names (exact or `*`-glob) the shell may inherit on top of the
+ /// fixed base allowlist. Empty on every surface that has not configured any,
+ /// so the shell env is unchanged by default. Resolved once per run from
+ /// `[tools].env_passthrough`; secret-looking names are never copied by a glob.
+ pub env_passthrough: &'a [String],
+ /// Explicit key=value pairs injected into the shell env, from
+ /// `[tools].env_set`. Applied after `env_passthrough` and winning per key;
+ /// the one way to inject a secret-named variable on purpose.
+ pub env_set: &'a [(String, String)],
}
impl std::fmt::Debug for ToolContext<'_> {
@@ -143,6 +152,8 @@ impl std::fmt::Debug for ToolContext<'_> {
.field("read_roots", &self.read_roots)
.field("write_roots", &self.write_roots)
.field("call_id", &self.call_id)
+ .field("env_passthrough", &self.env_passthrough)
+ .field("env_set", &self.env_set)
.finish()
}
}
@@ -167,6 +178,29 @@ impl<'a> ToolContext<'a> {
read_roots: &[],
write_roots: &[],
call_id: None,
+ env_passthrough: &[],
+ env_set: &[],
+ }
+ }
+
+ /// Host env-var names the shell may inherit beyond the base allowlist. See
+ /// [`Self::env_passthrough`].
+ pub fn with_env_passthrough(mut self, names: &'a [String]) -> Self {
+ self.env_passthrough = names;
+ self
+ }
+
+ /// Explicit key=value pairs injected into the shell env. See [`Self::env_set`].
+ pub fn with_env_set(mut self, set: &'a [(String, String)]) -> Self {
+ self.env_set = set;
+ self
+ }
+
+ /// The shell env policy this context carries, for [`crate::tools::proc::spawn`].
+ pub fn shell_env(&self) -> crate::tools::proc::ShellEnv<'a> {
+ crate::tools::proc::ShellEnv {
+ passthrough: self.env_passthrough,
+ set: self.env_set,
}
}
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
index d4ed4963b..439a61811 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs
@@ -478,10 +478,15 @@ fn match_update(monitor_id: &str, name: &str, content: &str) -> MonitorUpdate {
async fn eval_script(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 mut child = crate::tools::proc::spawn(
+ &shell,
+ script,
+ &ctx.project_root,
+ sandbox_tmp.as_deref(),
+ tool_ctx.shell_env(),
+ )
+ .await
+ .ok()?;
let pid = child.id();
let result = tokio::time::timeout(EVAL_TIMEOUT, async {
let stdout = child.stdout.take();
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
index 62d654136..d1efb6681 100644
--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs
@@ -25,6 +25,18 @@ pub struct ShellConfig {
pub description: &'static str,
}
+/// User-configured additions to the shell's environment, layered on top of the
+/// fixed [`SANDBOX_ENV_ALLOW`] base. Empty by default, so an unconfigured run is
+/// byte-for-byte unchanged. `passthrough` copies host vars by exact name or
+/// `*`-glob; `set` injects explicit key=value pairs and wins per key. Secret-
+/// looking names (`*KEY*`, `*TOKEN*`, ...) are never copied by `passthrough` --
+/// only an explicit `set` can inject one, which names it on purpose.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct ShellEnv<'a> {
+ pub passthrough: &'a [String],
+ pub set: &'a [(String, String)],
+}
+
/// Resolved shell for this process, computed once. Prefers a real `bash`
/// (matching the tool's name and documented guidance) and falls back to a
/// POSIX `sh`/`cmd` only when no bash is found.
@@ -223,11 +235,81 @@ fn confine_limits(cmd: &mut Command) {
}
}
+/// Case-insensitive markers a `passthrough` glob must never copy, so a broad
+/// pattern (`GIT_*`, `*`) cannot leak a credential into the shell. To inject one
+/// on purpose, name it in [`ShellEnv::set`], which is not scrubbed.
+fn is_secret_name(name: &str) -> bool {
+ const MARKERS: &[&str] = &["KEY", "SECRET", "TOKEN", "PASSWORD", "PASSWD", "CREDENTIAL"];
+ let upper = name.to_ascii_uppercase();
+ MARKERS.iter().any(|m| upper.contains(m))
+}
+
+/// Minimal case-insensitive `*`-glob, the one wildcard an env-var allowlist
+/// needs. `*` matches any run (including empty); every other character is
+/// literal. No `?`/`[]` -- env-var names do not use them.
+fn glob_match(pattern: &str, name: &str) -> bool {
+ let p = pattern.to_ascii_uppercase();
+ let n = name.to_ascii_uppercase();
+ if !p.contains('*') {
+ return p == n;
+ }
+ let parts: Vec<&str> = p.split('*').collect();
+ let last = parts.len() - 1;
+ let mut pos = 0usize;
+ for (i, part) in parts.iter().enumerate() {
+ if part.is_empty() {
+ continue;
+ }
+ if i == 0 {
+ if !n[pos..].starts_with(part) {
+ return false;
+ }
+ pos += part.len();
+ } else if i == last {
+ if !n[pos..].ends_with(part) {
+ return false;
+ }
+ } else {
+ match n[pos..].find(part) {
+ Some(idx) => pos += idx + part.len(),
+ None => return false,
+ }
+ }
+ }
+ true
+}
+
+/// The env additions for a run: host vars matched by `passthrough` (minus
+/// secret-looking names) followed by `set`, which wins per key. Pure over its
+/// `host` input so it is unit-tested without spawning a shell.
+pub(crate) fn resolve_env_overrides<I>(host: I, env: ShellEnv<'_>) -> Vec<(String, String)>
+where
+ I: IntoIterator<Item = (String, String)>,
+{
+ let mut out: Vec<(String, String)> = Vec::new();
+ if !env.passthrough.is_empty() {
+ for (name, val) in host {
+ if is_secret_name(&name) {
+ continue;
+ }
+ if env.passthrough.iter().any(|p| glob_match(p, &name)) {
+ out.push((name, val));
+ }
+ }
+ }
+ for (key, val) in env.set {
+ out.retain(|(n, _)| n != key);
+ out.push((key.clone(), val.clone()));
+ }
+ out
+}
+
pub async fn spawn(
cfg: &ShellConfig,
command: &str,
cwd: &Path,
scratch: Option<&Path>,
+ env: ShellEnv<'_>,
) -> std::io::Result<Child> {
let mut cmd = Command::new(&cfg.program);
cmd.args(&cfg.args);
@@ -243,6 +325,13 @@ pub async fn spawn(
cmd.env(key, val);
}
}
+ // Layer the run's configured pass-through and explicit overrides on top of
+ // the base allowlist. Deny-by-default is preserved: nothing here is copied
+ // unless the config named it, and a secret-looking host var is never copied
+ // by a glob (see [`resolve_env_overrides`]).
+ for (key, val) in resolve_env_overrides(std::env::vars(), env) {
+ cmd.env(key, val);
+ }
// Point the shell's temp env at the session scratch, overriding the host
// values the allowlist just copied in. Without this a command that writes
// through `mktemp`/`$TMPDIR` lands in the host temp dir -- unreachable to
@@ -380,7 +469,7 @@ mod tests {
#[tokio::test]
async fn runs_a_command_and_captures_stdout() {
- let child = spawn(shell(), "echo hello", &tmp(), None).await.unwrap();
+ let child = spawn(shell(), "echo hello", &tmp(), None, ShellEnv::default()).await.unwrap();
let pid = child.id().unwrap();
let out = child.wait_with_output().await.unwrap();
unregister(pid);
@@ -399,6 +488,7 @@ mod tests {
"echo \"$TMPDIR $TMP $TEMP\"",
&tmp(),
Some(&scratch),
+ ShellEnv::default(),
)
.await
.unwrap();
@@ -417,7 +507,7 @@ mod tests {
/// through, rather than being handed an empty temp dir.
#[tokio::test]
async fn temp_env_is_left_alone_without_a_scratch() {
- let child = spawn(shell(), "echo ${TMPDIR:-unset}", &tmp(), None)
+ let child = spawn(shell(), "echo ${TMPDIR:-unset}", &tmp(), None, ShellEnv::default())
.await
.unwrap();
let pid = child.id().unwrap();
@@ -431,7 +521,7 @@ mod tests {
async fn kill_tree_reaps_backgrounded_grandchild() {
// The shell backgrounds a long sleeper, prints its pid, then waits on
// it. Killing the group must take down that grandchild too.
- let mut child = spawn(shell(), "sleep 300 & echo $! ; wait", &tmp(), None)
+ let mut child = spawn(shell(), "sleep 300 & echo $! ; wait", &tmp(), None, ShellEnv::default())
.await
.unwrap();
let leader = child.id().unwrap();
@@ -476,14 +566,14 @@ mod tests {
async fn confine_limits_caps_the_child_process_count() {
// The rlimit mounting must actually reach the spawned child: with NPROC
// clamped we still run up to the cap, but a fork-bomb past it fails.
- let child = spawn(shell(), "exit 0", &tmp(), None).await.unwrap();
+ let child = spawn(shell(), "exit 0", &tmp(), None, ShellEnv::default()).await.unwrap();
let pid = child.id().unwrap();
child.wait_with_output().await.unwrap();
unregister(pid);
// Spawn a shell that reports its own soft NOFILE limit; confine_limits
// sets it to 1024, which should be visible inside the sandbox.
- let child = spawn(shell(), "ulimit -n", &tmp(), None).await.unwrap();
+ let child = spawn(shell(), "ulimit -n", &tmp(), None, ShellEnv::default()).await.unwrap();
let pid = child.id().unwrap();
let out = child.wait_with_output().await.unwrap();
unregister(pid);
@@ -491,3 +581,77 @@ mod tests {
assert_eq!(val, "1024", "NOFILE soft limit should be capped, got: {val}");
}
}
+
+#[cfg(test)]
+mod env_policy_tests {
+ use super::*;
+
+ fn host(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
+ pairs
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+ }
+
+ #[test]
+ fn glob_matches_prefix_suffix_and_infix_case_insensitively() {
+ assert!(glob_match("GIT_*", "GIT_AUTHOR_NAME"));
+ assert!(glob_match("git_*", "GIT_AUTHOR_NAME"));
+ assert!(glob_match("*_PROXY", "http_proxy".to_ascii_uppercase().as_str()));
+ assert!(glob_match("*PROXY*", "HTTPS_PROXY_HOST"));
+ assert!(glob_match("*", "ANYTHING"));
+ assert!(glob_match("PATH", "PATH"));
+ assert!(!glob_match("GIT_*", "CARGO_HOME"));
+ assert!(!glob_match("PATH", "PATHEXT"));
+ }
+
+ #[test]
+ fn secret_names_are_recognized() {
+ for name in ["OPENAI_API_KEY", "MY_SECRET", "GH_TOKEN", "DB_PASSWORD", "aws_credential"] {
+ assert!(is_secret_name(name), "{name} should read as secret");
+ }
+ for name in ["PATH", "HOME", "GIT_AUTHOR_NAME", "RUST_LOG"] {
+ assert!(!is_secret_name(name), "{name} should not read as secret");
+ }
+ }
+
+ #[test]
+ fn empty_policy_copies_nothing() {
+ let out = resolve_env_overrides(host(&[("PATH", "/bin"), ("FOO", "bar")]), ShellEnv::default());
+ assert!(out.is_empty());
+ }
+
+ #[test]
+ fn passthrough_copies_matches_and_skips_secret_named_vars() {
+ let pats = vec!["GIT_*".to_string(), "CARGO_HOME".to_string()];
+ let env = ShellEnv { passthrough: &pats, set: &[] };
+ let out = resolve_env_overrides(
+ host(&[
+ ("GIT_AUTHOR_NAME", "Ada"),
+ ("GIT_TOKEN", "leak"), // matches GIT_* but is secret-named
+ ("CARGO_HOME", "/c"),
+ ("UNRELATED", "x"),
+ ]),
+ env,
+ );
+ assert!(out.contains(&("GIT_AUTHOR_NAME".into(), "Ada".into())));
+ assert!(out.contains(&("CARGO_HOME".into(), "/c".into())));
+ assert!(!out.iter().any(|(k, _)| k == "GIT_TOKEN"), "secret-named var must not leak");
+ assert!(!out.iter().any(|(k, _)| k == "UNRELATED"));
+ }
+
+ #[test]
+ fn set_wins_over_passthrough_and_injects_verbatim() {
+ let pats = vec!["RUST_LOG".to_string()];
+ let set = vec![
+ ("RUST_LOG".to_string(), "debug".to_string()),
+ ("GH_TOKEN".to_string(), "explicit".to_string()), // secret-named but user-named
+ ];
+ let env = ShellEnv { passthrough: &pats, set: &set };
+ let out = resolve_env_overrides(host(&[("RUST_LOG", "info")]), env);
+ // Only one RUST_LOG, and it is the set value.
+ assert_eq!(out.iter().filter(|(k, _)| k == "RUST_LOG").count(), 1);
+ assert!(out.contains(&("RUST_LOG".into(), "debug".into())));
+ assert!(out.contains(&("GH_TOKEN".into(), "explicit".into())));
+ }
+}
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rs
index 122fd83fb..a70303b20 100644
--- a/src-tauri/src/core/agent/global_config.rs
+++ b/src-tauri/src/core/agent/global_config.rs
@@ -3,6 +3,7 @@
//! just one project. Optional: a missing file yields an empty provider set,
//! not an error.
+use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::PathBuf;
@@ -108,6 +109,17 @@ struct GlobalConfigToml {
/// one cell.
#[serde(default, skip_serializing_if = "Option::is_none")]
wave: Option<String>,
+ /// Host env-var names (exact or `*`-glob) the sandboxed `bash` may inherit
+ /// beyond the fixed base allowlist. Empty by default, so the shell env is
+ /// unchanged. Merged with a project's `[tools].env_passthrough`; a secret-
+ /// looking name is never copied by a glob (use `env_set` to inject one).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ env_passthrough: Vec<String>,
+ /// Explicit key=value pairs injected into the `bash` env, winning over
+ /// `env_passthrough` and over a project's per-key value. The one way to
+ /// inject a secret-named variable on purpose.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ env_set: BTreeMap<String, String>,
#[serde(default)]
providers: HashMap<String, GlobalProviderEntry>,
}
@@ -276,6 +288,25 @@ pub(crate) fn sandbox_setting() -> Option<bool> {
load_raw().ok().and_then(|config| config.sandbox)
}
+/// Host env-var names the sandboxed `bash` may inherit beyond the base
+/// allowlist (`env_passthrough` in `~/.jan/config.toml`), merged under a
+/// project's `[tools].env_passthrough`. Empty on an unreadable or malformed
+/// config: a shell-env preference must never block a session from starting.
+pub(crate) fn env_passthrough_setting() -> Vec<String> {
+ load_raw()
+ .map(|config| config.env_passthrough)
+ .unwrap_or_default()
+}
+
+/// Explicit key=value overrides for the `bash` env (`env_set` in
+/// `~/.jan/config.toml`), sorted by key. Same fail-open rationale as
+/// [`env_passthrough_setting`].
+pub(crate) fn env_set_setting() -> Vec<(String, String)> {
+ load_raw()
+ .map(|config| config.env_set.into_iter().collect())
+ .unwrap_or_default()
+}
+
/// Whether inline `<think>` tags in model content are parsed as reasoning
/// (`think_tags` in `~/.jan/config.toml`), defaulting to on. `false` makes the
/// tags ordinary prose: rendered verbatim, kept in the answer sent back as
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 4dbb73c40..4c6c93f9b 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -335,6 +335,11 @@ struct CompositeToolInvoker {
/// (see `workspace::scratch_dir`), so `bash` scratch files persist across
/// calls for the whole run. Created at run start and wiped at run end.
scratch_root: std::path::PathBuf,
+ /// Host env-var names/globs the shell may inherit beyond the base allowlist,
+ /// and explicit key=value overrides. Resolved once per run by merging
+ /// `~/.jan/config.toml` with the project's `[tools]` section.
+ env_passthrough: Vec<String>,
+ env_set: Vec<(String, String)>,
permissions: tauri_plugin_agent_tools::permissions::ToolPermissions,
events: mpsc::UnboundedSender<StreamEvent>,
permission_requests: PermissionRegistry,
@@ -461,6 +466,8 @@ struct ResolvedSettings {
allow_network: bool,
allow_home_read: bool,
sandbox: bool,
+ env_passthrough: Vec<String>,
+ env_set: Vec<(String, String)>,
}
/// Kept out of the invoker's struct literal so it is reachable from a test.
@@ -476,6 +483,72 @@ fn resolve_run_settings(
allow_network: resolve_allow_network(settings.allow_network),
allow_home_read: resolve_allow_home_read(settings.allow_home_read),
sandbox: resolve_sandbox(sandbox_flag, settings.sandbox),
+ env_passthrough: resolve_env_passthrough(settings.env_passthrough),
+ env_set: resolve_env_set(settings.env_set),
+ }
+}
+
+/// Merge the global `env_passthrough` with the project's: the union of both
+/// name lists (order-preserving, global first), since each entry is only a name
+/// to match against the host env. The global scope is the CLI's
+/// `~/.jan/config.toml`; the desktop has none, so it contributes nothing there.
+fn resolve_env_passthrough(project: Vec<String>) -> Vec<String> {
+ #[cfg(feature = "cli")]
+ let global = crate::core::agent::global_config::env_passthrough_setting();
+ #[cfg(not(feature = "cli"))]
+ let global = Vec::new();
+ merge_env_passthrough(global, project)
+}
+
+/// Merge the global `env_set` with the project's, the project winning per key.
+/// Global scope is CLI-only (see [`resolve_env_passthrough`]).
+fn resolve_env_set(project: Vec<(String, String)>) -> Vec<(String, String)> {
+ #[cfg(feature = "cli")]
+ let global = crate::core::agent::global_config::env_set_setting();
+ #[cfg(not(feature = "cli"))]
+ let global = Vec::new();
+ merge_env_set(global, project)
+}
+
+fn merge_env_passthrough(mut global: Vec<String>, project: Vec<String>) -> Vec<String> {
+ global.extend(project);
+ global
+}
+
+fn merge_env_set(
+ mut global: Vec<(String, String)>,
+ project: Vec<(String, String)>,
+) -> Vec<(String, String)> {
+ for (key, val) in project {
+ global.retain(|(existing, _)| existing != &key);
+ global.push((key, val));
+ }
+ global
+}
+
+#[cfg(test)]
+mod env_merge_tests {
+ use super::{merge_env_passthrough, merge_env_set};
+
+ fn s(v: &str) -> String {
+ v.to_string()
+ }
+
+ #[test]
+ fn passthrough_is_the_union_global_first() {
+ let out = merge_env_passthrough(vec![s("GIT_*")], vec![s("CARGO_HOME")]);
+ assert_eq!(out, vec![s("GIT_*"), s("CARGO_HOME")]);
+ }
+
+ #[test]
+ fn env_set_project_wins_per_key() {
+ let global = vec![(s("RUST_LOG"), s("info")), (s("A"), s("g"))];
+ let project = vec![(s("RUST_LOG"), s("debug")), (s("B"), s("p"))];
+ let out = merge_env_set(global, project);
+ assert!(out.contains(&(s("A"), s("g"))));
+ assert!(out.contains(&(s("B"), s("p"))));
+ assert!(out.contains(&(s("RUST_LOG"), s("debug"))));
+ assert_eq!(out.iter().filter(|(k, _)| k == "RUST_LOG").count(), 1);
}
}
@@ -527,6 +600,8 @@ impl CompositeToolInvoker {
.with_home_readonly(self.allow_home_read)
.with_sandbox(self.sandbox)
.with_scratch_root(&self.scratch_root)
+ .with_env_passthrough(&self.env_passthrough)
+ .with_env_set(&self.env_set)
}
/// A tool context whose output streams to the run's event channel as
@@ -2118,6 +2193,8 @@ async fn orchestrate_inner(
allow_home_read: settings.allow_home_read,
sandbox: settings.sandbox,
scratch_root: scratch_root.clone(),
+ env_passthrough: settings.env_passthrough,
+ env_set: settings.env_set,
project_root: root.clone(),
permissions: permissions.clone(),
events: events.clone(),
@@ -5095,6 +5172,8 @@ mod tests {
allow_network: DEFAULT_ALLOW_NETWORK,
allow_home_read: DEFAULT_ALLOW_HOME_READ,
scratch_root: tauri_plugin_agent_tools::workspace::scratch_dir("test-session"),
+ env_passthrough: Vec::new(),
+ env_set: Vec::new(),
project_root: root,
// Read-only default => write PROMPTS.
permissions: ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]),
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index c22441f23..d876ba227 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -1,5 +1,6 @@
//! `agent.toml` project config parsing and `.jan/agent/` scaffolding.
+use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::Deserialize;
@@ -156,6 +157,15 @@ pub(crate) struct ToolsSection {
/// checks it out.
#[serde(default)]
pub sandbox: Option<bool>,
+ /// Host env-var names (exact or `*`-glob) the sandboxed `bash` may inherit
+ /// beyond the fixed base allowlist, merged over `~/.jan/config.toml`. Empty
+ /// by default; a secret-looking name is never copied by a glob.
+ #[serde(default)]
+ pub env_passthrough: Vec<String>,
+ /// Explicit key=value pairs injected into the `bash` env, winning over
+ /// `env_passthrough` and over the global value for the same key.
+ #[serde(default)]
+ pub env_set: BTreeMap<String, String>,
}
const AGENT_TOML_TEMPLATE: &str = r#"[agent]
@@ -207,6 +217,15 @@ allow_write = []
# ~/.jan/config.toml; the desktop always confines. Set it here to require
# confinement for anyone working in this project.
# sandbox = true
+# Host environment variables the shell may inherit beyond the minimal base
+# (PATH, HOME, TMPDIR, ...). Names are exact or use a "*" wildcard; merged with
+# ~/.jan/config.toml. A secret-looking name (*KEY*, *TOKEN*, ...) is never
+# copied by a wildcard -- inject one deliberately with env_set below.
+# env_passthrough = ["SSH_AUTH_SOCK", "GIT_*", "http_proxy", "https_proxy"]
+# Explicit values for the shell env; win over env_passthrough and the global
+# value for the same key.
+# [tools.env_set]
+# RUST_LOG = "info"
[skills]
enabled = []
@@ -245,6 +264,11 @@ pub(crate) struct RunSettings {
/// `[tools].sandbox`; `None` when unset, so the caller applies the default
/// appropriate to its surface.
pub sandbox: Option<bool>,
+ /// `[tools].env_passthrough`: host env-var names/globs the shell may inherit
+ /// beyond the base allowlist. Merged with the global setting by the caller.
+ pub env_passthrough: Vec<String>,
+ /// `[tools].env_set`: explicit shell-env overrides, sorted by key.
+ pub env_set: Vec<(String, String)>,
}
/// A missing or malformed config yields defaults rather than an error: a project
@@ -258,6 +282,8 @@ pub(crate) fn run_settings(project_root: &Path) -> RunSettings {
allow_network: cfg.tools.allow_network,
allow_home_read: cfg.tools.allow_home_read,
sandbox: cfg.tools.sandbox,
+ env_passthrough: cfg.tools.env_passthrough,
+ env_set: cfg.tools.env_set.into_iter().collect(),
}
}