Craft Anything: understand how any software works, and craft your own.
Rust
Hand OpenCode runs over SSH the Craft Anything MCP server (#1003)
BFlat67963ecb63ba
diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rsindex c22e45fd..0b37dbe7 100644--- a/crates/ai/src/cli_agents/adapters.rs+++ b/crates/ai/src/cli_agents/adapters.rs@@ -170,6 +170,16 @@ pub trait AgentAdapter: Send + Sync {fn mcp_env(&self, _mcp: &McpCommand) -> Result<Option<(&'static str, String)>, ToolError> {Ok(None)}+ /// Whether what a build needs on a remote SSH host is there, checked before a build starts.+ /// Default: nothing to check on the host. `stop` ends the check when the person stops the build.+ fn check_remote_tool_server(&self, _host: &str, _stop: &CancelToken) -> Result<(), ToolError> {+ Ok(())+ }+ /// Prepare this run's tool server on a remote SSH host (a config file there), returning the+ /// environment variable to set on the remote command. Default: the agent can't carry one.+ fn remote_tool_server(&self, _host: &str, _mcp: &McpCommand) -> Result<Option<(&'static str, String)>, ToolError> {+ Ok(None)+ }/// The file in which this computer keeps the agent's saved session `id`, so the project can/// keep a copy that travels with it. `None`: it keeps none we can copy, or not here.fn session_file(&self, _id: &str) -> Option<std::path::PathBuf> {diff --git a/crates/ai/src/cli_agents/adapters/opencode.rs b/crates/ai/src/cli_agents/adapters/opencode.rsindex d6dede03..c446313d 100644--- a/crates/ai/src/cli_agents/adapters/opencode.rs+++ b/crates/ai/src/cli_agents/adapters/opencode.rs@@ -23,16 +23,32 @@ impl AgentAdapter for OpenCode {/// goes in a config file named by `OPENCODE_CONFIG`, which the private (`--standalone`)/// server merges over the person's own settings. The background service never sees it.fn mcp_env(&self, mcp: &McpCommand) -> Result<Option<(&'static str, String)>, ToolError> {- let command: Vec<&str> = std::iter::once(mcp.command.as_str()).chain(mcp.args.iter().map(String::as_str)).collect();- let content = json!({"mcp": {MCP_NAME: {"type": "local", "command": command, "enabled": true}}}).to_string();- // Named by its content, so runs with the same server share one file and none is left half-written.- let mut hash = std::collections::hash_map::DefaultHasher::new();- std::hash::Hash::hash(&content, &mut hash);- let path = std::env::temp_dir().join(format!("craft-anything-opencode-{:016x}.json", std::hash::Hasher::finish(&hash)));+ let content = config_content(mcp);+ let path = std::env::temp_dir().join(config_name(&content));craft_anything_platform::fs::write_atomic_private(&path, content.as_bytes())?;Ok(Some(("OPENCODE_CONFIG", path.to_string_lossy().into_owned())))}+ /// The remote helper is the same `craft-anything-cli` the local check starts; a build must+ /// not spend hours then find the remote helper missing. A missing program stops with the fix.+ fn check_remote_tool_server(&self, host: &str, stop: &CancelToken) -> Result<(), ToolError> {+ remote_check(host, Some(stop))+ }++ /// The config file is written on the remote host itself: one `ssh` invocation checks the+ /// helper, writes the file atomically and keeps it private (piped `printf`, octal-escaped,+ /// no interactive stdin). The private (`--standalone`) server reads it there.+ fn remote_tool_server(&self, host: &str, mcp: &McpCommand) -> Result<Option<(&'static str, String)>, ToolError> {+ let content = config_content(mcp);+ let name = config_name(&content);+ let line = remote_prepare_line(&name, &content);+ let output = ssh_run(host, &line, Duration::from_secs(30), None)?;+ if !output.success {+ return Err(remote_failure(host, &output));+ }+ Ok(Some(("OPENCODE_CONFIG", format!("~/.cache/craft-anything/{name}"))))+ }+/// Discover enabled chat models and thinking variants from the selected local or SSH installation.fn model_catalog(&self,@@ -141,6 +157,79 @@ impl AgentAdapter for OpenCode {}}+/// Our tool server's config for `mcp`: the bytes of the `OPENCODE_CONFIG` file (both local and+/// remote runs use the same content).+fn config_content(mcp: &McpCommand) -> String {+ let command: Vec<&str> = std::iter::once(mcp.command.as_str()).chain(mcp.args.iter().map(String::as_str)).collect();+ json!({"mcp": {MCP_NAME: {"type": "local", "command": command, "enabled": true}}}).to_string()+}++/// Named by its content, so runs with the same server share one file and none is left half-written.+fn config_name(content: &str) -> String {+ let mut hash = std::collections::hash_map::DefaultHasher::new();+ std::hash::Hash::hash(content, &mut hash);+ format!("craft-anything-opencode-{:016x}.json", std::hash::Hasher::finish(&hash))+}++/// Every byte as an octal escape for a POSIX `printf` format string, so no byte in `bytes` can+/// end the quoted string; safe for any path in any locale.+fn octal_escape(bytes: &[u8]) -> String {+ let mut out = String::with_capacity(bytes.len() * 4);+ for b in bytes {+ out.push('\\');+ out.push((((b / 64) & 7) + b'0') as char);+ out.push((((b / 8) & 7) + b'0') as char);+ out.push(((b & 7) + b'0') as char);+ }+ out+}++/// One `ssh` run for a remote set-up step. Never interactive (`BatchMode`, stdin closed).+fn ssh_run(host: &str, line: &str, timeout: std::time::Duration, stop: Option<&CancelToken>) -> Result<craft_anything_platform::Output, ToolError> {+ let argv = crate::ssh::ssh_line_args(host, line.to_string());+ let mut proc = craft_anything_platform::process::Process::new("ssh").args(&argv).timeout(timeout).stdout_cap(64 * 1024);+ if let Some(stop) = stop {+ let stop = stop.clone();+ proc = proc.cancel_when(move || stop.is_cancelled());+ }+ proc.run()+}++/// The remote helper is on PATH, checked before a build starts (the remote server runs it).+fn remote_check(host: &str, stop: Option<&CancelToken>) -> Result<(), ToolError> {+ let out = ssh_run(host, "command -v craft-anything-cli >/dev/null", std::time::Duration::from_secs(15), stop)?;+ if out.success {+ return Ok(());+ }+ Err(remote_failure(host, &out))+}++/// The remote shell line: the helper is on PATH, then the config file goes in atomically and+/// private (`printf` with octal escapes; no byte ends the quoted string). One line, no input.+fn remote_prepare_line(name: &str, content: &str) -> String {+ let escaped = octal_escape(content.as_bytes());+ format!(+ "command -v craft-anything-cli >/dev/null && mkdir -p \"$HOME/.cache/craft-anything\" && printf '{escaped}' > \"$HOME/.cache/craft-anything/{name}.tmp.$$\" && chmod 600 \"$HOME/.cache/craft-anything/{name}.tmp.$$\" && mv \"$HOME/.cache/craft-anything/{name}.tmp.$$\" \"$HOME/.cache/craft-anything/{name}\""+ )+}++/// Map the remote failure onto the fix, reusing the ssh failure wording other remote runs use.+fn remote_failure(host: &str, out: &craft_anything_platform::Output) -> ToolError {+ if let Some(failure) = crate::ssh::diagnose(host, "craft-anything-cli", crate::ssh::is_git_server(host), out.code, out.stderr_text().as_str()) {+ return ToolError::new(ErrorCode::EngineMissing, format!("Craft Anything can't set up its tools on {host}: {}.", failure.what))+ .with_remediation(failure.fix);+ }+ let stderr = out.stderr_text();+ let snippet: String = stderr.trim().chars().take(200).collect();+ let exit = out.code.map_or_else(|| "it was stopped".to_string(), |code| format!("exit {code}"));+ ToolError::new(ErrorCode::EngineMissing, format!("Craft Anything couldn't set up its tools on {host}: ssh didn't come back as expected ({exit})."))+ .with_remediation(if snippet.is_empty() {+ "Check that craft-anything-cli is on the PATH this ssh session uses, and that the host lets you run programs over ssh.".to_string()+ } else {+ format!("ssh said: {snippet}")+ })+}+/// OpenCode's JSON error carries the provider status and its own retry decision. In particular,/// an unclassified exit or an unsupported CLI flag cannot become retryable from display text.fn opencode_failure(error: &Value) -> TurnFailure {@@ -280,6 +369,89 @@ mod tests {assert!(OpenCode.check_native_options(&options).is_ok());}+ #[test]+ fn the_tool_server_config_and_name_are_stable() {+ let mcp = McpCommand { command: "craft-anything-cli".into(), args: vec!["mcp".into(), "--clean-room".into()], notes: None };+ let content = config_content(&mcp);+ assert_eq!(content, config_content(&mcp));+ assert!(content.contains("craft-anything-cli"));+ assert!(content.contains("--clean-room"));+ assert_eq!(config_name(&content), config_name(&content));+ let other = config_content(&McpCommand { command: "other".into(), args: vec![], notes: None });+ assert_ne!(config_name(&content), config_name(&other));+ }++ #[test]+ fn octal_escapes_every_byte() {+ assert_eq!(octal_escape(&[]), "");+ assert_eq!(octal_escape(&[0x41]), "\\101");+ assert_eq!(octal_escape(&[0x00, 0x27, 0x5C]), "\\000\\047\\134");+ }++ #[test]+ #[cfg(unix)]+ fn the_remote_line_runs_on_a_posix_shell() {+ use std::ffi::OsStr;+ use std::os::unix::fs::PermissionsExt;++ let root = std::env::temp_dir().join(format!("craft-anything-remote-line-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(root.join("bin")).unwrap();+ std::fs::create_dir_all(root.join("home")).unwrap();+ // A fake helper on PATH, so `command -v craft-anything-cli` succeeds or fails on purpose.+ std::fs::write(root.join("bin/craft-anything-cli"), "#!/bin/sh\nexit 0\n").unwrap();+ std::fs::set_permissions(root.join("bin/craft-anything-cli"), std::fs::Permissions::from_mode(0o755)).unwrap();++ let home = root.join("home");+ let bin = root.join("bin");+ let mcp = McpCommand { command: "craft-anything-cli".into(), args: vec!["mcp".into(), "--clean-room".into()], notes: None };+ let content = config_content(&mcp);+ let name = config_name(&content);+ let line = remote_prepare_line(&name, &content);++ let run = |path: &OsStr| {+ std::process::Command::new("sh")+ .arg("-c")+ .arg(format!(+ "export HOME={}; export PATH={}:/usr/bin:/bin; {line}",+ crate::ssh::shell_quote(&home.display().to_string()),+ crate::ssh::shell_quote(&path.to_string_lossy())+ ))+ .output()+ .unwrap()+ };+ let ok = run(bin.as_os_str());+ assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));+ let target = home.join(".cache/craft-anything").join(&name);+ assert_eq!(std::fs::read(&target).unwrap(), content.as_bytes());+ assert_eq!(std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, 0o600);++ // The helper missing: the line fails fast (127) and writes nothing.+ let missing = run(OsStr::new("/nonexistent-craft-anything-xyz"));+ assert_eq!(missing.status.code(), Some(127));+ let leftover = home.join(".cache/craft-anything").join(format!("{name}.tmp.1"));+ assert!(!leftover.exists());++ std::fs::remove_dir_all(&root).ok();+ }++ #[test]+ fn the_remote_line_needs_no_input_and_checks_the_helper_first() {+ let mcp = McpCommand { command: "craft-anything-cli".into(), args: vec!["mcp".into()], notes: None };+ let content = config_content(&mcp);+ let name = config_name(&content);+ let line = remote_prepare_line(&name, &content);+ assert!(line.starts_with("command -v craft-anything-cli "), "{line}");+ assert!(line.contains("mkdir -p \"$HOME/.cache/craft-anything\""), "{line}");+ assert!(line.contains(&format!("\"$HOME/.cache/craft-anything/{name}\"")), "{line}");+ assert!(line.contains("chmod 600"), "{line}");+ assert!(!line.contains('\n'), "{line}");+ // No byte in the content can end the printf format string: every octet is escaped.+ let full_escaped = octal_escape(content.as_bytes());+ assert_eq!(octal_escape("{}".as_bytes()), "\\173\\175");+ assert!(line.contains(&format!("printf '{full_escaped}'")), "{line}");+ }+/// OpenCode V2 (2.2.5) names the call `id`, beside a `partID`; V1 named it `callID`.#[test]fn v2_tool_events_reach_the_feed() {diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex b3ec8bec..e2b11844 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -855,13 +855,15 @@ fn run_cli(spec: &CliSpec, text: &str, retry: bool, tx: &Sender<AgentEvent>, sto// 30 minutes and a background build at 10).let (turn, quiet) = if builder { (24 * 3600, 8 * 3600) } else { (30 * 60, 15 * 60) };let mut env = agent_env(builder, spec.options.effort);- if remote.is_none() {- match adapter.mcp_env(&mcp) {- Ok(var) => env.extend(var),- Err(e) => {- let _ = tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation, log: None });- return nothing_done(&name);- }+ let tool_env = match &remote {+ None => adapter.mcp_env(&mcp),+ Some(host) => adapter.remote_tool_server(host, &mcp),+ };+ match tool_env {+ Ok(var) => env.extend(var),+ Err(e) => {+ let _ = tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation, log: None });+ return nothing_done(&name);}}// Here the adapter's process runs the agent in its folder (`AgentAdapter::in_folder`); ondiff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rsindex 4066bcd5..428d1bd1 100644--- a/crates/ai/src/rebuild/mod.rs+++ b/crates/ai/src/rebuild/mod.rs@@ -633,14 +633,19 @@ impl Worker {progress.save(&ws.root)?;}// Fail before any work when the agent's tools are missing or it can't sign in.- let remote = entry.config.ssh_host.as_deref().is_some_and(|h| !h.trim().is_empty());- if !remote && api.is_none() {+ let remote_host = entry.config.ssh_host.as_deref().map(str::trim).filter(|h| !h.is_empty());+ let remote = remote_host.is_some();+ if api.is_none() {let adapter = opts.adapters.for_backend(&entry.config.model, &entry.options);- crate::cli_agents::check_builder_tools(adapter.as_ref(), &entry.config.model, &entry.options, &self.stop)?;- let program = crate::cli_agents::program_of(&entry.config, &entry.options);- if adapter.signed_in(&program) == Some(false) {- return Err(ToolError::new(ErrorCode::BadSettings, not_signed_in(&entry.config.model, adapter.signed_in_before()))- .with_remediation(adapter.sign_in_fix().unwrap_or_default()));+ if let Some(host) = remote_host {+ adapter.check_remote_tool_server(host, &self.stop)?;+ } else {+ crate::cli_agents::check_builder_tools(adapter.as_ref(), &entry.config.model, &entry.options, &self.stop)?;+ let program = crate::cli_agents::program_of(&entry.config, &entry.options);+ if adapter.signed_in(&program) == Some(false) {+ return Err(ToolError::new(ErrorCode::BadSettings, not_signed_in(&entry.config.model, adapter.signed_in_before()))+ .with_remediation(adapter.sign_in_fix().unwrap_or_default()));+ }}}self.attach(ws)?;diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex c75126ac..f822a2a3 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -603,6 +603,12 @@ Owner: open · Status: in progressexplicit model/thinking execution: a config file in `OPENCODE_CONFIG` with `run --standalone`(verified live locally). — claimed: advokat11, branch bugfix/r2.2-opencode-native-mcp- [ ] Hand native OpenCode runs over SSH the Craft Anything MCP server (the config file is local).+- [x] Hand native OpenCode runs over SSH the Craft Anything MCP server (the config file is local).+ One `ssh` run checks `craft-anything-cli` is on the host's PATH and writes the config on the+ host (`~/.cache/craft-anything/`, mode 600, atomic rename); the builder fails fast with the+ fix if the helper is missing. Verified: POSIX-shell regression test (`the_remote_line_runs_on_a_posix_shell`)+ and an SSH round-trip to localhost (probe, byte-exact write, mode, cleanup). Not run with a live+ agent over SSH. — claimed: jelassiaymen94, branch feature/r2.2-opencode-remote-mcp- [ ] Verify OpenCode model discovery and an explicit thinking selection on a live SSH host,and complete a live generation with the selected model and variant (local catalogue verified).diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 350498f3..e5264f1a 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -50,6 +50,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| SQLite added columns | Short records include missing trailing fields using literal column defaults, or NULL when absent; unsupported default expressions produce NULL with a row note. Stored fields and records longer than the schema retain their values. Defaults are filled before restoring rowid aliases | Nine hand-built parser regressions and an engine tool test cover added-column defaults, rewritten records and short records with a rowid alias, including a missing alias field || OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs; none over SSH yet). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. No live SSH host or paid generation used || Gemini tool calls | A tool call's `extra_content` (Gemini's thought signature) goes back with it unchanged, so Gemini 3 builders get past their first tool call; errors Gemini wraps in an array show their message (#978) | Unit-tested; not run against the live API |+| OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit selections run natively with the Craft Anything MCP server (local runs, and over SSH: one `ssh` run checks `craft-anything-cli` on the host's PATH and writes the config on the host, `~/.cache/craft-anything/`, mode 600). See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks route explicit selections natively and parse V2 tool events. Live (2026-11-04, Windows, OpenCode 2.2.5, opencode-go/deepseek-v4.1-flash): a `--standalone` run connected the server (38 tools) and called `core_session_show`. The SSH path is covered by a POSIX-shell regression test (probe fails fast without the helper; config written byte-exact, mode 600, atomic rename) and was exercised against a localhost SSH host; it has not been run with a live agent over SSH. No paid generation used || Claude desktop app without Claude Code | When the `claude` command isn't found but the Claude desktop app is (Windows: the Store package's `claude-desktop` app alias or the older installer's `AnthropicClaude` folder; macOS: `Claude.app`), the builder dialog under "No coding agent was found" and `ai detect` (on stderr) say the desktop app is installed but building needs Claude Code, installed apart (#259). Typed as `DetectHint` from `AiHub::detect_hints` | A regression finds the app in temp folders laid out as each Windows installer leaves it, and nothing on Linux; a UI test shows the hint in the dialog. On Windows 10 the real Store package's alias was found. Not checked: macOS, the older installer, and a computer with no `claude` installed || OpenCode models and thinking | OpenCode V2 locally and over SSH; Settings → AI lists only that instance's enabled chat models and supported Low/Medium/High/Xhigh/Max variants. Selection is validated and saved through UI, CLI and `ai_models_list` / `ai_model_set`. Explicit-selection execution is refused until native MCP integration exists; local ACP runs require clearing the selection. See [OpenCode](opencode.md). | Stand-in catalogue/process, persistence, remote-command and UI tests; local live catalogue checks (34 models, all five depths represented). Regression checks reject native chat/builds before process I/O with ACP on/off, local/SSH and model-only/depth-only/combined selections. No live SSH host or paid generation used || Claude desktop app without Claude Code | When the `claude` command isn't found but the Claude desktop app is (Windows: the Store package's `claude-desktop` app alias, else its package folder, or the older installer's `AnthropicClaude` folder; macOS: `Claude.app`), the builder dialog under "No coding agent was found" and `ai detect` (on stderr) say the desktop app is installed but building needs Claude Code, installed apart (#259). The hint stays when the only suggestions are unchecked agents from `~/.ssh/config`. A `claude` program inside the desktop app (on PATH) is never offered or started as Claude Code: detection, the hint and a run's program look through one `cli_agents::find_program`. Typed as `DetectHint` from `AiHub::detect_hints` | A regression finds the app in temp folders laid out as each Windows installer leaves it, and nothing on Linux; a UI test shows the hint in the dialog, with only SSH suggestions too, and not once an agent here is found; a test passes over the desktop app's `claude.exe` on a search path. On Windows 10 the real Store package's alias was found. Not checked: macOS, the older installer, and a computer with no `claude` installed |diff --git a/docs/opencode.md b/docs/opencode.mdindex 71e82aba..81d24e61 100644--- a/docs/opencode.md+++ b/docs/opencode.md@@ -7,6 +7,13 @@ Model and thinking choices can be discovered, validated and saved. A run with anselection goes through the native adapter (`opencode run --standalone`), which hands a local runthe Craft Anything MCP server in a config file named by `OPENCODE_CONFIG`; the person's ownsettings stay unchanged. Over SSH the native run has no Craft Anything tools yet.+selection goes through the native adapter (`opencode run --standalone`), which hands the run+the Craft Anything MCP server in a config file named by `OPENCODE_CONFIG`; the person's own+settings stay unchanged. Over SSH one `ssh` run checks that `craft-anything-cli` is on the+remote PATH and writes the file on the host itself (`~/.cache/craft-anything/`, named by its+content, kept private), so the remote run gets the same tools. The host needs+`craft-anything-cli` on its PATH — install Craft Anything there (the app keeps the helper+next to it). If the check fails, the turn stops before any work with the fix.## Desktop@@ -97,6 +104,9 @@ even if `acp = true` was previously set and runs natively. OpenCode V2 ignores`OPENCODE_CONFIG_CONTENT`, and plain `opencode run` hands the turn to the background service,which never sees the run's environment; so the adapter writes the server to a temp config fileand starts a private server with `--standalone`. V2 names a tool call `id` (V1: `callID`); both+which never sees the run's environment; so the adapter writes the server to a config file+and starts a private server with `--standalone` (locally in this computer's temporary+folder, over SSH on the host itself). V2 names a tool call `id` (V1: `callID`); bothare read, so tool calls reach the feed while the turn runs.Model discovery uses `opencode api model.list --param location[directory]=...` (the V2