Craft Anything: understand how any software works, and craft your own.
Rust
A build stops with a plain message when craft-anything-cli is missing (#226)
Brandon Thomasda83b81be2af
diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rsindex 2de9cc13..db1d35d6 100644--- a/crates/ai/src/cli_agents/adapters.rs+++ b/crates/ai/src/cli_agents/adapters.rs@@ -75,6 +75,12 @@ pub trait AgentAdapter: Send + Sync {fn sign_in_fix(&self) -> Option<String> {None}+ /// Whether what a build needs from this computer is there, for an agent that's handed our tool+ /// server, checked before a build starts. An agent that isn't handed it has nothing to check.+ /// `stop` ends the check when the person stops the build.+ fn check_tool_server(&self, _stop: &CancelToken) -> Result<(), ToolError> {+ Ok(())+ }}/// The adapters a run can use.@@ -181,6 +187,10 @@ impl AgentAdapter for ClaudeCode {true}+ fn check_tool_server(&self, stop: &CancelToken) -> Result<(), ToolError> {+ cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop)+ }+fn args(&self, cx: &ArgsCx) -> Vec<String> {let mut a = cx.options.args.clone();if cx.question {@@ -299,6 +309,10 @@ impl AgentAdapter for Codex {&["codex"]}+ fn check_tool_server(&self, stop: &CancelToken) -> Result<(), ToolError> {+ cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop)+ }+fn args(&self, cx: &ArgsCx) -> Vec<String> {let mut v = vec!["exec".to_string(), "--json".into()];// Project folders aren't git repositories, and `codex exec` refuses to run outside onediff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex 936f1629..8e5cf558 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -17,13 +17,14 @@ pub use adapters::{AgentAdapter, AgentAdapters, ArgsCx};use crate::config::BackendOptions;use crate::model::Stop;use crate::{AgentEvent, BackendConfig, Conversation};-use craft_anything_evidence::ToolError;+use craft_anything_engine::CancelToken;+use craft_anything_evidence::{ErrorCode, ToolError};use craft_anything_platform::process::Process;use craft_anything_platform::sync::Mutex;use serde_json::{Value, json};use std::collections::HashMap;use std::ffi::OsStr;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::mpsc::{Receiver, Sender};use std::sync::{Arc, PoisonError};@@ -91,6 +92,39 @@ impl McpCommand {}}+/// Whether the `craft-anything-cli` a builder's tool server runs from (None: there isn't one) can+/// start. Without it Claude Code stops at its first approval with a stack trace (#91). A check+/// that ran out of time says nothing about the program, so the build goes ahead. Stopping the+/// build ends the check, as `ErrorCode::Cancelled`.+pub fn cli_can_start(cli: Option<&Path>, stop: &CancelToken) -> Result<(), ToolError> {+ const REINSTALL: &str = "Install the latest Craft Anything again: it keeps this helper next to the app. If you built the app yourself, run `cargo build -p craft-anything-cli` too.";+ let Some(cli) = cli else {+ return Err(ToolError::new(ErrorCode::EngineMissing, "Craft Anything's helper program (craft-anything-cli) is missing, so the builder can't start.")+ .with_remediation(REINSTALL));+ };+ let failed = |why: String| {+ ToolError::new(ErrorCode::EngineMissing, format!("Craft Anything's helper program at {} wouldn't start: {why}", cli.display()))+ .with_remediation(REINSTALL)+ };+ let stop = stop.clone();+ match Process::new(cli.as_os_str()).arg("--version").timeout(Duration::from_secs(30)).stdout_cap(64 * 1024).cancel_when(move || stop.is_cancelled()).run() {+ Ok(out) if out.success => Ok(()),+ Ok(out) => Err(failed(out.code.map_or_else(|| "it was stopped by the system".to_string(), |c| format!("it exited with code {c}")))),+ Err(e) if e.code == ErrorCode::TimedOut => Ok(()),+ Err(e) if e.code == ErrorCode::Cancelled => Err(e),+ Err(e) => Err(failed(e.message)),+ }+}++/// Whether a local build by `agent` can have our tool server: over ACP every agent is handed it,+/// else its adapter says.+pub fn check_builder_tools(adapter: &dyn AgentAdapter, agent: &str, options: &BackendOptions, stop: &CancelToken) -> Result<(), ToolError> {+ if options.acp == Some(true) && acp::acp_args(agent).is_some() {+ return cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop);+ }+ adapter.check_tool_server(stop)+}+fn toml_string(s: &str) -> String {serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())}@@ -1009,6 +1043,66 @@ mod tests {assert!(text.contains("Request"), "preamble is passed too");}+ /// #91: a Mac app with no CLI beside it reached Claude Code, which stopped with a stack trace.+ #[test]+ fn a_missing_or_broken_helper_is_said_plainly() {+ let stop = CancelToken::default();+ let none = cli_can_start(None, &stop).unwrap_err();+ assert!(none.message.contains("craft-anything-cli") && none.message.contains("missing"), "{none:?}");+ assert!(none.remediation.as_deref().is_some_and(|r| r.contains("Install the latest")), "{none:?}");++ let dir = tempfile::tempdir().unwrap();+ let gone = cli_can_start(Some(&dir.path().join("craft-anything-cli")), &stop).unwrap_err();+ assert!(gone.message.contains("wouldn't start"), "{gone:?}");+ assert!(gone.remediation.is_some());+ }++ #[cfg(unix)]+ #[test]+ fn a_helper_is_judged_by_whether_it_runs() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let helper = |name: &str, script: &str| {+ let p = dir.path().join(name);+ std::fs::write(&p, script).unwrap();+ std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();+ p+ };+ let stop = CancelToken::default();+ assert!(cli_can_start(Some(&helper("good", "#!/bin/sh\necho 1.0\n")), &stop).is_ok());+ let bad = cli_can_start(Some(&helper("bad", "#!/bin/sh\nexit 3\n")), &stop).unwrap_err();+ assert!(bad.message.contains("exited with code 3"), "{bad:?}");+ }++ /// Stopping a build doesn't wait for a helper that hangs, and reads as stopped, not as broken.+ #[cfg(unix)]+ #[test]+ fn stopping_ends_the_check_of_a_hung_helper() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let hung = dir.path().join("hung");+ std::fs::write(&hung, "#!/bin/sh\nexec sleep 25\n").unwrap();+ std::fs::set_permissions(&hung, std::fs::Permissions::from_mode(0o755)).unwrap();+ let stop = CancelToken::default();+ let stopper = stop.clone();+ std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(200));+ stopper.cancel();+ });+ let began = std::time::Instant::now();+ let e = cli_can_start(Some(&hung), &stop).unwrap_err();+ assert_eq!(e.code, ErrorCode::Cancelled, "{e:?}");+ assert!(began.elapsed() < Duration::from_secs(10), "it waited for the helper: {:?}", began.elapsed());+ }++ /// Agents that are never handed the tool server build without the helper.+ #[test]+ fn only_agents_handed_the_tool_server_need_the_helper() {+ for agent in ["gemini-cli", "aider", "no-such-agent"] {+ assert!(check_builder_tools(adapter_for(agent).as_ref(), agent, &BackendOptions::default(), &CancelToken::default()).is_ok(), "{agent}");+ }+ }+#[test]fn missing_cli_is_a_clear_error() {let spec = CliSpec::new(diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rsindex 09154da4..2af385d4 100644--- a/crates/ai/src/rebuild/mod.rs+++ b/crates/ai/src/rebuild/mod.rs@@ -574,10 +574,11 @@ impl Worker {extractor: Option<(String, crate::agent::ApiConversation)>,opts: &RunOptions,) -> Result<String, ToolError> {- // Fail before any work when the agent can't sign in.+ // 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 adapter = opts.adapters.for_agent(&entry.config.model);+ crate::cli_agents::check_builder_tools(adapter.as_ref(), &entry.config.model, &entry.options, &self.stop)?;let program = entry.options.command.clone().unwrap_or_else(|| crate::cli_agents::program_for(&entry.config.model));if adapter.signed_in(&program) == Some(false) {let who = crate::cli_agents::display_for(&entry.config.model);diff --git a/crates/ai/src/rebuild/tests.rs b/crates/ai/src/rebuild/tests.rsindex 7dee1628..2fc6e4ff 100644--- a/crates/ai/src/rebuild/tests.rs+++ b/crates/ai/src/rebuild/tests.rs@@ -899,6 +899,47 @@ mod picking_up_a_build {ws}+ /// #91: with the helper missing, the build stops before studying or asking the agent, and+ /// says why.+ #[test]+ fn a_missing_helper_stops_the_build_before_any_work() {+ struct NoHelper;+ impl crate::cli_agents::AgentAdapter for NoHelper {+ fn ids(&self) -> &'static [&'static str] {+ &["stand-in"]+ }+ fn args(&self, cx: &crate::cli_agents::ArgsCx) -> Vec<String> {+ vec![cx.prompt.to_string()]+ }+ fn streams_json(&self) -> bool {+ false+ }+ fn check_tool_server(&self, stop: &CancelToken) -> Result<(), ToolError> {+ crate::cli_agents::cli_can_start(None, stop)+ }+ }+ let b = bench();+ let ws = Workspace::create(&b.projects, "x", "A thing", TargetRef::None).unwrap();+ let mut adapters = crate::cli_agents::AgentAdapters::built_in();+ adapters.register(Arc::new(NoHelper));+ let run =+ RebuildRun::start(&b.hub, Workspace::open(&ws.root).unwrap(), RunOptions { adapters, backend: Some("Stand-in".into()), ..RunOptions::default() })+ .unwrap();+ let began = Instant::now();+ let finished = loop {+ assert!(began.elapsed() < Duration::from_secs(30), "the run never finished");+ match run.rx.recv_timeout(Duration::from_secs(30)) {+ Ok(RunEvent::Finished { ok, message, .. }) => break (ok, message),+ Ok(_) => {}+ Err(e) => panic!("the run went away: {e}"),+ }+ };+ assert!(!finished.0, "{finished:?}");+ assert!(finished.1.contains("craft-anything-cli"), "{finished:?}");+ assert_eq!(prompts_given(&b), 0, "the agent was asked anyway");+ assert!(!studied(&feed::load(&Workspace::open(&ws.root).unwrap())), "it studied first");+ }+#[test]fn try_again_after_a_check_that_could_not_run_only_checks() {let b = bench();diff --git a/docs/STATUS.md b/docs/STATUS.mdindex da08831e..f209e9ba 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -19,7 +19,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Clean room and Deep mode | Clean room (the default) runs only the tools in `engine/src/clean_room.rs`: ones that touch no target or watch from outside (the website as a visitor sees it, pictures of a window, its controls, recorded runs, a phone's screen). Every other tool, a plugin's included, is refused in the app, CLI, MCP and agents, with a way to turn on Deep mode. A Clean room build studies an app or a game only from the person's pictures and words (and a picture of its window when runtime study is on); its builder's reads and commands go through an approval rule that keeps it out of the original's folder and site. Deep mode (`deep_mode` in Settings, `--deep` for one CLI run) uses every tool: the builder sees them all, and a website's study also reads its JavaScript and watches its start page for ten seconds (capture/how-it-works.md). Ghidra adds its decompiler in Deep mode when it's installed: it is found, or installed after asking. Study starts one analysis of the main program, saved and shared with the builder's tool server through a lock file (up to 8 h, Java gets half the machine's memory or the amount set in Settings → Engines, 4 to 31 GB, four slow passes skipped). The builder must decompile before the build is checked; addresses the built-in analysis can't place go to Ghidra, which makes a function on demand (for this run only) where its analysis has none, e.g. code reached only through tables of pointers. Without Ghidra, Deep mode uses the built-in engines | Live runs with Ghidra 12.1.4 on Windows (a shared analysis, and a decompile in seconds on a large program). The guided install of Ghidra and its Java is offered on Linux and macOS too, but has only been tried on Windows. Clean room and Deep mode: engine, AI, MCP, CLI and app tests; no live Clean room build run yet || Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget | Unit tests || Generated assets | Off until the person turns them on for a game (the switch on Make and on the project, `project_assets_allow`, `rebuild --generate-assets`, saved in craft.json; turning it on without a fal.ai key asks for one); the brief and the asset tools need both that and a key. `assets_image_generate` (Nano Banana Pro by default) and `assets_model_generate` (picture → Tripo P1 low-poly GLB with a face limit) through the person's key for each asset provider (fal.ai today); per-project budget, $5 by default (`[assets] budget_usd` in config.toml); models and prices from the `assets.toml` table (picture model selectable: Nano Banana Pro, FLUX dev or schnell; priced per picture or per megapixel); every call reports its cost | Unit tests; a live 3D generation with a real key (picture, then model) with FLUX dev; Nano Banana Pro not yet run with a real key |-| Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; sign-in preflight | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) |+| Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) || Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode and goose in their ACP mode, one agent process per chat or build with our MCP server. In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode) | Protocol unit tests against scripted agent messages and an approval-policy test; not yet run against a real agent || WASM plugins | With `--features wasm-plugins`: `[[plugins.wasm]]` components exporting `craft-anything:plugin/tools` add tools, and ones exporting `craft-anything:plugin/checks` add checks run after each kind's own (they get the build's file list as JSON) (added, listed, turned on or off and removed in Settings → Plugins or with `plugins_add`/`plugins_remove`/`plugins_list`); no imports, fresh instance per call, fuel and memory limits | Tests with components written in WAT (describe, call, checks, a looping call stopped, imports refused, end to end through the engine); `examples/wasm-plugin-wordcount` built from Rust and loaded || Questions and approvals | A file inbox per project; `core_person_ask`, `core_action_approve` and MCP consent requests become cards in the app | Cross-handle round-trip tests, a full approval round trip through the engine |diff --git a/docs/claude-code.md b/docs/claude-code.mdindex ac8e2f88..42963b3f 100644--- a/docs/claude-code.md+++ b/docs/claude-code.md@@ -10,7 +10,11 @@ integration does, why it is shaped this way, and what remains to confirm.--output-format stream-json --verbose`, with `--resume <session>` to continue a project.- The working folder is the project folder. Craft Anything's own tools are offered through`--mcp-config` (our MCP server, `craft-anything-cli mcp --project … --inbox …`) with- `--strict-mcp-config`.+ `--strict-mcp-config`. A build checks that `craft-anything-cli` starts before doing anything+ else, and says so plainly if not. Without the server Claude Code stops at its first approval+ with `MCP tool mcp__craft-anything__core_action_approve … not found. Available MCP tools: none`,+ and its MCP log blames an executable called `stdio`: that's Claude Code's wording for a command+ that wouldn't start, whatever the command was, not something in our config.- Our MCP server runs in the build's mode (`--deep` or `--clean-room`); in Deep mode it listsevery tool (`--all-tools`).- Permissions: read-only tools (`Read`, `Glob`, `Grep`) and our MCP tools are pre-allowed in Deepdiff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 25ec7f85..60947cb7 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -127,6 +127,9 @@ It happened again in a release: the macOS app bundle had only `craft-anything`,a separate zip, so every Claude Code build from the 0.2.0 DMG failed the same way (#91). Everypackage that ships the app ships the CLI beside its executable, and the packaging script runsthe CLI from the finished package before it's published.+Its symptom misled people too: Claude Code's MCP log says `Executable not found in $PATH: "stdio"`+for any command that won't start, so #64 went looking for a bad config. Reproduce with the real+program before believing what a log's wording suggests.**A Windows path with forward slashes read as nothing.** rtl_433 decoded a recording in the shellbut found no messages, and exited 0, when the test passed `C:/…/x.cu8`; it only reads Windows