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): plugin API-key setup with masked paste in the TUI

thinhlpgc221d377b5b0
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 888e51206..f053fba6e 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -65,7 +65,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| `/model [id]` | Switch model. Bare: pick interactively. Opening the picker re-lists each provider's models once per session; <kbd>Ctrl</kbd>+<kbd>R</kbd> inside it re-lists them again on demand |
| `/effort [low\|medium\|high]` | Set reasoning effort. Bare: show current; `low` is faster, `high` thinks deeper |
| `/mcp` | List, toggle, add, edit, and remove MCP servers; Enter opens a server's detail screen, where you can list its tools and sign in to it |
-| `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |
+| `/plugin [list\|install <spec>\|remove <name>\|search [query]\|setup <name>]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace. `setup` collects a plugin's required API keys (masked paste; keys land in `~/.jan/agent/plugin-env/` 0600 and reach the sandboxed shell on the next run) |
| `/reload [config\|plugin\|skills\|system-prompt]` | Re-read on-disk state into the running session without a restart (bare: all). `config` re-applies the project's `agent.toml` limits - `context_window`, `compaction_ratio`, `compaction_reserve_tokens`, `max_tokens`, `send_reasoning`, `[budget].max_tokens` - to the next run and lists what changed; the model, `[tools]`, `[provider]` and `[budget].max_usd` still need a restart. `plugin`/`skills` re-scan and rebuild the catalog, reporting added/removed/changed entries. `system-prompt` re-reads `JAN.md`, which applies on the next run |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
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 3ff6d7e80..203be2879 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
@@ -7,11 +7,41 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
-use std::sync::{Mutex, OnceLock};
+use std::sync::{Mutex, OnceLock, RwLock};
use std::time::Instant;
use tokio::process::{Child, Command};
+/// Plugin-declared environment values, injected into every sandboxed shell on
+/// top of [`SANDBOX_ENV_ALLOW`]. The allowlist is static and minimal exactly
+/// so host secrets cannot leak into a `bash` call; plugin keys are the
+/// deliberate exception — a plugin's skills/commands cannot call the service
+/// they integrate with without their credentials. Only variables an installed
+/// plugin's manifest *declares* (see the host's `plugins::required_env`) may
+/// land here, and only with a value the user typed into the masked setup
+/// prompt; the map is replaced wholesale by the host on every run start.
+static PLUGIN_ENV: OnceLock<RwLock<std::collections::BTreeMap<String, String>>> = OnceLock::new();
+
+/// Replace the plugin-declared environment values handed to sandboxed shells.
+pub fn set_plugin_env(vars: std::collections::BTreeMap<String, String>) {
+ let lock = PLUGIN_ENV.get_or_init(|| RwLock::new(Default::default()));
+ *lock.write().unwrap() = vars;
+}
+
+/// A snapshot of the current plugin-declared environment values.
+fn plugin_env() -> std::collections::BTreeMap<String, String> {
+ PLUGIN_ENV
+ .get()
+ .map(|lock| lock.read().unwrap().clone())
+ .unwrap_or_default()
+}
+
+/// Read back the current plugin env values (tests / diagnostics).
+#[doc(hidden)]
+pub fn plugin_env_snapshot() -> std::collections::BTreeMap<String, String> {
+ plugin_env()
+}
+
/// How to invoke the host shell. `program` + `args` are fixed; the command
/// string is appended as the final argv element, or piped to stdin when
/// `via_stdin` is set (legacy WSL `bash.exe`, which cannot take `-c`).
@@ -390,6 +420,11 @@ pub async fn spawn_with_stdin(
for (key, val) in resolve_env_overrides(std::env::vars(), env) {
cmd.env(key, val);
}
+ // Plugin-declared credentials come last so they always win over an
+ // allowlist key of the same name.
+ for (key, val) in plugin_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
diff --git a/src-tauri/src/core/agent/plugins.rs b/src-tauri/src/core/agent/plugins.rs
index f4ef6596c..bce58901f 100644
--- a/src-tauri/src/core/agent/plugins.rs
+++ b/src-tauri/src/core/agent/plugins.rs
@@ -138,6 +138,88 @@ struct Manifest {
version: Option<String>,
#[serde(default)]
repo: Option<String>,
+ /// Optional setup requirements: environment variables the plugin needs
+ /// (typically API keys). `plugin.toml`:
+ ///
+ /// ```toml
+ /// [setup.env]
+ /// GITHUB_TOKEN = "https://github.com/settings/tokens"
+ /// ```
+ ///
+ /// The value is the URL the user can obtain the key from (empty when the
+ /// plugin author has no link to share).
+ #[serde(default)]
+ setup: Option<SetupSection>,
+ /// Claude-convention manifests declare their needs indirectly: an
+ /// `.claude-plugin/plugin.json` `mcpServers` block whose env values
+ /// reference `${VAR}`. Those references are collected as required
+ /// variables without a URL.
+ #[serde(default, rename = "mcpServers")]
+ mcp_servers: Option<std::collections::BTreeMap<String, McpServerDecl>>,
+}
+
+/// The `[setup]` manifest section.
+#[derive(Debug, Default, Deserialize)]
+struct SetupSection {
+ #[serde(default)]
+ env: Option<std::collections::BTreeMap<String, String>>,
+}
+
+/// One Claude `mcpServers` entry: only its env block matters here.
+#[derive(Debug, Default, Deserialize)]
+struct McpServerDecl {
+ #[serde(default)]
+ env: Option<std::collections::BTreeMap<String, String>>,
+}
+
+impl Manifest {
+ /// Environment variables this plugin requires, as `(var, url)` pairs —
+ /// the URL the user can obtain the value from, empty when unknown.
+ fn required_env(&self) -> std::collections::BTreeMap<String, String> {
+ let mut out = std::collections::BTreeMap::new();
+ if let Some(setup) = &self.setup {
+ for (key, url) in setup.env.iter().flatten() {
+ if is_env_name(key) {
+ out.insert(key.clone(), url.trim().to_string());
+ }
+ }
+ }
+ for server in self.mcp_servers.iter().flat_map(|m| m.values()) {
+ for value in server.env.iter().flatten().map(|(_, v)| v) {
+ for var in template_refs(value) {
+ if is_env_name(&var) {
+ out.entry(var).or_default();
+ }
+ }
+ }
+ }
+ out
+ }
+}
+
+/// A plausible environment-variable name (used as a file stem and registry
+/// key, so it must not contain path separators or control characters).
+fn is_env_name(name: &str) -> bool {
+ !name.is_empty()
+ && name
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '_')
+ && !name.chars().next().unwrap().is_ascii_digit()
+}
+
+/// Every `${VAR}` reference in a manifest value.
+fn template_refs(value: &str) -> Vec<String> {
+ let mut out = Vec::new();
+ let mut rest = value;
+ while let Some(start) = rest.find("${") {
+ if let Some(len) = rest[start + 2..].find('}') {
+ out.push(rest[start + 2..start + 2 + len].to_string());
+ rest = &rest[start + 2 + len + 1..];
+ } else {
+ break;
+ }
+ }
+ out
}
fn client() -> Result<reqwest::Client, String> {
@@ -175,6 +257,159 @@ pub(crate) fn find_installed(root: &Path, query: &str) -> Option<(String, Instal
.find(|(directory, plugin)| directory == &query || plugin.name == query)
}
+/// `~/.jan/agent/plugin-env/` — where the setup prompt stores plugin API keys.
+/// Resolved from the home directory directly (not the cli-gated global config
+/// helpers) so the desktop run path syncs the same registry.
+fn plugin_env_dir() -> Result<PathBuf, String> {
+ dirs::home_dir()
+ .map(|home| home.join(".jan").join("agent").join("plugin-env"))
+ .ok_or_else(|| "could not resolve the user's home directory".to_string())
+}
+
+/// `plugin-env/<plugin>.toml` under `dir`.
+fn plugin_env_path(dir: &Path, plugin: &str) -> Result<PathBuf, String> {
+ let stem = crate::core::agent::skills::safe_stem(plugin)?;
+ Ok(dir.join(format!("{stem}.toml")))
+}
+
+/// The stored env values for one plugin. Missing or malformed file -> empty.
+#[cfg(feature = "cli")]
+pub(crate) fn stored_plugin_env(plugin: &str) -> std::collections::BTreeMap<String, String> {
+ match plugin_env_dir() {
+ Ok(dir) => stored_plugin_env_in(&dir, plugin),
+ Err(_) => Default::default(),
+ }
+}
+
+/// [`stored_plugin_env`] against an explicit directory (tests).
+pub(crate) fn stored_plugin_env_in(
+ dir: &Path,
+ plugin: &str,
+) -> std::collections::BTreeMap<String, String> {
+ plugin_env_path(dir, plugin)
+ .ok()
+ .and_then(|p| std::fs::read_to_string(p).ok())
+ .and_then(|raw| toml::from_str(&raw).ok())
+ .unwrap_or_default()
+}
+
+/// Persist one env value for a plugin, merging with what is already stored.
+#[cfg(feature = "cli")]
+pub(crate) fn save_plugin_env(plugin: &str, key: &str, value: &str) -> Result<(), String> {
+ save_plugin_env_in(&plugin_env_dir()?, plugin, key, value)
+}
+
+/// [`save_plugin_env`] against an explicit directory (tests).
+#[cfg(any(feature = "cli", test))]
+pub(crate) fn save_plugin_env_in(
+ dir: &Path,
+ plugin: &str,
+ key: &str,
+ value: &str,
+) -> Result<(), String> {
+ if !is_env_name(key) {
+ return Err(format!("invalid environment variable name '{key}'"));
+ }
+ let path = plugin_env_path(dir, plugin)?;
+ let mut values: std::collections::BTreeMap<String, String> = std::fs::read_to_string(&path)
+ .ok()
+ .and_then(|raw| toml::from_str(&raw).ok())
+ .unwrap_or_default();
+ values.insert(key.to_string(), value.to_string());
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| format!("could not create {parent:?}: {e}"))?;
+ }
+ let serialized = toml::to_string(&values).map_err(|e| e.to_string())?;
+ #[cfg(unix)]
+ let perms = {
+ use std::os::unix::fs::OpenOptionsExt;
+ std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .mode(0o600)
+ .open(&path)
+ };
+ #[cfg(not(unix))]
+ let perms = std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(&path);
+ perms
+ .and_then(|mut f| f.write_all(serialized.as_bytes()))
+ .map_err(|e| format!("could not write {}: {e}", path.display()))
+}
+
+/// Every env variable one plugin declares as required, as `(var, url)` in
+/// manifest order. Unlike [`missing_plugin_env`] this includes satisfied
+/// entries: an explicit `/plugin setup <name>` re-runs the whole prompt.
+#[cfg(feature = "cli")]
+pub(crate) fn declared_plugin_env(root: &Path, plugin: &str) -> Vec<(String, String)> {
+ skills::find_plugin_dir(root, plugin)
+ .map(|dir| read_manifest(&dir).required_env().into_iter().collect())
+ .unwrap_or_default()
+}
+
+/// Setup requirements that are not yet satisfied: `(plugin, var, url)` in
+/// scan order. A var is satisfied when the user stored a value or the process
+/// environment already provides one (CI, shells, direnv...).
+#[cfg(feature = "cli")]
+pub(crate) fn missing_plugin_env(root: &Path) -> Vec<(String, String, String)> {
+ match plugin_env_dir() {
+ Ok(dir) => missing_plugin_env_in(root, &dir),
+ Err(_) => Vec::new(),
+ }
+}
+
+/// [`missing_plugin_env`] against an explicit store directory (tests).
+#[cfg(any(feature = "cli", test))]
+fn missing_plugin_env_in(root: &Path, env_dir: &Path) -> Vec<(String, String, String)> {
+ let mut out = Vec::new();
+ for (directory, _) in installed_entries(root) {
+ let Some(dir) = skills::find_plugin_dir(root, &directory) else {
+ continue;
+ };
+ let stored = stored_plugin_env_in(env_dir, &directory);
+ for (var, url) in read_manifest(&dir).required_env() {
+ let in_store = stored.get(&var).is_some_and(|v| !v.is_empty());
+ let in_host = std::env::var_os(&var).is_some_and(|v| !v.is_empty());
+ if !in_store && !in_host {
+ out.push((directory.clone(), var, url));
+ }
+ }
+ }
+ out
+}
+
+/// Hand the sandboxed shells their plugin-declared credentials: values stored
+/// via the setup prompt, intersected with the variables the installed
+/// plugins' manifests still declare (a plugin that dropped a requirement
+/// stops receiving it). Runs on every run start via `ensure_project` and
+/// after `/reload`, so install/remove/setup changes are picked up live.
+pub(crate) fn sync_env_registry(root: &Path) {
+ if let Ok(dir) = plugin_env_dir() {
+ sync_env_registry_in(root, &dir);
+ }
+}
+
+/// [`sync_env_registry`] against an explicit store directory (tests).
+fn sync_env_registry_in(root: &Path, env_dir: &Path) {
+ let mut values: std::collections::BTreeMap<String, String> = Default::default();
+ for (directory, _) in installed_entries(root) {
+ let Some(dir) = skills::find_plugin_dir(root, &directory) else {
+ continue;
+ };
+ let stored = stored_plugin_env_in(env_dir, &directory);
+ for var in read_manifest(&dir).required_env().into_keys() {
+ if let Some(value) = stored.get(&var).filter(|v| !v.is_empty()) {
+ values.insert(var, value.clone());
+ }
+ }
+ }
+ tauri_plugin_agent_tools::tools::proc::set_plugin_env(values);
+}
+
fn installed_entries(root: &Path) -> Vec<(String, InstalledPlugin)> {
// A linked git worktree also sees the main worktree's plugins, the
// project-local one shadowing a same-named shared one. Counts come from
@@ -1662,4 +1897,87 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
let _ = std::fs::remove_dir_all(repo);
}
+
+ /// An installed plugin (by directory convention) whose manifest declares
+ /// one required env var, plus the store dir tests use instead of `~/.jan`.
+ fn plugin_with_env_requirement(tag: &str, var: &str, url: &str) -> (PathBuf, PathBuf) {
+ let root = unique_root(tag);
+ let dir = root.join(".jan/agent/plugins/acme");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(
+ dir.join("plugin.toml"),
+ format!("name = \"acme\"\n\n[setup.env]\n{var} = \"{url}\"\n"),
+ )
+ .unwrap();
+ let env_dir = root.join("plugin-env-store");
+ std::fs::create_dir_all(&env_dir).unwrap();
+ (root, env_dir)
+ }
+
+ #[test]
+ fn required_env_reads_setup_section_and_claude_mcp_refs() {
+ let root = unique_root("reqenv");
+ std::fs::create_dir_all(root.join("acme")).unwrap();
+ std::fs::write(
+ root.join("acme/plugin.toml"),
+ "name = \"acme\"\n\n[setup.env]\nACME_TOKEN = \"https://example.com/keys\"\n",
+ )
+ .unwrap();
+ let req = read_manifest(&root.join("acme")).required_env();
+ assert_eq!(
+ req.get("ACME_TOKEN").map(String::as_str),
+ Some("https://example.com/keys")
+ );
+
+ // The Claude convention declares needs indirectly: ${VAR} references
+ // inside an mcpServers env block, with no URL to show.
+ std::fs::create_dir_all(root.join("claude").join(".claude-plugin")).unwrap();
+ std::fs::write(
+ root.join("claude/.claude-plugin/plugin.json"),
+ r#"{"name":"claude","mcpServers":{"gh":{"command":"x","env":{"GITHUB_TOKEN":"${GITHUB_TOKEN}"}}}}"#,
+ )
+ .unwrap();
+ let req = read_manifest(&root.join("claude")).required_env();
+ assert_eq!(req.get("GITHUB_TOKEN").map(String::as_str), Some(""));
+
+ // Malformed names are filtered, not propagated.
+ std::fs::create_dir_all(root.join("bad")).unwrap();
+ std::fs::write(
+ root.join("bad/plugin.toml"),
+ "[setup.env]\n\"../evil\" = \"https://x\"\n\"HAS SPACE\" = \"https://y\"\n",
+ )
+ .unwrap();
+ let req = read_manifest(&root.join("bad")).required_env();
+ assert!(req.is_empty(), "{req:?}");
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
+ #[test]
+ fn save_store_and_missing_report_roundtrip() {
+ let (root, env_dir) = plugin_with_env_requirement("envstore", "ACME_TOKEN", "https://x");
+
+ // Nothing stored: the requirement is reported as missing.
+ let missing = missing_plugin_env_in(&root, &env_dir);
+ assert_eq!(
+ missing,
+ vec![("acme".to_string(), "ACME_TOKEN".to_string(), "https://x".to_string())]
+ );
+
+ // Store a value: the requirement is satisfied.
+ save_plugin_env_in(&env_dir, "acme", "ACME_TOKEN", "secret").unwrap();
+ assert_eq!(
+ stored_plugin_env_in(&env_dir, "acme").get("ACME_TOKEN"),
+ Some(&"secret".to_string())
+ );
+ assert!(missing_plugin_env_in(&root, &env_dir).is_empty());
+ assert!(plugin_env_path(&env_dir, "acme").unwrap().exists());
+
+ // Sync registers exactly the declared+stored variable.
+ sync_env_registry_in(&root, &env_dir);
+ let snapshot =
+ tauri_plugin_agent_tools::tools::proc::plugin_env_snapshot();
+ assert_eq!(snapshot.get("ACME_TOKEN").map(String::as_str), Some("secret"));
+
+ let _ = std::fs::remove_dir_all(&root);
+ }
}
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 3ea571687..e7a6d6675 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -504,6 +504,10 @@ pub(crate) fn permissions_from(cfg: &AgentToml) -> ToolPermissions {
/// scaffolded: an empty placeholder costs prompt space and teaches nothing, so
/// it is written by `/init` or by hand.
pub(crate) fn ensure_project(project_root: &Path) -> Result<PathBuf, String> {
+ // Refresh the plugin env registry first: this is the one choke point
+ // every run path calls, so a stored API key reaches the sandboxed shells
+ // of the run about to start.
+ super::plugins::sync_env_registry(project_root);
if !project_root.is_dir() {
return Err(format!(
"project directory does not exist: {}. Pass --project with a path to an existing directory (paths are case-sensitive).",
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index c5de0cda3..7cb9f4acc 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -962,6 +962,53 @@ impl LoginPrompt {
}
}
+/// One required environment variable of a plugin: its name and, when the
+/// manifest declares it, the URL the user can obtain the value from.
+struct PluginEnvEntry {
+ key: String,
+ url: String,
+}
+
+/// `/plugin setup`: a docked, `/login`-styled prompt collecting the API keys a
+/// plugin declares it needs. One entry per variable; the field is masked (the
+/// value never reaches the screen, scrollback, or transcript), Enter saves and
+/// advances, `s` skips, Esc abandons the remaining entries. Values go to
+/// `~/.jan/agent/plugin-env/<plugin>.toml` (0600) and are injected into the
+/// sandboxed shell on the next run.
+struct PluginSetupPrompt {
+ plugin: String,
+ entries: Vec<PluginEnvEntry>,
+ current: usize,
+ input: String,
+ error: Option<String>,
+}
+
+impl PluginSetupPrompt {
+ fn entry(&self) -> Option<&PluginEnvEntry> {
+ self.entries.get(self.current)
+ }
+
+ fn masked(&self) -> String {
+ super::secret_input::mask(self.input.chars().count())
+ }
+
+ fn paste(&mut self, text: &str) {
+ self.input.push_str(super::secret_input::pasted(text));
+ }
+
+ /// Advance past the current entry; `None` once every entry is done.
+ fn advance(&mut self) {
+ self.current += 1;
+ self.input.clear();
+ self.error = None;
+ }
+
+ /// Whether every entry has been visited.
+ fn done(&self) -> bool {
+ self.current >= self.entries.len()
+ }
+}
+
/// `/login` account entry: owns an OAuth descriptor while the browser callback
/// task races the loopback callback with a manually pasted redirect URL/code.
struct AccountLoginPrompt {
@@ -2060,6 +2107,9 @@ struct App {
model_picker: Option<ModelPicker>,
/// Active `/login` prompt; owns the keyboard while open.
login: Option<LoginPrompt>,
+ /// Active `/plugin setup` prompt (docked like `/login`); owns the keyboard
+ /// while open and collects the plugin's required API keys, masked.
+ plugin_setup: Option<PluginSetupPrompt>,
/// Active `/settings` edit prompt (docked like `/login`); owns the
/// keyboard while open. Holds the setting being edited and any validation
/// error; writes go straight to agent.toml on Enter.
@@ -2704,6 +2754,7 @@ impl App {
provider_prompt: None,
probed_models: std::collections::HashSet::new(),
login_submit: None,
+ plugin_setup: None,
account_login: None,
account_login_submit: None,
account_login_manual_tx: None,
@@ -9327,7 +9378,7 @@ fn finish_plugin_install(
if plugins.is_empty() {
app.note("nothing installed");
}
- for p in plugins {
+ for p in &plugins {
app.note(&format!(
"installed plugin '{}' ({} skills, {} commands, {} agents, {} tools, {} hooks)",
p.name, p.skills, p.commands, p.agents, p.tools, p.hooks
@@ -9356,6 +9407,10 @@ fn finish_plugin_install(
);
}
}
+ // A plugin that declares required API keys opens its setup dock
+ // right away: the link to obtain each key plus a masked paste
+ // field, so the user never has to edit env files by hand.
+ open_plugin_setup(app);
}
Ok(GitInstall::Collection(candidates)) => {
let Some(url) = url else {
@@ -10664,6 +10719,9 @@ fn route_paste_event(app: &mut App, event: Event) {
// A pasted API key belongs to the login field, not the chat composer
// (where it would echo).
prompt.paste(&text);
+ } else if let Some(prompt) = app.plugin_setup.as_mut() {
+ // A pasted plugin API key belongs to the setup field.
+ prompt.paste(&text);
} else if let Some(prompt) = app.settings_prompt.as_mut() {
prompt.paste(&text);
} else if let Some(prompt) = app.mcp_prompt.as_mut() {
@@ -10937,6 +10995,133 @@ fn clipboard_text() -> Result<String, String> {
super::secret_input::clipboard_text()
}
+/// Open `/plugin setup` for the first installed plugin whose declared env
+/// variables are not yet satisfied. Returns whether a dock opened.
+fn open_plugin_setup(app: &mut App) -> bool {
+ let missing = crate::core::agent::plugins::missing_plugin_env(&app.project_root);
+ let Some((plugin, _, _)) = missing.first() else {
+ return false;
+ };
+ let plugin = plugin.clone();
+ let entries = missing
+ .into_iter()
+ .filter(|(p, _, _)| p == &plugin)
+ .map(|(_, key, url)| PluginEnvEntry { key, url })
+ .collect::<Vec<_>>();
+ start_plugin_setup(app, &plugin, entries)
+}
+
+/// Open `/plugin setup` for a named plugin, offering every variable it
+/// declares (even satisfied ones, so a value can be replaced). Returns whether
+/// a dock opened.
+fn open_plugin_setup_for(app: &mut App, plugin: &str) -> bool {
+ let entries = crate::core::agent::plugins::declared_plugin_env(&app.project_root, plugin)
+ .into_iter()
+ .map(|(key, url)| PluginEnvEntry { key, url })
+ .collect::<Vec<_>>();
+ if entries.is_empty() {
+ return false;
+ }
+ start_plugin_setup(app, plugin, entries)
+}
+
+/// Install the dock state for `plugin` with `entries`, after announcing it.
+fn start_plugin_setup(app: &mut App, plugin: &str, entries: Vec<PluginEnvEntry>) -> bool {
+ app.note(&format!(
+ "◈ plugin setup · {} needs {} API key{} - paste them below",
+ plugin,
+ entries.len(),
+ if entries.len() == 1 { "" } else { "s" }
+ ));
+ app.plugin_setup = Some(PluginSetupPrompt {
+ plugin: plugin.to_string(),
+ entries,
+ current: 0,
+ input: String::new(),
+ error: None,
+ });
+ true
+}
+
+/// Keys for the `/plugin setup` prompt: Enter saves the value and advances,
+/// `s` skips an entry, Esc/Ctrl-C abandons the rest. Same masked-entry rules
+/// as the `/login` paste field.
+fn handle_plugin_setup_key(app: &mut App, key: KeyEvent, ctrl: bool) {
+ let cancel = key.code == KeyCode::Esc
+ || (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')));
+ if cancel {
+ app.plugin_setup = None;
+ app.note("plugin setup cancelled - resume with /plugin setup <name>");
+ return;
+ }
+ // Ctrl-V: some terminals send a paste as a key rather than Event::Paste.
+ if ctrl && key.code == KeyCode::Char('v') {
+ match super::secret_input::clipboard_text() {
+ Ok(text) => {
+ if let Some(prompt) = app.plugin_setup.as_mut() {
+ prompt.paste(&text);
+ }
+ }
+ Err(e) => {
+ if let Some(prompt) = app.plugin_setup.as_mut() {
+ prompt.error = Some(format!("could not read the clipboard: {e}"));
+ }
+ }
+ }
+ return;
+ }
+ let Some(prompt) = app.plugin_setup.as_mut() else {
+ return;
+ };
+ match key.code {
+ KeyCode::Enter => {
+ let plugin = prompt.plugin.clone();
+ let Some(entry) = prompt.entry() else { return };
+ let value = prompt.input.trim().to_string();
+ if value.is_empty() {
+ prompt.error = Some("nothing pasted - paste the key or press s to skip".into());
+ return;
+ }
+ if let Err(e) = crate::core::agent::plugins::save_plugin_env(&plugin, &entry.key, &value)
+ {
+ prompt.error = Some(e);
+ return;
+ }
+ let key_name = entry.key.clone();
+ prompt.advance();
+ if prompt.done() {
+ app.plugin_setup = None;
+ crate::core::agent::plugins::sync_env_registry(&app.project_root);
+ app.note(&format!("plugin setup · {plugin} · {key_name} saved"));
+ // Chain into the next plugin that still needs keys.
+ open_plugin_setup(app);
+ } else {
+ app.note(&format!(
+ "plugin setup · {plugin} · {key_name} saved"
+ ));
+ }
+ }
+ KeyCode::Char('s') | KeyCode::Char('S') if !ctrl => {
+ let plugin = prompt.plugin.clone();
+ let key_name = prompt
+ .entry()
+ .map(|e| e.key.clone())
+ .unwrap_or_default();
+ prompt.advance();
+ if prompt.done() {
+ app.plugin_setup = None;
+ app.note(&format!("plugin setup · {plugin} · skipped {key_name}"));
+ open_plugin_setup(app);
+ }
+ }
+ KeyCode::Backspace => {
+ prompt.input.pop();
+ }
+ KeyCode::Char(ch) if !ctrl => prompt.input.push(ch),
+ _ => {}
+ }
+}
+
async fn handle_model_picker_key(app: &mut App, key: KeyEvent, ctrl: bool) {
if key.code == KeyCode::Esc
|| (ctrl && matches!(key.code, KeyCode::Char('c') | KeyCode::Char('d')))
@@ -11060,6 +11245,12 @@ async fn handle_key(
return;
}
+ // Same for `/plugin setup`: it is collecting masked API keys.
+ if app.plugin_setup.is_some() {
+ handle_plugin_setup_key(app, key, ctrl);
+ return;
+ }
+
// A pending browser question owns the keyboard the same way, so a `y`/`n`
// meant for it can never reach the input box or a transcript shortcut.
if app.browser_confirm.is_some() {
@@ -12213,8 +12404,8 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
},
SlashCommand {
name: "/plugin",
- hint: "[list|install <spec>|remove <name>|search [query]]",
- description: "Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace",
+ hint: "[list|install <spec>|remove <name>|search [query]|setup <name>]",
+ description: "Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace, set up required API keys",
alias_of: None,
},
SlashCommand {
@@ -14398,6 +14589,14 @@ async fn plugin_command(app: &mut App, arg: &str) {
for p in &plugins {
app.push(Line::styled(summary_line(p), Style::new().cyan().bold()));
}
+ // Surface unsatisfied setup requirements right in the list:
+ // a plugin whose key is missing explains itself here.
+ for (plugin, var, _) in crate::core::agent::plugins::missing_plugin_env(&root) {
+ app.push(Line::styled(
+ format!(" {plugin}: key missing ({var}) - /plugin setup {plugin}"),
+ Style::new().yellow(),
+ ));
+ }
} else {
match crate::core::agent::plugins::find_installed(&root, &rest) {
Some((directory, p)) => {
@@ -14462,6 +14661,19 @@ async fn plugin_command(app: &mut App, arg: &str) {
app.plugin_install_request = Some(rest);
app.note("installing plugin...");
}
+ "setup" => {
+ if rest.is_empty() {
+ if !open_plugin_setup(app) {
+ app.note(
+ "no plugin is missing keys (usage: /plugin setup <name>)",
+ );
+ }
+ } else if !open_plugin_setup_for(app, &rest) {
+ app.note(&format!(
+ "plugin '{rest}' declares no setup keys (declare [setup.env] in its plugin.toml)"
+ ));
+ }
+ }
"remove" => {
if rest.is_empty() {
app.note("usage: /plugin remove <name>");
@@ -17799,6 +18011,18 @@ fn draw(f: &mut Frame, app: &mut App) {
height,
};
draw_login(f, rect, prompt);
+ } else if let Some(prompt) = &app.plugin_setup {
+ let height =
+ (plugin_setup_lines(prompt, chunks[2].width.saturating_sub(2)).len() as u16 + 2)
+ .min(chunks[1].height);
+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);
+ let rect = ratatui::layout::Rect {
+ x: chunks[2].x,
+ y,
+ width: chunks[2].width,
+ height,
+ };
+ draw_plugin_setup(f, rect, prompt);
} else if let Some(confirm) = &app.browser_confirm {
draw_browser_confirm_overlay(f, confirm, chunks[2], chunks[1]);
} else if let Some(prompt) = &app.settings_prompt {
@@ -18270,6 +18494,82 @@ fn draw_login(f: &mut Frame, area: ratatui::layout::Rect, prompt: &LoginPrompt)
);
}
+/// Docked `/plugin setup` prompt, styled like the `/login` dock: which plugin,
+/// which variable, the URL to obtain the key at, a masked field, and keys.
+fn draw_plugin_setup(f: &mut Frame, area: ratatui::layout::Rect, prompt: &PluginSetupPrompt) {
+ use ratatui::widgets::Clear;
+
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().cyan())
+ .title(Span::styled(
+ format!(" plugin setup: {} ", prompt.plugin),
+ Style::new().on_cyan().black().bold(),
+ ));
+
+ f.render_widget(Clear, area);
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+ f.render_widget(
+ Paragraph::new(plugin_setup_lines(prompt, inner.width)),
+ inner,
+ );
+}
+
+/// The `/plugin setup` box's contents. The width parameter mirrors the other
+/// prompt-line builders (call sites size the dock from the row count).
+fn plugin_setup_lines(prompt: &PluginSetupPrompt, _width: u16) -> Vec<Line<'static>> {
+ let dim = Style::new().dark_gray();
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ let total = prompt.entries.len();
+ match prompt.entry() {
+ Some(entry) => {
+ lines.push(Line::from(Span::styled(
+ format!(
+ "{} needs {} ({}/{})",
+ prompt.plugin,
+ entry.key,
+ prompt.current + 1,
+ total
+ ),
+ Style::new().cyan().bold(),
+ )));
+ if entry.url.is_empty() {
+ lines.push(Line::from(Span::styled(
+ "ask the plugin author where to obtain this key".to_string(),
+ dim,
+ )));
+ } else {
+ lines.push(Line::from(vec![
+ Span::styled("get it at: ", dim),
+ Span::styled(entry.url.clone(), Style::new().cyan()),
+ ]));
+ }
+ }
+ None => {
+ lines.push(Line::from(Span::styled(
+ format!("{} setup complete", prompt.plugin),
+ Style::new().cyan().bold(),
+ )));
+ }
+ }
+ if let Some(error) = &prompt.error {
+ lines.push(Line::from(Span::styled(
+ error.clone(),
+ Style::new().red(),
+ )));
+ }
+ lines.push(Line::from(vec![
+ Span::styled(prompt.masked(), Style::new().bold()),
+ Span::styled(" ← paste here", dim),
+ ]));
+ lines.push(Line::from(Span::styled(
+ "Enter save · s skip · Esc cancel - the key is masked and never echoed",
+ dim,
+ )));
+ lines
+}
+
/// Docked `/settings` edit prompt, styled like the `/login` dock: description,
/// the current on-disk value, the field being edited, an inline validation
/// error when one fired, and the save/cancel keys.
@@ -37466,6 +37766,48 @@ mod tests {
);
}
+ /// A plugin whose manifest declares one required env var.
+ fn plugin_with_setup_requirement(root: &std::path::Path, var: &str, url: &str) {
+ let dir = root.join(".jan/agent/plugins/acme");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(
+ dir.join("plugin.toml"),
+ format!("name = \"acme\"\n\n[setup.env]\n{var} = \"{url}\"\n"),
+ )
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn plugin_setup_dock_masks_input_and_skips() {
+ let (mut app, root) = skill_test_app("deploy", "How to deploy.");
+ plugin_with_setup_requirement(&root, "ACME_TOKEN", "https://example.com/keys");
+
+ // The dock opens for the named plugin and shows the URL and a masked
+ // field; the hint row appears in `/plugin list` too.
+ run_command(&mut app, "plugin setup acme", &no_mcp()).await;
+ assert!(app.plugin_setup.is_some(), "dock must open");
+ let rows = render_rows(&mut app, 100, 30);
+ let rendered = rows.join("\n");
+ assert!(rendered.contains("ACME_TOKEN"), "{rendered}");
+ assert!(rendered.contains("https://example.com/keys"), "{rendered}");
+
+ // Typed characters render masked, never verbatim. Simulate the paste
+ // path directly: the typed secret must not appear in the frame.
+ if let Some(prompt) = app.plugin_setup.as_mut() {
+ prompt.paste("supersecret123");
+ }
+ let rows = render_rows(&mut app, 100, 30);
+ let rendered = rows.join("\n");
+ assert!(!rendered.contains("supersecret123"), "{rendered}");
+ assert!(rendered.contains('*'), "mask row: {rendered}");
+
+ // Esc cancels the dock.
+ handle_plugin_setup_key(&mut app, key(KeyCode::Esc), false);
+ assert!(app.plugin_setup.is_none());
+ assert!(transcript_text(&app).contains("plugin setup cancelled"));
+ let _ = std::fs::remove_dir_all(&root);
+ }
+
#[tokio::test]
async fn plugin_command_installs_lists_dispatch_removes() {
// Local git repo fixture with a plugin payload.