Craft Anything: understand how any software works, and craft your own.
Rust
Give native OpenCode runs the Craft Anything tools and show their tool calls (#800)
advokat1192109f08f94a
diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rsindex 0992cc8b..7f8a0108 100644--- a/crates/ai/src/cli_agents/adapters.rs+++ b/crates/ai/src/cli_agents/adapters.rs@@ -165,6 +165,11 @@ pub trait AgentAdapter: Send + Sync {fn check_tool_server(&self, _stop: &CancelToken) -> Result<(), ToolError> {Ok(())}+ /// An environment variable that hands a local native run our tool server, for an agent that+ /// takes it from its environment rather than its arguments.+ fn mcp_env(&self, _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 ffa3dfb9..d6dede03 100644--- a/crates/ai/src/cli_agents/adapters/opencode.rs+++ b/crates/ai/src/cli_agents/adapters/opencode.rs@@ -15,16 +15,22 @@ impl AgentAdapter for OpenCode {true}- /// Native model selection cannot yet carry this run's Craft Anything MCP server.- fn check_native_options(&self, options: &BackendOptions) -> Result<(), ToolError> {- if options.cli_model.is_some() || options.cli_thinking.is_some() {- return Err(ToolError::new(- ErrorCode::BadSettings,- "OpenCode's native model/thinking selection cannot yet connect this run's Craft Anything tools.",- )- .with_remediation("For a local OpenCode run, clear the model and thinking selection and enable ACP, or choose another AI. Native MCP configuration is not implemented yet."));- }- Ok(())+ fn check_tool_server(&self, stop: &CancelToken) -> Result<(), ToolError> {+ cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop)+ }++ /// `opencode run` takes no MCP flag, and V2 ignores `OPENCODE_CONFIG_CONTENT`: the server+ /// 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)));+ craft_anything_platform::fs::write_atomic_private(&path, content.as_bytes())?;+ Ok(Some(("OPENCODE_CONFIG", path.to_string_lossy().into_owned())))}/// Discover enabled chat models and thinking variants from the selected local or SSH installation.@@ -53,7 +59,8 @@ impl AgentAdapter for OpenCode {/// Build native `run` arguments, encoding an optional thinking depth as `provider/model#variant`.fn args(&self, cx: &ArgsCx) -> Vec<String> {- let mut a = vec!["run".to_string()];+ // A private server reads this run's `OPENCODE_CONFIG`; the background service would not.+ let mut a = vec!["run".to_string(), "--standalone".to_string()];// A builder works unattended: what OpenCode would stop to ask is allowed, unless its own// settings deny it (as Codex gets a workspace-write sandbox).if cx.builder {@@ -70,7 +77,7 @@ impl AgentAdapter for OpenCode {}fn required_flags(&self) -> (&'static [&'static str], &'static [&'static str]) {- (&["run", "--help"], &["--format"])+ (&["run", "--help"], &["--format", "--standalone"])}fn plain_fallback(&self) -> bool {@@ -92,9 +99,9 @@ impl AgentAdapter for OpenCode {}}Some("tool_use") => {- if let (Some(id), Some(name), Some(state)) =- (part.get("callID").and_then(Value::as_str), part.get("tool").and_then(Value::as_str), part.get("state"))- {+ // V1 names the call `callID` (its `id` is the part's); V2 names it `id` (beside `partID`).+ let call = part.get("callID").or_else(|| part.get("id"));+ if let (Some(id), Some(name), Some(state)) = (call.and_then(Value::as_str), part.get("tool").and_then(Value::as_str), part.get("state")) {if !p.tool_names.contains_key(id) {events.push(p.started(id, name, state.get("input").cloned().unwrap_or_else(|| json!({}))));}@@ -178,12 +185,12 @@ mod tests {#[test]fn the_prompt_goes_to_run_after_the_flags() {- assert_eq!(args(false, &BackendOptions::default()), ["run", "--format", "json", "PRE make a game"]);+ assert_eq!(args(false, &BackendOptions::default()), ["run", "--standalone", "--format", "json", "PRE make a game"]);let options =BackendOptions { cli_model: Some("anthropic/claude-sonnet-4-5".into()), args: vec!["--agent".into(), "build".into()], ..Default::default() };assert_eq!(args(true, &options),- ["run", "--auto", "--model", "anthropic/claude-sonnet-4-5", "--agent", "build", "--format", "json", "PRE make a game"]+ ["run", "--standalone", "--auto", "--model", "anthropic/claude-sonnet-4-5", "--agent", "build", "--format", "json", "PRE make a game"]);assert!(AgentAdapters::built_in().for_agent("opencode").ids().contains(&"opencode"), "registered, not the plain adapter");}@@ -262,6 +269,29 @@ mod tests {assert_eq!(zero.cost_usd, Some(0.0), "an explicit zero is a known cost");}+ #[test]+ fn native_runs_get_the_tool_server_from_a_config_file() {+ let mcp = McpCommand { command: "craft-anything-cli".into(), args: vec!["mcp".into()], notes: None };+ let (var, path) = OpenCode.mcp_env(&mcp).unwrap().unwrap();+ assert_eq!(var, "OPENCODE_CONFIG");+ let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert_eq!(v["mcp"][MCP_NAME]["command"], json!(["craft-anything-cli", "mcp"]));+ let options = BackendOptions { cli_model: Some("test/model".into()), ..Default::default() };+ assert!(OpenCode.check_native_options(&options).is_ok());+ }++ /// OpenCode V2 (2.2.5) names the call `id`, beside a `partID`; V1 named it `callID`.+ #[test]+ fn v2_tool_events_reach_the_feed() {+ let mut p = StreamParser::new(Arc::new(OpenCode));+ let line = json!({"type":"tool_use","part":{"partID":"prt_1","type":"tool","id":"call_1","tool":"shell","state":{"status":"completed","input":{"command":"echo one"},"output":"one"}}});+ let events = p.line(&line.to_string());+ assert!(+ matches!(events.as_slice(), [AgentEvent::ToolStarted { tool, .. }, AgentEvent::ToolFinished { ok: true, .. }] if tool == "shell"),+ "{events:?}"+ );+ }+/// Every supported depth reaches native chat and builder runs in the selected model reference.#[test]fn thinking_depth_is_part_of_the_selected_model_reference() {@@ -294,7 +324,7 @@ mod tests {BackendOptions { command: Some("missing-test-opencode".into()), args: extra.iter().map(|s| s.to_string()).collect(), ..Default::default() };assert!(OpenCode.validate_model(&config, &options, None, &Stop::default()).is_ok());let argv = args(false, &options);- assert_eq!(argv.get(1..1 + extra.len()).unwrap(), extra.as_slice());+ assert_eq!(argv.get(2..2 + extra.len()).unwrap(), extra.as_slice());for (model, thinking) in [(Some("test/selected"), None), (None, Some(crate::Effort::High)), (Some("test/selected"), Some(crate::Effort::High))] {let selected = BackendOptions { cli_model: model.map(str::to_string), cli_thinking: thinking, ..options.clone() };let error = OpenCode.validate_model(&config, &selected, None, &Stop::default()).unwrap_err();diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex c006df65..47e65da4 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -821,6 +821,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);+ }+ }+ }// Here the adapter's process runs the agent in its folder (`AgentAdapter::in_folder`); on// another computer over SSH it's the folder chosen there, else the agent keeps its own.if remote.is_some()@@ -1277,61 +1286,21 @@ mod tests {}use crate::BackendKind;- /// Explicit OpenCode picks cannot pass ACP preflight then run natively without our MCP server.+ /// Explicit OpenCode picks run natively, where the tool server comes through inline config.#[test]- fn explicit_opencode_picks_are_refused_before_native_chat_or_build() {+ fn explicit_opencode_picks_run_natively_with_our_tools() {let adapter = adapter_for("opencode");let defaults = BackendOptions { acp: Some(true), ..Default::default() };assert!(selected_acp_args(adapter.as_ref(), "opencode", &defaults).is_some());for (model, thinking) in [(Some("test/model"), None), (None, Some(crate::Effort::High)), (Some("test/model"), Some(crate::Effort::Max))] {for acp in [false, true] {- let options = BackendOptions {- command: Some("missing-test-opencode".into()),- cli_model: model.map(str::to_string),- cli_thinking: thinking,- acp: Some(acp),- ..Default::default()- };- let refused = check_builder_tools(adapter.as_ref(), "opencode", &options, &CancelToken::default()).unwrap_err();- assert_eq!(refused.code, ErrorCode::BadSettings);- assert!(refused.message.contains("cannot yet connect"));- for host in [None, Some("test-host")] {- for building in [false, true] {- let config = BackendConfig {- name: "OpenCode".into(),- kind: BackendKind::AgentCli,- model: "opencode".into(),- base_url: None,- ssh_host: host.map(str::to_string),- enabled: true,- };- let mut spec = CliSpec::new(config, options.clone(), false, None);- if building {- spec.builder = Some(Builder { investigation: None, inbox: PathBuf::from("test-inbox") });- }- assert!(acp_for(&spec).is_none());- let mut c = if building { builder_conversation(spec, Arc::new(|_, _| false)) } else { conversation(spec) };- c.send("test");- let deadline = std::time::Instant::now() + Duration::from_secs(5);- let mut events = Vec::new();- while !events.iter().any(|e| matches!(e, AgentEvent::TurnDone { .. })) {- assert!(std::time::Instant::now() < deadline, "missing terminal event: {events:?}");- events.extend(c.poll());- std::thread::sleep(Duration::from_millis(1));- }- assert!(!c.is_busy());- events.extend(c.poll());- assert!(- matches!(events.as_slice(), [- AgentEvent::Error { message, remediation: Some(_), log: None },- AgentEvent::TurnDone { backend, input_tokens: 0, output_tokens: 0, cost_usd: None, cost_is_estimate: false }- ] if message == &refused.message && backend == "OpenCode"),- "{events:?}"- );- }- }+ let options = BackendOptions { cli_model: model.map(str::to_string), cli_thinking: thinking, acp: Some(acp), ..Default::default() };+ assert!(selected_acp_args(adapter.as_ref(), "opencode", &options).is_none());+ assert!(adapter.check_native_options(&options).is_ok());}}+ let mcp = McpCommand { command: "craft-anything-cli".into(), args: vec![], notes: None };+ assert!(adapter.mcp_env(&mcp).unwrap().is_some());}/// Validation failures finish exactly once, preserving cancellation status and other error details.diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex b66fc2f8..b8a9a58a 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -169,10 +169,10 @@ fn hub() -> (AiHub, tempfile::TempDir) {(h, dir)}-/// A CLI stand-in checks saved selections and refuses native execution until its MCP server is wired.+/// A CLI stand-in checks saved selections, and an explicit one runs natively with our MCP server.#[cfg(unix)]#[test]-fn opencode_selection_is_validated_saved_and_refused_without_native_mcp() {+fn opencode_selection_is_validated_saved_and_run_natively_with_our_mcp_server() {use std::os::unix::fs::PermissionsExt;let (h, dir) = hub();let program = dir.path().join("agent");@@ -180,8 +180,9 @@ fn opencode_selection_is_validated_saved_and_refused_without_native_mcp() {let seen = dir.path().join("arguments.txt");let quote = |p: &std::path::Path| ssh::shell_quote(&p.display().to_string());let script = format!(- "#!/bin/sh\ncase \"$1\" in\napi) cat {};;\nrun) printf '%s\\n' \"$@\" > {}; printf 'done';;\n*) exit 8;;\nesac\n",+ "#!/bin/sh\ncase \"$1\" in\napi) cat {};;\nrun) printf '%s\\n' \"$@\" > {}; cat \"$OPENCODE_CONFIG\" >> {}; printf 'done';;\n*) exit 8;;\nesac\n",quote(&catalogue),+ quote(&seen),quote(&seen));std::fs::write(&program, script).unwrap();@@ -209,12 +210,13 @@ fn opencode_selection_is_validated_saved_and_refused_without_native_mcp() {}events.extend(conversation.poll());events.retain(|event| !matches!(event, AgentEvent::Status { .. }));- assert!(- matches!(events.as_slice(), [AgentEvent::Error { message, .. }, AgentEvent::TurnDone { .. }]- if message.contains("cannot yet connect")),- "{events:?}"- );- assert!(!seen.exists(), "an explicit selection must not start a run without its MCP server");+ assert!(matches!(events.last(), Some(AgentEvent::TurnDone { .. })), "{events:?}");+ // The arguments, one per line, then the config file the run was handed.+ let ran = std::fs::read_to_string(&seen).unwrap();+ let args: Vec<&str> = ran.lines().collect();+ assert_eq!(args.get(..4), Some(["run", "--standalone", "--model", "test/alias#max"].as_slice()), "{ran}");+ let config: Value = serde_json::from_str(ran.lines().find(|l| l.starts_with("{\"mcp\"")).unwrap()).unwrap();+ assert_eq!(config["mcp"][cli_agents::MCP_NAME]["type"], "local", "the run gets our MCP server: {ran}");assert!(h.set_agent_model("OpenCode", Some("test/alias"), Some(Effort::Xhigh)).is_err());assert_eq!(h.options()["OpenCode"].cli_thinking, Some(Effort::Max), "a failed validation changes nothing");let stale = h.model_context("OpenCode").unwrap();diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 3033e257..0c324e65 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -494,8 +494,10 @@ Owner: open · Status: in progressand model-with-variant command forms, and share transport selection between preflight and runs.- [x] Rebase after #567 and translate the ten model-selection strings and two agent tool titlesin the Russian catalogue, restoring coverage and catalogue key parity.-- [ ] Supply and verify the run's Craft Anything MCP server in native OpenCode before enabling- explicit model/thinking execution (currently refused for chat and builds, locally and over SSH).+- [x] Supply and verify the run's Craft Anything MCP server in native OpenCode before enabling+ explicit 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).- [ ] 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 f0943f8f..ea4a9a77 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -13,7 +13,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Settings saved on exit | Pending app settings merge the session's latest AI table when its guard is available. A busy session defers non-AI edits in `config.pending.toml` without waiting for the tool; startup recovers them with the latest committed AI table | Isolated child-process regression exercises idle and busy exit saves, a late AI commit, startup recovery and pending non-AI edits; engine tests cover sidecar migrations and damaged/newer files. No live desktop shutdown was exercised || SQLite payload limits | Capped records retain column positions, disclose partial TEXT and BLOB values, omit incomplete BLOB hashes, and report partial coverage with read notes | Hand-built overflow-page regressions for five oversized records (including WITHOUT ROWID in declaration order) and two controls; table and index engine coverage and limitation regressions || 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-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 |+| 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 || 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 || Missing program paths | A program started by its path (a saved agent program, for one) that has no file there is reported with that path, as possibly moved by an update, with reason `path_missing`, instead of "isn't installed or isn't on your PATH"; a bare name still speaks of PATH. A relative path is looked up where the program starts (on Unix, its working folder), so a script there whose interpreter is missing isn't called a path with no file. It stays a missing program (`EngineMissing`), so builder turns aren't retried (#721). `ai test` names the agent program it ran and the saved one it replaced (`program`, `saved_program_replaced`), and `doctor` says a saved path has no program there | `a_saved_program_that_is_gone_is_named_by_test_and_doctor` runs both with a removed path. A regression starts a program at a path with no file on Windows 10 and checks the message, remediation and reason, with a bare-name control; on Linux (Docker), a relative script with a missing interpreter started in its folder, through `Process` and `Launch`. Not checked: a real Codex desktop update, or the app's Settings screen with a stale path || Mach-O Objective-C pointers | Chained offsets mapped only into file-empty `__PAGEZERO` reach the image-base fallback; pointer candidates must be backed by file bytes | Synthetic thin and fat Mach-O regression, plain-pointer and authenticated-rebase controls, null and unmapped-pointer checks. Real binaries were not checked for this correction |diff --git a/docs/opencode.md b/docs/opencode.mdindex c0d88b86..71e82aba 100644--- a/docs/opencode.md+++ b/docs/opencode.md@@ -3,10 +3,10 @@Craft Anything can run OpenCode V2 locally or on an SSH host. OpenCode owns its providerconnections and sign-in. Set these up in OpenCode on the computer where it will run.-Model and thinking choices can be discovered, validated and saved. Running with an explicit-selection is currently refused: our ACP transport cannot select it, and our native adapter-does not yet supply the run's Craft Anything MCP server. For local runs, clear both choices-and enable ACP, or use another AI. Native MCP integration remains pending in roadmap R2.2.+Model and thinking choices can be discovered, validated and saved. A run with an explicit+selection goes through the native adapter (`opencode run --standalone`), which hands a local run+the Craft Anything MCP server in a config file named by `OPENCODE_CONFIG`; the person's own+settings stay unchanged. Over SSH the native run has no Craft Anything tools yet.## Desktop@@ -93,8 +93,11 @@ the sidecar is removed after recovery or a successful full exit save that supersIt uses the existing settings schema and migrations; unreadable or newer files are not overwrittenby recovery.The current ACP transport cannot select models or variants. An explicit choice bypasses ACP-even if `acp = true` was previously set, but native preflight and execution reject it until-the run's MCP server can be supplied. The refusal completes the turn without starting OpenCode.+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 file+and starts a private server with `--standalone`. V2 names a tool call `id` (V1: `callID`); both+are read, so tool calls reach the feed while the turn runs.Model discovery uses `opencode api model.list --param location[directory]=...` (the V2`GET /api/model` operation). This keeps credentials and configuration resolution inside OpenCode.diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 5da5cd8e..400d5482 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -420,6 +420,13 @@ builder preflight still checked ACP's helper and the native adapter never suppliShare transport selection between preflight and execution; reject unsupported native optionsbefore running a process rather than starting an agent without the tools its task requires.+**A config route the installed version ignores.** OpenCode V2 (2.2.5) ignores+`OPENCODE_CONFIG_CONTENT`, and `opencode run` hands the turn to a background service that never sees the+run's environment, so the builder ran without our tools and fell back to calling the CLI from a shell.+V2 also names a tool call `id` (V1: `callID`), so every tool event was dropped and the feed stayed empty+for the whole turn. Use a file in `OPENCODE_CONFIG` with `run --standalone`, and confirm a live run+reached the server (`mcp connected server=craft-anything` in OpenCode's log), not just that it started.+**Keywords that only some code paths honour.** "…in Rust" picked Rust for apps but not for games, soa headless game rebuild stopped at once for want of Unity. It was found only by a live run. Run thereal flow end to end after changing how requests are read, and add the case as a test.