Craft Anything: understand how any software works, and craft your own.
Rust
Choose OpenCode models and thinking depth locally or over SSH (#413)
Matthias Bodsch1d66a6ba4b0e
diff --git a/apps/craft-anything-cli/src/ai_cmd.rs b/apps/craft-anything-cli/src/ai_cmd.rsindex 4a22bb94..de349923 100644--- a/apps/craft-anything-cli/src/ai_cmd.rs+++ b/apps/craft-anything-cli/src/ai_cmd.rs@@ -61,7 +61,16 @@ pub enum AiCommand {Program { name: String, path: Option<String> },/// Set the model an AI uses (Claude Code: the model it's asked for); leave it out to list the/// ones it can use.- Model { name: String, model: Option<String> },+ Model {+ name: String,+ model: Option<String>,+ /// OpenCode thinking variant; only those offered by the selected model are accepted.+ #[arg(long, value_parser = ["low", "medium", "high", "xhigh", "max"])]+ thinking: Option<String>,+ /// Use OpenCode's default model and thinking depth.+ #[arg(long, conflicts_with_all = ["model", "thinking"])]+ default: bool,+ },/// Set how hard a Claude backend thinks (the Claude API or Claude Code): low, medium, high,/// xhigh or max, or `default` for the usual level; leave it out to see the level and choices.Effort { name: String, level: Option<String> },@@ -186,6 +195,8 @@ fn read_key(key_env: &Option<String>, key_stdin: bool) -> Result<Option<String>,Ok(None)}+/// Dispatch AI configuration, discovery and model-selection commands through the shared hub.+/// Render results in the requested format and return an exit status for success or failure.pub fn ai(cli: &Cli, c: &AiCommand, f: Format) -> u8 {let hub = match hub(cli) {Ok(h) => h,@@ -258,14 +269,38 @@ pub fn ai(cli: &Cli, c: &AiCommand, f: Format) -> u8 {Err(e) => fail(&e, f),}}- AiCommand::Model { name, model: None } => match hub.model_choices(name) {+ AiCommand::Model { name, model, thinking, default } if *default || thinking.is_some() => {+ let depth = thinking.as_deref().and_then(craft_anything_ai::Effort::parse);+ let model = if *default { None } else { model.clone().or_else(|| hub.options().get(name).and_then(|o| o.cli_model.clone())) };+ match hub.set_agent_model(name, model.as_deref(), depth) {+ Ok(found) => {+ emit(&json!({"name": name, "model": model, "thinking": depth, "found": found}), f);+ if found { 0 } else { 1 }+ }+ Err(e) => fail(&e, f),+ }+ }+ AiCommand::Model { name, model: None, .. }+ if hub.model_context(name).is_ok_and(|c| {+ c.backend.config.kind == BackendKind::AgentCli && craft_anything_ai::cli_agents::adapter_for(&c.backend.config.model).has_model_catalog()+ }) =>+ {+ match hub.model_context(name).and_then(|c| hub.agent_models(&c)) {+ Ok(models) => {+ emit(&json!({"name": name, "models": models}), f);+ 0+ }+ Err(e) => fail(&e, f),+ }+ }+ AiCommand::Model { name, model: None, .. } => match hub.model_choices(name) {Ok(models) => {emit(&json!({"name": name, "models": models}), f);0}Err(e) => fail(&e, f),},- AiCommand::Model { name, model: Some(model) } => match hub.set_model(name, model) {+ AiCommand::Model { name, model: Some(model), .. } => match hub.set_model(name, model) {Ok(found) => {emit(&json!({"name": name, "model": model.trim(), "found": found}), f);if found { 0 } else { 1 }diff --git a/apps/craft-anything-cli/tests/cli.rs b/apps/craft-anything-cli/tests/cli.rsindex 6d8b799e..5fbd8c3a 100644--- a/apps/craft-anything-cli/tests/cli.rs+++ b/apps/craft-anything-cli/tests/cli.rs@@ -8,6 +8,31 @@ fn cli(args: &[&str], config: &std::path::Path) -> Output {Process::new(env!("CARGO_BIN_EXE_craft-anything-cli")).args(args).env("CRAFT_ANYTHING_CONFIG_DIR", config).timeout(Duration::from_secs(60)).run().unwrap()}+/// The CLI lists installation-specific depths and refuses unsupported selections using an isolated agent fixture.+#[cfg(unix)]+#[test]+fn opencode_cli_lists_supported_depths_and_rejects_unsupported_choices() {+ use std::os::unix::fs::PermissionsExt;+ let cfg = tempfile::tempdir().unwrap();+ let program = cfg.path().join("agent");+ let response = json!({"data":[{"id":"model","providerID":"test","name":"Test model","enabled":true,"type":"chat","variants":[{"id":"low"},{"id":"max"}]}]});+ std::fs::write(&program, format!("#!/bin/sh\ncat <<'MODELS'\n{response}\nMODELS\n")).unwrap();+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();+ assert!(cli(&["ai", "add", "OpenCode", "--kind", "agent_cli", "--model", "opencode"], cfg.path()).success);+ assert!(cli(&["ai", "program", "OpenCode", program.to_str().unwrap()], cfg.path()).success);+ let listing = cli(&["ai", "model", "OpenCode", "--format", "json"], cfg.path());+ let list: Value = serde_json::from_slice(&listing.stdout).unwrap();+ assert_eq!(list["models"][0]["thinking"], json!(["low", "max"]));+ assert!(cli(&["ai", "model", "OpenCode", "test/model", "--thinking", "max"], cfg.path()).success);+ assert!(!cli(&["ai", "model", "OpenCode", "--thinking", "xhigh"], cfg.path()).success);+ let saved = std::fs::read_to_string(cfg.path().join("config.toml")).unwrap();+ assert!(saved.contains("cli_thinking = \"max\""), "invalid choices must not replace the saved choice");+ assert!(cli(&["ai", "model", "OpenCode", "--default"], cfg.path()).success);+ let saved = std::fs::read_to_string(cfg.path().join("config.toml")).unwrap();+ assert!(!saved.contains("cli_model") && !saved.contains("cli_thinking"));+ assert_eq!(cli(&["ai", "model", "OpenCode", "test/model", "--default"], cfg.path()).code, Some(2));+}+#[test]fn commands_and_exit_codes() {let cfg = tempfile::tempdir().unwrap();diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rsindex 01b9644d..eafb3dc1 100644--- a/crates/ai/src/cli_agents/adapters.rs+++ b/crates/ai/src/cli_agents/adapters.rs@@ -38,6 +38,30 @@ pub trait AgentAdapter: Send + Sync {fn ids(&self) -> &'static [&'static str];/// argv after the program for one message.fn args(&self, cx: &ArgsCx) -> Vec<String>;+ /// Whether this agent supplies its own live model and thinking choices.+ fn has_model_catalog(&self) -> bool {+ false+ }+ /// Query models visible in this backend's execution context, respecting cancellation.+ /// Agents without catalogue support return an empty list.+ fn model_catalog(+ &self,+ _config: &BackendConfig,+ _options: &BackendOptions,+ _directory: Option<&Path>,+ _stop: &Stop,+ ) -> Result<Vec<models::AgentModel>, ToolError> {+ Ok(Vec::new())+ }+ /// Check a saved choice in the actual run context before invoking the agent.+ fn validate_model(&self, _config: &BackendConfig, _options: &BackendOptions, _directory: Option<&Path>, _stop: &Stop) -> Result<(), ToolError> {+ Ok(())+ }+ /// Refuse options that the native transport cannot support, before preflight or process I/O.+ /// Saving a model choice and discovering its catalogue do not imply native execution support.+ fn check_native_options(&self, _options: &BackendOptions) -> Result<(), ToolError> {+ Ok(())+ }/// `(help invocation, substrings it must mention)`, checked once before the first run; when/// they're missing the run falls back to the plain adapter. Empty: nothing to check.fn required_flags(&self) -> (&'static [&'static str], &'static [&'static str]) {diff --git a/crates/ai/src/cli_agents/adapters/opencode.rs b/crates/ai/src/cli_agents/adapters/opencode.rsindex 68a9a4ef..ffa3dfb9 100644--- a/crates/ai/src/cli_agents/adapters/opencode.rs+++ b/crates/ai/src/cli_agents/adapters/opencode.rs@@ -10,6 +10,48 @@ impl AgentAdapter for OpenCode {&["opencode"]}+ /// OpenCode V2 exposes a catalogue through its authenticated CLI.+ fn has_model_catalog(&self) -> bool {+ 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(())+ }++ /// Discover enabled chat models and thinking variants from the selected local or SSH installation.+ fn model_catalog(+ &self,+ config: &BackendConfig,+ options: &BackendOptions,+ directory: Option<&Path>,+ stop: &Stop,+ ) -> Result<Vec<models::AgentModel>, ToolError> {+ models::discover(config, options, directory, stop)+ }++ /// Validate explicit choices against the live catalogue and refuse conflicting extra model arguments.+ /// With no selection, leave extra arguments to OpenCode and skip the catalogue query.+ fn validate_model(&self, config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>, stop: &Stop) -> Result<(), ToolError> {+ if options.cli_model.is_none() && options.cli_thinking.is_none() {+ return Ok(());+ }+ // Extra flags must not silently override the selected model or its thinking variant.+ if options.args.iter().any(|a| a == "--model" || a.starts_with("--model=") || a.starts_with("-m")) {+ return Err(ToolError::invalid("Choose OpenCode's model in its model setting, rather than in extra arguments."));+ }+ models::validate(options, &self.model_catalog(config, options, directory, stop)?)+ }++ /// 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 builder works unattended: what OpenCode would stop to ask is allowed, unless its own@@ -18,7 +60,8 @@ impl AgentAdapter for OpenCode {a.push("--auto".into());}if let Some(m) = &cx.options.cli_model {- a.extend(["--model".into(), m.clone()]);+ let model = cx.options.cli_thinking.map_or_else(|| m.clone(), |d| format!("{m}#{}", d.as_str()));+ a.extend(["--model".into(), model]);}a.extend(cx.options.args.iter().cloned());a.extend(["--format".into(), "json".into()]);@@ -218,4 +261,45 @@ mod tests {zero.line(&step(json!(0)));assert_eq!(zero.cost_usd, Some(0.0), "an explicit zero is a known cost");}++ /// 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() {+ for depth in crate::Effort::ALL {+ let options = BackendOptions { cli_model: Some("test/model".into()), cli_thinking: Some(depth), ..Default::default() };+ for builder in [false, true] {+ let argv = args(builder, &options);+ let model = argv.iter().position(|a| a == "--model").unwrap();+ assert_eq!(argv[model + 1], format!("test/model#{}", depth.as_str()));+ assert_eq!(argv.last().unwrap(), "PRE make a game");+ }+ }+ let argv = args(false, &BackendOptions::default());+ assert!(!argv.iter().any(|a| a == "--model"));+ }++ /// Extra model arguments work without a saved selection, but cannot override an explicit model or depth.+ #[test]+ fn extra_model_arguments_are_checked_only_for_explicit_selections() {+ let config = BackendConfig {+ name: "OpenCode".into(),+ kind: crate::BackendKind::AgentCli,+ model: "opencode".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ };+ for extra in [vec!["--model", "test/legacy"], vec!["--model=test/legacy"], vec!["-m", "test/legacy"], vec!["-mtest/legacy"]] {+ let options =+ 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());+ 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();+ assert_eq!(error.code, craft_anything_evidence::ErrorCode::BadInput);+ }+ }+ }}diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rsindex 8fa4c6ce..3fcbdbdd 100644--- a/crates/ai/src/cli_agents/mod.rs+++ b/crates/ai/src/cli_agents/mod.rs@@ -10,6 +10,7 @@pub mod acp;pub mod adapters;+pub mod models;pub use acp::AcpConversation;pub use adapters::{AgentAdapter, AgentAdapters, ArgsCx};@@ -120,12 +121,22 @@ pub fn cli_can_start(cli: Option<&Path>, stop: &CancelToken) -> Result<(), ToolE/// 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() {+ if selected_acp_args(adapter, agent, options).is_some() {return cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop);}+ adapter.check_native_options(options)?;adapter.check_tool_server(stop)}+/// The requested transport, shared by builder preflight and execution. ACP cannot carry explicit+/// catalogue model/variant selections yet, so those must pass the native adapter's checks.+fn selected_acp_args(adapter: &dyn AgentAdapter, agent: &str, options: &BackendOptions) -> Option<&'static [&'static str]> {+ if adapter.has_model_catalog() && (options.cli_model.is_some() || options.cli_thinking.is_some()) {+ return None;+ }+ acp::acp_args(agent).filter(|_| options.acp == Some(true))+}+fn toml_string(s: &str) -> String {serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())}@@ -435,7 +446,8 @@ pub fn builder_conversation(spec: CliSpec, approver: acp::Approver) -> Box<dyn Cfn acp_for(spec: &CliSpec) -> Option<AcpConversation> {let agent = spec.config.model.clone();let local = spec.config.ssh_host.as_deref().is_none_or(|h| h.trim().is_empty());- let acp_args = acp::acp_args(&agent).filter(|_| spec.options.acp == Some(true) && local)?;+ let adapter = spec.adapters.for_agent(&agent);+ let acp_args = selected_acp_args(adapter.as_ref(), &agent, &spec.options).filter(|_| local)?;let program = spec.options.command.clone().unwrap_or_else(|| program_for(&agent));let mut args = spec.options.args.clone();args.extend(acp_args.iter().map(|a| a.to_string()));@@ -549,6 +561,19 @@ fn run_cli(spec: &CliSpec, text: &str, tx: &Sender<AgentEvent>, stop: &Stop, stalet program = spec.options.command.clone().unwrap_or_else(|| program_for(&agent));let remote = spec.config.ssh_host.clone().filter(|h| !h.trim().is_empty());let mut adapter = spec.adapters.for_agent(&agent);+ if let Err(e) = adapter.check_native_options(&spec.options) {+ let _ = tx.send(AgentEvent::Error { message: e.message, remediation: e.remediation, log: None });+ return nothing_done(&name);+ }+ if let Err(e) = adapter.validate_model(&spec.config, &spec.options, spec.project.as_deref(), stop) {+ let event = if e.code == ErrorCode::Cancelled {+ AgentEvent::Status { text: "Stopped.".into() }+ } else {+ AgentEvent::Error { message: e.message, remediation: e.remediation, log: None }+ };+ let _ = tx.send(event);+ return nothing_done(&name);+ }let (help, needed) = adapter.required_flags();if !needed.is_empty() {let ok = match remote {@@ -979,6 +1004,115 @@ mod tests {}use crate::BackendKind;+ /// Explicit OpenCode picks cannot pass ACP preflight then run natively without our MCP server.+ #[test]+ fn explicit_opencode_picks_are_refused_before_native_chat_or_build() {+ 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:?}"+ );+ }+ }+ }+ }+ }++ /// Validation failures finish exactly once, preserving cancellation status and other error details.+ #[test]+ fn cancelled_model_validation_reports_stopped_and_other_failures_stay_errors() {+ struct RefusedModel(ErrorCode);+ impl AgentAdapter for RefusedModel {+ /// Register the fixture without replacing any built-in agent.+ fn ids(&self) -> &'static [&'static str] {+ &["test-validation"]+ }+ /// Fail the test if a rejected model reaches command construction.+ fn args(&self, _cx: &ArgsCx) -> Vec<String> {+ panic!("failed validation must not start the agent")+ }+ /// Return the selected validation failure without performing I/O.+ fn validate_model(&self, _config: &BackendConfig, _options: &BackendOptions, _directory: Option<&Path>, _stop: &Stop) -> Result<(), ToolError> {+ Err(ToolError::new(self.0, "Validation stopped").with_remediation("Reload the models."))+ }+ }+ for code in [ErrorCode::Cancelled, ErrorCode::BadInput, ErrorCode::TimedOut] {+ let config = BackendConfig {+ name: "Test".into(),+ kind: BackendKind::AgentCli,+ model: "test-validation".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ };+ let mut spec = CliSpec::new(config, BackendOptions::default(), false, None);+ spec.adapters.register(Arc::new(RefusedModel(code)));+ let mut conversation = CliConversation::new(spec);+ conversation.send("test");+ let events: Vec<_> = (0..2).map(|_| conversation.rx.recv_timeout(Duration::from_secs(5)).unwrap()).collect();+ assert!(!conversation.is_busy(), "the next message is accepted before TurnDone");+ assert!(conversation.poll().is_empty(), "exactly one terminal event");+ if code == ErrorCode::Cancelled {+ assert!(matches!(events.as_slice(), [AgentEvent::Status { text }, AgentEvent::TurnDone { .. }] if text == "Stopped."), "{events:?}");+ } else {+ assert!(+ matches!(events.as_slice(), [AgentEvent::Error { message, remediation: Some(help), log: None }, AgentEvent::TurnDone { .. }]+ if message == "Validation stopped" && help == "Reload the models."),+ "{events:?}"+ );+ }+ assert!(+ matches!(events.last(), Some(AgentEvent::TurnDone {+ backend, input_tokens: 0, output_tokens: 0, cost_usd: None, cost_is_estimate: false,+ }) if backend == "Test"),+ "{events:?}"+ );+ }+ }+fn mcp() -> McpCommand {McpCommand { command: "/opt/ca/craft-anything-cli".into(), args: vec!["mcp".into(), "--project".into(), "/p/x.cany".into()], notes: None }}diff --git a/crates/ai/src/cli_agents/models.rs b/crates/ai/src/cli_agents/models.rsnew file mode 100644index 00000000..39472c6f--- /dev/null+++ b/crates/ai/src/cli_agents/models.rs@@ -0,0 +1,320 @@+//! Model discovery through the selected agent's own CLI, in the same execution context as a run.+//! Only public model metadata is retained; provider headers and credentials are never returned.++use crate::model::{Effort, Stop};+use crate::{BackendConfig, BackendEntry, BackendOptions};+use craft_anything_evidence::{ErrorCode, ToolError};+use craft_anything_platform::Process;+use serde::{Deserialize, Serialize};+use std::path::{Path, PathBuf};+use std::time::Duration;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct AgentModel {+ /// The selectable reference (provider/id), including aliases defined in OpenCode.+ pub id: String,+ pub name: String,+ pub thinking: Vec<Effort>,+}++/// A snapshot of the context a picker queried. Also used to reject stale background results.+#[derive(Debug, Clone, PartialEq)]+pub struct ModelContext {+ pub backend: BackendEntry,+ pub directory: Option<PathBuf>,+}++const MAX_OUTPUT: usize = 8 * 1024 * 1024;+const MAX_MODELS: usize = 10_000;++#[derive(Deserialize)]+struct Response {+ data: Vec<WireModel>,+}++#[derive(Deserialize)]+struct WireModel {+ id: String,+ #[serde(rename = "providerID")]+ provider: String,+ name: String,+ enabled: bool,+ #[serde(rename = "type")]+ kind: Option<String>,+ variants: Vec<Variant>,+}++#[derive(Deserialize)]+struct Variant {+ id: String,+}++/// Describe an invalid catalogue without including potentially sensitive raw CLI output.+fn malformed() -> ToolError {+ ToolError::new(ErrorCode::GarbledOutput, "OpenCode returned an unreadable model list.")+ .with_remediation("Use OpenCode V2 on the selected computer and try loading its models again.")+}++/// Parse a bounded V2 catalogue into sorted, deduplicated enabled chat models and known depths.+/// Reject malformed references or oversized responses; discard unrelated provider metadata.+pub(crate) fn parse_models(bytes: &[u8]) -> Result<Vec<AgentModel>, ToolError> {+ if bytes.len() >= MAX_OUTPUT {+ return Err(ToolError::new(ErrorCode::OverLimit, "OpenCode's model list is too large."));+ }+ let response: Response = serde_json::from_slice(bytes).map_err(|_| malformed())?;+ if response.data.len() > MAX_MODELS {+ return Err(ToolError::new(ErrorCode::OverLimit, "OpenCode returned too many models."));+ }+ let mut models = std::collections::BTreeMap::new();+ for m in response.data {+ if !m.enabled || m.kind.as_deref().is_some_and(|k| k != "chat") {+ continue;+ }+ if m.id.is_empty() || m.provider.is_empty() || m.id.contains('#') || m.provider.contains(['/', '#']) {+ return Err(malformed());+ }+ let id = format!("{}/{}", m.provider, m.id);+ let thinking = Effort::ALL.into_iter().filter(|d| m.variants.iter().any(|v| v.id == d.as_str())).collect();+ models.insert(id.clone(), AgentModel { id, name: m.name, thinking });+ }+ Ok(models.into_values().collect())+}++/// Only connection flags belong on both `api` and `run`; prompt/run flags never leak into discovery.+fn connection_args(options: &BackendOptions) -> Result<Vec<String>, ToolError> {+ let mut result = Vec::new();+ let mut args = options.args.iter();+ while let Some(arg) = args.next() {+ if arg == "--standalone" || arg.starts_with("--server=") {+ result.push(arg.clone());+ } else if arg == "--server" {+ let server =+ args.next().filter(|s| !s.is_empty() && !s.starts_with('-')).ok_or_else(|| ToolError::invalid("OpenCode's --server needs an address."))?;+ result.extend([arg.clone(), server.clone()]);+ }+ }+ Ok(result)+}++/// Build the model-list operation with connection flags shared by discovery and execution.+pub(crate) fn query_args(options: &BackendOptions) -> Result<Vec<String>, ToolError> {+ let mut args = vec!["api".into(), "model.list".into()];+ args.extend(connection_args(options)?);+ Ok(args)+}++/// Select the configured executable and catalogue location, quoting SSH arguments for the remote shell.+/// Local queries use the supplied directory or current directory; SSH queries expand remote `$PWD`.+fn query_command(config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>) -> Result<(String, Vec<String>), ToolError> {+ let program = options.command.clone().unwrap_or_else(|| super::program_for(&config.model));+ let mut args = query_args(options)?;+ match config.ssh_host.as_deref().filter(|h| !h.trim().is_empty()) {+ Some(host) => {+ let mut remote = vec![program];+ remote.extend(args);+ let mut args = crate::ssh::ssh_args(host, &remote);+ // Expand only the remote shell's working directory. No local path is sent to SSH.+ // The operation-id form accepts deep-object query parameters; raw `get` does not.+ if let Some(command) = args.last_mut() {+ command.push_str(" --param \"location[directory]=$PWD\"");+ }+ Ok(("ssh".into(), args))+ }+ None => {+ let directory = match directory {+ Some(dir) => dir.to_path_buf(),+ None => std::env::current_dir().map_err(|e| ToolError::io(".", e))?,+ };+ args.extend(["--param".into(), format!("location[directory]={}", directory.display())]);+ Ok((program, args))+ }+ }+}++/// Prepare an unstarted catalogue process with bounded output, deadlines and a local-only working directory.+pub(crate) fn query_process(config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>) -> Result<Process, ToolError> {+ let (program, args) = query_command(config, options, directory)?;+ let mut process = Process::new(program).args(args);+ if let Some(dir) = directory.filter(|_| config.ssh_host.as_deref().is_none_or(|h| h.trim().is_empty())) {+ process = process.cwd(dir);+ }+ Ok(process.timeout(Duration::from_secs(20)).idle_timeout(Duration::from_secs(15)).stdout_cap(MAX_OUTPUT).stderr_cap(64 * 1024))+}++/// Query the selected installation, propagating cancellation, process failures and invalid catalogue errors.+pub(crate) fn discover(config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>, stop: &Stop) -> Result<Vec<AgentModel>, ToolError> {+ let stop = stop.clone();+ let out = query_process(config, options, directory)?+ .cancel_when(move || stop.is_stopped())+ .remediation("Check OpenCode V2 and its provider setup on the selected computer, then reload the models.")+ .run_checked()?;+ parse_models(&out.stdout)+}++/// Validate explicit selections against the current instance before saving or starting a run.+pub(crate) fn validate(options: &BackendOptions, models: &[AgentModel]) -> Result<(), ToolError> {+ let Some(id) = options.cli_model.as_deref() else {+ return if options.cli_thinking.is_none() { Ok(()) } else { Err(ToolError::invalid("Choose an OpenCode model before choosing its thinking depth.")) };+ };+ let Some(model) = models.iter().find(|m| m.id == id) else {+ return Err(ToolError::invalid(format!("The selected OpenCode model {id:?} is no longer available."))+ .with_remediation("Reload the models on this computer and choose an available model or the OpenCode default."));+ };+ if let Some(depth) = options.cli_thinking.filter(|d| !model.thinking.contains(d)) {+ return Err(ToolError::invalid(format!("{} does not offer {} thinking.", model.id, depth.title()))+ .with_remediation("Choose a thinking depth listed for this model, or use its default."));+ }+ Ok(())+}++/// Shared by the hub and headless tools. An empty model means OpenCode chooses its own default.+pub fn select(context: &ModelContext, model: Option<&str>, thinking: Option<Effort>) -> Result<BackendOptions, ToolError> {+ select_with_stop(context, model, thinking, &Stop::default())+}++/// Return validated options for a catalogue-capable agent without persisting them.+/// Empty model names select the default; cancellation is checked before any discovery I/O.+pub fn select_with_stop(context: &ModelContext, model: Option<&str>, thinking: Option<Effort>, stop: &Stop) -> Result<BackendOptions, ToolError> {+ stop.check()?;+ let adapter = super::adapter_for(&context.backend.config.model);+ if context.backend.config.kind != crate::BackendKind::AgentCli || !adapter.has_model_catalog() {+ return Err(ToolError::invalid("This agent does not offer a live model and thinking catalogue."));+ }+ let mut options = context.backend.options.clone();+ options.cli_model = model.map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);+ options.cli_thinking = thinking;+ adapter.validate_model(&context.backend.config, &options, context.directory.as_deref(), stop)?;+ Ok(options)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ /// An owner's cancellation survives reset and prevents model-selection I/O.+ #[test]+ fn a_cancelled_tool_stops_selection_before_io() {+ let cancel = craft_anything_engine::CancelToken::default();+ let stop = Stop::for_tool(cancel.clone());+ cancel.cancel();+ assert!(stop.is_stopped());+ stop.reset();+ assert!(stop.is_stopped(), "a conversation reset cannot revive its cancelled owner");+ let context = ModelContext { backend: BackendEntry { config: config(), options: BackendOptions::default() }, directory: None };+ assert_eq!(select_with_stop(&context, None, None, &stop).unwrap_err().code, ErrorCode::Cancelled);+ }++ /// Build catalogue metadata with an alias distinct from its upstream model id.+ fn model(id: &str, enabled: bool, kind: &str, variants: &[&str]) -> serde_json::Value {+ json!({"id":id,"modelID":"upstream-name","providerID":"test","name":id,"enabled":enabled,"type":kind,+ "variants":variants.iter().map(|v| json!({"id":v})).collect::<Vec<_>>()})+ }++ /// Filtering retains selectable aliases and supported depths while rejecting malformed or oversized input.+ #[test]+ fn only_enabled_chat_models_and_their_actual_variants_are_offered() {+ let text = json!({"data":[+ model("alias",true,"chat", &["max","low","none","xhigh","high","medium"]),+ model("hidden",false,"chat", &["max"]), model("picture",true,"image", &[]),+ model("small",true,"chat", &["low","high"]), model("alias",true,"chat", &["low","medium","high","xhigh","max"])+ ]});+ let list = parse_models(text.to_string().as_bytes()).unwrap();+ assert_eq!(list.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["test/alias", "test/small"]);+ assert_eq!(list[0].thinking, Effort::ALL);+ assert_eq!(list[1].thinking, [Effort::Low, Effort::High]);+ assert!(parse_models(br#"{"data":[]}"#).unwrap().is_empty());+ for invalid in [b"not json".as_slice(), br#"{"data":[{}]}"#, br#"{}"#] {+ assert_eq!(parse_models(invalid).unwrap_err().code, ErrorCode::GarbledOutput);+ }+ assert_eq!(parse_models(&vec![b' '; MAX_OUTPUT]).unwrap_err().code, ErrorCode::OverLimit);+ }++ /// Explicit unavailable models and unsupported depths fail instead of silently changing the selection.+ #[test]+ fn a_selection_never_falls_back_to_another_model_or_thinking_depth() {+ let list = vec![AgentModel { id: "test/model".into(), name: "Test".into(), thinking: vec![Effort::High] }];+ let mut options = BackendOptions::default();+ assert!(validate(&options, &list).is_ok());+ options.cli_thinking = Some(Effort::High);+ assert!(validate(&options, &list).is_err());+ options.cli_model = Some("test/model".into());+ assert!(validate(&options, &list).is_ok());+ options.cli_thinking = Some(Effort::Max);+ assert!(validate(&options, &list).is_err());+ options.cli_model = Some("test/removed".into());+ options.cli_thinking = None;+ assert!(validate(&options, &list).is_err());+ }++ /// An isolated local backend for catalogue fixtures.+ fn config() -> BackendConfig {+ BackendConfig { name: "OpenCode".into(), kind: crate::BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true }+ }++ /// Discovery preserves the chosen executable and server, omitting run-only flags and local paths over SSH.+ #[test]+ fn remote_discovery_uses_the_remote_program_and_connection_context() {+ let mut cfg = config();+ cfg.ssh_host = Some("test-box".into());+ let options = BackendOptions {+ command: Some("/opt/agent's tools/opencode".into()),+ args: ["--agent", "build", "--server", "http://localhost:4096"].map(String::from).into(),+ ..Default::default()+ };+ let (program, args) = query_command(&cfg, &options, None).unwrap();+ assert_eq!(program, "ssh");+ assert!(args.iter().any(|a| a == "BatchMode=yes"));+ assert!(args.iter().any(|a| a == "test-box"));+ assert_eq!(+ args.last().unwrap(),+ "'/opt/agent'\\''s tools/opencode' api model.list --server http://localhost:4096 --param \"location[directory]=$PWD\""+ );+ cfg.ssh_host = None;+ let (program, args) = query_command(&cfg, &options, Some(Path::new("/work/test"))).unwrap();+ assert_eq!(program, "/opt/agent's tools/opencode");+ assert_eq!(args, ["api", "model.list", "--server", "http://localhost:4096", "--param", "location[directory]=/work/test"]);+ }++ /// A shell stand-in checks remote directory expansion and quoting of paths with special characters.+ #[cfg(unix)]+ #[test]+ fn a_remote_query_expands_only_the_remote_working_directory() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let remote = dir.path().join("remote & project # one");+ std::fs::create_dir(&remote).unwrap();+ let program = dir.path().join("agent's program");+ std::fs::write(&program, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n").unwrap();+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();+ let mut cfg = config();+ cfg.ssh_host = Some("test-box".into());+ let options = BackendOptions { command: Some(program.display().to_string()), ..Default::default() };+ let (_, args) = query_command(&cfg, &options, Some(Path::new("/local/ignored"))).unwrap();+ let output = Process::new("sh").arg("-c").arg(args.last().unwrap()).cwd(&remote).timeout(Duration::from_secs(2)).run_checked().unwrap();+ assert_eq!(output.stdout_text().lines().collect::<Vec<_>>(), ["api", "model.list", "--param", &format!("location[directory]={}", remote.display())]);+ }++ /// A local CLI stand-in verifies project-specific discovery, malformed output, exit errors and deadlines.+ #[cfg(unix)]+ #[test]+ fn discovery_reads_the_selected_program_in_the_project_and_reports_errors() {+ use std::os::unix::fs::PermissionsExt;+ let dir = tempfile::tempdir().unwrap();+ let program = dir.path().join("fake agent");+ let script = "#!/bin/sh\n[ \"$1 $2\" = 'api model.list' ] || exit 9\ncat models.json\n";+ std::fs::write(&program, script).unwrap();+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();+ let options = BackendOptions { command: Some(program.display().to_string()), ..Default::default() };+ let data = json!({"data":[model("project-only",true,"chat", &["high"])]});+ std::fs::write(dir.path().join("models.json"), data.to_string()).unwrap();+ assert_eq!(discover(&config(), &options, Some(dir.path()), &Stop::default()).unwrap()[0].id, "test/project-only");+ std::fs::write(dir.path().join("models.json"), "invalid").unwrap();+ assert_eq!(discover(&config(), &options, Some(dir.path()), &Stop::default()).unwrap_err().code, ErrorCode::GarbledOutput);+ std::fs::write(&program, "#!/bin/sh\nexit 7\n").unwrap();+ assert!(discover(&config(), &options, Some(dir.path()), &Stop::default()).is_err());+ std::fs::write(&program, "#!/bin/sh\nsleep 5\n").unwrap();+ let err = query_process(&config(), &options, Some(dir.path())).unwrap().timeout(Duration::from_millis(50)).run_checked().unwrap_err();+ assert_eq!(err.code, ErrorCode::TimedOut);+ }+}diff --git a/crates/ai/src/config.rs b/crates/ai/src/config.rsindex c6d73f98..d8a984e9 100644--- a/crates/ai/src/config.rs+++ b/crates/ai/src/config.rs@@ -27,6 +27,43 @@ use craft_anything_engine::Settings;use craft_anything_evidence::{ErrorCode, ToolError};use serde::{Deserialize, Serialize};use std::collections::BTreeMap;+use std::path::Path;++/// Read settings strictly before a model-selection save; only a missing file uses the current session.+/// Malformed files and I/O errors are returned rather than replaced by default settings.+fn settings_for_selection(path: &Path, current: &Settings) -> Result<Settings, ToolError> {+ match std::fs::read_to_string(path) {+ Ok(text) => craft_anything_engine::settings::read_settings(&text).map_err(|e| {+ ToolError::new(ErrorCode::BadSettings, format!("The settings couldn't be read: {e}"))+ .with_remediation("Fix config.toml before changing the AI's model.")+ }),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(current.clone()),+ Err(e) => Err(ToolError::io(path.display(), e)),+ }+}++/// Commit validated options through one path for hub and tool callers, which already hold the session.+/// Preserve unrelated disk changes, reject a changed backend or project, and update memory only after saving.+pub(crate) fn save_agent_selection(+ session: &mut craft_anything_engine::Session,+ path: &Path,+ context: &crate::ModelContext,+ options: BackendOptions,+) -> Result<bool, ToolError> {+ let current = AiConfig::from_table(&session.settings.ai)?;+ let name = &context.backend.config.name;+ let mut next = settings_for_selection(path, &session.settings)?;+ let mut config = AiConfig::from_table(&next.ai)?;+ let Some(entry) = config.backends.iter_mut().find(|e| &e.config.name == name) else { return Ok(false) };+ if current.get(name) != Some(&context.backend) || *entry != context.backend || session.project.as_ref().map(|p| p.root.clone()) != context.directory {+ return Err(ToolError::invalid("The AI settings changed while its models were loading. Reload the models and try again."));+ }+ entry.options = options;+ next.ai = config.to_table()?;+ next.save_to(path)?;+ session.settings = next;+ Ok(true)+}/// Per-backend options beyond [`BackendConfig`].#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]@@ -58,6 +95,9 @@ pub struct BackendOptions {/// Agent CLIs: the model to ask the CLI for (passed with its model flag when it has one).#[serde(skip_serializing_if = "Option::is_none")]pub cli_model: Option<String>,+ /// OpenCode's model variant. Absent means the model's own default thinking depth.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cli_thinking: Option<Effort>,/// Wall-clock limit in seconds for one agent CLI turn (default: 24 hours for a builder, which may/// analyse and build a big game; 30 minutes for questions).#[serde(skip_serializing_if = "Option::is_none")]@@ -78,6 +118,16 @@ pub struct BackendEntry {}impl BackendEntry {+ /// Older configurations can put OpenCode's variant directly in its model reference.+ fn thinking_from_model(&mut self) {+ if self.config.kind != BackendKind::AgentCli || self.config.model != "opencode" {+ return;+ }+ let Some((model, variant)) = self.options.cli_model.as_deref().and_then(|m| m.rsplit_once('#')) else { return };+ let Some(depth) = Effort::parse(variant) else { return };+ self.options.cli_thinking.get_or_insert(depth);+ self.options.cli_model = Some(model.to_string());+ }/// An agent CLI's `model` names the agent (`opencode`), and the model it should use goes in/// `cli_model`. People also write the agent's program in `command` and the model in `model`/// (`command = "opencode"`, `model = "deepseek/deepseek-flash"`); that ran the plain adapter@@ -143,7 +193,10 @@ impl AiConfig {ToolError::new(ErrorCode::BadSettings, format!("The [ai] settings couldn't be read: {e}")).with_remediation("Fix or remove the [ai] section in config.toml.")})?;- c.backends.iter_mut().for_each(BackendEntry::model_from_command);+ for backend in &mut c.backends {+ backend.model_from_command();+ backend.thinking_from_model();+ }Ok(c)}@@ -214,6 +267,23 @@ impl AiConfig {#[cfg(test)]mod tests {+ /// Legacy embedded variants migrate to separate model/depth settings and survive serialization.+ #[test]+ fn opencode_embedded_variants_migrate_and_every_depth_round_trips() {+ for depth in crate::Effort::ALL {+ let table: toml::Table = toml::from_str(&format!(+ "[[backends]]\nname = 'OpenCode'\nkind = 'agent_cli'\nmodel = 'opencode'\ncli_model = 'test/model#{}'\n",+ depth.as_str()+ ))+ .unwrap();+ let config = super::AiConfig::from_table(&table).unwrap();+ let entry = config.get("OpenCode").unwrap();+ assert_eq!(entry.options.cli_model.as_deref(), Some("test/model"));+ assert_eq!(entry.options.cli_thinking, Some(depth));+ assert_eq!(super::AiConfig::from_table(&config.to_table().unwrap()).unwrap(), config);+ }+ }+#[test]fn the_default_builder_is_the_same_from_the_list_as_from_the_config() {use crate::{BackendConfig, BackendKind, Role, default_builder};diff --git a/crates/ai/src/detect.rs b/crates/ai/src/detect.rsindex 81aa43b5..4906d813 100644--- a/crates/ai/src/detect.rs+++ b/crates/ai/src/detect.rs@@ -214,23 +214,38 @@ pub fn detect_all() -> Vec<Detected> {}let mut hosts = crate::ssh::ssh_hosts();hosts.truncate(5);- let ssh: Vec<Detected> = hosts- .into_iter()- .map(|h| {- let mut c = cfg(&format!("Claude Code on {h}"), BackendKind::AgentCli, "claude-code");- c.ssh_host = Some(h.clone());- Detected { suggestion: c, reason: format!("SSH host {h} from ~/.ssh/config (runs an agent CLI there)"), needs_key: false }- })- .collect();+ let ssh: Vec<Detected> = hosts.into_iter().flat_map(remote_agents).collect();parts.push((100, ssh));parts.sort_by_key(|(i, _)| *i);parts.into_iter().flat_map(|(_, v)| v).collect()}+/// SSH aliases are suggestions, not proof that an agent is installed there.+fn remote_agents(host: String) -> Vec<Detected> {+ [("claude-code", "Claude Code"), ("opencode", "OpenCode")]+ .into_iter()+ .map(|(id, label)| {+ let mut c = cfg(&format!("{label} on {host}"), BackendKind::AgentCli, id);+ c.ssh_host = Some(host.clone());+ Detected { suggestion: c, reason: format!("SSH host {host} from ~/.ssh/config (check that {label} is installed there)"), needs_key: false }+ })+ .collect()+}+#[cfg(test)]mod tests {use super::*;+ /// Non-Git SSH hosts offer both supported agent suggestions without probing the remote computer.+ #[test]+ fn ssh_hosts_offer_opencode_as_well_as_claude_code() {+ let found = remote_agents("test-box".into());+ assert_eq!(found.iter().map(|d| d.suggestion.model.as_str()).collect::<Vec<_>>(), ["claude-code", "opencode"]);+ let oc = &found[1].suggestion;+ assert_eq!(oc.name, "OpenCode on test-box");+ assert_eq!(oc.ssh_host.as_deref(), Some("test-box"));+ }+#[test]fn env_detection() {let d = env_keys(|v| (v == "OPENROUTER_API_KEY").then(|| "k".to_string()));diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex d58c496d..68941c18 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -18,12 +18,14 @@ pub mod http;pub mod key_tools;pub mod keys;pub mod model;+pub mod model_tools;pub mod openai;pub mod price;pub mod prompt;pub mod rebuild;pub mod ssh;+pub use cli_agents::models::{AgentModel, ModelContext};pub use config::{AiConfig, BackendEntry, BackendOptions, Price};pub use failure::{FailureKind, TurnFailure};pub use keys::KeyStore;@@ -118,6 +120,9 @@ pub fn model_in_use(config: &BackendConfig, options: Option<&BackendOptions>) ->BackendKind::AgentCli if config.model == "claude-code" => {Some(options.and_then(|o| o.cli_model.clone()).unwrap_or_else(|| anthropic::DEFAULT_MODEL.to_string()))}+ BackendKind::AgentCli if cli_agents::adapter_for(&config.model).has_model_catalog() => {+ Some(options.and_then(|o| o.cli_model.clone()).unwrap_or_else(|| "OpenCode default".into()))+ }BackendKind::AgentCli => None,_ => Some(config.model.clone()),}@@ -285,6 +290,7 @@ impl ChatModel for Tunneled {pub fn tools() -> Vec<craft_anything_engine::ToolSpec> {let mut v = rebuild::tools::specs();v.extend(key_tools::specs());+ v.extend(model_tools::specs());v}@@ -464,13 +470,16 @@ impl AiHub {self.config().backends.into_iter().map(|b| (b.config.name, b.options)).collect()}- /// The model a backend uses: an API's model, or the one Claude Code is asked for. Returns+ /// The model a backend uses: an API's model, or the one its agent is asked for. Returns/// false when there was no such backend.pub fn set_model(&self, name: &str, model: &str) -> Result<bool, ToolError> {let model = model.trim();if model.is_empty() {return Err(ToolError::invalid("Name a model."));}+ if self.config().get(name).is_some_and(|e| e.config.kind == BackendKind::AgentCli && cli_agents::adapter_for(&e.config.model).has_model_catalog()) {+ return self.set_agent_model(name, Some(model), None);+ }let mut cfg = self.config_to_change()?;let Some(b) = cfg.backends.iter_mut().find(|b| b.config.name == name) else { return Ok(false) };match b.config.kind {@@ -498,6 +507,9 @@ impl AiHub {/// Code. Empty for an agent app that picks its own. Blocking (bounded); run it off the UI thread.pub fn model_choices(&self, name: &str) -> Result<Vec<String>, ToolError> {let e = self.entry(name)?;+ if e.config.kind == BackendKind::AgentCli && cli_agents::adapter_for(&e.config.model).has_model_catalog() {+ return Ok(self.agent_models(&self.model_context(name)?)?.into_iter().map(|m| m.id).collect());+ }match (e.config.kind, model_in_use(&e.config, Some(&e.options))) {(_, None) => Ok(Vec::new()),(BackendKind::AgentCli, Some(_)) => Ok(anthropic::MODELS.iter().map(|m| m.to_string()).collect()),@@ -505,6 +517,40 @@ impl AiHub {}}+ /// Capture the exact settings and working directory that model discovery will use.+ pub fn model_context(&self, name: &str) -> Result<ModelContext, ToolError> {+ // Capture both fields under one guard: a busy session is not an absent project,+ // and a concurrent settings change must not produce a mixed snapshot.+ let session = self.engine.try_session().ok_or_else(|| ToolError::invalid("The app is busy with another task. Try again in a moment."))?;+ let config = AiConfig::from_table(&session.settings.ai)?;+ let backend = config.get(name).cloned().ok_or_else(|| {+ ToolError::invalid(format!("No AI backend named {name:?}")).with_remediation("See `craft-anything-cli ai list`, or add one in Settings → AI.")+ })?;+ Ok(ModelContext { backend, directory: session.project.as_ref().map(|p| p.root.clone()) })+ }++ /// Model metadata from an agent's own instance; no API-provider catalogue is substituted.+ pub fn agent_models(&self, context: &ModelContext) -> Result<Vec<AgentModel>, ToolError> {+ let e = &context.backend;+ cli_agents::adapter_for(&e.config.model).model_catalog(&e.config, &e.options, context.directory.as_deref(), &Stop::default())+ }++ /// Set an agent's model and thinking together. None uses OpenCode's default.+ /// Discovery happens before taking the session lock, and stale settings aren't overwritten.+ pub fn set_agent_model(&self, name: &str, model: Option<&str>, thinking: Option<Effort>) -> Result<bool, ToolError> {+ let context = self.model_context(name)?;+ self.set_agent_selection(&context, model, thinking)+ }++ /// Commit a picker selection only if its captured settings and project are still current.+ pub fn set_agent_selection(&self, context: &ModelContext, model: Option<&str>, thinking: Option<Effort>) -> Result<bool, ToolError> {+ let options = cli_agents::models::select(context, model, thinking)?;+ // Re-read and compare under the same lock as the save. A long catalogue lookup must+ // not overwrite another settings change that finished while it was running.+ let mut session = self.engine.session();+ config::save_agent_selection(&mut session, &self.settings_path(), context, options)+ }+/// Remove a backend and its stored key. Returns false when there was no such backend.pub fn remove_backend(&self, name: &str) -> Result<bool, ToolError> {let mut cfg = self.config_to_change()?;@@ -715,7 +761,7 @@ impl AiHub {}openai::OpenAi::compatible(&e.config.name, base.unwrap_or("http://127.0.0.1:11434/v1"), self.keys.get(&e.config.name), "").list_models(t)}- BackendKind::AgentCli => Ok(BackendKind::AgentCli.suggested_models().iter().map(|s| s.to_string()).collect()),+ BackendKind::AgentCli => self.model_choices(name),}}diff --git a/crates/ai/src/model.rs b/crates/ai/src/model.rsindex fac497bf..b24079b2 100644--- a/crates/ai/src/model.rs+++ b/crates/ai/src/model.rs@@ -81,9 +81,10 @@ pub struct ToolDef {pub schema: Value,}-/// How hard the model should think: Claude's effort levels, least to most (the order counts: a-/// level a model lacks steps down to the nearest one below).-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]+/// Shared thinking levels for API backends and agent CLI variants, ordered least to most.+/// Claude maps unsupported levels down with [`Effort::within`]; OpenCode requires the exact+/// variant in its live catalogue. The `effort` and `cli_thinking` settings remain independent.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]#[serde(rename_all = "snake_case")]pub enum Effort {Low,@@ -100,6 +101,7 @@ impl Effort {/// Every level, least to most.pub const ALL: [Effort; 5] = [Effort::Low, Effort::Medium, Effort::High, Effort::Xhigh, Effort::Max];+ /// The stable lowercase id used in settings, API requests and agent model references.pub fn as_str(self) -> &'static str {match self {Effort::Low => "low",@@ -110,11 +112,23 @@ impl Effort {}}+ /// Parse a known level, ignoring surrounding whitespace and case.pub fn parse(s: &str) -> Option<Effort> {let s = s.trim();Effort::ALL.into_iter().find(|e| e.as_str().eq_ignore_ascii_case(s))}+ /// The display label for this level in model pickers and validation messages.+ pub fn title(self) -> &'static str {+ match self {+ Self::Low => "Low",+ Self::Medium => "Medium",+ Self::High => "High",+ Self::Xhigh => "Xhigh",+ Self::Max => "Max",+ }+ }+/// This level on a model that offers only `levels`: the nearest one at or below it (as Claude/// Code does), else the lowest it has. Unchanged when `levels` is empty.pub fn within(self, levels: &[Effort]) -> Effort {@@ -206,20 +220,30 @@ pub enum Delta {/// Cooperative cancellation for a conversation.#[derive(Debug, Clone, Default)]-pub struct Stop(Arc<AtomicBool>);+pub struct Stop {+ stopped: Arc<AtomicBool>,+ tool: Option<craft_anything_engine::CancelToken>,+}impl Stop {+ /// Link discovery to cancellation of the engine tool that owns it.+ pub fn for_tool(cancel: craft_anything_engine::CancelToken) -> Self {+ Self { tool: Some(cancel), ..Default::default() }+ }++ /// Request cancellation for every clone sharing this conversation's stop flag.pub fn stop(&self) {- self.0.store(true, Ordering::SeqCst);+ self.stopped.store(true, Ordering::SeqCst);}/// Clear a previous stop (at the start of the next message).pub fn reset(&self) {- self.0.store(false, Ordering::SeqCst);+ self.stopped.store(false, Ordering::SeqCst);}+ /// Whether the conversation or its owning engine tool has requested cancellation.pub fn is_stopped(&self) -> bool {- self.0.load(Ordering::SeqCst)+ self.stopped.load(Ordering::SeqCst) || self.tool.as_ref().is_some_and(|c| c.is_cancelled())}pub fn check(&self) -> Result<(), ToolError> {diff --git a/crates/ai/src/model_tools.rs b/crates/ai/src/model_tools.rsnew file mode 100644index 00000000..6b4aaaee--- /dev/null+++ b/crates/ai/src/model_tools.rs@@ -0,0 +1,232 @@+//! The same agent model catalogue and validated selection for CLI/MCP clients.++use crate::{AiConfig, Effort, ModelContext, cli_agents};+use craft_anything_engine::tool::{Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of};+use craft_anything_evidence::ToolError;+use schemars::JsonSchema;+use serde::Deserialize;+use serde_json::{Value, json};++/// Register headless catalogue and selection tools, including the CLI's possible process, network and cache effects.+pub fn specs() -> Vec<ToolSpec> {+ let effects = Effects::LAUNCHES_PROCESS.union(Effects::ACCESSES_NETWORK).union(Effects::WRITES_FILESYSTEM);+ vec![+ ToolSpec {+ id: "ai_models_list",+ title: "List an agent's models",+ summary: "List the visible, enabled chat models and supported thinking depths of a configured OpenCode V2 backend, locally or on its SSH host. Uses that installation's configuration and credentials. Returns a total and a page (offset, limit: default 200, maximum 1000). OpenCode may start its background service and update its cache.",+ beginner: "Shows which models this OpenCode can use.",+ toolset: Toolset::Setup,+ effects,+ requires: Requires::Nothing,+ input_schema: schema_of::<ListParams>,+ run: ai_models_list,+ },+ ToolSpec {+ id: "ai_model_set",+ title: "Choose an agent's model and thinking",+ summary: "Save a configured OpenCode backend's model (provider/id) and optional thinking depth (low, medium, high, xhigh, max), validated against that instance's current model catalogue. Omit model and thinking to use OpenCode's default; omit thinking to use the selected model's default. Unsupported selections are refused.",+ beginner: "Chooses the model and how deeply it thinks.",+ toolset: Toolset::Setup,+ effects,+ requires: Requires::Nothing,+ input_schema: schema_of::<SetParams>,+ run: ai_model_set,+ },+ ]+}++#[derive(Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+struct ListParams {+ /// Configured backend name.+ name: String,+ #[serde(default)]+ offset: usize,+ /// Page size (default 200, at most 1000).+ limit: Option<usize>,+}++#[derive(Deserialize, JsonSchema)]+#[serde(deny_unknown_fields)]+struct SetParams {+ name: String,+ model: Option<String>,+ thinking: Option<Effort>,+}++/// Capture a catalogue-capable backend from the tool's already-held session without locking it again.+fn context(ctx: &Ctx<'_>, name: &str) -> Result<ModelContext, ToolError> {+ let config = AiConfig::from_table(&ctx.session.settings.ai)?;+ let backend = config.get(name).cloned().ok_or_else(|| ToolError::invalid(format!("No AI backend named {name:?}.")))?;+ if backend.config.kind != crate::BackendKind::AgentCli || !cli_agents::adapter_for(&backend.config.model).has_model_catalog() {+ return Err(ToolError::invalid("Choose an OpenCode backend with a live model catalogue."));+ }+ Ok(ModelContext { backend, directory: ctx.session.project.as_ref().map(|p| p.root.clone()) })+}++/// Discover models with tool-linked cancellation and return a bounded page alongside the total count.+fn ai_models_list(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {+ let p: ListParams = parse_params(params)?;+ let c = context(ctx, &p.name)?;+ let stop = crate::model::Stop::for_tool(ctx.cancel.clone());+ let models = cli_agents::adapter_for(&c.backend.config.model).model_catalog(&c.backend.config, &c.backend.options, c.directory.as_deref(), &stop)?;+ let total = models.len();+ let page: Vec<_> = models.into_iter().skip(p.offset).take(p.limit.unwrap_or(200).min(1000)).collect();+ Ok(ToolOutput::Value(json!({"name": p.name, "total": total, "offset": p.offset, "models": page})))+}++/// Validate and persist a model/depth selection, updating session settings only after the save succeeds.+fn ai_model_set(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {+ let p: SetParams = parse_params(params)?;+ let c = context(ctx, &p.name)?;+ let options = cli_agents::models::select_with_stop(&c, p.model.as_deref(), p.thinking, &crate::model::Stop::for_tool(ctx.cancel.clone()))?;+ let result = json!({"name": p.name, "model": options.cli_model, "thinking": options.cli_thinking});+ let path = ctx.session.config_dir().join("config.toml");+ if !crate::config::save_agent_selection(ctx.session, &path, &c, options)? {+ return Err(ToolError::invalid("The AI backend was removed while its models were loading. Reload the settings and try again."));+ }+ Ok(ToolOutput::Value(result))+}++#[cfg(test)]+mod tests {+ use super::*;+ use craft_anything_engine::{CallOptions, Caller, Engine};++ /// Build hub and tool clients sharing an isolated settings file and an explicit saved selection.+ fn selection_clients() -> (crate::AiHub, std::path::PathBuf) {+ let mut session = craft_anything_engine::testing::session();+ let path = session.config_dir().join("config.toml");+ let mut config = AiConfig::default();+ config.upsert(crate::BackendEntry {+ config: crate::BackendConfig {+ name: "OpenCode".into(),+ kind: crate::BackendKind::AgentCli,+ model: "opencode".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ },+ options: crate::BackendOptions { cli_model: Some("test/old".into()), ..Default::default() },+ });+ session.settings.ai = config.to_table().unwrap();+ session.settings.save_to(&path).unwrap();+ let hub = crate::AiHub::with_stores(Engine::shared(session, specs()), path.clone(), crate::KeyStore::file_only(path.with_file_name("ai-keys.toml")));+ (hub, path)+ }++ /// Reset through either public entry point so both exercise the shared persistence contract.+ fn reset_selection(hub: &crate::AiHub, tool: bool) -> Result<(), ToolError> {+ if tool {+ hub.engine.call("ai_model_set", json!({"name":"OpenCode"}), CallOptions::new(Caller::Cli)).map(|_| ())+ } else {+ hub.set_agent_model("OpenCode", None, None).and_then(|found| if found { Ok(()) } else { Err(ToolError::invalid("Backend was removed.")) })+ }+ }++ /// Both clients merge unrelated disk edits instead of replacing them with their older session snapshot.+ #[test]+ fn selection_saves_preserve_external_settings_and_other_backends() {+ for tool in [false, true] {+ let (hub, path) = selection_clients();+ let mut disk = hub.engine.session().settings.clone();+ disk.language = "zh-hans".into();+ let mut config = AiConfig::from_table(&disk.ai).unwrap();+ let mut other = config.get("OpenCode").unwrap().clone();+ other.config.name = "Other".into();+ other.options.timeout_secs = Some(123);+ config.upsert(other.clone());+ config.roles.insert("builder".into(), "Other".into());+ disk.ai = config.to_table().unwrap();+ disk.save_to(&path).unwrap();+ reset_selection(&hub, tool).unwrap();+ let saved = craft_anything_engine::Settings::load_from(&path);+ let config = AiConfig::from_table(&saved.ai).unwrap();+ assert_eq!(saved.language, "zh-hans");+ assert_eq!(config.get("Other"), Some(&other));+ assert_eq!(config.roles.get("builder").map(String::as_str), Some("Other"));+ assert!(config.get("OpenCode").unwrap().options.cli_model.is_none());+ assert_eq!(hub.engine.session().settings, saved);+ }+ }++ /// Syntax errors, invalid AI tables and future versions remain byte-for-byte intact on refused saves.+ #[test]+ fn selection_saves_refuse_damaged_or_newer_disk_settings() {+ for tool in [false, true] {+ for damaged in [Some("not valid = ["), Some("[ai]\nbackends = 123\n"), None] {+ let (hub, path) = selection_clients();+ let before = hub.engine.session().settings.clone();+ let text = damaged.map(str::to_string).unwrap_or_else(|| {+ let mut newer = before.clone();+ newer.version = u32::MAX;+ toml::to_string(&newer).unwrap()+ });+ std::fs::write(&path, &text).unwrap();+ assert_eq!(reset_selection(&hub, tool).unwrap_err().code, craft_anything_evidence::ErrorCode::BadSettings);+ assert_eq!(std::fs::read_to_string(&path).unwrap(), text);+ assert_eq!(hub.engine.session().settings, before);+ }+ }+ }++ /// A backend changed or removed on disk cannot be restored or overwritten by a stale selection.+ #[test]+ fn selection_saves_reject_external_changes_to_the_selected_backend() {+ for tool in [false, true] {+ for removed in [false, true] {+ let (hub, path) = selection_clients();+ let before = hub.engine.session().settings.clone();+ let mut disk = before.clone();+ let mut config = AiConfig::from_table(&disk.ai).unwrap();+ if removed {+ config.remove("OpenCode");+ } else {+ let mut entry = config.get("OpenCode").unwrap().clone();+ entry.options.command = Some("different-agent".into());+ config.upsert(entry);+ }+ disk.ai = config.to_table().unwrap();+ disk.save_to(&path).unwrap();+ let bytes = std::fs::read(&path).unwrap();+ assert!(reset_selection(&hub, tool).is_err());+ assert_eq!(std::fs::read(&path).unwrap(), bytes);+ assert_eq!(hub.engine.session().settings, before);+ }+ }+ }++ /// Engine dispatch rejects invalid requests and persists default selection without a running agent.+ #[test]+ fn model_tools_are_headless_and_default_selection_persists_in_the_session_store() {+ let mut session = craft_anything_engine::testing::session();+ let path = session.config_dir().join("config.toml");+ let mut cfg = AiConfig::default();+ cfg.upsert(crate::BackendEntry {+ config: crate::BackendConfig {+ name: "OpenCode".into(),+ kind: crate::BackendKind::AgentCli,+ model: "opencode".into(),+ base_url: None,+ ssh_host: None,+ enabled: true,+ },+ options: crate::BackendOptions {+ command: Some("missing-test-agent".into()),+ cli_model: Some("test/old".into()),+ cli_thinking: Some(Effort::High),+ ..Default::default()+ },+ });+ session.settings.ai = cfg.to_table().unwrap();+ let engine = Engine::shared(session, specs());+ let call = |id, params| engine.call(id, params, CallOptions::new(Caller::Cli));+ assert!(call("ai_models_list", json!({"name":"missing"})).is_err());+ assert!(call("ai_model_set", json!({"name":"OpenCode","thinking":"unsupported"})).is_err());+ call("ai_model_set", json!({"name":"OpenCode"})).unwrap();+ let saved = AiConfig::from_settings(&craft_anything_engine::Settings::load_from(&path));+ assert!(saved.get("OpenCode").unwrap().options.cli_model.is_none());+ assert!(saved.get("OpenCode").unwrap().options.cli_thinking.is_none());+ }+}diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex e3968a1e..4e161801 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -137,6 +137,85 @@ fn hub() -> (AiHub, tempfile::TempDir) {(h, dir)}+/// A CLI stand-in checks saved selections and refuses native execution until its MCP server is wired.+#[cfg(unix)]+#[test]+fn opencode_selection_is_validated_saved_and_refused_without_native_mcp() {+ use std::os::unix::fs::PermissionsExt;+ let (h, dir) = hub();+ let program = dir.path().join("agent");+ let catalogue = dir.path().join("models.json");+ 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",+ quote(&catalogue),+ quote(&seen)+ );+ std::fs::write(&program, script).unwrap();+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o700)).unwrap();+ let model = json!({"id":"alias","providerID":"test","name":"Test","enabled":true,"type":"chat","variants":[{"id":"high"},{"id":"max"}]});+ std::fs::write(&catalogue, json!({"data":[model]}).to_string()).unwrap();+ let cfg = BackendConfig { name: "OpenCode".into(), kind: BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true };+ h.add_backend_with(+ BackendEntry { config: cfg, options: BackendOptions { command: Some(program.display().to_string()), acp: Some(true), ..Default::default() } },+ None,+ )+ .unwrap();+ assert_eq!(h.model_choices("OpenCode").unwrap(), ["test/alias"]);+ assert!(h.set_agent_model("OpenCode", Some("test/alias"), Some(Effort::Max)).unwrap());+ let saved = AiConfig::from_settings(&Settings::load_from(&dir.path().join("config.toml")));+ assert_eq!(saved.get("OpenCode").unwrap().options.cli_thinking, Some(Effort::Max));+ assert_eq!(saved.get("OpenCode").unwrap().config.model, "opencode");+ let mut conversation = h.start(Some("OpenCode"), false).unwrap();+ conversation.send("test prompt");+ let deadline = Instant::now() + Duration::from_secs(5);+ let mut events = Vec::new();+ while conversation.is_busy() && Instant::now() < deadline {+ events.extend(conversation.poll());+ std::thread::sleep(Duration::from_millis(10));+ }+ events.extend(conversation.poll());+ 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!(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();+ h.set_enabled("OpenCode", false).unwrap();+ assert!(h.set_agent_selection(&stale, None, None).is_err(), "a late picker cannot overwrite newer settings");+ std::fs::write(&catalogue, r#"{"data":[]}"#).unwrap();+ assert!(h.set_model("OpenCode", "test/alias").is_err(), "removed models are not offered as a fallback");+ h.set_agent_model("OpenCode", None, None).unwrap();+ assert!(h.options()["OpenCode"].cli_model.is_none());+ assert!(h.options()["OpenCode"].cli_thinking.is_none());+}++/// Contention is an error, while an available session retains its actual optional project and remains saveable.+#[test]+fn model_context_distinguishes_a_busy_session_from_no_project() {+ use craft_anything_engine::project::{Project, Purpose};+ let (h, dir) = hub();+ let backend =+ BackendConfig { name: "OpenCode".into(), kind: BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true };+ h.add_backend(backend.clone(), None).unwrap();+ assert_eq!(h.model_context("OpenCode").unwrap().directory, None);+ let root = dir.path().join("test.cany");+ {+ let mut session = h.engine.session();+ session.open_project(Project::create(&root, "test", Purpose::Education).unwrap()).unwrap();+ assert!(h.model_context("OpenCode").is_err(), "lock contention must not capture a missing project");+ }+ let context = h.model_context("OpenCode").unwrap();+ assert_eq!(context.directory.as_ref(), Some(&root));+ assert_eq!(context.backend.config, backend);+ assert!(h.set_agent_selection(&context, None, None).unwrap(), "a capture after contention must remain saveable");+ assert!(h.model_context("missing").is_err());+}+#[test]fn a_failed_save_changes_nothing() {let dir = tempfile::tempdir().unwrap();diff --git a/crates/engine/src/clean_room.rs b/crates/engine/src/clean_room.rsindex 7972b481..85266231 100644--- a/crates/engine/src/clean_room.rs+++ b/crates/engine/src/clean_room.rs@@ -82,6 +82,8 @@ pub const TOOLS: &[&str] = &[// Settings, engines, plugins and this computer's setup."settings_show","settings_set",+ "ai_models_list",+ "ai_model_set","engines_list","engines_install","engines_app_open",@@ -157,10 +159,11 @@ pub fn is_refusal(e: &ToolError) -> bool {mod tests {use super::*;+ /// Clean-room entries are unique and resolve to engine tools or a recognised higher-layer namespace.#[test]fn every_engine_tool_in_the_table_exists_and_none_is_listed_twice() {let r = crate::Registry::with_all_tools();- let higher_layers = ["rebuild_", "assets_key_", "setup_"];+ let higher_layers = ["rebuild_", "assets_key_", "ai_", "setup_"];for id in TOOLS {assert!(r.get(id).is_some() || higher_layers.iter().any(|p| id.starts_with(p)), "{id} isn't a tool");assert_eq!(TOOLS.iter().filter(|t| *t == id).count(), 1, "{id} is listed twice");diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rsindex dd0d1bac..f6b08c98 100644--- a/crates/engine/src/settings.rs+++ b/crates/engine/src/settings.rs@@ -356,8 +356,56 @@ impl Settings {}}+ /// Load startup settings, first recovering app edits deferred by a busy shutdown.pub fn load() -> Settings {- Settings::load_from(&Settings::path())+ let path = Settings::path();+ if let Err(e) = Self::recover_pending(&path) {+ log::warn!("Couldn't recover pending settings: {}", e.message);+ }+ Settings::load_from(&path)+ }++ /// Keep pending non-AI edits without touching config.toml or waiting for the engine session.+ /// The sidecar uses the settings schema/version and migrations; startup merges it with the+ /// latest committed AI table, so a writer still finishing at shutdown cannot be overwritten.+ pub fn defer_save_to(&self, path: &Path) -> Result<(), ToolError> {+ let mut pending = self.clone();+ pending.ai.clear();+ pending.save_to(&path.with_extension("pending.toml"))+ }++ /// Remove deferred edits superseded by a successful full save. A missing sidecar is fine.+ pub fn discard_pending(path: &Path) -> Result<(), ToolError> {+ let pending_path = path.with_extension("pending.toml");+ match std::fs::remove_file(&pending_path) {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(ToolError::io(pending_path.display(), e)),+ }+ }++ /// Recover a deferred snapshot only when both files are readable and supported. Leave the+ /// sidecar intact on failure, and remove it only after the merged settings are saved.+ fn recover_pending(path: &Path) -> Result<(), ToolError> {+ let pending_path = path.with_extension("pending.toml");+ let text = match std::fs::read_to_string(&pending_path) {+ Ok(text) => text,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) => return Err(ToolError::io(pending_path.display(), e)),+ };+ let bad_settings = |e: String| ToolError::new(ErrorCode::BadSettings, e);+ let mut pending = read_settings(&text).map_err(bad_settings)?;+ let current = match std::fs::read_to_string(path) {+ Ok(text) => read_settings(&text).map_err(bad_settings)?,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Settings::default(),+ Err(e) => return Err(ToolError::io(path.display(), e)),+ };+ if current.version > SETTINGS_VERSION || pending.version > SETTINGS_VERSION {+ return Err(ToolError::new(ErrorCode::BadSettings, "Update Craft Anything to recover settings saved by a newer version."));+ }+ pending.ai = current.ai;+ pending.save_to(path)?;+ Self::discard_pending(path)}pub fn save_to(&self, path: &Path) -> Result<(), ToolError> {@@ -562,6 +610,51 @@ default = "Claude Code"assert!(path.with_extension("toml.broken").exists());}+ /// Deferred saves cannot replace damaged/newer data, and failed recovery keeps both originals.+ #[test]+ fn deferred_settings_keep_ai_and_refuse_unsupported_files() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("config.toml");+ let pending_path = path.with_extension("pending.toml");+ let mut pending = Settings { language: "de".into(), ..Settings::default() };+ pending.ai.insert("model".into(), "stale".into());+ pending.defer_save_to(&path).unwrap();+ let pending_text = std::fs::read_to_string(&pending_path).unwrap();+ assert!(read_settings(&pending_text).unwrap().ai.is_empty());+ assert!(!path.exists(), "deferring never writes the shared config");+ for invalid in ["mode = [[[", "version = 999\n", "version = 999\nmode = []"] {+ std::fs::write(&path, invalid).unwrap();+ assert!(Settings::recover_pending(&path).is_err());+ assert_eq!(std::fs::read_to_string(&path).unwrap(), invalid);+ assert_eq!(std::fs::read_to_string(&pending_path).unwrap(), pending_text);+ }+ let mut current = Settings::default();+ current.ai.insert("model".into(), "latest".into());+ current.save_to(&path).unwrap();+ let original = std::fs::read_to_string(&path).unwrap();+ for invalid in ["mode = [[[", "version = 999\n"] {+ std::fs::write(&pending_path, invalid).unwrap();+ assert!(Settings::recover_pending(&path).is_err());+ assert_eq!(std::fs::read_to_string(&path).unwrap(), original);+ assert_eq!(std::fs::read_to_string(&pending_path).unwrap(), invalid);+ }+ std::fs::write(&pending_path, &pending_text).unwrap();+ std::fs::remove_file(&path).unwrap();+ std::fs::create_dir(&path).unwrap();+ assert!(Settings::recover_pending(&path).is_err(), "I/O failure must not consume pending edits");+ assert_eq!(std::fs::read_to_string(&pending_path).unwrap(), pending_text);+ std::fs::remove_dir(&path).unwrap();+ std::fs::write(&path, original).unwrap();+ // An old sidecar migrates through the existing settings schema before recovery.+ std::fs::write(&pending_path, "language = \"de\"\n[ai]\nmodel = \"stale\"\n").unwrap();+ Settings::recover_pending(&path).unwrap();+ let recovered = Settings::load_from(&path);+ assert_eq!(recovered.version, SETTINGS_VERSION);+ assert_eq!(recovered.language, "de");+ assert_eq!(recovered.ai, current.ai);+ assert!(!pending_path.exists());+ }+#[test]fn the_asset_budget_is_a_setting_and_old_configs_load() {let old: Settings = toml::from_str("mode = \"experienced\"\nauto_mode = false\n").unwrap();diff --git a/crates/engine/src/tool_list.rs b/crates/engine/src/tool_list.rsindex 3f59092c..f013d30d 100644--- a/crates/engine/src/tool_list.rs+++ b/crates/engine/src/tool_list.rs@@ -14,7 +14,7 @@ pub fn report(registry: &Registry) -> String {let _ = writeln!(out, "# Tools\n\nGenerated by `cargo xtask tools`. Do not edit by hand.\n");let _ = writeln!(out,- "**{} engine tools** in {} toolsets. Each is an MCP tool, a CLI command (`craft-anything-cli <id with dashes>`) and a tool the agent can call. The AI and setup layers add their own on top (`rebuild_*`, `assets_key_*`, `setup_*`); `craft-anything-cli commands` lists them all.\n",+ "**{} engine tools** in {} toolsets. Each is an MCP tool, a CLI command (`craft-anything-cli <id with dashes>`) and a tool the agent can call. The AI and setup layers add their own on top (`rebuild_*`, `assets_key_*`, `ai_models_list`, `ai_model_set`, `setup_*`); `craft-anything-cli commands` lists them all. [OpenCode model and thinking selection](opencode.md) describes the AI model tools.\n",registry.all().len(),sets.len());diff --git a/crates/ui-egui/src/builders.rs b/crates/ui-egui/src/builders.rsindex c32d0939..7e9c70fc 100644--- a/crates/ui-egui/src/builders.rs+++ b/crates/ui-egui/src/builders.rs@@ -9,6 +9,81 @@ use crate::{CraftApp, icons, widgets};use craft_anything_ai::{BackendConfig, BackendKind};use egui::{RichText, Ui, Vec2};+/// A live agent catalogue and a draft selection, tied to the settings that were queried.+pub struct AgentModelPicker {+ pub request: u64,+ pub context: craft_anything_ai::ModelContext,+ pub result: Option<Result<Vec<craft_anything_ai::AgentModel>, String>>,+ pub model: Option<String>,+ pub thinking: Option<craft_anything_ai::Effort>,+}++/// The UI keeps the draft; discovery, validation and persistence live in the AI layer.+pub fn agent_model_picker(ui: &mut Ui, picker: &mut AgentModelPicker) -> bool {+ let t = Tokens::get(ui.ctx());+ let Some(result) = &picker.result else {+ ui.add(egui::Spinner::new().size(theme::CAPTION));+ ui.label(tr("Asking for its models…"));+ return false;+ };+ let models = match result {+ Ok(models) => models,+ Err(message) => {+ ui.label(RichText::new(message).color(t.warning));+ return false;+ }+ };+ if models.is_empty() {+ ui.label(tr("OpenCode has no visible chat models. Connect a provider in OpenCode, then reload."));+ }+ let default = tr("OpenCode default");+ let selected = picker.model.as_deref().unwrap_or(&default);+ let response = egui::ComboBox::from_id_salt(("agent-model", &picker.context.backend.config.name))+ .icon(widgets::combo_icon)+ .selected_text(selected)+ .show_ui(ui, |ui| {+ if ui.selectable_label(picker.model.is_none(), &default).clicked() {+ picker.model = None;+ picker.thinking = None;+ }+ for model in models {+ let label = format!("{} · {}", model.name, model.id);+ if ui.selectable_label(picker.model.as_ref() == Some(&model.id), label).clicked() && picker.model.as_ref() != Some(&model.id) {+ picker.model = Some(model.id.clone());+ picker.thinking = None;+ }+ }+ });+ widgets::named(response.response, "OpenCode model");+ let model = models.iter().find(|m| picker.model.as_ref() == Some(&m.id));+ let missing = picker.model.is_some() && model.is_none();+ if missing {+ ui.label(RichText::new(tr("The saved model is no longer visible. Choose another model or the OpenCode default.")).color(t.warning));+ }+ let depths = model.map(|m| m.thinking.as_slice()).unwrap_or_default();+ ui.label(tr("Thinking depth"));+ let default_depth = tr("Model default");+ let response = egui::ComboBox::from_id_salt(("agent-thinking", &picker.context.backend.config.name))+ .icon(widgets::combo_icon)+ .selected_text(picker.thinking.map(|d| d.title()).unwrap_or(&default_depth))+ .show_ui(ui, |ui| {+ if ui.selectable_label(picker.thinking.is_none(), &default_depth).clicked() {+ picker.thinking = None;+ }+ for depth in depths {+ if ui.selectable_label(picker.thinking == Some(*depth), depth.title()).clicked() {+ picker.thinking = Some(*depth);+ }+ }+ });+ widgets::named(response.response, "Thinking depth");+ let unsupported = picker.thinking.is_some_and(|d| !depths.contains(&d));+ if unsupported {+ ui.label(RichText::new(tr("The saved thinking depth is unavailable for this model. Choose its default or an offered depth.")).color(t.warning));+ }+ ui.add_enabled_ui(!missing && !unsupported, |ui| widgets::link(ui, "Apply").clicked()).inner+}+/// One AI that could build.#[derive(Debug, Clone, PartialEq)]pub struct Choice {@@ -93,6 +168,42 @@ impl CraftApp {});}+ /// Capture the backend context and load its catalogue in a worker tagged with a fresh picker request id.+ /// If the session cannot be read, report the error and keep the existing draft.+ pub fn pick_agent_model(&mut self, name: &str) {+ let context = match self.hub.model_context(name) {+ Ok(context) => context,+ Err(e) => {+ self.toast(e.for_people(), true);+ return;+ }+ };+ self.model_request = self.model_request.wrapping_add(1);+ let request = self.model_request;+ self.agent_model_picker = Some(AgentModelPicker {+ request,+ model: context.backend.options.cli_model.clone(),+ thinking: context.backend.options.cli_thinking,+ context: context.clone(),+ result: None,+ });+ let hub = self.hub.clone();+ self.jobs.spawn(tr("List an AI's models"), false, move |_| {+ let result = hub.agent_models(&context);+ Ok(crate::Done::AgentModelChoices { request, context, result })+ });+ }++ /// Submit the matching picker's selection for background validation and persistence against its captured context.+ pub fn set_agent_model(&mut self, name: &str, model: Option<String>, thinking: Option<craft_anything_ai::Effort>) {+ let Some(picker) = self.agent_model_picker.take().filter(|p| p.context.backend.config.name == name) else { return };+ let hub = self.hub.clone();+ self.jobs.spawn(tr("Change an AI's model"), false, move |_| {+ hub.set_agent_selection(&picker.context, model.as_deref(), thinking).map_err(|e| e.for_people())?;+ Ok(crate::backends(&hub))+ });+ }+/// Use `model` for an AI from now on.pub fn set_model(&mut self, name: &str, model: &str) {self.model_picker = None;@@ -126,6 +237,7 @@ impl CraftApp {/// Run an agent app from this program (`None`: find it by its usual name again).pub fn set_agent_program(&mut self, name: &str, program: Option<String>) {+ self.agent_model_picker = None;let (hub, name) = (self.hub.clone(), name.to_string());self.jobs.spawn(tr("Set an AI's program"), false, move |_| {hub.set_command(&name, program.as_deref()).map_err(|e| e.message)?;diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex a04266a2..4782fc60 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -129,6 +129,7 @@ Answers come from {brain}. To build, set up a coding agent in Settings → AI.App ПриложениеApp details on device Сведения о приложении на устройствеApple apps Приложения Apple+Apply ПрименитьApprove an agent action Одобрить действие агентаApps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. Приложения и игры: продолжать уточнение, пока они не станут похожи на ваши изображения настолько. Выключено — сходство только сообщается.Architectures Архитектуры@@ -225,6 +226,7 @@ Choose a file Выбрать файлChoose a folder… Выбрать папку…Choose a function, string or section to see it here. Выберите функцию, строку или раздел, чтобы увидеть их здесь.Choose an AI's job Выбрать задачу ИИ+Choose an agent's model and thinking Выбрать модель агента и глубину размышленияChoose the folder Ghidra is installed in. Выберите папку, в которую установлен Ghidra.Choose what the builder's questions get Выберите, что получают вопросы конструктораChoose what to recreate, say what you want, then press Start. Выберите, что пересоздать, скажите, что хотите, затем нажмите «Старт».@@ -599,6 +601,7 @@ List a node's event listeners Список слушателей событийList an AI's models Список моделей ИИList an Unreal IoStore container Список контейнера Unreal IoStoreList an Unreal pak Список пака Unreal+List an agent's models Список моделей агентаList bookmarks Список закладокList browser pages Список страниц браузераList documents Список документов@@ -664,6 +667,7 @@ Memory for Ghidra Память для GhidraMinimise СвернутьMode РежимModel Модель+Model default По умолчанию для моделиModel: {model} Модель: {model}Modules МодулиMore detail Подробнее@@ -772,6 +776,9 @@ Open the folder Открыть папкуOpen the installer app Открыть приложение-установщикOpen the website Открыть веб-сайтOpen {name} Открыть {name}+OpenCode default По умолчанию для OpenCode+OpenCode has no visible chat models. Connect a provider in OpenCode, then reload. В OpenCode нет доступных моделей для чата. Подключите провайдера в OpenCode и обновите список.+OpenCode model Модель OpenCodeOpened {name} Открыто: {name}Opened {name}. Taking a first look… Открыто: {name}. Делаем первый взгляд…Opened {} Открыто: {}@@ -885,7 +892,9 @@ Refining rounds Раунды уточненияRefresh plugins Обновить плагиныRegions of a program file, each with one purpose: code, text, pictures, settings. Регионы файла программы, каждый с одной целью: код, текст, изображения, настройки.Reload Перезагрузить+Reload models Обновить моделиRemember permission Запомнить разрешение+Remote program Программа на удалённом компьютереRemove УдалитьRemove a pin Удалить закреплениеRemove a pinned build Удалить закреплённую сборку@@ -1078,6 +1087,8 @@ The packed contents of an Electron app (a website inside a desktop app) УпакThe program's machine code written out as one tiny instruction per line. Машинный код программы, записанный в виде одной крошечной инструкции на строку.The project's name and round Название проекта и раундThe raw result Сырой результат+The saved model is no longer visible. Choose another model or the OpenCode default. Сохранённая модель больше не доступна. Выберите другую модель или модель OpenCode по умолчанию.+The saved thinking depth is unavailable for this model. Choose its default or an offered depth. Сохранённая глубина размышления недоступна для этой модели. Выберите значение по умолчанию или одно из предложенных.The smallest unit of data in a file: a number from 0 to 255. Наименьшая единица данных в файле: число от 0 до 255.The smallest units of data in a file: numbers from 0 to 255. Наименьшие единицы данных в файле: числа от 0 до 255.The {name} view isn't available yet in this build. Вид «{name}» пока недоступен в этой сборке.@@ -1089,6 +1100,7 @@ They're my app: edit them in place Это моё приложение: редаThings a program borrows from the operating system or libraries, like "open a file" or "draw a window". То, что программа берёт у операционной системы или библиотек, например «открыть файл» или «нарисовать окно».Things a program or library offers for other programs to use. То, что программа или библиотека предлагает другим программам для использования.Things we couldn't establish yet are listed here, with what would settle them. То, что мы пока не смогли установить, перечислено здесь вместе с тем, что помогло бы это разрешить.+Thinking depth Глубина размышленияThis answer won't be there after a restart: Этот ответ не сохранится после перезапуска:This build stopped part-way Эта сборка остановилась на полпутиThis can't be undone. Это нельзя отменить.diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex fa4e8099..c93396d1 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -1,5 +1,17 @@# zh-hans: original Chinese UI translations. Licensed MIT OR Apache-2.0.# UTF-8: English source<TAB>translation. Keep placeholders and escapes intact.+OpenCode default OpenCode 默认设置+Model default 模型默认设置+Thinking depth 思考深度+OpenCode model OpenCode 模型+Remote program 远程程序+Reload models 重新加载模型+Apply 应用+OpenCode has no visible chat models. Connect a provider in OpenCode, then reload. OpenCode 中没有可见的聊天模型。请在 OpenCode 中连接服务提供商,然后重新加载。+The saved model is no longer visible. Choose another model or the OpenCode default. 已保存的模型不再可见。请选择其他模型或使用 OpenCode 默认设置。+The saved thinking depth is unavailable for this model. Choose its default or an offered depth. 此模型不支持已保存的思考深度。请选择默认设置或可用的深度。+List an agent's models 列出智能体的模型+Choose an agent's model and thinking 选择智能体的模型和思考深度GB GBand {n} more ,另有 {n} 项{ascii} {ascii}diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex cbdd2a5c..bcbd5116 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -1,5 +1,17 @@# zh-hant: original Chinese UI translations. Licensed MIT OR Apache-2.0.# UTF-8: English source<TAB>translation. Keep placeholders and escapes intact.+OpenCode default OpenCode 預設設定+Model default 模型預設設定+Thinking depth 思考深度+OpenCode model OpenCode 模型+Remote program 遠端程式+Reload models 重新載入模型+Apply 套用+OpenCode has no visible chat models. Connect a provider in OpenCode, then reload. OpenCode 中沒有可見的聊天模型。請在 OpenCode 中連線至服務供應商,然後重新載入。+The saved model is no longer visible. Choose another model or the OpenCode default. 已儲存的模型不再可見。請選擇其他模型或使用 OpenCode 預設設定。+The saved thinking depth is unavailable for this model. Choose its default or an offered depth. 此模型不支援已儲存的思考深度。請選擇預設設定或可用的深度。+List an agent's models 列出代理程式的模型+Choose an agent's model and thinking 選擇代理程式的模型與思考深度GB GBand {n} more ,另有 {n} 項{ascii} {ascii}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 45fb954b..9e607a24 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -159,6 +159,11 @@ pub enum Done {name: String,result: Result<Vec<String>, ToolError>,},+ AgentModelChoices {+ request: u64,+ context: craft_anything_ai::ModelContext,+ result: Result<Vec<craft_anything_ai::AgentModel>, ToolError>,+ },Picked {pick: Pick,path: Option<PathBuf>,@@ -350,6 +355,8 @@ pub struct CraftApp {/// The AI whose model is being chosen in Settings → AI, and the models it offers once they've/// come (`None`: still asking).pub model_picker: Option<(String, Option<Vec<String>>)>,+ pub agent_model_picker: Option<builders::AgentModelPicker>,+ model_request: u64,/// The agent app whose program the file dialog is choosing.pub picking_program_for: Option<String>,/// The backend the person chose to build with (Settings → AI), if any.@@ -431,6 +438,7 @@ pub struct CraftApp {}impl CraftApp {+ /// Initialize UI state from the shared engine's saved settings, waiting rather than substituting defaults.pub fn new(engine: Arc<Engine>, hub: Arc<AiHub>) -> Self {// Wait for the engine if it's busy: defaults here would show Clean room and no AI, and the// next settings change would save them over the person's own.@@ -449,6 +457,8 @@ impl CraftApp {backends: Vec::new(),backend_options: Default::default(),model_picker: None,+ agent_model_picker: None,+ model_request: 0,picking_program_for: None,builder: None,extractor: None,@@ -649,8 +659,11 @@ impl CraftApp {let engine = self.engine.clone();// What's in the session when it runs, so the newest settings are the ones written.self.saving = Some(self.jobs.spawn("Save settings", false, move |_| {- let settings = engine.session().settings.clone();- settings.save().map_err(|e| e.message)?;+ // Keep the guard through the write so a model-selection save cannot be overtaken+ // by an older settings snapshot. This runs on the worker, never the UI thread.+ let session = engine.session();+ session.label("Save settings");+ session.settings.save().map_err(|e| e.message)?;Ok(Done::Nothing)}));}@@ -1219,6 +1232,7 @@ impl CraftApp {// ---- results ----------------------------------------------------------------------------+ /// Apply a completed background job, reporting failures and accepting picker results only for matching requests.fn handle_done(&mut self, done: jobs::Finished<Done>) {let job = done.job;if self.saving == Some(job) {@@ -1316,6 +1330,13 @@ impl CraftApp {self.toast(e.for_people(), true);}},+ Done::AgentModelChoices { request, context, result } => {+ // Keep a matching result even while the engine is busy. Settings invalidates+ // changed contexts once it can read the session again; saving rechecks too.+ if let Some(picker) = self.agent_model_picker.as_mut().filter(|p| p.request == request && p.context == context) {+ picker.result = Some(result.map_err(|e| e.for_people()));+ }+ }Done::BackendAdded { name, result } => match result {Ok(()) => {if self.server_form.name.trim() == name {@@ -1713,7 +1734,25 @@ impl eframe::App for CraftApp {}// A change not written yet (or one being written as the window closed) is written now.if self.persist && (self.settings_dirty || self.save_due.is_some() || self.saving.is_some()) {- let _ = self.settings.save();+ let saved = if let Some(mut session) = self.engine.try_session() {+ session.label("Save settings on exit");+ // AI changes belong to the session; keep the app's other pending edits.+ self.settings.ai = session.settings.ai.clone();+ session.settings = self.settings.clone();+ session.settings.save().is_ok()+ } else {+ false+ };+ if saved {+ // This full save supersedes any deferred edits left by a failed recovery.+ if let Err(e) = Settings::discard_pending(&Settings::path()) {+ log::error!("Couldn't discard superseded settings on exit: {}", e.message);+ }+ } else if let Err(e) = self.settings.defer_save_to(&Settings::path()) {+ // A tool can hold the session for hours. Keep edits separately for startup recovery;+ // never race its eventual save by merging a disk snapshot into config.toml here.+ log::error!("Couldn't keep pending settings on exit: {}", e.message);+ }}}}diff --git a/crates/ui-egui/src/settings_ui.rs b/crates/ui-egui/src/settings_ui.rsindex 2efa5c4e..5d566c3c 100644--- a/crates/ui-egui/src/settings_ui.rs+++ b/crates/ui-egui/src/settings_ui.rs@@ -305,7 +305,11 @@ fn engines(app: &mut CraftApp, ui: &mut Ui) {}}+/// Draw AI settings and model pickers, preserving drafts during contention and invalidating confirmed context changes.fn ai(app: &mut CraftApp, ui: &mut Ui) {+ if app.agent_model_picker.as_ref().is_some_and(|p| app.hub.model_context(&p.context.backend.config.name).is_ok_and(|current| current != p.context)) {+ app.agent_model_picker = None;+ }let t = Tokens::get(ui.ctx());crate::engine_ui::assets_settings(app, ui);ui.add_space(16.0);@@ -318,6 +322,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {let (mut choose_program, mut usual_program) = (None, None);let (mut pick_model, mut chosen_model, mut close_picker) = (None, None, false);let mut chosen_effort = None;+ let (mut pick_agent_model, mut chosen_agent_model, mut remote_program) = (None, None, None);// The AI whose Remove was pressed once: asked again before its key is deleted.let confirm_id = egui::Id::new("remove-ai");let confirming: Option<String> = ui.data(|d| d.get_temp(confirm_id));@@ -331,6 +336,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {ui.vertical(|ui| {ui.add(egui::Label::new(RichText::new(&b.name).font(theme::semibold(theme::SMALL))).truncate());let model_in_use = craft_anything_ai::model_in_use(b, app.backend_options.get(&b.name));+ let live_catalog = b.kind == BackendKind::AgentCli && craft_anything_ai::cli_agents::adapter_for(&b.model).has_model_catalog();// An API's model has its own line below; an agent app is named by its `model`.let what = if model_in_use.is_some() && b.kind != BackendKind::AgentCli { String::new() } else { format!(" · {}", b.model) };let ssh = b.ssh_host.as_ref().map(|h| format!(" · ssh {h}")).unwrap_or_default();@@ -354,8 +360,43 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {}// How hard it thinks: the Claude API and Claude Code take every Claude level.let effort = craft_anything_ai::effort_in_use(b, app.backend_options.get(&b.name));+ if b.kind == BackendKind::AgentCli && b.ssh_host.as_deref().is_some_and(|h| !h.trim().is_empty()) {+ let id = egui::Id::new(("remote-agent-program", &b.name));+ let mut program = ui+ .data_mut(|d| d.get_temp::<String>(id))+ .unwrap_or_else(|| app.backend_options.get(&b.name).and_then(|o| o.command.clone()).unwrap_or_default());+ ui.horizontal_wrapped(|ui| {+ ui.label(tr("Remote program"));+ ui.add(egui::TextEdit::singleline(&mut program).hint_text(&b.model).desired_width(200.0));+ if widgets::link(ui, "Apply").clicked() {+ remote_program = Some((b.name.clone(), program.clone()));+ }+ });+ ui.data_mut(|d| d.insert_temp(id, program));+ }// Which model it uses, and the ones it can be set to (#123).- if let Some(current) = model_in_use {+ if live_catalog {+ let options = app.backend_options.get(&b.name);+ let current = options.and_then(|o| o.cli_model.as_deref()).map(str::to_string).unwrap_or_else(|| tr("OpenCode default"));+ ui.label(trf("Model: {model}", &[("model", ¤t)]));+ let thinking = options.and_then(|o| o.cli_thinking).map(|d| d.title().to_string()).unwrap_or_else(|| tr("Model default"));+ ui.label(format!("{}: {thinking}", tr("Thinking depth")));+ if let Some(picker) = app.agent_model_picker.as_mut().filter(|p| p.context.backend.config.name == b.name) {+ if crate::builders::agent_model_picker(ui, picker) {+ chosen_agent_model = Some((b.name.clone(), picker.model.clone(), picker.thinking));+ }+ ui.horizontal(|ui| {+ if widgets::link(ui, "Reload models").clicked() {+ pick_agent_model = Some(b.name.clone());+ }+ if widgets::link(ui, "Cancel").clicked() {+ close_picker = true;+ }+ });+ } else if widgets::link(ui, "Change…").clicked() {+ pick_agent_model = Some(b.name.clone());+ }+ } else if let Some(current) = model_in_use {ui.horizontal_wrapped(|ui| {ui.style_mut().override_font_id = Some(egui::FontId::proportional(theme::CAPTION));ui.add(@@ -468,6 +509,15 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {if let Some(name) = pick_model {app.pick_model(&name);}+ if let Some((name, program)) = remote_program {+ app.set_agent_program(&name, Some(program));+ }+ if let Some(name) = pick_agent_model {+ app.pick_agent_model(&name);+ }+ if let Some((name, model, thinking)) = chosen_agent_model {+ app.set_agent_model(&name, model, thinking);+ }if let Some((name, model)) = chosen_model {app.set_model(&name, &model);}@@ -476,6 +526,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {}if close_picker {app.model_picker = None;+ app.agent_model_picker = None;}if let Some(name) = remove {ui.data_mut(|d| d.remove::<String>(confirm_id));@@ -813,3 +864,45 @@ fn safety(app: &mut CraftApp, ui: &mut Ui) {}}}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{Done, builders::AgentModelPicker, demo, jobs::Finished};+ use craft_anything_ai::{BackendConfig, BackendKind};++ /// Busy frames retain matching catalogue results, ignore older requests and defer context invalidation until readable.+ #[test]+ fn a_busy_session_keeps_the_picker_and_its_matching_result() {+ let mut app = demo::app(demo::engine(craft_anything_engine::Mode::Experienced, true));+ app.hub+ .add_backend(+ BackendConfig { name: "OpenCode".into(), kind: BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true },+ None,+ )+ .unwrap();+ app.backends = app.hub.backends();+ app.backend_options = app.hub.options();+ let context = app.hub.model_context("OpenCode").unwrap();+ app.agent_model_picker = Some(AgentModelPicker { request: 2, context: context.clone(), result: None, model: None, thinking: None });+ let ctx = egui::Context::default();+ theme::install_fonts(&ctx);+ let draw = |app: &mut CraftApp| {+ let mut output = ctx.run_ui(Default::default(), |ui| ai(app, ui));+ output.textures_delta.clear();+ };+ let engine = app.engine.clone();+ let session = engine.session();+ app.handle_done(Finished { job: 0, result: Ok(Done::AgentModelChoices { request: 1, context: context.clone(), result: Ok(Vec::new()) }) });+ assert!(app.agent_model_picker.as_ref().unwrap().result.is_none(), "an older reload must still be ignored");+ app.handle_done(Finished { job: 0, result: Ok(Done::AgentModelChoices { request: 2, context, result: Ok(Vec::new()) }) });+ draw(&mut app);+ assert!(app.agent_model_picker.as_ref().unwrap().result.as_ref().unwrap().is_ok(), "a busy frame must keep the completed catalogue");+ drop(session);+ draw(&mut app);+ assert!(app.agent_model_picker.is_some(), "unlocking an unchanged session keeps the draft");+ app.hub.set_enabled("OpenCode", false).unwrap();+ draw(&mut app);+ assert!(app.agent_model_picker.is_none(), "a confirmed settings change still invalidates the picker");+ }+}diff --git a/crates/ui-egui/tests/exit_settings.rs b/crates/ui-egui/tests/exit_settings.rsnew file mode 100644index 00000000..5209a6fd--- /dev/null+++ b/crates/ui-egui/tests/exit_settings.rs@@ -0,0 +1,97 @@+//! Exercise the real exit-save path in a child whose global config directory is isolated.++use craft_anything_ai::{AiConfig, AiHub, BackendConfig, BackendEntry, BackendKind, BackendOptions, Effort, KeyStore};+use craft_anything_engine::{Engine, Mode, Session, Settings};+use craft_anything_platform::process::Process;+use craft_anything_ui_egui::CraftApp;+use eframe::App;+use std::{sync::Arc, time::Duration};++/// Closing with pending app edits must preserve an AI selection committed since the app snapshot.+#[test]+fn exit_save_preserves_latest_ai_and_pending_app_settings() {+ const CHILD: &str = "CRAFT_ANYTHING_EXIT_SAVE_TEST";+ let Some(dir) = std::env::var_os(CHILD) else {+ for busy in ["false", "true"] {+ let dir = tempfile::tempdir().unwrap();+ Process::new(std::env::current_exe().unwrap())+ .args(["--exact", "exit_save_preserves_latest_ai_and_pending_app_settings", "--nocapture"])+ .env(CHILD, dir.path())+ .env("CRAFT_ANYTHING_CONFIG_DIR", dir.path())+ .env("CRAFT_ANYTHING_EXIT_SAVE_BUSY", busy)+ .timeout(Duration::from_secs(30))+ .run_checked()+ .unwrap();+ }+ return;+ };+ let dir = std::path::PathBuf::from(dir);+ assert_eq!(Settings::path(), dir.join("config.toml"));+ let engine = Arc::new(Engine::new(Session::isolated(&dir)));+ let hub = Arc::new(AiHub::with_stores(engine.clone(), Settings::path(), KeyStore::file_only(dir.join("keys.toml"))));+ let mut entry = BackendEntry {+ config: BackendConfig { name: "OpenCode".into(), kind: BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true },+ options: BackendOptions { cli_model: Some("test/old".into()), cli_thinking: Some(Effort::Low), ..Default::default() },+ };+ hub.add_backend_with(entry.clone(), None).unwrap();+ let mut app = CraftApp::new(engine.clone(), hub.clone());+ app.settings.mode = Mode::Experienced;+ app.settings.language = "de".into();+ app.settings_changed();++ // Commit the newer selection through the hub, leaving the app's AI snapshot stale.+ entry.options.cli_model = Some("test/new".into());+ entry.options.cli_thinking = Some(Effort::Max);+ hub.add_backend_with(entry.clone(), None).unwrap();+ let mut latest_ai = engine.session().settings.ai.clone();+ assert_ne!(app.settings.ai, latest_ai);+ if std::env::var("CRAFT_ANYTHING_EXIT_SAVE_BUSY").as_deref() == Ok("true") {+ // A long tool holds the session until after shutdown returns, then commits newer AI data.+ entry.options.cli_model = Some("test/final".into());+ let mut config = AiConfig::from_table(&latest_ai).unwrap();+ config.upsert(entry.clone());+ latest_ai = config.to_table().unwrap();+ let (ready_tx, ready_rx) = std::sync::mpsc::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel();+ let worker_engine = engine.clone();+ let committed = latest_ai.clone();+ let worker = std::thread::spawn(move || {+ let mut session = worker_engine.session();+ session.label("Test running tool");+ ready_tx.send(()).unwrap();+ let _ = release_rx.recv_timeout(Duration::from_secs(5));+ session.settings.ai = committed;+ session.settings.save().unwrap();+ });+ ready_rx.recv_timeout(Duration::from_secs(5)).unwrap();+ let start = std::time::Instant::now();+ app.on_exit();+ assert!(start.elapsed() < Duration::from_secs(1), "shutdown must not wait for the tool");+ assert!(Settings::path().with_extension("pending.toml").exists());+ release_tx.send(()).unwrap();+ worker.join().unwrap();+ let saved = Settings::load();+ assert_eq!(saved.ai, latest_ai, "startup keeps even an AI commit made after shutdown returned");+ assert_eq!(saved.mode, Mode::Experienced);+ assert_eq!(saved.language, "de");+ assert!(!Settings::path().with_extension("pending.toml").exists());+ assert_eq!(Settings::load(), saved, "recovery is durable and runs only once");+ return;+ }+ // A sidecar left by an earlier failed recovery must not undo this successful full save.+ let stale = Settings { language: "fr".into(), mode: Mode::Beginner, ..app.settings.clone() };+ stale.defer_save_to(&Settings::path()).unwrap();+ app.on_exit();+ assert!(!Settings::path().with_extension("pending.toml").exists());+ Settings::discard_pending(&Settings::path()).unwrap(); // Already absent is also success.++ let saved = Settings::load();+ assert_eq!(AiConfig::from_table(&saved.ai).unwrap().get("OpenCode"), Some(&entry));+ assert_eq!(saved.mode, Mode::Experienced);+ assert_eq!(saved.language, "de");+ assert_eq!(app.settings.ai, latest_ai);+ let session = engine.session();+ assert_eq!(session.settings.ai, latest_ai);+ assert_eq!(session.settings.mode, saved.mode);+ assert_eq!(session.settings.language, saved.language);+}diff --git a/crates/ui-egui/tests/headless_parity.rs b/crates/ui-egui/tests/headless_parity.rsindex 98d9edac..5ad19d80 100644--- a/crates/ui-egui/tests/headless_parity.rs+++ b/crates/ui-egui/tests/headless_parity.rs@@ -110,6 +110,8 @@ const ACTIONS: &[Action] = &[a("pick_model", "list the models an AI can use", Cli("ai model <name>")),a("set_model", "change the model an AI uses", Cli("ai model <name> <model>")),a("set_effort", "change how hard a Claude AI thinks", Cli("ai effort <name> <level>")),+ a("pick_agent_model", "list an agent's visible models and thinking depths", Tool(&["ai_models_list"])),+ a("set_agent_model", "choose an agent's model and thinking depth", Tool(&["ai_model_set"])),a("choose_backend", "pick the AI brain", Cli("chat <question> --backend")),a("set_role", "choose which AI builds or extracts", Cli("ai extractor <name>")),diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rsindex e0636e36..c6ac8e09 100644--- a/crates/ui-egui/tests/smoke.rs+++ b/crates/ui-egui/tests/smoke.rs@@ -1082,6 +1082,56 @@ fn a_claude_ais_effort_is_set_in_settings() {h.get_by_value("max");}+/// The picker exposes only the chosen model's depths and clears an old depth when changing models.+#[test]+fn opencode_picker_offers_only_the_selected_models_thinking_depths() {+ use craft_anything_ai::{AgentModel, BackendConfig, BackendKind, Effort};+ use craft_anything_ui_egui::builders::AgentModelPicker;+ let mut h = harness(|| {+ let mut a = demo::app(demo::engine(Mode::Experienced, true));+ a.hub+ .add_backend(+ BackendConfig { name: "OpenCode".into(), kind: BackendKind::AgentCli, model: "opencode".into(), base_url: None, ssh_host: None, enabled: true },+ None,+ )+ .unwrap();+ a.backends = a.hub.backends();+ a.backend_options = a.hub.options();+ a.state.settings_open = true;+ a.state.settings_tab = craft_anything_ui_egui::state::SettingsTab::Ai;+ a.agent_model_picker = Some(AgentModelPicker {+ request: 1,+ context: a.hub.model_context("OpenCode").unwrap(),+ model: Some("test/deep".into()),+ thinking: None,+ result: Some(Ok(vec![+ AgentModel { id: "test/deep".into(), name: "Deep".into(), thinking: Effort::ALL.into() },+ AgentModel { id: "test/small".into(), name: "Small".into(), thinking: vec![Effort::Low] },+ ])),+ });+ a+ });+ h.run_steps(3);+ h.get_all_by_label("Thinking depth").last().unwrap().click();+ h.run_steps(2);+ for label in ["Low", "Medium", "High", "Xhigh", "Max"] {+ h.get_by_label(label);+ }+ h.get_by_label("Max").click();+ h.run_steps(2);+ assert_eq!(h.state().agent_model_picker.as_ref().unwrap().thinking, Some(Effort::Max));+ h.get_by_label("OpenCode model").click();+ h.run_steps(2);+ h.get_by_label("Small · test/small").click();+ h.run_steps(2);+ assert!(h.state().agent_model_picker.as_ref().unwrap().thinking.is_none(), "a model change resets the draft depth");+ h.get_all_by_label("Thinking depth").last().unwrap().click();+ h.run_steps(2);+ h.get_by_label("Low");+ assert!(h.query_by_label("Max").is_none());+ assert!(h.query_by_label("Xhigh").is_none());+}+#[test]fn settings_window_tabs_draw() {let mut h = harness(|| {diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex e4df6d07..c1cae368 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -305,6 +305,36 @@ Owner: maintainers · Status: in progress### R2.2 More coding agentsOwner: open · Status: in progress+- [x] Offer OpenCode locally and over SSH with its own visible chat models and supported thinking+ depths (Low, Medium, High, Xhigh, Max) in settings and headless clients. Choices are validated+ before saving; explicit choices are refused at execution until native MCP support is available.+ See [OpenCode](opencode.md).+- [x] Capture OpenCode settings and project together; refuse a busy session instead of treating+ it as no project, and preserve open model pickers and matching results during contention.+- [x] Report cancelled model validation as stopped, while preserving error events for other failures.+- [x] Finish rejected or cancelled model validation with a terminal event so headless chat exits;+ document functions touched by the OpenCode model-selection changes.+- [x] Integrate the five-level `Effort` type from #395 for agent variants, and share a strict+ disk-based selection save between the hub and headless tools, preserving unrelated edits.+- [x] Rebase onto main after #395's squash merge, preserve extra model arguments without a saved+ selection, and render the remote-host placeholder visibly in the setup instructions.+- [x] Hold the UI settings worker's session guard through its disk save so it cannot overwrite+ a newer model selection; reverify the existing terminal-event regression for validation failures.+- [x] Label the settings-save guard so filesystem I/O is identifiable as a running job by the lock tracker.+- [x] Finish a failed CLI worker-thread start with a terminal event after its error so headless chat stops polling.+- [x] Synchronize the UI exit-time settings save with the session's latest AI table and other writers;+ an isolated exit-save regression preserves the latest model/depth and pending app settings.+- [x] Never wait for a running tool's session lock at shutdown: defer non-AI app edits in a versioned+ sidecar when busy, then recover against the latest committed AI settings at startup.+- [x] Discard superseded deferred settings after a successful full exit save; document model-only+ and 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 titles+ in 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).+- [ ] 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).+"Found on this computer" has to mean "can do the job". Today only Claude Code gets everything.**Every builder gets the same tools:**- [ ] A table of what each adapter gets (our tool server, approvals, resume, notes mid-turn, adiff --git a/docs/STATUS.md b/docs/STATUS.mdindex e14bd030..ed7deda5 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -8,12 +8,14 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Area | State | Verified by ||---|---|---|+| 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 || 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 || Apple app graphs | Selecting a macOS bundle recognises its root-relative `Contents/Info.plist` and retains its service/extension type; nested XPC bundles appear in `services` and as `xpc-service` graph nodes, including their executables when hosted in frameworks | Synthetic inventory tests, including parent-directory and flat bundle layouts, selected services/extensions, framework-hosted service executables, and bare-program controls. Ordinary selected directories with `Contents/Info.plist` need an Apple bundle suffix; archives retain layout-based recognition. Framework libraries and dylibs stay excluded from executables. Real app bundles were not checked for this correction || Chinese UI | Simplified (`zh-hans`) and Traditional (`zh-hant`) Chinese in Settings → General → Language; System chooses a supported OS language, otherwise English. Both catalogs cover UI controls and tool titles; translated titles are searchable. Raw tool data, AI text, logs, CLI/MCP and the separate browser viewer keep their original text. See [localisation](localization.md). | Catalog integrity and locale-resolution tests; `cargo xtask i18n-coverage`; isolated UI language-switch test. Platform visual checks are recorded separately. |-| Engine | 298 engine tools (314 with the AI and setup layers') across native, managed, Java, Android, Apple, JS/Electron, web, firmware, packets, databases, game archives and assets; see [tools.md](tools.md) and [tool-status.md](tool-status.md). A saved result can be narrowed without running again (`core_evidence_browse` keeps the rows matching given field values, cut to chosen fields) | A functional audit that ran every tool on real inputs on Windows, plus 600+ unit and integration tests |+| Engine | 299 engine tools (317 with the AI and setup layers') across native, managed, Java, Android, Apple, JS/Electron, web, firmware, packets, databases, game archives and assets; see [tools.md](tools.md) and [tool-status.md](tool-status.md). A saved result can be narrowed without running again (`core_evidence_browse` keeps the rows matching given field values, cut to chosen fields) | A functional audit that ran every tool on real inputs on Windows, plus 600+ unit and integration tests || Tool argument correction | Shared parameter parsing keeps schema types strict and reports the rejected value's JSON Pointer when known, the original type error and guidance to correct the call. Unknown locations are null; a root failure uses the empty pointer | Parser regressions cover string/array mismatches, nested indices, escaped keys, oversized paths, enum locations, defaults and strict fields. Shared engine dispatch is checked for Agent, MCP and CLI callers: rejected arrays create no record, and corrected input creates one. No live Qwen or Ollama build was run for this correction || Java class usage | `java_class_users_find` includes the component class of multidimensional object arrays; primitive-array descriptors do not match an unrelated class with the same descriptor letter | Synthetic class files parsed by the built-in reader: one- and two-dimensional allocations, class names beginning with `L`, primitive arrays, hit limits and method filters; formats tests. This correction was not checked with javac output or a JVM || Single-file apps and game files | `core_packed_files_list` and `core_packed_files_unpack` read Bun and Node.js single-file programs, .NET single-file apps, PyInstaller and Godot packs through one seam (`formats::packed`); `formats_bytecode_show` reads Python bytecode, `game_unity_code_names_show` Unity IL2CPP metadata, `formats_ai_weights_show` GGUF and safetensors headers. `app_folder_explain` says what an install folder is made with and what to run next | Unit tests with damaged files. Real files: a 279 MB Bun program, Node blobs, PyInstaller programs (Python 3.9, 3.14), .NET 8 single-file apps (macOS, Linux, Windows, compressed), Godot 3.6, 4.3 and 4.5 packs, 214 Python modules against CPython's own reader, a GGUF and a safetensors file, about 25 installed Mac apps. IL2CPP on synthetic files only |@@ -97,6 +99,13 @@ correction also passed [hosted CI](https://github.com/storytold/craft-anything/ain PR #544. This correction concerns reported finish reasons; handling of a missing finishreason is unchanged. No live provider or local-model build was run.+### OpenCode review follow-up++OpenCode variants now use the shared five-level `Effort` type while retaining exact catalogue+validation. Hub and headless tool selections share a strict disk-based save that preserves unrelated+settings changes and refuses damaged files or changed backends. Regression tests cover both entry+points. Rejected or cancelled model validation emits a terminal turn event so headless chat exits.+### Linux Unreal setupUnreal installations registered in `~/.config/Epic/UnrealEngine/Install.ini` are found on Linux.diff --git a/docs/opencode.md b/docs/opencode.mdnew file mode 100644index 00000000..c0d88b86--- /dev/null+++ b/docs/opencode.md@@ -0,0 +1,103 @@+# OpenCode as an AI backend++Craft Anything can run OpenCode V2 locally or on an SSH host. OpenCode owns its provider+connections 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.++## Desktop++1. Open **Settings → AI → Detect**, then add **OpenCode**, or **OpenCode on `<host>`**.+ Remote suggestions come from SSH aliases; they do not confirm that OpenCode is installed.+2. If needed, choose the local program, or enter its full path in **Remote program**.+3. Under the backend, click **Change…** to load the models from that OpenCode installation.+4. Choose a model and, if available, a **Thinking depth**, then **Apply**.++The model picker lists only enabled chat models returned by OpenCode. Provider/model ids+distinguish similarly named models and preserve custom aliases. The five thinking depths are+**Low**, **Medium**, **High**, **Xhigh** and **Max**; only those reported as variants of the+selected model are offered. A model can offer fewer depths, or none.++**OpenCode default** delegates model choice to OpenCode. **Model default** leaves thinking to+the selected model. Changing the draft model resets its draft thinking depth. **Reload models**+refreshes both lists after provider or configuration changes. A missing saved model or variant+is marked unavailable; there is no fallback catalogue or silent downgrade.++Discovery runs in the background with deadlines and output limits. Listing models launches+the selected OpenCode process, may start its background service, and may update its cache;+discovery is not read-only. Local queries explicitly use the current project directory;+SSH queries use the remote shell's working directory, as the existing remote runner does.+Local model lists are never substituted for a remote one.+Changing the program, backend settings or project invalidates an open picker. Saving an explicit+choice checks it against the selected installation's live catalogue.+If another task holds the session, opening or reloading the picker asks you to retry rather+than querying without the project directory. An already open picker keeps its draft and any+matching background result until the session can be checked again.+If validation fails or is cancelled, the conversation emits its error or stopped status followed+by a terminal turn event, so headless chat finishes without waiting for an agent that never started.++## CLI++```sh+craft-anything-cli ai add OpenCode --kind agent_cli --model opencode+craft-anything-cli ai model OpenCode+craft-anything-cli ai model OpenCode my-provider/my-model --thinking high+craft-anything-cli ai model OpenCode --thinking max+craft-anything-cli ai model OpenCode --default++craft-anything-cli ai add "OpenCode on studio" --kind agent_cli --model opencode --ssh-host studio+craft-anything-cli ai program "OpenCode on studio" /opt/opencode/bin/opencode+craft-anything-cli ai model "OpenCode on studio"+```++Replace `my-provider/my-model` with an id from the listing. Listing an OpenCode backend also+returns each model's supported `thinking` values. Naming a new model without `--thinking`+uses that model's default depth. `--thinking` alone applies to the configured explicit model.++The `ai_models_list` and `ai_model_set` tools expose the same discovery and validation to MCP+and other headless clients. For example, `ai_model_set` accepts+`{"name":"OpenCode","model":"my-provider/my-model","thinking":"high"}`. Omit both+`model` and `thinking` to restore the OpenCode default.+`ai_models_list` returns a total and a page controlled by `offset` and `limit` (200 by default,+at most 1000); the desktop picker and `ai model` command load the whole bounded catalogue.++## Configuration and execution++The agent identity stays `model = "opencode"`. Its optional choices are saved separately:++```toml+[[ai.backends]]+name = "OpenCode"+kind = "agent_cli"+model = "opencode"+cli_model = "my-provider/my-model"+cli_thinking = "high"+```++These fields extend the existing versioned settings file. Old settings without them retain+OpenCode's defaults; a known variant embedded in an existing `cli_model` reference is read into+`cli_thinking`. A model-only command uses `opencode run --model provider/model`;+adding a thinking depth uses `opencode run --model provider/model#variant`.+The shared `Effort` type represents all five levels. OpenCode's `cli_thinking` remains a separate+setting from API/Claude `effort`: an unavailable OpenCode variant is refused, never stepped down.+Hub and tool selections use the same save path: reread the settings file strictly, preserve unrelated+disk changes, and reject a changed backend or project. Malformed settings are left untouched, and+the session is updated only after a successful save.+Closing the app also preserves the latest AI selection. If a running tool holds the session,+pending non-AI app settings are kept in `config.pending.toml` instead of waiting for the tool or+overwriting its settings. At the next startup they are merged with the latest saved AI table;+the sidecar is removed after recovery or a successful full exit save that supersedes it.+It uses the existing settings schema and migrations; unreadable or newer files are not overwritten+by 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.++Model discovery uses `opencode api model.list --param location[directory]=...` (the V2+`GET /api/model` operation). This keeps credentials and configuration resolution inside OpenCode.+Global `--server` and `--standalone` arguments are shared with discovery. Extra model arguments+remain available when no model or thinking selection is saved. With an explicit selection,+conflicting extra model arguments are refused; choose the model through its settings instead.diff --git a/docs/pitfalls.md b/docs/pitfalls.mdindex 6497e655..0cc26862 100644--- a/docs/pitfalls.md+++ b/docs/pitfalls.md@@ -97,6 +97,11 @@ after and compare them byte for byte (done for every brief across 162 combinatio## Building and running+**A model catalogue queried in the wrong project.** OpenCode V2's raw `api get /api/model` does+not reliably select the invoking CLI's directory. Use the `model.list` operation with an explicit+`location[directory]` parameter, and test that the returned Location matches it. Over SSH,+expand the remote shell's working directory, never send a local project path.+**Rebuilding a binary that is running fails on Windows** ("Access is denied"), and the next commandsilently used the old binary. Long-running binaries (live rebuilds, servers) get their own`CARGO_TARGET_DIR`.@@ -239,6 +244,11 @@ edit, right before committing.## Design+**An early error without a terminal event.** Model validation returned after reporting an error,+but headless chat waits for `TurnDone`, not just an idle worker. Preflight failures and cancellation+must finish the event sequence too; regression tests check both the error/status and the terminal event.+Worker-thread creation failures need the same terminal event even though no worker ever started.+**Reading literals and skipping the rest.** The Electron window reader skipped a spread inside`webPreferences`, so a window whose preferences came partly from another object was reported as"contextIsolation is not set; the default applies", which nobody had checked until a live run on@@ -270,6 +280,20 @@ And again inside one process: the engine had its own `write_atomic` whose temp fby process only, so two threads saving `craft.json` wrote the same temp file and one rename foundit gone (#273). There is one atomic writer, `craft_anything_platform::fs::write_atomic`; don'twrite another.+The UI settings worker also released the session guard after cloning settings, letting that stale+snapshot overwrite a later model-selection save. Keep the guard through the worker's disk write+so session-based writers cannot overtake each other between reading and saving.+The exit-time save must merge the session's latest AI table before writing the app's pending settings;+the UI's AI snapshot may predate a selection already committed by the hub. But waiting for that guard+can hold shutdown behind a tool for hours. Try it once; if busy, durably defer only non-AI settings+and recover them at startup against the latest committed AI table, rather than racing a live writer.+After a successful full exit save, discard an older deferred snapshot so startup cannot replay it+over the newer app settings.++**Preflight checked a different transport.** An explicit OpenCode selection bypassed ACP, but+builder preflight still checked ACP's helper and the native adapter never supplied the MCP server.+Share transport selection between preflight and execution; reject unsupported native options+before running a process rather than starting an agent without the tools its task requires.**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 the@@ -352,6 +376,9 @@ the screen shows the last result.`try_session().unwrap_or_default()` at startup, so a busy engine meant Clean room and no AI, andthe next settings change saved those defaults over theirs. Seen once in a live run. A fallbackmust never stand in for data that gets saved back: wait (it's startup), or keep what's on disk.+The model picker later captured a busy session as "no project", queried in the wrong directory,+and rejected the save as a settings change. Capture settings and project under one guard; report+contention, preserve the draft and matching background results, and check again when available.**A save that changed memory first.** Adding an AI in the app put it in the session's settings,then the file write failed (on Windows, likely a virus scan holding config.toml), so the app showeddiff --git a/docs/tools.md b/docs/tools.mdindex 478d84bb..49a8f612 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -2,7 +2,7 @@Generated by `cargo xtask tools`. Do not edit by hand.-**299 engine tools** in 17 toolsets. Each is an MCP tool, a CLI command (`craft-anything-cli <id with dashes>`) and a tool the agent can call. The AI and setup layers add their own on top (`rebuild_*`, `assets_key_*`, `setup_*`); `craft-anything-cli commands` lists them all.+**299 engine tools** in 17 toolsets. Each is an MCP tool, a CLI command (`craft-anything-cli <id with dashes>`) and a tool the agent can call. The AI and setup layers add their own on top (`rebuild_*`, `assets_key_*`, `ai_models_list`, `ai_model_set`, `setup_*`); `craft-anything-cli commands` lists them all. [OpenCode model and thinking selection](opencode.md) describes the AI model tools.## Essentials (`core`, 34)