Craft Anything: understand how any software works, and craft your own.
Rust
Build with an API backend without adding an agent (R5.5) (#819)
Alex Joaquim Pereiraf8d6e3585a84
diff --git a/apps/craft-anything-cli/src/rebuild_cmd.rs b/apps/craft-anything-cli/src/rebuild_cmd.rsindex 66924ce3..1fa99066 100644--- a/apps/craft-anything-cli/src/rebuild_cmd.rs+++ b/apps/craft-anything-cli/src/rebuild_cmd.rs@@ -71,9 +71,11 @@ pub fn rebuild(cli: &Cli, a: &RebuildArgs) -> u8 {}}-/// Use the configured agent app, or add the first one found on this computer.+/// Add the first agent app found on this computer when no enabled AI can build at all.fn ensure_agent(hub: &AiHub) -> Result<(), ToolError> {- if hub.backends().iter().any(|b| b.kind == BackendKind::AgentCli && b.enabled) {+ // An enabled API backend builds with our own agent loop, so this run needs no agent app. Only a+ // computer with no AI set up needs one found for it.+ if hub.backends().iter().any(|b| b.enabled) {return Ok(());}if let Some(d) = hub.detect().into_iter().find(|d| d.suggestion.kind == BackendKind::AgentCli) {@@ -86,7 +88,6 @@ fn ensure_agent(hub: &AiHub) -> Result<(), ToolError> {fn run(cli: &Cli, a: &RebuildArgs) -> Result<bool, ToolError> {let engine = make_engine(None, cli.deep_for_run())?;let hub = AiHub::new(engine.clone());- ensure_agent(&hub)?;if a.build_with.is_some() && a.continue_in.is_some() {return Err(ToolError::invalid("--build-with is for new projects; a project keeps the stack it was built with.").with_remediation("Leave out --build-with, or start a new project."));@@ -94,6 +95,7 @@ fn run(cli: &Cli, a: &RebuildArgs) -> Result<bool, ToolError> {if a.generate_assets && a.continue_in.is_some() {return Err(ToolError::invalid("--generate-assets is for new projects.").with_remediation("Use project-assets-allow for an existing project."));}+ ensure_agent(&hub)?;let (ws, message) = match &a.continue_in {Some(dir) => (Workspace::open(&std::path::absolute(dir).map_err(|e| ToolError::io(dir.display(), e))?)?, (!a.resume).then(|| a.request.clone())),None => {diff --git a/apps/craft-anything-cli/tests/rebuild_choice.rs b/apps/craft-anything-cli/tests/rebuild_choice.rsnew file mode 100644index 00000000..61a437d1--- /dev/null+++ b/apps/craft-anything-cli/tests/rebuild_choice.rs@@ -0,0 +1,146 @@+//! `rebuild` picks the AI it was told to use: a run on an API backend must not add a coding agent.+//! Each test gives the binary its own config, home and `PATH`, so the person's settings and the+//! agents installed on the machine don't decide the result.+//!+//! The command stops when it opens `--continue-in`'s empty folder, right after the builder check:+//! the test sees exactly the choice `rebuild` made before doing any work. An invalid command is+//! refused before that check, so it cannot add an agent either.+#![cfg(unix)]++use craft_anything_platform::process::{Output, Process};+use std::path::{Path, PathBuf};+use std::time::Duration;++/// Run the built CLI with only what the test gives it: no provider keys or installed agents leak in.+fn cli(args: &[&str], config: &Path, home: &Path, bin: &Path) -> Output {+ let path = format!("{}:/usr/bin:/bin", bin.display());+ Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))+ .args(args)+ .env_clear()+ .env("CRAFT_ANYTHING_CONFIG_DIR", config)+ .env("HOME", home)+ .env("PATH", path)+ .timeout(Duration::from_secs(90))+ .run()+ .unwrap()+}++/// A stand-in `claude` that Detect can find; it is never asked to build in these tests.+fn fake_claude(bin: &Path) -> PathBuf {+ use std::os::unix::fs::PermissionsExt;+ let program = bin.join("claude");+ std::fs::write(&program, "#!/bin/sh\nexit 0\n").unwrap();+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();+ program+}++fn api_config(config: &Path) {+ std::fs::write(+ config.join("config.toml"),+ "[[ai.backends]]\nname = \"API\"\nkind = \"openai_compatible\"\nmodel = \"test-model\"\nbase_url = \"http://127.0.0.1:9/v1\"\nenabled = true\n",+ )+ .unwrap();+}++fn stopped_run(project: &Path, backend: Option<&str>) -> Vec<String> {+ let mut args = vec![+ "rebuild".to_string(),+ "-".to_string(),+ "make a small page".to_string(),+ "--continue-in".to_string(),+ project.display().to_string(),+ "--rounds".to_string(),+ "0".to_string(),+ "--unattended".to_string(),+ ];+ if let Some(name) = backend {+ args.extend(["--backend".to_string(), name.to_string()]);+ }+ args+}++/// R5.5: the run names the API backend, so it needs no agent app and must not add one.+#[test]+fn an_api_backend_build_does_not_add_a_coding_agent() {+ let config = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let bin = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ api_config(config.path());+ fake_claude(bin.path());++ let args = stopped_run(project.path(), Some("API"));+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();+ let out = cli(&refs, config.path(), home.path(), bin.path());+ let log = out.stderr_text();+ assert!(!out.success, "the empty project folder must stop the run:\n{log}");+ assert!(log.contains("craft.json"), "the run must stop at the missing project, before any build:\n{log}");+ assert!(!log.contains("Using "), "a run on the API backend must not pick an agent:\n{log}");+ let saved = std::fs::read_to_string(config.path().join("config.toml")).unwrap();+ assert!(!saved.contains("agent_cli"), "no agent app may be saved for a run on an API backend:\n{saved}");+}++/// An enabled API backend is enough even when the request doesn't name it: the build can fall back+/// to it, so no agent app should be added either.+#[test]+fn an_enabled_api_backend_is_enough_without_being_named() {+ let config = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let bin = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ api_config(config.path());+ fake_claude(bin.path());++ let args = stopped_run(project.path(), None);+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();+ let out = cli(&refs, config.path(), home.path(), bin.path());+ let log = out.stderr_text();+ assert!(!out.success, "the empty project folder must stop the run:\n{log}");+ assert!(log.contains("craft.json"), "the run must stop at the missing project, before any build:\n{log}");+ assert!(!log.contains("Using "), "an enabled API backend must be enough without naming it:\n{log}");+ let saved = std::fs::read_to_string(config.path().join("config.toml")).unwrap();+ assert!(!saved.contains("agent_cli"), "no agent app may be saved when an API backend is enabled:\n{saved}");+}++/// A command refused before any build starts must not change the person's AI settings either.+#[test]+fn an_invalid_command_does_not_add_an_agent() {+ let config = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let bin = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ fake_claude(bin.path());++ let out = cli(+ &["rebuild", "-", "make a small page", "--continue-in", project.path().to_str().unwrap(), "--build-with", "rust", "--rounds", "0", "--unattended"],+ config.path(),+ home.path(),+ bin.path(),+ );+ let log = out.stderr_text();+ assert!(!out.success, "the refused command must fail:\n{log}");+ assert!(log.contains("--build-with is for new projects"), "the command must stop at validation:\n{log}");+ assert!(!log.contains("Using "), "a refused command must not pick an agent:\n{log}");+ let saved = std::fs::read_to_string(config.path().join("config.toml")).unwrap_or_default();+ assert!(!saved.contains("agent_cli"), "a refused command must not save an agent:\n{saved}");+}++/// The guard must not stop a computer with no AI at all from finding and saving an agent.+#[test]+fn a_computer_with_no_ai_still_finds_an_agent() {+ let config = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let bin = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ fake_claude(bin.path());++ let args = stopped_run(project.path(), None);+ let refs: Vec<&str> = args.iter().map(String::as_str).collect();+ let out = cli(&refs, config.path(), home.path(), bin.path());+ let log = out.stderr_text();+ assert!(!out.success, "the empty project folder must stop the run:\n{log}");+ assert!(log.contains("craft.json"), "the run must stop at the missing project, before any build:\n{log}");+ assert!(log.contains("Using Claude Code"), "an agent must still be found when no AI is set up:\n{log}");+ let saved = std::fs::read_to_string(config.path().join("config.toml")).unwrap();+ assert!(saved.contains("agent_cli"), "the found agent must still be saved:\n{saved}");+}diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 59dd4f68..602ba8dd 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -315,9 +315,12 @@ been run live.### R5.5 API-key builds fail in words people can useOwner: open · Status: todo-- [ ] `rebuild --backend <an API backend>` still adds the first agent app it finds to the person's+- [x] `rebuild --backend <an API backend>` still adds the first agent app it finds to the person'ssettings and prints "Using Claude Code (…)": `ensure_agent` (`rebuild_cmd.rs`) runs whenever noagent app is set up, though this run won't use one. Run it only when the build needs one+ — claimed: AlexJoaquimPereira, branch `bugfix/r5.5-no-agent-with-api-backend`+- [ ] `--backend <an unknown or disabled name>` with no enabled AI still finds and saves an agent+ before the name is refused: check the name before `ensure_agent` runs- [x] Bound accumulated data across all lines of one server-sent event, so short lines cannotgrow a streamed API response without limit— claimed: Afloat16, branch bugfix/r5.5-bounded-sse-events-20261103