Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Add Copilot CLI support and shared agent investigations (#455)

Ryan Missel87174476d9e8
diff --git a/README.md b/README.md
index 97f7314a..c8714387 100644
--- a/README.md
+++ b/README.md
@@ -83,7 +83,7 @@
</td>
<td width="25%" valign="top">
<h3>🤖 Agent-ready</h3>
- 314 tools, each one a CLI command and an MCP tool, so any agent can drive the same engine the app uses. No AI is needed to inspect.
+ 320 tools, each one a CLI command and an MCP tool, so any agent can drive the same engine the app uses. No AI is needed to inspect.
</td>
</tr>
</table>
@@ -152,7 +152,8 @@ Building needs a coding agent on your computer. **Claude Code** is supported fir
Anything runs your own, unmodified `claude` program, which uses your own sign-in; Craft Anything
never sees or handles your account. Your use of it falls under your own agreement with
Anthropic. See [docs/claude-code.md](docs/claude-code.md) for how and why. A Codex adapter
-exists but hasn't been verified on a real install yet. Other agents that speak ACP (Gemini CLI,
+exists but hasn't been verified on a real install yet. **GitHub Copilot** can use your installed
+Copilot CLI through ACP: sign in separately with `copilot login`. Other agents that speak ACP (Gemini CLI,
Qwen Code, opencode, goose, Hermes, Maki) can be switched to it per backend; of those, only Maki has
been run live. Anthropic, OpenAI, OpenRouter and local
OpenAI-compatible servers are available for questions and analysis (Settings → AI).
@@ -174,7 +175,7 @@ connects Craft Anything to coding-agent apps.
## Under the hood
-A pure-Rust reverse-engineering engine with 314 tools (298 in the engine, the rest from the AI and
+A pure-Rust reverse-engineering engine with 320 tools (300 in the engine, the rest from the AI and
setup layers) for native programs, .NET, Java, Android, Apple, Electron/JavaScript, websites,
firmware, packet captures, databases and game files. Its own decoders, disassembler and
decompiler work without any outside program; Deep mode uses them all, and Ghidra when it's
diff --git a/apps/craft-anything-cli/src/main.rs b/apps/craft-anything-cli/src/main.rs
index 17e0c5f5..b9c2df20 100644
--- a/apps/craft-anything-cli/src/main.rs
+++ b/apps/craft-anything-cli/src/main.rs
@@ -61,6 +61,9 @@ pub enum Command {
/// `core_action_approve`); the Craft Anything app answers them.
#[arg(long)]
inbox: Option<PathBuf>,
+ /// Target metadata from the desktop (JSON); repeat for each target, active target last.
+ #[arg(long = "target")]
+ targets: Vec<String>,
},
/// Connect Craft Anything to your coding-agent apps.
Setup(setup_cmd::SetupArgs),
@@ -243,7 +246,7 @@ fn run(cli: Cli) -> u8 {
}
0
}
- Command::Mcp { all_tools, inbox } => {
+ Command::Mcp { all_tools, inbox, targets } => {
let engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => {
@@ -261,6 +264,15 @@ fn run(cli: Cli) -> u8 {
engine.session().ext.insert(Arc::new(keys));
}
let mut opts = craft_anything_mcp::ServerOptions::from_env();
+ // Share target metadata without reading original files in Clean room.
+ let targets: Result<Vec<craft_anything_engine::target::TargetContext>, _> = targets.iter().map(|target| serde_json::from_str(target)).collect();
+ let restored = targets
+ .map_err(|error| ToolError::invalid(format!("Invalid shared target: {error}")))
+ .and_then(|targets| engine.session().restore_targets(&targets));
+ if let Err(error) = restored {
+ eprintln!("craft-anything mcp: {}", error.message);
+ return 1;
+ }
opts.all_tools |= *all_tools;
opts.allow_run = cli.allow_run;
match craft_anything_mcp::serve_stdio(engine, opts) {
diff --git a/apps/craft-anything-cli/tests/cli.rs b/apps/craft-anything-cli/tests/cli.rs
index 5fbd8c3a..ce440988 100644
--- a/apps/craft-anything-cli/tests/cli.rs
+++ b/apps/craft-anything-cli/tests/cli.rs
@@ -140,6 +140,31 @@ fn mcp_over_stdio() {
assert_eq!(by_id(3)["result"]["isError"], false);
}
+#[test]
+fn mcp_restores_the_desktop_target_before_listing_tools() {
+ use craft_anything_engine::target::{Target, TargetContext};
+ let config = tempfile::tempdir().unwrap();
+ let directory = tempfile::tempdir().unwrap();
+ let file = directory.path().join("shared.bin");
+ std::fs::write(&file, b"shared-target").unwrap();
+ let target = Target::load(&file).unwrap();
+ let context = serde_json::to_string(&TargetContext::from_target(&target)).unwrap();
+ let input = [
+ json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}),
+ json!({"jsonrpc":"2.0","method":"notifications/initialized"}),
+ json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"core_targets_list","arguments":{}}}),
+ ].iter().map(|message| format!("{message}\n")).collect::<String>();
+ for mode in ["--deep", "--clean-room"] {
+ let output = cli_with_stdin(&["mcp", mode, "--target", &context], config.path(), input.as_bytes());
+ assert!(output.success, "{}", output.stderr_text());
+ let messages: Vec<Value> = output.stdout_text().lines().map(|line| serde_json::from_str(line).unwrap()).collect();
+ let response = messages.iter().find(|message| message["id"] == 2).unwrap();
+ assert_eq!(response["result"]["isError"], false, "{response}");
+ let value: Value = serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
+ assert_eq!(value["result"]["targets"][0]["target_id"], target.id, "{value}");
+ }
+}
+
#[test]
fn raw_binary_open_params_tool_format_and_project_evidence_across_processes() {
let cfg = tempfile::tempdir().unwrap();
diff --git a/crates/ai/src/anthropic.rs b/crates/ai/src/anthropic.rs
index 432b0262..8dfc84b7 100644
--- a/crates/ai/src/anthropic.rs
+++ b/crates/ai/src/anthropic.rs
@@ -20,6 +20,7 @@ pub const EFFORT_LEVELS: &[(&str, &[Effort])] = &[
/// The effort level `model` is sent: `effort`, or the nearest level below it the model has.
pub fn effort_for(model: &str, effort: Effort) -> Effort {
+ let effort = effort.within(&Effort::ALL);
let model = model.trim().trim_start_matches("anthropic/").trim_start_matches("anthropic.");
EFFORT_LEVELS.iter().find(|(prefix, _)| model.starts_with(prefix)).map_or(effort, |(_, levels)| effort.within(levels))
}
@@ -374,6 +375,15 @@ mod tests {
assert_eq!(effort_for("claude-opus-5-5", e), e);
assert_eq!(Effort::parse(&e.as_str().to_uppercase()), Some(e));
}
+ for model in ["claude-opus-5-5", "claude-sonnet-4-6", "anthropic/claude-future", "anthropic.claude-future"] {
+ let client = Anthropic::new(None, "sk-test".into(), model);
+ for effort in [Effort::None, Effort::Minimal] {
+ assert_eq!(effort_for(model, effort), Effort::Low);
+ let body = client.body(&TurnRequest { system: "s", messages: &[], tools: &[], effort, max_tokens: 10 });
+ assert_eq!(body["output_config"]["effort"], "low");
+ assert_eq!(Effort::parse(effort.as_str()), Some(effort));
+ }
+ }
assert_eq!(effort_for("claude-sonnet-4-6", Effort::Xhigh), Effort::High);
assert_eq!(effort_for("anthropic/claude-opus-4-6", Effort::Max), Effort::Max);
assert_eq!(effort_for("claude-opus-4-5-20251101", Effort::Max), Effort::High);
diff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rs
index 6c36c862..1a4909dc 100644
--- a/crates/ai/src/cli_agents/acp.rs
+++ b/crates/ai/src/cli_agents/acp.rs
@@ -8,9 +8,10 @@
//! process; [`AcpConversation`] runs it against the agent through `craft_anything_platform`.
use super::{McpCommand, display_for};
+use crate::model::Stop;
use crate::{AgentEvent, Conversation, FailureKind, TurnFailure};
use craft_anything_platform::sync::Mutex;
-use craft_anything_platform::{Process, RunningProcess, StdinMode};
+use craft_anything_platform::{RunningProcess, StdinMode};
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::io::Write;
@@ -19,7 +20,7 @@ use std::process::ChildStdin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, PoisonError};
-use std::time::Duration;
+use std::time::{Duration, Instant};
/// Agents known to speak ACP, and the arguments that start them in that mode.
pub const ACP_AGENTS: &[(&str, &[&str])] = &[
@@ -29,6 +30,7 @@ pub const ACP_AGENTS: &[(&str, &[&str])] = &[
("goose", &["acp"]),
("hermes", &["acp"]),
("maki", &["acp"]),
+ ("copilot", &["--acp", "--stdio"]),
];
/// Agents whose ACP mode takes the backend's model (`cli_model`), and the flag after the ACP
@@ -82,6 +84,13 @@ pub fn clean_room_chat_approver() -> Approver {
Arc::new(|tool, _input| !matches!(tool, "Read" | "Write" | "Bash" | "WebFetch"))
}
+/// Session metadata only: no prompt is sent to discover a model's selectable settings.
+pub struct ModelMetadata {
+ pub models: Vec<String>,
+ pub current_model: String,
+ pub config_options: Vec<Value>,
+}
+
/// An ACP tool call in the approval policy's shape.
fn policy_action(call: &Value) -> (String, Value) {
let s = |p: &str| call.pointer(p).and_then(Value::as_str).map(str::to_string);
@@ -136,6 +145,14 @@ pub struct AcpCore {
/// Permission requests go to an approver ([`Out::Decide`]) instead of the person's chat.
decides: bool,
failure: Option<TurnFailure>,
+ /// A read-only question: no MCP server and no permission escalation into a build.
+ question: bool,
+ /// The adapter's startup remediation. Sign-in itself stays outside the ACP connection.
+ sign_in_fix: Option<String>,
+ /// Model ids advertised by the opened or loaded session, not a local guess at its catalogue.
+ models: Vec<String>,
+ current_model: String,
+ config_options: Vec<Value>,
}
impl AcpCore {
@@ -156,6 +173,11 @@ impl AcpCore {
tools: HashMap::new(),
decides: false,
failure: None,
+ question: false,
+ sign_in_fix: None,
+ models: Vec::new(),
+ current_model: String::new(),
+ config_options: Vec::new(),
}
}
@@ -214,7 +236,7 @@ impl AcpCore {
}
fn mcp_servers(&self) -> Value {
- json!([{"name": super::MCP_NAME, "command": self.mcp.command, "args": self.mcp.args, "env": []}])
+ if self.question { json!([]) } else { json!([{"name": super::MCP_NAME, "command": self.mcp.command, "args": self.mcp.args, "env": []}]) }
}
/// One line from the agent.
@@ -238,6 +260,8 @@ impl AcpCore {
}
fn turn_done(&self) -> Out {
+ // This client has no attributable ACP usage totals. Leave the cost unknown instead of
+ // treating another provider's prices, or a session-wide total, as this turn's bill.
Out::Event(AgentEvent::TurnDone { backend: self.backend.clone(), input_tokens: 0, output_tokens: 0, cost_usd: None, cost_is_estimate: false })
}
@@ -257,8 +281,9 @@ impl AcpCore {
Some(-32602..=-32600) => FailureKind::Configuration,
_ => FailureKind::Unknown,
}));
- let fix = matches!(kind, Pending::Initialize | Pending::NewSession)
- .then(|| format!("Check that {} is installed and signed in: run it once in a terminal.", self.agent_name));
+ let fix = matches!(kind, Pending::Initialize | Pending::NewSession).then(|| {
+ self.sign_in_fix.clone().unwrap_or_else(|| format!("Check that {} is installed and signed in: run it once in a terminal.", self.agent_name))
+ });
return self.fail(format!("{}: {text}", self.agent_name), fix);
}
let result = msg.get("result").unwrap_or(&Value::Null);
@@ -278,6 +303,18 @@ impl AcpCore {
}
}
Pending::NewSession | Pending::LoadSession => {
+ self.current_model = result.pointer("/models/currentModelId").and_then(Value::as_str).unwrap_or_default().to_string();
+ self.config_options = result.get("configOptions").and_then(Value::as_array).cloned().unwrap_or_default();
+ // The running agent decides what's available to this account. Entries without
+ // an id can't be selected, so skip them rather than inventing one from a label.
+ self.models = result
+ .pointer("/models/availableModels")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|model| model.get("modelId").and_then(Value::as_str))
+ .map(str::to_string)
+ .collect();
if let Some(sid) = result.get("sessionId").and_then(Value::as_str) {
self.session = Some(sid.to_string());
}
@@ -311,6 +348,11 @@ impl AcpCore {
let err = json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": format!("{method} isn't offered by this client")}});
return vec![Out::Send(err.to_string())];
}
+ if self.question {
+ // Startup already limits the tools; a question cannot ask for broader access or
+ // turn an unexpected permission request into an approval card for the person.
+ return vec![Out::Send(json!({"jsonrpc": "2.0", "id": id, "result": {"outcome": {"outcome": "cancelled"}}}).to_string())];
+ }
let call = params.get("toolCall").unwrap_or(&Value::Null);
let s = |k: &str| call.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
let call_id = format!("acp-perm-{}", id.as_u64().map(|n| n.to_string()).unwrap_or_else(|| id.to_string()));
@@ -466,6 +508,8 @@ impl Shared {
pub struct AcpConversation {
program: String,
args: Vec<String>,
+ /// Process setup and startup guidance from the same registered adapter that chose the flags.
+ adapter: Arc<dyn super::AgentAdapter>,
agent: String,
backend: String,
cwd: PathBuf,
@@ -480,9 +524,84 @@ pub struct AcpConversation {
preamble: String,
logs: Option<PathBuf>,
failure: Option<TurnFailure>,
+ /// Suppress MCP attachment and refuse permission requests; startup flags restrict native tools.
+ question: bool,
+ /// Report invalid backend settings through the conversation before starting a child process.
+ validation_error: Option<craft_anything_evidence::ToolError>,
}
impl AcpConversation {
+ /// Open a session and read its model catalogue without sending a prompt. Waits for metadata
+ /// until `timeout`, carrying startup errors back to the caller; dropping this temporary
+ /// conversation stops its process. Blocking: call off the UI thread.
+ pub fn model_choices(self, timeout: Duration) -> Result<Vec<String>, craft_anything_evidence::ToolError> {
+ self.model_metadata(timeout).map(|metadata| metadata.models)
+ }
+
+ /// Read a fresh session's selected model and configuration choices without a model turn.
+ /// Blocking and bounded, with the same process cleanup as model catalogue discovery.
+ pub fn model_metadata(self, timeout: Duration) -> Result<ModelMetadata, craft_anything_evidence::ToolError> {
+ self.model_metadata_with_stop(timeout, &Stop::default())
+ }
+
+ pub(crate) fn model_metadata_with_stop(mut self, timeout: Duration, stop: &Stop) -> Result<ModelMetadata, craft_anything_evidence::ToolError> {
+ stop.check()?;
+ self.spawn()?;
+ self.busy.store(true, Ordering::SeqCst);
+ let started = Instant::now();
+ loop {
+ stop.check()?;
+ let ready = self.lock().as_ref().filter(|shared| shared.core.ready).map(|shared| ModelMetadata {
+ models: shared.core.models.clone(),
+ current_model: shared.core.current_model.clone(),
+ config_options: shared.core.config_options.clone(),
+ });
+ if let Some(metadata) = ready {
+ return Ok(metadata);
+ }
+ for event in self.poll() {
+ if let AgentEvent::Error { message, remediation, .. } = event {
+ let error = craft_anything_evidence::ToolError::unavailable(message);
+ return Err(match remediation {
+ Some(fix) => error.with_remediation(fix),
+ None => error,
+ });
+ }
+ }
+ if started.elapsed() >= timeout {
+ return Err(self.model_metadata_timeout());
+ }
+ std::thread::park_timeout(Duration::from_millis(10));
+ }
+ }
+
+ fn model_metadata_timeout(&self) -> craft_anything_evidence::ToolError {
+ craft_anything_evidence::ToolError::unavailable(format!("{} did not list its models before the deadline.", display_for(&self.agent)))
+ .with_remediation(self.adapter.sign_in_fix().unwrap_or_else(|| "Check the agent in a terminal, then try again.".into()))
+ }
+
+ /// Keep an adapter's settings check until the conversation starts. A failure is reported
+ /// through the usual events without launching a process or changing the person's settings.
+ pub fn with_validation(mut self, result: Result<(), craft_anything_evidence::ToolError>) -> Self {
+ self.validation_error = result.err();
+ self
+ }
+
+ /// A read-only question: attach no MCP server and refuse permission requests. The caller
+ /// must also choose a fresh session and restrictive agent flags; this switch alone doesn't
+ /// prevent native tools from running without a permission request.
+ pub fn with_question(mut self, question: bool) -> Self {
+ self.question = question;
+ self
+ }
+
+ /// Use the selected registry adapter for process setup and startup remediation. This keeps
+ /// custom adapters and test stand-ins on the same path as the built-in agents.
+ pub fn with_adapter(mut self, adapter: Arc<dyn super::AgentAdapter>) -> Self {
+ self.adapter = adapter;
+ self
+ }
+
/// Where to write a log if the agent stops unexpectedly ([`crate::failure_log`]).
pub fn with_logs(mut self, logs: Option<PathBuf>) -> Self {
self.logs = logs;
@@ -508,6 +627,7 @@ impl AcpConversation {
AcpConversation {
program,
args,
+ adapter: super::adapter_for(agent),
agent: agent.into(),
backend: backend.into(),
cwd,
@@ -522,6 +642,8 @@ impl AcpConversation {
preamble: String::new(),
logs: None,
failure: None,
+ question: false,
+ validation_error: None,
}
}
@@ -531,9 +653,14 @@ impl AcpConversation {
/// Start the agent and send `initialize`.
fn spawn(&mut self) -> Result<(), craft_anything_evidence::ToolError> {
+ if let Some(error) = &self.validation_error {
+ return Err(error.clone());
+ }
let name = display_for(&self.agent);
let resume = self.lock().as_ref().and_then(|s| s.core.session_id()).or_else(|| self.resume.clone());
let mut core = AcpCore::new(&self.backend, &name, self.cwd.clone(), self.mcp.clone(), resume);
+ core.question = self.question;
+ core.sign_in_fix = self.adapter.sign_in_fix();
if self.approver.is_some() {
core = core.deciding();
}
@@ -541,7 +668,9 @@ impl AcpConversation {
let (shared, tx, busy) = (self.shared.clone(), self.tx.clone(), self.busy.clone());
let shared_err = self.shared.clone();
let tx_err = tx.clone();
- let mut proc = Process::new(&self.program)
+ let mut proc = self
+ .adapter
+ .process(&self.program)
.args(&self.args)
.cwd(&self.cwd)
.stdin(StdinMode::Piped)
@@ -579,6 +708,7 @@ impl AcpConversation {
let outs = s.core.start();
s.apply(outs, &self.shared, &self.tx, &self.busy);
}
+ let _ = self.tx.send(AgentEvent::Status { text: "Usage totals are unavailable over ACP. Check usage and billing in the agent CLI.".into() });
Ok(())
}
@@ -700,6 +830,56 @@ impl Drop for AcpConversation {
mod tests {
use super::*;
+ #[test]
+ fn copilot_uses_stdio_acp() {
+ assert_eq!(acp_args("copilot"), Some(["--acp", "--stdio"].as_slice()));
+ assert!(acp_args("unknown-agent").is_none());
+ }
+
+ #[test]
+ fn copilot_authentication_stays_in_its_cli() {
+ let mut core = core(None);
+ core.sign_in_fix = super::super::adapter_for("copilot").sign_in_fix();
+ core.start();
+ let output = events(core.line(r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"Authentication required"}}"#));
+ assert!(
+ matches!(&output[0], AgentEvent::Error { remediation: Some(fix), .. } if fix.contains("copilot login") && fix.contains("restart Craft Anything"))
+ );
+ }
+
+ #[test]
+ fn copilot_model_choices_come_from_the_session_not_a_fixed_catalogue() {
+ let mut core = core(None);
+ core.start();
+ core.line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#);
+ core.line(r#"{"jsonrpc":"2.0","id":2,"result":{"sessionId":"copilot-test","models":{"availableModels":[{"modelId":"model-one","name":"One"},{"modelId":"model-two","name":"Two"},{"name":"missing-id"}]}}}"#);
+ assert_eq!(core.models, ["model-one", "model-two"]);
+ assert!(core.ready);
+ }
+
+ #[test]
+ fn model_metadata_deadlines_name_the_current_agent() {
+ for (agent, name) in [("gemini-cli", "Gemini CLI"), ("copilot", "GitHub Copilot")] {
+ let mcp = McpCommand { command: "not-started".into(), args: Vec::new(), notes: None };
+ let conversation = AcpConversation::new("Test", agent, "not-started".into(), Vec::new(), PathBuf::new(), mcp, None);
+ let error = conversation.model_metadata_timeout();
+ assert_eq!(error.message, format!("{name} did not list its models before the deadline."));
+ assert_eq!(error.remediation.unwrap().contains("copilot login"), agent == "copilot");
+ }
+ }
+
+ #[test]
+ fn a_read_only_question_opens_a_fresh_session_without_mcp_and_refuses_permissions() {
+ let mut core = core(None);
+ core.question = true;
+ core.start();
+ let new = sent(&core.line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#));
+ assert_eq!(new[0]["method"], "session/new");
+ assert_eq!(new[0]["params"]["mcpServers"], json!([]));
+ let reply = sent(&core.line(r#"{"jsonrpc":"2.0","id":"permission","method":"session/request_permission","params":{"toolCall":{"kind":"edit"},"options":[{"optionId":"allow","kind":"allow_once"}]}}"#));
+ assert_eq!(reply[0]["result"]["outcome"]["outcome"], "cancelled");
+ }
+
fn core(resume: Option<&str>) -> AcpCore {
let mcp = McpCommand { command: "/opt/ca/craft-anything-cli".into(), args: vec!["mcp".into()], notes: None };
AcpCore::new("Gemini", "Gemini CLI", PathBuf::from("/w/project"), mcp, resume.map(str::to_string))
diff --git a/crates/ai/src/cli_agents/adapters.rs b/crates/ai/src/cli_agents/adapters.rs
index aea5e012..199c4804 100644
--- a/crates/ai/src/cli_agents/adapters.rs
+++ b/crates/ai/src/cli_agents/adapters.rs
@@ -6,10 +6,12 @@
use super::*;
mod antigravity;
+mod copilot;
mod hermes;
mod maki;
mod opencode;
pub use antigravity::Antigravity;
+pub use copilot::Copilot;
pub use hermes::Hermes;
pub use maki::Maki;
pub use opencode::OpenCode;
@@ -27,8 +29,8 @@ pub struct ArgsCx<'a> {
pub builder: bool,
/// Clean room: reads go through our approval tool too, so the original stays out of reach.
pub reads_checked: bool,
- /// A question about a build: only reading (none in Clean room), a resumed session forked and
- /// not kept, no tool server.
+ /// A question about a build: only reading (none in Clean room), no tool server, and a fresh
+ /// session or a fork that leaves the builder's session unchanged.
pub question: bool,
}
@@ -42,6 +44,10 @@ pub trait AgentAdapter: Send + Sync {
fn has_model_catalog(&self) -> bool {
false
}
+
+ fn model_catalog_depends_on_selection(&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(
@@ -62,6 +68,41 @@ pub trait AgentAdapter: Send + Sync {
fn check_native_options(&self, _options: &BackendOptions) -> Result<(), ToolError> {
Ok(())
}
+
+ /// Use ACP by default and refuse the per-message CLI runner. An explicit `acp = false` or
+ /// an SSH host must fail rather than opening an interactive agent with no approval channel.
+ fn requires_acp(&self) -> bool {
+ false
+ }
+ /// Startup arguments before the ACP flags: models, effort and the tools this access mode
+ /// may expose. The default keeps the backend's extra arguments unchanged.
+ fn acp_options(&self, options: &BackendOptions, _access: Access) -> Vec<String> {
+ options.args.clone()
+ }
+ /// Session-only MCP startup flags for an agent that needs more than `session/new`'s server
+ /// list. Questions never receive these flags, and the person's saved config isn't changed.
+ fn acp_mcp_options(&self, _mcp: &McpCommand) -> Vec<String> {
+ Vec::new()
+ }
+ /// Refuse backend options that could bypass this adapter's restrictions, before its ACP
+ /// process starts. The refusal is kept on the conversation and reported by `send`.
+ fn validate_options(&self, _options: &BackendOptions) -> Result<(), ToolError> {
+ Ok(())
+ }
+ /// The model shown in Settings: an explicit choice or the CLI's own default. `None` means
+ /// the agent picks its model and doesn't offer a model selector here.
+ fn model_in_use(&self, _options: Option<&BackendOptions>) -> Option<String> {
+ None
+ }
+ /// Models the person can choose, from a catalogue or a bounded agent query. May block:
+ /// call off the UI thread. Empty means this agent offers no choices.
+ fn model_choices(&self, _config: &BackendConfig, _options: &BackendOptions) -> Result<Vec<String>, ToolError> {
+ Ok(Vec::new())
+ }
+ /// Whether this adapter offers context and reasoning controls beyond the model selector.
+ fn supports_model_tuning(&self) -> bool {
+ false
+ }
/// `(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]) {
@@ -85,8 +126,8 @@ pub trait AgentAdapter: Send + Sync {
fn resumes(&self) -> bool {
false
}
- /// It honours [`ArgsCx::question`]: it can be held to reading only, and a resumed session
- /// isn't changed. Questions about a build go only to adapters that say so.
+ /// It honours [`ArgsCx::question`]: it can be held to reading only, using a fresh session
+ /// or leaving a resumed session unchanged. Questions go only to adapters that say so.
fn answers_questions(&self) -> bool {
false
}
@@ -109,7 +150,7 @@ pub trait AgentAdapter: Send + Sync {
fn signed_in(&self, _program: &str) -> Option<bool> {
None
}
- /// The plain-words fix when [`signed_in`](AgentAdapter::signed_in) says no.
+ /// The plain-words fix when sign-in preflight or ACP startup fails. Login stays in the CLI.
fn sign_in_fix(&self) -> Option<String> {
None
}
@@ -157,7 +198,7 @@ impl Default for AgentAdapters {
}
impl AgentAdapters {
- /// Claude Code, Codex, Gemini CLI, OpenCode, Antigravity, Hermes and Maki.
+ /// The built-in coding agents, including Copilot's ACP-only adapter.
pub fn built_in() -> AgentAdapters {
AgentAdapters {
adapters: vec![
@@ -168,6 +209,7 @@ impl AgentAdapters {
Arc::new(Antigravity),
Arc::new(Hermes),
Arc::new(Maki),
+ Arc::new(Copilot),
],
}
}
@@ -277,6 +319,14 @@ impl AgentAdapter for ClaudeCode {
cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop)
}
+ fn model_in_use(&self, options: Option<&BackendOptions>) -> Option<String> {
+ Some(options.and_then(|options| options.cli_model.clone()).unwrap_or_else(|| crate::anthropic::DEFAULT_MODEL.into()))
+ }
+
+ fn model_choices(&self, _config: &BackendConfig, _options: &BackendOptions) -> Result<Vec<String>, ToolError> {
+ Ok(crate::anthropic::MODELS.iter().map(|model| model.to_string()).collect())
+ }
+
fn args(&self, cx: &ArgsCx) -> Vec<String> {
let mut a = cx.options.args.clone();
if cx.question {
diff --git a/crates/ai/src/cli_agents/adapters/copilot.rs b/crates/ai/src/cli_agents/adapters/copilot.rs
new file mode 100644
index 00000000..7bed4a15
--- /dev/null
+++ b/crates/ai/src/cli_agents/adapters/copilot.rs
@@ -0,0 +1,268 @@
+//! The person's installed Copilot CLI, driven over ACP with our MCP tools rather than its
+//! native file and shell tools. Sign-in, credential storage and refresh stay in Copilot CLI.
+
+use super::*;
+
+/// Copilot's ACP-only adapter. Unsupported connection modes fail instead of falling back to
+/// a CLI invocation that has no way to ask Craft Anything for approval.
+pub struct Copilot;
+
+impl AgentAdapter for Copilot {
+ fn ids(&self) -> &'static [&'static str] {
+ &["copilot"]
+ }
+
+ fn args(&self, _cx: &ArgsCx) -> Vec<String> {
+ // The native runner refuses `requires_acp` before it asks for arguments.
+ Vec::new()
+ }
+
+ fn requires_acp(&self) -> bool {
+ true
+ }
+
+ fn has_model_catalog(&self) -> bool {
+ true
+ }
+
+ fn model_catalog_depends_on_selection(&self) -> bool {
+ true
+ }
+
+ fn model_catalog(
+ &self,
+ config: &BackendConfig,
+ options: &BackendOptions,
+ directory: Option<&Path>,
+ stop: &Stop,
+ ) -> Result<Vec<models::AgentModel>, ToolError> {
+ let metadata = super::super::acp_model_metadata(config, options, directory, stop)?;
+ Ok(catalogue(&metadata, options))
+ }
+
+ fn validate_model(&self, config: &BackendConfig, options: &BackendOptions, directory: Option<&Path>, stop: &Stop) -> Result<(), ToolError> {
+ stop.check()?;
+ self.validate_options(options)?;
+ if options.cli_model.is_none() && options.cli_thinking.is_none() {
+ return Ok(());
+ }
+ models::validate(options, &self.model_catalog(config, options, directory, stop)?)
+ }
+
+ fn plain_fallback(&self) -> bool {
+ false
+ }
+
+ fn answers_questions(&self) -> bool {
+ true
+ }
+
+ fn model_in_use(&self, options: Option<&BackendOptions>) -> Option<String> {
+ // No override means the CLI's saved model, not an implicit request for `auto`.
+ Some(options.and_then(|options| options.cli_model.clone()).unwrap_or_else(|| "Copilot CLI default".into()))
+ }
+
+ fn model_choices(&self, config: &BackendConfig, options: &BackendOptions) -> Result<Vec<String>, ToolError> {
+ super::super::acp_model_choices(config, options)
+ }
+
+ fn supports_model_tuning(&self) -> bool {
+ true
+ }
+
+ fn check_tool_server(&self, stop: &CancelToken) -> Result<(), ToolError> {
+ cli_can_start(craft_anything_platform::self_cli_path().as_deref(), stop)
+ }
+
+ fn acp_options(&self, options: &BackendOptions, access: Access) -> Vec<String> {
+ // Keep questions in our inbox, inherited instructions out of the run, and the installed
+ // CLI version stable. Copilot already protects the other GitHub token variable names.
+ let mut args: Vec<String> =
+ ["--disable-builtin-mcps", "--no-ask-user", "--no-auto-update", "--no-custom-instructions", "--secret-env-vars=GH_TOKEN"].map(String::from).into();
+ // An empty allowlist restores native tools in CLI 1.0.105. A nonempty list containing
+ // only the disabled `ask_user` tool really leaves a Clean room question with no tools.
+ let tools = match access {
+ Access::Question => "view,glob,grep".to_string(),
+ Access::CleanRoomQuestion => "ask_user".to_string(),
+ _ => mcp_tools(),
+ };
+ args.push(format!("--available-tools={tools}"));
+ if !matches!(access, Access::Question | Access::CleanRoomQuestion) {
+ // Only our server is pre-allowed; its tools still enforce mode, effects and consent.
+ args.push(format!("--allow-tool={MCP_NAME}"));
+ }
+ if let Some(model) = options.cli_model.as_deref().filter(|model| !model.trim().is_empty()) {
+ args.extend(["--model".into(), model.into()]);
+ }
+ if let Some(context) = options.cli_context {
+ args.extend(["--context".into(), context.as_str().into()]);
+ }
+ if let Some(effort) = options
+ .cli_thinking
+ .map(|effort| effort.as_str())
+ .or_else(|| options.cli_reasoning_effort.map(|effort| effort.as_str()))
+ .or_else(|| options.effort.map(|effort| effort.as_str()))
+ {
+ args.extend(["--reasoning-effort".into(), effort.into()]);
+ }
+ args
+ }
+
+ fn validate_options(&self, options: &BackendOptions) -> Result<(), ToolError> {
+ // Extra arguments could replace the allowlist, attach another server or choose another
+ // credential store. Expose supported settings explicitly instead of merging those flags.
+ if options.args.is_empty() {
+ Ok(())
+ } else {
+ Err(ToolError::invalid("Extra Copilot CLI arguments could bypass Craft Anything's tool restrictions.")
+ .with_remediation("Remove this backend's extra arguments. Set its program, cli_model and effort through the backend options instead."))
+ }
+ }
+
+ fn process(&self, program: &str) -> Process {
+ // Inherited blanket approval must not bypass the app's policy. Authentication and the
+ // person's CLI home stay untouched; the CLI itself resolves its credentials.
+ Process::new(program).env("COPILOT_ALLOW_ALL", "false").env("COPILOT_ASSISTED_APPROVAL", "false")
+ }
+
+ fn acp_mcp_options(&self, mcp: &McpCommand) -> Vec<String> {
+ // CLI 1.0.105 exposed no tools with ACP's server list alone. Its documented startup
+ // config works without rewriting settings; the tool deadline matches a long build.
+ let config = json!({"mcpServers": {MCP_NAME: {"type": "stdio", "command": mcp.command, "args": mcp.args, "tools": ["*"], "timeout": 86_400_000}}});
+ vec![format!("--additional-mcp-config={config}")]
+ }
+
+ fn sign_in_fix(&self) -> Option<String> {
+ Some("Sign in separately in a terminal with `copilot login`, then try again. If authentication still fails, restart Craft Anything. Copilot CLI manages your credentials.".into())
+ }
+}
+
+fn catalogue(metadata: &super::super::acp::ModelMetadata, options: &BackendOptions) -> Vec<models::AgentModel> {
+ let tuning = crate::model_options::ModelTuning::from_metadata(metadata.current_model.clone(), &metadata.config_options);
+ let active = options.cli_model.as_deref().unwrap_or(&metadata.current_model);
+ let thinking: Vec<_> = tuning.reasoning.iter().filter_map(|choice| crate::Effort::parse(choice.value.as_str())).collect();
+ let mut ids = metadata.models.clone();
+ ids.insert(0, "auto".into());
+ if !metadata.current_model.is_empty() {
+ ids.push(metadata.current_model.clone());
+ }
+ ids.sort();
+ ids.dedup();
+ ids.into_iter().map(|id| models::AgentModel { name: id.clone(), thinking: if id == active { thinking.clone() } else { Vec::new() }, id }).collect()
+}
+
+/// CLI-level names for our built-in tools and the progressive-toolset helpers. Read them from
+/// the same catalogues as the MCP server so new built-ins aren't lost to a handwritten list.
+/// Runtime plugin tools stay out until their exposure has its own restriction test.
+fn mcp_tools() -> String {
+ let specs = craft_anything_engine::tools::all().into_iter().chain(crate::tools());
+ let mut names: Vec<String> = specs.map(|spec| format!("{MCP_NAME}-{}", spec.id)).collect();
+ names.extend(["list_toolsets", "enable_toolset"].map(|name| format!("{MCP_NAME}-{name}")));
+ names.sort();
+ names.dedup();
+ names.join(",")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn shared_catalogue_exposes_only_the_selected_models_advertised_thinking() {
+ let metadata = super::super::super::acp::ModelMetadata {
+ models: vec!["first".into(), "second".into()],
+ current_model: "first".into(),
+ config_options: vec![json!({"id":"reasoning_effort", "options":[{"value":"none","name":"None"},{"value":"high","name":"High"}]})],
+ };
+ let mut options = BackendOptions { cli_model: Some("first".into()), cli_thinking: Some(crate::Effort::None), ..Default::default() };
+ let models = catalogue(&metadata, &options);
+ assert_eq!(models.iter().find(|model| model.id == "first").unwrap().thinking, [crate::Effort::None, crate::Effort::High]);
+ assert!(models.iter().find(|model| model.id == "second").unwrap().thinking.is_empty());
+ assert!(models::validate(&options, &models).is_ok());
+ options.cli_thinking = Some(crate::Effort::Minimal);
+ assert!(models::validate(&options, &models).is_err());
+ for effort in crate::Effort::CLI_ALL {
+ options.cli_thinking = Some(effort);
+ options.cli_reasoning_effort = Some(crate::config::CliReasoningEffort::High);
+ assert!(Copilot.acp_options(&options, Access::Build).windows(2).any(|pair| pair == ["--reasoning-effort", effort.as_str()]));
+ }
+ }
+
+ #[test]
+ fn copilot_context_and_full_reasoning_range_round_trip_and_reach_the_cli() {
+ use crate::config::{CliContext, CliReasoningEffort};
+ for context in [CliContext::Standard, CliContext::Long] {
+ for effort in CliReasoningEffort::ALL {
+ let options = BackendOptions {
+ cli_context: Some(context),
+ cli_reasoning_effort: Some(*effort),
+ effort: Some(crate::model::Effort::Low),
+ ..Default::default()
+ };
+ let saved = toml::to_string(&options).unwrap();
+ assert_eq!(toml::from_str::<BackendOptions>(&saved).unwrap(), options);
+ let args = Copilot.acp_options(&options, Access::Build);
+ assert!(args.windows(2).any(|pair| pair == ["--context", context.as_str()]));
+ assert!(args.windows(2).any(|pair| pair == ["--reasoning-effort", effort.as_str()]));
+ assert_eq!(args.iter().filter(|argument| argument.as_str() == "--reasoning-effort").count(), 1);
+ }
+ }
+ let defaults: BackendOptions = toml::from_str("").unwrap();
+ assert_eq!(defaults.cli_context, None);
+ assert_eq!(defaults.cli_reasoning_effort, None);
+ assert!(!Copilot.acp_options(&defaults, Access::Build).iter().any(|argument| argument == "--context" || argument == "--reasoning-effort"));
+ }
+
+ #[test]
+ fn copilot_uses_acp_and_the_persons_model_without_a_key() {
+ let options = BackendOptions { cli_model: Some("auto".into()), effort: Some(crate::model::Effort::High), ..Default::default() };
+ let args = Copilot.acp_options(&options, Access::Build);
+ assert!(Copilot.requires_acp() && !Copilot.plain_fallback());
+ assert!(args.windows(2).any(|pair| pair == ["--model", "auto"]));
+ assert!(args.windows(2).any(|pair| pair == ["--reasoning-effort", "high"]));
+ assert!(args.contains(&"--secret-env-vars=GH_TOKEN".to_string()));
+ assert!(!args.iter().any(|arg| arg.starts_with("--allow-all")));
+ let fix = Copilot.sign_in_fix().unwrap();
+ assert!(fix.contains("copilot login") && fix.contains("restart Craft Anything"));
+ }
+
+ #[test]
+ fn copilot_exposes_only_our_mcp_tools_for_analysis_and_builds() {
+ for access in [Access::Analyse, Access::Build, Access::CleanRoomBuild] {
+ let args = Copilot.acp_options(&BackendOptions::default(), access);
+ let tools = args.iter().find_map(|arg| arg.strip_prefix("--available-tools=")).unwrap();
+ assert!(tools.split(',').all(|tool| tool.starts_with("craft-anything-")));
+ assert!(tools.split(',').any(|tool| tool == "craft-anything-build_file_write"));
+ assert!(tools.split(',').any(|tool| tool == "craft-anything-enable_toolset"));
+ assert!(args.contains(&"--allow-tool=craft-anything".to_string()));
+ assert!(args.contains(&"--no-custom-instructions".to_string()));
+ }
+ }
+
+ #[test]
+ fn copilot_questions_have_no_mcp_or_writing_tools() {
+ for (access, expected) in [(Access::Question, "--available-tools=view,glob,grep"), (Access::CleanRoomQuestion, "--available-tools=ask_user")] {
+ let args = Copilot.acp_options(&BackendOptions::default(), access);
+ assert!(args.iter().any(|arg| arg == expected));
+ assert!(args.contains(&"--no-ask-user".to_string()));
+ assert!(!args.iter().any(|arg| arg.starts_with("--allow-tool")));
+ }
+ }
+
+ #[test]
+ fn copilot_rejects_arguments_that_can_override_safety_or_authentication() {
+ assert!(Copilot.validate_options(&BackendOptions::default()).is_ok());
+ for argument in ["--allow-all", "--allow-tool=shell", "--available-tools=bash", "--config-dir=other", "--additional-mcp-config={}"] {
+ let options = BackendOptions { args: vec![argument.into()], ..Default::default() };
+ assert!(Copilot.validate_options(&options).is_err());
+ }
+ }
+
+ #[test]
+ fn copilot_uses_its_own_model_default_not_an_anthropic_model() {
+ assert_eq!(Copilot.model_in_use(None).as_deref(), Some("Copilot CLI default"));
+ assert!(!Copilot.acp_options(&BackendOptions::default(), Access::Build).iter().any(|argument| argument == "--model"));
+ let options = BackendOptions { cli_model: Some("chosen-copilot-model".into()), ..Default::default() };
+ assert_eq!(Copilot.model_in_use(Some(&options)).as_deref(), Some("chosen-copilot-model"));
+ }
+}
diff --git a/crates/ai/src/cli_agents/mod.rs b/crates/ai/src/cli_agents/mod.rs
index fb189c05..72cc3393 100644
--- a/crates/ai/src/cli_agents/mod.rs
+++ b/crates/ai/src/cli_agents/mod.rs
@@ -11,6 +11,9 @@
pub mod acp;
pub mod adapters;
pub mod models;
+mod shared;
+
+pub(crate) use shared::SharedConversation;
pub use acp::AcpConversation;
pub use adapters::{AgentAdapter, AgentAdapters, ArgsCx};
@@ -38,6 +41,7 @@ pub const MCP_NAME: &str = "craft-anything";
pub const KNOWN: &[(&str, &str, &str)] = &[
("claude-code", "claude", "Claude Code"),
("codex", "codex", "Codex"),
+ ("copilot", "copilot", "GitHub Copilot"),
("gemini-cli", "gemini", "Gemini CLI"),
("antigravity", "agy", "Antigravity"),
("opencode", "opencode", "OpenCode"),
@@ -130,10 +134,10 @@ pub fn check_builder_tools(adapter: &dyn AgentAdapter, agent: &str, options: &Ba
/// 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()) {
+ if adapter.has_model_catalog() && !adapter.requires_acp() && (options.cli_model.is_some() || options.cli_thinking.is_some()) {
return None;
}
- acp::acp_args(agent).filter(|_| options.acp == Some(true))
+ acp::acp_args(agent).filter(|_| options.acp.unwrap_or_else(|| adapter.requires_acp()))
}
fn toml_string(s: &str) -> String {
@@ -377,6 +381,8 @@ pub struct CliSpec {
pub beginner: bool,
/// The working folder (and, without `builder`, the investigation handed to our MCP server).
pub project: Option<PathBuf>,
+ /// The desktop's open targets, active last; the MCP child restores them before serving.
+ pub targets: Vec<craft_anything_engine::target::TargetContext>,
/// Build mode: the agent may edit files in the working folder.
pub builder: Option<Builder>,
/// A saved agent session to continue.
@@ -389,7 +395,7 @@ pub struct CliSpec {
pub preamble: Option<String>,
/// How each agent CLI is driven.
pub adapters: AgentAdapters,
- /// A question about a build: read-only, and a resumed session is forked and not kept, so the
+ /// A question about a build: read-only, with a fresh session or an unkept fork, so the
/// builder's own session is never changed. Only adapters that
/// [answer questions](adapters::AgentAdapter::answers_questions) take it.
pub question: bool,
@@ -417,6 +423,13 @@ fn mcp_for(spec: &CliSpec, remote: bool) -> McpCommand {
if spec.deep && spec.builder.is_some() {
mcp.args.push("--all-tools".into());
}
+ if !remote {
+ for target in spec.targets.iter().skip(spec.targets.len().saturating_sub(128)) {
+ if let Ok(target) = serde_json::to_string(target) {
+ mcp.args.extend(["--target".into(), target]);
+ }
+ }
+ }
mcp
}
@@ -427,6 +440,7 @@ impl CliSpec {
options,
beginner,
project,
+ targets: Vec::new(),
builder: None,
resume: None,
deep: false,
@@ -438,8 +452,8 @@ impl CliSpec {
}
}
-/// The conversation for a chat with an agent CLI: over ACP when the backend asks for it and the
-/// agent speaks it (a local, non-building run), else one CLI run per message.
+/// The conversation for a chat with an agent CLI: over ACP when the backend enables or requires
+/// it and the agent speaks it (a local, non-building run), else one CLI run per message.
pub fn conversation(spec: CliSpec) -> Box<dyn Conversation> {
match acp_for(&spec).filter(|_| spec.builder.is_none()) {
// In Clean room the agent's own file, shell and web requests are refused, not put to the
@@ -451,8 +465,8 @@ pub fn conversation(spec: CliSpec) -> Box<dyn Conversation> {
}
/// The conversation for a builder run: over ACP (permission requests decided by `approver`, the
-/// approval policy) when the backend asks for it and the agent speaks it, else one CLI run per
-/// message (approvals through our approval tool).
+/// approval policy) when the backend enables or requires it and the agent speaks it, else one
+/// CLI run per message (approvals through our approval tool).
pub fn builder_conversation(spec: CliSpec, approver: acp::Approver) -> Box<dyn Conversation> {
match acp_for(&spec) {
Some(c) => Box::new(c.with_approver(approver)),
@@ -460,21 +474,82 @@ pub fn builder_conversation(spec: CliSpec, approver: acp::Approver) -> Box<dyn C
}
}
-/// An ACP conversation for `spec`, when its backend asks for ACP (`acp = true`), runs locally
-/// and its agent speaks ACP.
+/// An ACP conversation for a local backend that enables or requires ACP. The adapter chooses
+/// the tool restrictions for this access mode; questions omit MCP startup flags and never load
+/// the builder's session. Unsupported routes return to the CLI runner, which refuses ACP-only agents.
fn 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 adapter = spec.adapters.for_agent(&agent);
+ if spec.question && !adapter.answers_questions() {
+ return None;
+ }
+ let local = spec.config.ssh_host.as_deref().is_none_or(|h| h.trim().is_empty());
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();
+ let access = match (spec.question, spec.deep, spec.builder.is_some()) {
+ (true, true, _) => Access::Question,
+ (true, false, _) => Access::CleanRoomQuestion,
+ (false, true, true) => Access::Build,
+ (false, false, true) => Access::CleanRoomBuild,
+ _ => Access::Analyse,
+ };
+ let mut args = adapter.acp_options(&spec.options, access);
args.extend(acp_args.iter().map(|a| a.to_string()));
args.extend(acp::model_args(&agent, spec.options.cli_model.as_deref()));
let cwd = spec.project.clone().or_else(|| std::env::current_dir().ok()).unwrap_or_else(std::env::temp_dir);
let mcp = mcp_for(spec, false);
+ if !spec.question {
+ args.extend(adapter.acp_mcp_options(&mcp));
+ }
let preamble = spec.preamble.clone().unwrap_or_else(|| crate::prompt::cli_preamble(spec.beginner));
- Some(AcpConversation::new(&spec.config.name, &agent, program, args, cwd, mcp, spec.resume.clone()).with_preamble(preamble).with_logs(spec.logs.clone()))
+ Some(
+ AcpConversation::new(&spec.config.name, &agent, program, args, cwd, mcp, if spec.question { None } else { spec.resume.clone() })
+ .with_validation(adapter.validate_options(&spec.options))
+ .with_adapter(adapter)
+ .with_question(spec.question)
+ .with_preamble(preamble)
+ .with_logs(spec.logs.clone()),
+ )
+}
+
+/// Copilot's selectable models from a fresh local ACP session, with `auto` offered once at the
+/// front. No MCP server or model prompt is sent, and a stale model override can't prevent the
+/// catalogue from loading. Blocking, with a 15-second metadata wait: call off the UI thread.
+pub fn acp_model_choices(config: &BackendConfig, options: &BackendOptions) -> Result<Vec<String>, ToolError> {
+ let mut spec = CliSpec::new(config.clone(), options.clone(), false, None);
+ spec.question = true;
+ spec.options.cli_model = None;
+ spec.options.cli_context = None;
+ spec.options.cli_reasoning_effort = None;
+ spec.options.effort = None;
+ let conversation = acp_for(&spec).ok_or_else(|| ToolError::invalid("This agent needs a local ACP connection to list its models."))?;
+ let mut models = conversation.model_choices(Duration::from_secs(15))?;
+ models.retain(|model| model != "auto");
+ models.insert(0, "auto".into());
+ Ok(models)
+}
+
+/// Discover settings for the backend's selected model, without a tool server or model prompt.
+pub fn acp_model_tuning(config: &BackendConfig, options: &BackendOptions, stop: &Stop) -> Result<crate::model_options::ModelTuning, ToolError> {
+ stop.check()?;
+ let metadata = acp_model_metadata(config, options, None, stop)?;
+ Ok(crate::model_options::ModelTuning::from_metadata(metadata.current_model, &metadata.config_options))
+}
+
+pub(crate) fn acp_model_metadata(
+ config: &BackendConfig,
+ options: &BackendOptions,
+ directory: Option<&Path>,
+ stop: &Stop,
+) -> Result<acp::ModelMetadata, ToolError> {
+ let mut spec = CliSpec::new(config.clone(), options.clone(), false, directory.map(Path::to_path_buf));
+ spec.question = true;
+ spec.options.cli_context = None;
+ spec.options.cli_reasoning_effort = None;
+ spec.options.cli_thinking = None;
+ spec.options.effort = None;
+ let conversation = acp_for(&spec).ok_or_else(|| ToolError::invalid("Model settings need a local ACP connection."))?;
+ conversation.model_metadata_with_stop(Duration::from_secs(15), stop)
}
/// A conversation backed by an agent CLI. Each message is one CLI run; Claude Code runs resume
@@ -612,6 +687,15 @@ fn run_cli(spec: &CliSpec, text: &str, retry: bool, tx: &Sender<AgentEvent>, sto
let 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 adapter.requires_acp() {
+ let sign_in = adapter.sign_in_fix().map(|fix| format!(" {fix}")).unwrap_or_default();
+ let _ = tx.send(AgentEvent::Error {
+ message: format!("{name} requires a local ACP connection."),
+ remediation: Some(format!("Run {} on this computer, remove the SSH host and do not disable ACP.{sign_in}", display_for(&agent))),
+ log: None,
+ });
+ return nothing_done(&name);
+ }
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);
@@ -2045,6 +2129,116 @@ echo '{"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}'
assert!(reg.for_agent("claude").resumes() && !reg.for_agent("codex").resumes() && reg.for_agent("antigravity").resumes());
// Registering an adapter for an existing id replaces that one.
reg.register(Arc::new(EchoAgent));
- assert_eq!(format!("{reg:?}"), r#"["claude-code", "codex", "gemini-cli", "opencode", "antigravity", "hermes", "maki", "echo-agent"]"#);
+ assert_eq!(format!("{reg:?}"), r#"["claude-code", "codex", "gemini-cli", "opencode", "antigravity", "hermes", "maki", "copilot", "echo-agent"]"#);
+ }
+
+ #[test]
+ fn copilot_defaults_to_local_acp_without_changing_other_agents() {
+ let config =
+ BackendConfig { name: "Copilot".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: None, enabled: true };
+ let mut spec = CliSpec::new(config, BackendOptions::default(), false, None);
+ assert!(acp_for(&spec).is_some());
+ assert_eq!(program_for("copilot"), "copilot");
+ assert_eq!(display_for("copilot"), "GitHub Copilot");
+ spec.options.acp = Some(false);
+ assert!(acp_for(&spec).is_none());
+ spec.options.acp = Some(true);
+ spec.config.ssh_host = Some("build-machine".into());
+ assert!(acp_for(&spec).is_none());
+ spec.config.ssh_host = None;
+ spec.options.acp = None;
+ spec.config.model = "gemini-cli".into();
+ assert!(acp_for(&spec).is_none());
+ spec.options.acp = Some(true);
+ assert!(acp_for(&spec).is_some());
+ spec.question = true;
+ assert!(acp_for(&spec).is_none());
+ spec.config.model = "copilot".into();
+ assert!(acp_for(&spec).is_some());
+ }
+
+ #[test]
+ fn mcp_target_handoff_is_bounded_and_keeps_the_active_target_last() {
+ use craft_anything_engine::{TargetKind, target::TargetContext};
+ let directory = tempfile::tempdir().unwrap();
+ for count in [0, 128, 129, 130] {
+ let config =
+ BackendConfig { name: "Test".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: None, enabled: true };
+ let mut spec = CliSpec::new(config, BackendOptions::default(), false, None);
+ spec.targets = (0..count)
+ .map(|index| TargetContext {
+ path: directory.path().join(format!("target-{index}")),
+ sha256: format!("{index:064x}"),
+ kind: TargetKind::Elf,
+ raw: None,
+ })
+ .collect();
+ let command = mcp_for(&spec, false);
+ let shared: Vec<TargetContext> =
+ command.args.windows(2).filter(|pair| pair[0] == "--target").map(|pair| serde_json::from_str(&pair[1]).unwrap()).collect();
+ assert_eq!(shared.len(), count.min(128));
+ assert_eq!(
+ shared.iter().map(|target| &target.path).collect::<Vec<_>>(),
+ spec.targets.iter().skip(count.saturating_sub(128)).map(|target| &target.path).collect::<Vec<_>>()
+ );
+ assert_eq!(shared.last().map(|target| &target.path), spec.targets.last().map(|target| &target.path));
+ assert!(!mcp_for(&spec, true).args.iter().any(|argument| argument == "--target"));
+ }
+ }
+
+ #[test]
+ fn copilot_never_falls_back_to_native_or_ssh_execution() {
+ for host in [None, Some("build-machine".to_string())] {
+ let config =
+ BackendConfig { name: "Copilot".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: host, enabled: true };
+ let options = BackendOptions { acp: Some(false), command: Some("no-such-copilot-xyz".into()), ..Default::default() };
+ let spec = CliSpec::new(config, options, false, None);
+ let (sender, receiver) = std::sync::mpsc::channel();
+ let state = RunState { session: Arc::default(), verified: Arc::default(), lost: Arc::default(), failure: Arc::default() };
+ let done = run_cli(&spec, "hello", false, &sender, &Stop::default(), &state);
+ let mut output: Vec<_> = receiver.try_iter().collect();
+ output.push(done);
+ assert!(matches!(&output[..], [AgentEvent::Error { message, .. }, AgentEvent::TurnDone { .. }] if message.contains("local ACP")));
+ }
+ }
+
+ #[test]
+ fn acp_only_refusals_use_the_registered_adapters_sign_in_guidance() {
+ struct AcpOnlyAgent(Option<&'static str>);
+ impl AgentAdapter for AcpOnlyAgent {
+ fn ids(&self) -> &'static [&'static str] {
+ &["test-acp-agent"]
+ }
+ fn args(&self, _context: &ArgsCx) -> Vec<String> {
+ Vec::new()
+ }
+ fn requires_acp(&self) -> bool {
+ true
+ }
+ fn sign_in_fix(&self) -> Option<String> {
+ self.0.map(str::to_string)
+ }
+ }
+ for guidance in [None, Some("Use test-agent sign-in.")] {
+ let config = BackendConfig {
+ name: "Test agent".into(),
+ kind: BackendKind::AgentCli,
+ model: "test-acp-agent".into(),
+ base_url: None,
+ ssh_host: None,
+ enabled: true,
+ };
+ let mut spec = CliSpec::new(config, BackendOptions::default(), false, None);
+ spec.adapters.register(Arc::new(AcpOnlyAgent(guidance)));
+ let (sender, receiver) = std::sync::mpsc::channel();
+ let state = RunState { session: Arc::default(), verified: Arc::default(), lost: Arc::default(), failure: Arc::default() };
+ let done = run_cli(&spec, "hello", false, &sender, &Stop::default(), &state);
+ let mut output: Vec<_> = receiver.try_iter().collect();
+ output.push(done);
+ let [AgentEvent::Error { remediation: Some(fix), .. }, AgentEvent::TurnDone { .. }] = output.as_slice() else { panic!("{output:?}") };
+ assert!(fix.contains("test-acp-agent") && fix.contains("remove the SSH host") && fix.contains("do not disable ACP"), "{fix}");
+ assert!(!fix.to_lowercase().contains("copilot"), "{fix}");
+ assert_eq!(fix.contains("Use test-agent sign-in."), guidance.is_some());
+ }
}
}
diff --git a/crates/ai/src/cli_agents/models.rs b/crates/ai/src/cli_agents/models.rs
index 39472c6f..16b700a4 100644
--- a/crates/ai/src/cli_agents/models.rs
+++ b/crates/ai/src/cli_agents/models.rs
@@ -154,11 +154,11 @@ pub(crate) fn discover(config: &BackendConfig, options: &BackendOptions, directo
/// 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.")) };
+ return if options.cli_thinking.is_none() { Ok(()) } else { Err(ToolError::invalid("Choose a 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."));
+ return Err(ToolError::invalid(format!("The selected model {id:?} is no longer available."))
+ .with_remediation("Reload the models on this computer and choose an available model or the agent's 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()))
@@ -183,6 +183,13 @@ pub fn select_with_stop(context: &ModelContext, model: Option<&str>, thinking: O
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;
+ if adapter.requires_acp() {
+ options.cli_reasoning_effort = None;
+ options.effort = None;
+ if options.cli_model != context.backend.options.cli_model {
+ options.cli_context = None;
+ }
+ }
adapter.validate_model(&context.backend.config, &options, context.directory.as_deref(), stop)?;
Ok(options)
}
diff --git a/crates/ai/src/cli_agents/shared.rs b/crates/ai/src/cli_agents/shared.rs
new file mode 100644
index 00000000..1e9ee8e7
--- /dev/null
+++ b/crates/ai/src/cli_agents/shared.rs
@@ -0,0 +1,221 @@
+//! Agent chats with a project shared by the desktop and MCP process. All preparation, polling
+//! and project refresh work stays on this worker, so drawing never waits for filesystem I/O.
+
+use super::*;
+use crate::BackendEntry;
+use craft_anything_engine::Engine;
+use std::sync::mpsc::RecvTimeoutError;
+
+enum Command {
+ Send(String),
+ Answer(String, bool),
+ Stop,
+ Quit,
+}
+
+pub(crate) struct SharedConversation {
+ commands: Sender<Command>,
+ events: Receiver<AgentEvent>,
+ report: Sender<AgentEvent>,
+ busy: Arc<AtomicBool>,
+ session: Arc<Mutex<Option<String>>>,
+}
+
+impl SharedConversation {
+ pub(crate) fn new(engine: Arc<Engine>, entry: BackendEntry, beginner: bool) -> Result<Self, ToolError> {
+ let (commands, requests) = std::sync::mpsc::channel();
+ let (output, events) = std::sync::mpsc::channel();
+ let report = output.clone();
+ let busy = Arc::new(AtomicBool::new(false));
+ let session = Arc::new(Mutex::new(None));
+ let (working, saved_session) = (busy.clone(), session.clone());
+ std::thread::Builder::new()
+ .name("ai-shared-project".into())
+ .spawn(move || {
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let mut conversation: Option<Box<dyn Conversation>> = None;
+ let mut context: Option<Value> = None;
+ loop {
+ match requests.recv_timeout(Duration::from_millis(25)) {
+ Ok(Command::Quit) | Err(RecvTimeoutError::Disconnected) => break,
+ Ok(Command::Send(text)) => {
+ let _ = output.send(AgentEvent::Status { text: "Preparing the shared investigation...".into() });
+ match prepare(&engine, &entry, beginner) {
+ Ok(mut spec) => {
+ let next = json!({"project": spec.project, "targets": spec.targets, "deep": spec.deep, "options": spec.options});
+ if context.as_ref() != Some(&next) {
+ if context.as_ref().and_then(|context| context.get("project")) == next.get("project") {
+ spec.resume = conversation.as_ref().and_then(|conversation| conversation.session_id());
+ }
+ conversation = Some(super::conversation(spec));
+ context = Some(next);
+ }
+ }
+ Err(error) => {
+ let _ = output.send(AgentEvent::Error { message: error.message, remediation: error.remediation, log: None });
+ let _ = output.send(AgentEvent::TurnDone {
+ backend: entry.config.name.clone(),
+ input_tokens: 0,
+ output_tokens: 0,
+ cost_usd: None,
+ cost_is_estimate: false,
+ });
+ working.store(false, Ordering::SeqCst);
+ continue;
+ }
+ }
+ if let Some(conversation) = conversation.as_mut() {
+ conversation.send(&text);
+ }
+ }
+ Ok(Command::Answer(id, allow)) => {
+ if let Some(conversation) = conversation.as_mut() {
+ conversation.answer_consent(&id, allow);
+ }
+ }
+ Ok(Command::Stop) => {
+ if let Some(conversation) = conversation.as_mut() {
+ conversation.stop();
+ }
+ }
+ Err(RecvTimeoutError::Timeout) => {}
+ }
+ let Some(conversation) = conversation.as_mut() else { continue };
+ let events = conversation.poll();
+ if events.iter().any(|event| matches!(event, AgentEvent::ToolFinished { .. } | AgentEvent::TurnDone { .. })) {
+ let refresh = {
+ let mut session = engine.session();
+ let project = session.project.clone();
+ project.map(|project| session.open_project(project)).transpose()
+ };
+ if let Err(error) = refresh {
+ let _ = output.send(AgentEvent::Error {
+ message: format!("Couldn't refresh the shared investigation: {}", error.message),
+ remediation: error.remediation,
+ log: None,
+ });
+ }
+ }
+ *saved_session.lock().unwrap_or_else(PoisonError::into_inner) = conversation.session_id();
+ for event in events {
+ let _ = output.send(event);
+ }
+ working.store(conversation.is_busy(), Ordering::SeqCst);
+ }
+ }));
+ if result.is_err() {
+ let _ = output.send(AgentEvent::Error {
+ message: "The shared investigation worker stopped safely after an internal error.".into(),
+ remediation: None,
+ log: None,
+ });
+ let _ = output.send(AgentEvent::TurnDone {
+ backend: entry.config.name.clone(),
+ input_tokens: 0,
+ output_tokens: 0,
+ cost_usd: None,
+ cost_is_estimate: false,
+ });
+ }
+ working.store(false, Ordering::SeqCst);
+ })
+ .map_err(|error| ToolError::internal(format!("Couldn't start the investigation worker: {error}")))?;
+ Ok(Self { commands, events, report, busy, session })
+ }
+}
+
+fn prepare(engine: &Engine, entry: &BackendEntry, beginner: bool) -> Result<CliSpec, ToolError> {
+ let mut session = engine.session();
+ let config = crate::AiConfig::from_settings(&session.settings);
+ let entry = config.get(&entry.config.name).unwrap_or(entry);
+ let project = session.ensure_shared_project()?;
+ let targets = session.shared_targets();
+ serde_json::to_value(&targets).map_err(|error| ToolError::invalid(format!("Couldn't share the target metadata: {error}")))?;
+ let mut spec = CliSpec::new(entry.config.clone(), entry.options.clone(), beginner, Some(project));
+ spec.targets = targets;
+ spec.deep = !session.clean_room();
+ spec.logs = Some(crate::failure_log::dir_in(&session.config_dir()));
+ Ok(spec)
+}
+
+impl Conversation for SharedConversation {
+ fn send(&mut self, text: &str) {
+ if self.busy.swap(true, Ordering::SeqCst) {
+ let _ = self.report.send(AgentEvent::Error {
+ message: "Still working on the last message.".into(),
+ remediation: Some("Wait for it to finish or press stop.".into()),
+ log: None,
+ });
+ return;
+ }
+ if self.commands.send(Command::Send(text.into())).is_err() {
+ self.busy.store(false, Ordering::SeqCst);
+ let _ = self.report.send(AgentEvent::Error {
+ message: "The investigation worker is no longer running.".into(),
+ remediation: Some("Start a new conversation and try again.".into()),
+ log: None,
+ });
+ }
+ }
+
+ fn session_id(&self) -> Option<String> {
+ self.session.lock().unwrap_or_else(PoisonError::into_inner).clone()
+ }
+ fn poll(&mut self) -> Vec<AgentEvent> {
+ self.events.try_iter().collect()
+ }
+ fn answer_consent(&mut self, id: &str, allow: bool) {
+ let _ = self.commands.send(Command::Answer(id.into(), allow));
+ }
+ fn stop(&mut self) {
+ let _ = self.commands.send(Command::Stop);
+ }
+ fn is_busy(&self) -> bool {
+ self.busy.load(Ordering::SeqCst)
+ }
+}
+
+impl Drop for SharedConversation {
+ fn drop(&mut self) {
+ let _ = self.commands.send(Command::Quit);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{BackendConfig, BackendKind};
+ use craft_anything_engine::target::Target;
+
+ #[test]
+ fn preparation_shares_the_project_and_keeps_the_active_target_last() {
+ let directory = tempfile::tempdir().unwrap();
+ let engine = Engine::new(craft_anything_engine::Session::isolated(directory.path()));
+ let first = directory.path().join("first.bin");
+ let second = directory.path().join("second.bin");
+ std::fs::write(&first, b"first").unwrap();
+ std::fs::write(&second, b"second").unwrap();
+ let active = engine.session().add_target(Target::load(&first).unwrap());
+ engine.session().add_target(Target::load(&second).unwrap());
+ engine.session().set_active(&active).unwrap();
+ let entry = BackendEntry {
+ config: BackendConfig { name: "Agent".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: None, enabled: true },
+ options: BackendOptions::default(),
+ };
+ let spec = prepare(&engine, &entry, false).unwrap();
+ assert_eq!(spec.targets.len(), 2);
+ assert_eq!(spec.targets.last().unwrap().path, first);
+ assert_eq!(spec.project, engine.session().project.as_ref().map(|project| project.root.clone()));
+ let command = super::super::mcp_for(&spec, false);
+ assert_eq!(command.args.iter().filter(|argument| argument.as_str() == "--target").count(), 2);
+ let mut updated = entry.clone();
+ updated.options.cli_context = Some(crate::config::CliContext::Long);
+ updated.options.cli_reasoning_effort = Some(crate::config::CliReasoningEffort::Max);
+ let mut config = crate::AiConfig::default();
+ config.upsert(updated);
+ engine.session().settings.ai = config.to_table().unwrap();
+ let refreshed = prepare(&engine, &entry, false).unwrap();
+ assert_eq!(refreshed.options.cli_context, Some(crate::config::CliContext::Long));
+ assert_eq!(refreshed.options.cli_reasoning_effort, Some(crate::config::CliReasoningEffort::Max));
+ }
+}
diff --git a/crates/ai/src/config.rs b/crates/ai/src/config.rs
index b28745bc..7cc4f1e6 100644
--- a/crates/ai/src/config.rs
+++ b/crates/ai/src/config.rs
@@ -98,16 +98,70 @@ pub struct BackendOptions {
/// 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>,
+ /// Copilot's context tier. Unset keeps the CLI's own choice; token limits depend on the model.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cli_context: Option<CliContext>,
+ /// Copilot's full named reasoning range. Unset falls back to `effort` or the CLI default;
+ /// `none` is an explicit choice, not the absence of an override.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cli_reasoning_effort: Option<CliReasoningEffort>,
/// 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")]
pub timeout_secs: Option<u64>,
/// Agent CLIs that speak ACP (`cli_agents::acp::ACP_AGENTS`): chat over it, one agent process
- /// per conversation (off unless set).
+ /// per conversation (on for Copilot, off for other agents unless set).
#[serde(skip_serializing_if = "Option::is_none")]
pub acp: Option<bool>,
}
+/// A provider's context tier, not a guessed token count. Copilot reports each model's limits.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
+pub enum CliContext {
+ #[serde(rename = "default")]
+ Standard,
+ #[serde(rename = "long_context")]
+ Long,
+}
+
+impl CliContext {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Standard => "default",
+ Self::Long => "long_context",
+ }
+ }
+}
+
+/// The CLI's named reasoning levels; these are not numeric thinking-token budgets.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum CliReasoningEffort {
+ None,
+ Minimal,
+ Low,
+ Medium,
+ High,
+ Xhigh,
+ Max,
+}
+
+impl CliReasoningEffort {
+ pub const ALL: &'static [Self] = &[Self::None, Self::Minimal, Self::Low, Self::Medium, Self::High, Self::Xhigh, Self::Max];
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::None => "none",
+ Self::Minimal => "minimal",
+ Self::Low => "low",
+ Self::Medium => "medium",
+ Self::High => "high",
+ Self::Xhigh => "xhigh",
+ Self::Max => "max",
+ }
+ }
+}
+
/// One configured backend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BackendEntry {
diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rs
index 036f361a..fd0ab66c 100644
--- a/crates/ai/src/lib.rs
+++ b/crates/ai/src/lib.rs
@@ -18,6 +18,7 @@ pub mod http;
pub mod key_tools;
pub mod keys;
pub mod model;
+pub mod model_options;
pub mod model_tools;
pub mod openai;
pub mod price;
@@ -75,7 +76,7 @@ impl BackendKind {
BackendKind::Openrouter => openai::OPENROUTER_MODELS,
BackendKind::Gemini => openai::GEMINI_MODELS,
BackendKind::OpenaiCompatible => &[],
- BackendKind::AgentCli => &["claude-code", "codex", "gemini-cli", "opencode", "antigravity", "hermes", "maki"],
+ BackendKind::AgentCli => &["claude-code", "codex", "copilot", "gemini-cli", "opencode", "antigravity", "hermes", "maki"],
}
}
@@ -154,16 +155,13 @@ pub fn effort_in_use(config: &BackendConfig, options: Option<&BackendOptions>) -
}
/// The model an AI uses, when it can be chosen (Settings → AI, #123): an API's own, or the one
-/// Claude Code is asked for. `None` for an agent app that picks its own.
+/// a coding agent is asked for. `None` for an agent app that picks its own.
pub fn model_in_use(config: &BackendConfig, options: Option<&BackendOptions>) -> Option<String> {
match config.kind {
- 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()))
+ Some(options.and_then(|o| o.cli_model.clone()).unwrap_or_else(|| format!("{} default", cli_agents::display_for(&config.model))))
}
- BackendKind::AgentCli => None,
+ BackendKind::AgentCli => cli_agents::adapter_for(&config.model).model_in_use(options),
_ => Some(config.model.clone()),
}
}
@@ -331,6 +329,7 @@ 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.extend(model_options::specs());
v
}
@@ -532,7 +531,14 @@ impl AiHub {
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 {
- BackendKind::AgentCli => b.options.cli_model = Some(model.to_string()),
+ BackendKind::AgentCli => {
+ if model_options::supported(&b.config) && b.options.cli_model.as_deref() != Some(model) {
+ b.options.cli_context = None;
+ b.options.cli_reasoning_effort = None;
+ b.options.effort = None;
+ }
+ b.options.cli_model = Some(model.to_string());
+ }
_ => b.config.model = model.to_string(),
}
self.save_config(&cfg)?;
@@ -552,8 +558,8 @@ impl AiHub {
Ok(true)
}
- /// The models a backend can be set to (#123): the API's own list, or Claude's models for Claude
- /// Code. Empty for an agent app that picks its own. Blocking (bounded); run it off the UI thread.
+ /// The models a backend can be set to: the API's or registered agent's list.
+ /// 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() {
@@ -561,7 +567,7 @@ impl AiHub {
}
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()),
+ (BackendKind::AgentCli, Some(_)) => cli_agents::adapter_for(&e.config.model).model_choices(&e.config, &e.options),
_ => self.list_models(name),
}
}
@@ -600,6 +606,23 @@ impl AiHub {
config::save_agent_selection(&mut session, &self.settings_path(), context, options)
}
+ /// Context tiers and reasoning choices for a selected CLI model. Discovery is bounded and
+ /// sends no model prompt; call off the UI thread.
+ pub fn model_tuning(&self, name: &str) -> Result<model_options::ModelTuning, ToolError> {
+ let entry = self.entry(name)?;
+ if !model_options::supported(&entry.config) {
+ return Err(ToolError::invalid("This backend does not offer CLI model options."));
+ }
+ cli_agents::acp_model_tuning(&entry.config, &entry.options, &Stop::default())
+ }
+
+ /// Save a model picker's two settings together, before replacing the in-memory config.
+ pub fn set_model_options(&self, params: &model_options::SetModelOptions) -> Result<(), ToolError> {
+ let mut config = self.config_to_change()?;
+ model_options::update(&mut config, params)?;
+ self.save_config(&config)
+ }
+
/// 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()?;
@@ -723,10 +746,6 @@ impl AiHub {
})
}
- fn project_root(&self) -> Option<PathBuf> {
- self.engine.try_session().and_then(|s| s.project.as_ref().map(|p| p.root.clone()))
- }
-
/// Start a conversation with the lead backend (or the named one).
pub fn start(&self, backend: Option<&str>, beginner: bool) -> Result<Box<dyn Conversation>, ToolError> {
let cfg = self.config();
@@ -738,12 +757,7 @@ impl AiHub {
.ok_or_else(|| ToolError::unavailable("No AI is set up yet.").with_remediation("Add one in Settings → AI."))?,
};
if first.config.kind == BackendKind::AgentCli {
- let spec = cli_agents::CliSpec::new(first.config.clone(), first.options.clone(), beginner, self.project_root());
- let (deep, logs) = {
- let session = self.engine.session();
- (!session.clean_room(), failure_log::dir_in(&session.config_dir()))
- };
- return Ok(cli_agents::conversation(cli_agents::CliSpec { deep, logs: Some(logs), ..spec }));
+ return Ok(Box::new(cli_agents::SharedConversation::new(self.engine.clone(), first, beginner)?));
}
let mut chain = vec![self.build_model(&first)?];
for name in cfg.chain_from(&first.config.name).into_iter().skip(1) {
diff --git a/crates/ai/src/model.rs b/crates/ai/src/model.rs
index b24079b2..a13e76c9 100644
--- a/crates/ai/src/model.rs
+++ b/crates/ai/src/model.rs
@@ -87,6 +87,8 @@ pub struct ToolDef {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Effort {
+ None,
+ Minimal,
Low,
#[default]
Medium,
@@ -98,12 +100,16 @@ pub enum Effort {
}
impl Effort {
- /// Every level, least to most.
+ /// The API/Claude levels, least to most.
pub const ALL: [Effort; 5] = [Effort::Low, Effort::Medium, Effort::High, Effort::Xhigh, Effort::Max];
+ pub const CLI_ALL: [Effort; 7] = [Effort::None, Effort::Minimal, 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::None => "none",
+ Effort::Minimal => "minimal",
Effort::Low => "low",
Effort::Medium => "medium",
Effort::High => "high",
@@ -115,12 +121,14 @@ 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))
+ Effort::CLI_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::None => "None",
+ Self::Minimal => "Minimal",
Self::Low => "Low",
Self::Medium => "Medium",
Self::High => "High",
diff --git a/crates/ai/src/model_options.rs b/crates/ai/src/model_options.rs
new file mode 100644
index 00000000..ff44d4cc
--- /dev/null
+++ b/crates/ai/src/model_options.rs
@@ -0,0 +1,203 @@
+//! Model-specific CLI tuning. Reasoning choices come from the selected model's ACP metadata;
+//! context uses the CLI's named tiers when it does not advertise numeric window limits.
+
+use crate::config::{CliContext, CliReasoningEffort};
+use crate::{AiConfig, BackendConfig, BackendKind};
+use craft_anything_engine::tool::{Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of};
+use craft_anything_evidence::ToolError;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// A cheap capability query for the settings UI; model discovery itself runs on a worker.
+pub fn supported(config: &BackendConfig) -> bool {
+ config.kind == BackendKind::AgentCli && crate::cli_agents::adapter_for(&config.model).supports_model_tuning()
+}
+
+/// Persistable choices, with the selected backend model captured to reject a stale picker.
+#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct SetModelOptions {
+ pub backend: String,
+ /// The backend's cli_model when these choices were loaded; null means the CLI default.
+ pub expected_cli_model: Option<String>,
+ /// Null inherits the CLI's context choice.
+ pub context: Option<CliContext>,
+}
+
+pub(crate) fn update(config: &mut AiConfig, params: &SetModelOptions) -> Result<(), ToolError> {
+ let entry = config.backends.iter_mut().find(|entry| entry.config.name == params.backend).ok_or_else(|| ToolError::invalid("No such AI backend."))?;
+ if !supported(&entry.config) {
+ return Err(ToolError::invalid("This backend does not offer CLI model options."));
+ }
+ if entry.options.cli_model != params.expected_cli_model {
+ return Err(ToolError::invalid("The model changed while its options were being edited.").with_remediation("Reload the model options and choose again."));
+ }
+ entry.options.cli_context = params.context;
+ Ok(())
+}
+
+#[derive(Deserialize, schemars::JsonSchema)]
+#[serde(deny_unknown_fields)]
+struct ShowModelOptions {
+ backend: String,
+}
+
+pub fn specs() -> Vec<ToolSpec> {
+ vec![
+ ToolSpec {
+ id: "ai_model_options_show",
+ title: "Show model options",
+ summary: "Discover the selected Copilot model's context tiers without sending a model prompt. Returns cli_model for the expected_cli_model guard when saving. Use ai_models_list for model and thinking choices.",
+ beginner: "See this model's context choices.",
+ toolset: Toolset::Setup,
+ effects: Effects::READ_ONLY.union(Effects::LAUNCHES_PROCESS),
+ requires: Requires::Nothing,
+ input_schema: schema_of::<ShowModelOptions>,
+ run: show,
+ },
+ ToolSpec {
+ id: "ai_model_options_set",
+ title: "Set model options",
+ summary: "Save a Copilot backend's context tier. Null inherits the CLI default. Refuses a stale expected_cli_model and leaves thinking unchanged; use ai_model_set for model and thinking choices.",
+ beginner: "Choose context for this model.",
+ toolset: Toolset::Setup,
+ effects: Effects::MUTATES_SESSION.union(Effects::WRITES_FILESYSTEM),
+ requires: Requires::Nothing,
+ input_schema: schema_of::<SetModelOptions>,
+ run: set,
+ },
+ ]
+}
+
+fn show(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {
+ let params: ShowModelOptions = parse_params(params)?;
+ let config = AiConfig::from_table(&ctx.session.settings.ai)?;
+ let entry = config.get(&params.backend).ok_or_else(|| ToolError::invalid("No such AI backend."))?;
+ if !supported(&entry.config) {
+ return Err(ToolError::invalid("This backend does not offer CLI model options."));
+ }
+ let stop = crate::model::Stop::for_tool(ctx.cancel.clone());
+ let tuning = crate::cli_agents::acp_model_tuning(&entry.config, &entry.options, &stop)?;
+ Ok(ToolOutput::Value(
+ serde_json::json!({"backend": params.backend, "cli_model": entry.options.cli_model, "choices": tuning, "context": entry.options.cli_context, "reasoning": entry.options.cli_reasoning_effort}),
+ ))
+}
+
+fn set(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {
+ let params: SetModelOptions = parse_params(params)?;
+ let mut config = AiConfig::from_table(&ctx.session.settings.ai)?;
+ update(&mut config, &params)?;
+ let mut settings = ctx.session.settings.clone();
+ settings.ai = config.to_table()?;
+ settings.save_to(&ctx.session.config_dir().join("config.toml"))?;
+ ctx.session.settings = settings;
+ Ok(ToolOutput::Value(serde_json::json!({"backend": params.backend, "context": params.context})))
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
+pub struct ModelOption<T> {
+ pub value: T,
+ pub label: String,
+ pub description: Option<String>,
+}
+
+/// Choices for one selected model. A default is separate from an explicit `none` effort.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
+pub struct ModelTuning {
+ pub model: String,
+ pub context: Vec<ModelOption<CliContext>>,
+ pub reasoning: Vec<ModelOption<CliReasoningEffort>>,
+}
+
+impl ModelTuning {
+ pub(crate) fn from_metadata(model: String, options: &[Value]) -> Self {
+ fn choices<T: serde::de::DeserializeOwned>(options: &[Value], ids: &[&str]) -> Vec<ModelOption<T>> {
+ options
+ .iter()
+ .find(|option| option.get("id").and_then(Value::as_str).is_some_and(|id| ids.contains(&id)))
+ .and_then(|option| option.get("options"))
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|option| {
+ let value = serde_json::from_value(option.get("value")?.clone()).ok()?;
+ let label = option.get("name").and_then(Value::as_str)?.to_string();
+ Some(ModelOption { value, label, description: option.get("description").and_then(Value::as_str).map(str::to_string) })
+ })
+ .collect()
+ }
+ let mut context = choices(options, &["context", "context_window", "context_tier"]);
+ if context.is_empty() {
+ context = vec![
+ ModelOption { value: CliContext::Standard, label: "Standard".into(), description: None },
+ ModelOption { value: CliContext::Long, label: "Extended".into(), description: None },
+ ];
+ }
+ Self { model, context, reasoning: choices(options, &["reasoning_effort"]) }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn cancelled_context_discovery_stops_before_starting_a_cli() {
+ let cancel = craft_anything_engine::CancelToken::default();
+ cancel.cancel();
+ let stop = crate::model::Stop::for_tool(cancel);
+ let config =
+ BackendConfig { name: "Test Copilot".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: None, enabled: true };
+ let options = crate::BackendOptions { command: Some("craft-anything-no-such-test-agent".into()), ..Default::default() };
+ assert_eq!(crate::cli_agents::acp_model_tuning(&config, &options, &stop).unwrap_err().code, craft_anything_evidence::ErrorCode::Cancelled);
+ }
+
+ #[test]
+ fn model_choices_preserve_advertised_windows_and_exclude_unsupported_efforts() {
+ let options = vec![
+ json!({"id":"context_window", "options":[{"value":"default", "name":"272k"},{"value":"long_context", "name":"1M"}]}),
+ json!({"id":"reasoning_effort", "options":[{"value":"none", "name":"None"},{"value":"high", "name":"High"},{"value":"unsupported", "name":"Unknown"}]}),
+ ];
+ let tuning = ModelTuning::from_metadata("test-model".into(), &options);
+ assert_eq!(tuning.context[0].label, "272k");
+ assert_eq!(tuning.context[1].value, CliContext::Long);
+ assert_eq!(tuning.reasoning.iter().map(|option| option.value).collect::<Vec<_>>(), [CliReasoningEffort::None, CliReasoningEffort::High]);
+ let fallback = ModelTuning::from_metadata("other-model".into(), &[]);
+ assert_eq!(fallback.context[0].label, "Standard");
+ assert!(fallback.reasoning.is_empty());
+ }
+
+ #[test]
+ fn context_tools_preserve_shared_thinking_and_refuse_stale_model_edits() {
+ use crate::{BackendEntry, BackendOptions};
+ use craft_anything_engine::{CallOptions, Caller, Engine, Session};
+ let directory = tempfile::tempdir().unwrap();
+ let mut session = Session::isolated(directory.path());
+ let mut config = AiConfig::default();
+ config.upsert(BackendEntry {
+ config: BackendConfig {
+ name: "Copilot".into(),
+ kind: BackendKind::AgentCli,
+ model: "copilot".into(),
+ base_url: None,
+ ssh_host: None,
+ enabled: true,
+ },
+ options: BackendOptions { cli_model: Some("test-model".into()), cli_thinking: Some(crate::Effort::None), ..Default::default() },
+ });
+ session.settings.ai = config.to_table().unwrap();
+ let engine = Engine::shared(session, specs());
+ let params = json!({"backend":"Copilot", "expected_cli_model":"test-model", "context":"long_context"});
+ engine.call("ai_model_options_set", params, CallOptions::new(Caller::Agent)).unwrap();
+ let saved = AiConfig::from_settings(&engine.session().settings);
+ assert_eq!(saved.get("Copilot").unwrap().options.cli_thinking, Some(crate::Effort::None));
+ assert_eq!(saved.get("Copilot").unwrap().options.cli_context, Some(CliContext::Long));
+ let mut stale = SetModelOptions { backend: "Copilot".into(), expected_cli_model: Some("old-model".into()), context: None };
+ let mut saved = saved;
+ assert!(update(&mut saved, &stale).is_err());
+ stale.expected_cli_model = Some("test-model".into());
+ update(&mut saved, &stale).unwrap();
+ assert_eq!(saved.get("Copilot").unwrap().options.cli_thinking, Some(crate::Effort::None));
+ }
+}
diff --git a/crates/ai/src/model_tools.rs b/crates/ai/src/model_tools.rs
index 6b4aaaee..e5ebbb96 100644
--- a/crates/ai/src/model_tools.rs
+++ b/crates/ai/src/model_tools.rs
@@ -14,8 +14,8 @@ pub fn specs() -> Vec<ToolSpec> {
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.",
+ summary: "List the visible chat models and supported thinking depths of a configured catalogue-capable coding agent. Uses the selected installation's configuration and credentials; only OpenCode supports SSH discovery. Returns a total and a page (offset, limit: default 200, maximum 1000). Discovery may start a process and update the CLI cache.",
+ beginner: "Shows which models this agent can use.",
toolset: Toolset::Setup,
effects,
requires: Requires::Nothing,
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<ToolSpec> {
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.",
+ summary: "Save a configured coding agent's model and optional thinking depth, validated against that instance's current model catalogue. Omit model and thinking to use the agent'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,
@@ -60,7 +60,7 @@ 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."));
+ return Err(ToolError::invalid("Choose an agent backend with a live model catalogue."));
}
Ok(ModelContext { backend, directory: ctx.session.project.as_ref().map(|p| p.root.clone()) })
}
diff --git a/crates/ai/src/prompt.rs b/crates/ai/src/prompt.rs
index 161bfc72..1261736f 100644
--- a/crates/ai/src/prompt.rs
+++ b/crates/ai/src/prompt.rs
@@ -19,7 +19,7 @@ How to work:
Working memory (the investigation files):
1. The current brief, plan, hypotheses, findings and handoff are below. Read them before acting; if a handoff exists, resume from it instead of starting over.
2. On a new question, call core_brief_write and core_plan_update before any analysis tool.
-3. After each batch of tool calls, keep the memory current: core_plan_update step statuses, core_hypothesis_record / core_hypothesis_update as claims are tested, core_finding_record once something is settled (findings must cite evidence ids).
+3. After each batch of tool calls, keep the memory current: core_plan_update step statuses, core_hypothesis_record / core_hypothesis_update as claims are tested, core_finding_record once something is settled (findings must cite evidence ids). Correct an existing finding with core_finding_edit, keeping its id and citing the evidence for the correction; pass based_on_revision from core_investigation_show.
4. Before you finish your reply, call core_handoff_write: where things stand, what's next, and traps to avoid.
5. Reports come from findings and evidence, never from chat alone.";
@@ -44,7 +44,7 @@ pub fn system_prompt(beginner: bool, clean_room: bool, investigation: &str) -> S
/// loop, and point it at our MCP tools.
pub fn cli_preamble(beginner: bool) -> String {
format!(
- "{METHOD}\n\n{}\n\nUse the craft-anything MCP tools for all analysis (start with core_investigation_show).\n\n## Request\n",
+ "{METHOD}\n\n{}\n\nUse the craft-anything MCP tools for all analysis (start with core_session_show, core_targets_list and core_investigation_show). The MCP server shares this investigation with the app; use its open targets and recorded findings rather than inventing ids or maintaining a separate findings file.\n\n## Request\n",
if beginner { BEGINNER } else { EXPERIENCED }
)
}
diff --git a/crates/ai/src/rebuild/mod.rs b/crates/ai/src/rebuild/mod.rs
index 955e884d..132be733 100644
--- a/crates/ai/src/rebuild/mod.rs
+++ b/crates/ai/src/rebuild/mod.rs
@@ -565,13 +565,14 @@ impl Worker {
/// How the builder's agent runs. Reads the session once: a lock taken twice in one statement
/// is held by the first until the statement ends, and the second then waits forever.
fn agent_spec(&self, ws: &Workspace, entry: &crate::BackendEntry, opts: &RunOptions) -> CliSpec {
- let (deep, config_dir) = {
+ let (deep, config_dir, targets) = {
let session = self.engine.session();
- (!session.clean_room(), session.config_dir())
+ (!session.clean_room(), session.config_dir(), session.shared_targets())
};
CliSpec {
builder: Some(Builder { investigation: Some(ws.investigation_dir()), inbox: ws.inbox_dir() }),
deep,
+ targets,
logs: Some(crate::failure_log::dir_in(&config_dir)),
resume: ws.manifest.agent_session.clone(),
preamble: Some(
@@ -1046,6 +1047,15 @@ impl Worker {
agent.stop();
}
for e in agent.poll() {
+ if matches!(e, AgentEvent::ToolFinished { .. } | AgentEvent::TurnDone { .. }) {
+ let mut session = self.engine.session();
+ let project = session.project.clone().filter(|project| project.root == ws.investigation_dir());
+ if let Some(project) = project
+ && let Err(error) = session.open_project(project)
+ {
+ log::warn!("Couldn't refresh the investigation: {}", error.message);
+ }
+ }
match &e {
AgentEvent::TextDelta { text } => reply.push_str(text),
// Our own loop asks before tools that need consent. The Build tools are the
diff --git a/crates/ai/src/rebuild/question.rs b/crates/ai/src/rebuild/question.rs
index 5ed8a182..a89e50af 100644
--- a/crates/ai/src/rebuild/question.rs
+++ b/crates/ai/src/rebuild/question.rs
@@ -4,6 +4,8 @@
//! - a coding agent that keeps a session (Claude Code) answers from a copy of the builder's own
//! session (`--fork-session`), which isn't kept, with only Read, Glob and Grep (none in Clean
//! room) and no tool server, so the builder's session and files stay as they are;
+//! - Copilot starts a fresh ACP session with no tool server: only view, glob and grep in Deep
+//! mode, no tools in Clean room. It answers from the project context, not the builder's chat;
//! - an AI with an API key answers with our agent loop on a [`ReadOnlyHost`]: the engine's tools
//! that change nothing, pointed at this project in an engine of its own;
//! - any other agent is refused, since it can't be held to reading.
@@ -13,7 +15,7 @@
use super::*;
use crate::agent::{EngineHost, LoopConfig, ReadOnlyHost};
-use crate::cli_agents::{CliConversation, CliSpec};
+use crate::cli_agents::CliSpec;
use craft_anything_engine::Toolset;
use serde::Serialize;
use std::time::{Duration, Instant, SystemTime};
@@ -80,7 +82,7 @@ pub fn ask(
preamble: Some(PREAMBLE.into()),
..CliSpec::new(entry.config.clone(), entry.options.clone(), false, Some(ws.root.clone()))
};
- Box::new(CliConversation::new(spec))
+ crate::cli_agents::conversation(spec)
};
let (mut conv, mut from): (Box<dyn Conversation>, AnsweredFrom) = match entry.config.kind {
BackendKind::AgentCli => {
@@ -88,8 +90,19 @@ pub fn ask(
if let Some(id) = session.as_deref() {
bring_back_session(ws, &entry, id);
}
- let from = if session.is_some() { AnsweredFrom::BuildersSession } else { AnsweredFrom::TheFiles };
- (cli(session), from)
+ // Only a native adapter that resumes can answer from a copy of the builder's chat.
+ // Copilot's ACP question starts fresh, even when the project has a saved session id.
+ let native_session = crate::cli_agents::adapter_for(&entry.config.model).resumes();
+ let from = if session.is_some() && native_session { AnsweredFrom::BuildersSession } else { AnsweredFrom::TheFiles };
+ let spec = CliSpec {
+ question: true,
+ deep,
+ logs: logs.clone(),
+ resume: session,
+ preamble: Some(PREAMBLE.into()),
+ ..CliSpec::new(entry.config.clone(), entry.options.clone(), false, Some(ws.root.clone()))
+ };
+ (crate::cli_agents::conversation(spec), from)
}
_ => {
// An engine of its own, pointed at this project, so a build running meanwhile keeps its.
diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs
index 573e0876..0a6d6bb1 100644
--- a/crates/ai/src/tests.rs
+++ b/crates/ai/src/tests.rs
@@ -184,6 +184,7 @@ fn opencode_selection_is_validated_saved_and_refused_without_native_mcp() {
std::thread::sleep(Duration::from_millis(10));
}
events.extend(conversation.poll());
+ events.retain(|event| !matches!(event, AgentEvent::Status { .. }));
assert!(
matches!(events.as_slice(), [AgentEvent::Error { message, .. }, AgentEvent::TurnDone { .. }]
if message.contains("cannot yet connect")),
@@ -262,6 +263,8 @@ input_per_mtok = 1.0
assert!(h.set_role(Role::Builder, None).is_err());
assert!(h.set_enabled("Claude Code", false).is_err());
assert!(h.remove_backend("Claude Code").is_err());
+ let options = crate::model_options::SetModelOptions { backend: "Claude Code".into(), expected_cli_model: None, context: None };
+ assert_eq!(h.set_model_options(&options).unwrap_err().code, ErrorCode::BadSettings);
assert_eq!(std::fs::read(&file).unwrap(), before, "the settings file was changed");
assert!(h.keys.get("Other").is_none(), "a refused add stored its key");
}
@@ -345,6 +348,173 @@ fn a_claude_ais_effort_is_changed() {
assert!(!h.set_effort("Nobody", Some(Effort::Low)).unwrap());
}
+#[test]
+fn copilot_uses_shared_selection_and_rejects_failed_discovery_without_saving() {
+ let (hub, _directory) = hub();
+ let config =
+ BackendConfig { name: "GitHub Copilot".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: None, enabled: true };
+ assert!(!config.kind.needs_key());
+ assert_eq!(model_in_use(&config, None).as_deref(), Some("GitHub Copilot default"));
+ hub.add_backend_with(
+ BackendEntry {
+ config,
+ options: BackendOptions {
+ cli_model: Some("chosen-copilot-model".into()),
+ command: Some("craft-anything-no-such-test-agent".into()),
+ ..Default::default()
+ },
+ },
+ None,
+ )
+ .unwrap();
+ assert!(hub.set_model("GitHub Copilot", "unavailable-model").is_err());
+ let backend = hub.backends().into_iter().find(|backend| backend.name == "GitHub Copilot").unwrap();
+ let options = hub.options();
+ assert_eq!(backend.model, "copilot");
+ assert_eq!(model_in_use(&backend, options.get(&backend.name)).as_deref(), Some("chosen-copilot-model"));
+}
+
+#[test]
+fn copilot_context_is_saved_without_changing_shared_thinking() {
+ use crate::config::CliContext;
+ let (hub, _directory) = hub();
+ let config = BackendConfig { name: "Copilot".into(), kind: BackendKind::AgentCli, model: "copilot".into(), base_url: None, ssh_host: None, enabled: true };
+ hub.add_backend_with(
+ BackendEntry {
+ config: config.clone(),
+ options: BackendOptions { cli_model: Some("test-model".into()), cli_thinking: Some(Effort::Max), ..Default::default() },
+ },
+ None,
+ )
+ .unwrap();
+ let params =
+ crate::model_options::SetModelOptions { backend: "Copilot".into(), expected_cli_model: Some("test-model".into()), context: Some(CliContext::Long) };
+ hub.set_model_options(&params).unwrap();
+ assert_eq!(hub.options()["Copilot"].cli_context, Some(CliContext::Long));
+ assert_eq!(hub.options()["Copilot"].cli_thinking, Some(Effort::Max));
+ hub.add_backend_with(BackendEntry { config, options: BackendOptions { cli_model: Some("another-model".into()), ..Default::default() } }, None).unwrap();
+ assert_eq!(hub.options()["Copilot"].cli_context, None);
+ assert_eq!(hub.options()["Copilot"].cli_reasoning_effort, None);
+ assert!(hub.set_model_options(&params).is_err());
+}
+
+/// Exercise the installed CLI, not just our argument builder: the loopback model must see
+/// exactly the allowed tools in every access mode, including genuinely tool-free questions.
+/// Kept opt-in because it needs external programs, never because it needs a real account.
+#[test]
+#[ignore = "requires Copilot CLI and Node.js; uses an isolated CLI home and a loopback model, never a real account"]
+fn copilot_cli_enforces_mcp_only_and_empty_tool_filters() {
+ use crate::cli_agents::{Access, AcpConversation, AgentAdapter, ArgsCx, McpCommand};
+ use craft_anything_platform::Process;
+
+ /// Only the child's environment changes: no saved CLI credentials, inherited provider key
+ /// or token helper may reach the fixture. The production adapter still supplies its policy.
+ struct OfflineCopilot {
+ url: String,
+ home: PathBuf,
+ }
+
+ impl AgentAdapter for OfflineCopilot {
+ fn ids(&self) -> &'static [&'static str] {
+ &["copilot"]
+ }
+
+ fn args(&self, _context: &ArgsCx) -> Vec<String> {
+ Vec::new()
+ }
+
+ fn process(&self, program: &str) -> Process {
+ crate::cli_agents::adapters::Copilot
+ .process(program)
+ .env("HOME", &self.home)
+ .env("COPILOT_HOME", &self.home)
+ .env("COPILOT_OFFLINE", "true")
+ .env("COPILOT_PROVIDER_BASE_URL", &self.url)
+ .env("COPILOT_PROVIDER_TYPE", "openai")
+ .env("COPILOT_MODEL", "craft-test")
+ .env_remove("COPILOT_PROVIDER_API_KEY")
+ .env_remove("COPILOT_PROVIDER_API_KEY_COMMAND")
+ .env_remove("COPILOT_PROVIDERS_CONFIG")
+ .env_remove("COPILOT_GITHUB_TOKEN")
+ .env_remove("GH_TOKEN")
+ .env_remove("GITHUB_TOKEN")
+ }
+ }
+
+ for (access, mut expected) in [
+ (Access::Analyse, vec!["craft-anything-core_target_triage"]),
+ (Access::Build, vec!["craft-anything-core_target_triage"]),
+ (Access::CleanRoomBuild, vec!["craft-anything-core_target_triage"]),
+ (Access::Question, vec!["view", "grep", "glob"]),
+ (Access::CleanRoomQuestion, Vec::new()),
+ ] {
+ let directory = tempfile::tempdir().unwrap();
+ let script = directory.path().join("mcp.cjs");
+ // Offer one registered tool and one that must be filtered out. Record requests so a
+ // question that accidentally starts the server is caught even if it calls no tool.
+ std::fs::write(
+ &script,
+ r#"const readline = require('node:readline');
+const input = readline.createInterface({input: process.stdin});
+input.on('line', line => {
+ const request = JSON.parse(line);
+ require('node:fs').appendFileSync(__dirname + '/mcp-requests.log', request.method + '\n');
+ if (request.id === undefined) return;
+ let result = {};
+ if (request.method === 'initialize') {
+ result = {protocolVersion: '2024-11-05', capabilities: {tools: {}}, serverInfo: {name: 'craft-test', version: '1'}};
+ } else if (request.method === 'tools/list') {
+ result = {tools: ['core_target_triage', 'unexpected_fixture_tool'].map(name => ({name, description: name, inputSchema: {type: 'object', properties: {}}}))};
+ }
+ process.stdout.write(JSON.stringify({jsonrpc: '2.0', id: request.id, result}) + '\n');
+});
+"#,
+ )
+ .unwrap();
+ let body = chat_sse(&[
+ json!({"id":"test", "choices":[{"index":0,"delta":{"role":"assistant","content":"done"},"finish_reason":null}]}),
+ json!({"id":"test", "choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}),
+ ]);
+ let (url, seen) = mock(vec![(200, "text/event-stream", body)]);
+ let program = std::env::var("CRAFT_TEST_COPILOT").unwrap_or_else(|_| "copilot".into());
+ let mut args = crate::cli_agents::adapters::Copilot.acp_options(&BackendOptions::default(), access);
+ args.extend(["--acp".into(), "--stdio".into()]);
+ let mcp = McpCommand { command: "node".into(), args: vec![script.display().to_string()], notes: None };
+ let question = matches!(access, Access::Question | Access::CleanRoomQuestion);
+ if !question {
+ args.extend(crate::cli_agents::adapters::Copilot.acp_mcp_options(&mcp));
+ }
+ let mut conversation = AcpConversation::new("Copilot test", "copilot", program, args, directory.path().into(), mcp, None)
+ .with_adapter(Arc::new(OfflineCopilot { url, home: directory.path().into() }))
+ .with_question(question);
+ conversation.send("Reply with done. Do not call any tools.");
+ let started = Instant::now();
+ let mut output = Vec::new();
+ while started.elapsed() < Duration::from_secs(30) && !output.iter().any(|event| matches!(event, AgentEvent::TurnDone { .. })) {
+ output.extend(conversation.poll());
+ std::thread::park_timeout(Duration::from_millis(10));
+ }
+ assert!(output.iter().any(|event| matches!(event, AgentEvent::TurnDone { .. })), "{output:?}");
+ assert!(!output.iter().any(|event| matches!(event, AgentEvent::Error { .. })), "{output:?}");
+ let requests = seen.lock().unwrap();
+ assert_eq!(requests.len(), 1, "{requests:?}");
+ // Assert what reached the model, not what the CLI accepted on its command line:
+ // startup can succeed while a tool is missing or an empty filter restores native tools.
+ let mut tools: Vec<&str> = requests[0]
+ .body
+ .get("tools")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|tool| tool.pointer("/function/name").and_then(Value::as_str))
+ .collect();
+ tools.sort();
+ expected.sort();
+ assert_eq!(tools, expected, "{access:?}");
+ assert_eq!(directory.path().join("mcp-requests.log").exists(), !question);
+ }
+}
+
/// #54, #98: a server on another computer is added by its address, with a model that can chat
/// when none is named; one that doesn't answer with its models isn't added.
#[test]
diff --git a/crates/engine/src/clean_room.rs b/crates/engine/src/clean_room.rs
index 85266231..23f04f68 100644
--- a/crates/engine/src/clean_room.rs
+++ b/crates/engine/src/clean_room.rs
@@ -33,6 +33,7 @@ pub const TOOLS: &[&str] = &[
"core_hypothesis_record",
"core_hypothesis_update",
"core_finding_record",
+ "core_finding_edit",
"core_handoff_write",
"core_journal_read",
"core_report_save",
@@ -43,6 +44,8 @@ pub const TOOLS: &[&str] = &[
"assets_key_set",
"assets_key_remove",
"assets_key_status",
+ "ai_model_options_show",
+ "ai_model_options_set",
// Projects and the rebuild run.
"project_list",
"project_show",
diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs
index 493605e1..9ba383b4 100644
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@ -128,6 +128,53 @@ impl Session {
// ---- targets ----
+ /// Metadata for a local MCP child, with the active target last so restoring the list also
+ /// restores selection. No file bytes or analysis caches cross the process boundary.
+ pub fn shared_targets(&self) -> Vec<crate::target::TargetContext> {
+ let active = self.active().ok().map(|target| &target.target.path);
+ let mut targets: Vec<_> = self.targets().map(|target| crate::target::TargetContext::from_target(&target.target)).collect();
+ targets.sort_by_key(|target| active == Some(&target.path));
+ targets
+ }
+
+ /// Restore a bounded target handoff before serving MCP. Validate every target before
+ /// changing the session; the last entry is the desktop's active target.
+ pub fn restore_targets(&mut self, targets: &[crate::target::TargetContext]) -> Result<(), ToolError> {
+ if targets.len() > 128 {
+ return Err(ToolError::invalid("At most 128 targets can be shared with an agent."));
+ }
+ let opened: Result<Vec<_>, _> = targets.iter().map(|target| target.open(self.clean_room())).collect();
+ for target in opened? {
+ self.add_target(target);
+ }
+ Ok(())
+ }
+
+ /// Give an external agent a durable store shared with this session. Existing projects stay
+ /// open; unsaved evidence, unknowns and investigation memory are copied before attaching a
+ /// new project. Call on a worker: creating and refreshing projects does disk I/O.
+ pub fn ensure_shared_project(&mut self) -> Result<std::path::PathBuf, ToolError> {
+ if let Some(project) = &self.project {
+ return Ok(project.root.clone());
+ }
+ let investigation = crate::tools::investigation_tools::load(self);
+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| ToolError::internal(error.to_string()))?;
+ let root = self.config_dir().join("investigations").join(format!("session-{}.cany", stamp.as_nanos()));
+ let project = Project::create(&root, "Investigation", crate::project::Purpose::default())?;
+ for evidence in self.ledger() {
+ project.store_evidence(evidence)?;
+ }
+ for unknown in self.unknowns() {
+ project.store_unknown(unknown)?;
+ }
+ self.project = Some(project);
+ if let Err(error) = crate::tools::investigation_tools::save_new_project(self, investigation) {
+ self.project = None;
+ return Err(error);
+ }
+ Ok(root)
+ }
+
pub fn add_target(&mut self, target: Target) -> TargetId {
let id = target.id.clone();
let annotations = self.project.as_ref().and_then(|p| p.load_annotations(&target.sha256).ok()).unwrap_or_default();
@@ -298,6 +345,8 @@ impl Session {
self.ledger.insert(ev.id.clone(), ev);
}
self.project = Some(project);
+ let investigation = crate::tools::investigation_tools::load(self);
+ crate::tools::investigation_tools::cache(self, investigation);
Ok(())
}
}
diff --git a/crates/engine/src/target.rs b/crates/engine/src/target.rs
index 40c0ba18..137ed7c8 100644
--- a/crates/engine/src/target.rs
+++ b/crates/engine/src/target.rs
@@ -10,6 +10,52 @@ pub const MAX_TARGET_BYTES: u64 = 2 * 1024 * 1024 * 1024;
pub type TargetId = String;
+/// Metadata handed to an agent's MCP session. No file contents or caches cross the command
+/// line; Deep mode reloads and verifies the file, while Clean room keeps only this metadata.
+#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct TargetContext {
+ pub path: PathBuf,
+ pub sha256: String,
+ pub kind: TargetKind,
+ pub raw: Option<RawSpec>,
+}
+
+impl TargetContext {
+ pub fn from_target(target: &Target) -> Self {
+ Self { path: target.path.clone(), sha256: target.sha256.clone(), kind: target.kind, raw: target.raw.clone() }
+ }
+
+ pub fn open(&self, clean_room: bool) -> Result<Target, ToolError> {
+ if !self.path.is_absolute() || self.sha256.len() != 64 || !self.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) {
+ return Err(ToolError::invalid("A shared target needs an absolute path and a SHA-256 hash."));
+ }
+ let mut target = if clean_room {
+ Target {
+ id: format!("t_{}", self.sha256.get(..12).unwrap_or_default()),
+ path: self.path.clone(),
+ name: self.path.file_name().unwrap_or_default().to_string_lossy().into_owned(),
+ sha256: self.sha256.clone(),
+ kind: self.kind,
+ bytes: Arc::from([]),
+ raw: self.raw.clone(),
+ }
+ } else {
+ let target = Target::load(&self.path)?;
+ if target.sha256 != self.sha256 {
+ return Err(ToolError::invalid("The shared target changed after it was opened.")
+ .with_remediation("Reopen the target in Craft Anything, then start a new conversation."));
+ }
+ target
+ };
+ if self.raw.is_some() || self.kind == TargetKind::DosCom {
+ target.kind = self.kind;
+ target.raw = self.raw.clone();
+ }
+ Ok(target)
+ }
+}
+
/// What kind of thing a target is. Detected from content, never from the extension alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
diff --git a/crates/engine/src/tools/investigation_tools.rs b/crates/engine/src/tools/investigation_tools.rs
index 3202473c..837cae39 100644
--- a/crates/engine/src/tools/investigation_tools.rs
+++ b/crates/engine/src/tools/investigation_tools.rs
@@ -17,6 +17,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::{Arc, PoisonError};
+use std::time::{Duration, Instant};
pub fn specs() -> Vec<ToolSpec> {
let w = Effects::MUTATES_SESSION.union(Effects::WRITES_FILESYSTEM);
@@ -87,6 +88,17 @@ pub fn specs() -> Vec<ToolSpec> {
input_schema: schema_of::<FindingParams>,
run: core_finding_record,
},
+ ToolSpec {
+ id: "core_finding_edit",
+ title: "Update a finding",
+ summary: "Correct a recorded finding without changing its id. Requires a statement and existing evidence ids; pass based_on_revision to refuse a stale investigation update.",
+ beginner: "Correct something we found, keeping its proof and reference.",
+ toolset: Toolset::Core,
+ effects: w,
+ requires: Requires::Nothing,
+ input_schema: schema_of::<EditFindingParams>,
+ run: core_finding_edit,
+ },
ToolSpec {
id: "core_handoff_write",
title: "Write the handoff",
@@ -198,6 +210,19 @@ pub struct Investigation {
type Slot = Mutex<Investigation>;
+/// The last loaded state, for clients that cannot read the project while drawing. Writers and
+/// project refreshes update this snapshot; an external writer is picked up by open_project.
+pub fn cached(session: &Session) -> Investigation {
+ session.ext.get::<Slot>().map(|slot| slot.lock().unwrap_or_else(PoisonError::into_inner).clone()).unwrap_or_default()
+}
+
+pub(crate) fn cache(session: &mut Session, investigation: Investigation) {
+ match session.ext.get::<Slot>() {
+ Some(slot) => *slot.lock().unwrap_or_else(PoisonError::into_inner) = investigation,
+ None => session.ext.insert(Arc::new(Mutex::new(investigation))),
+ }
+}
+
fn dir(session: &Session) -> Option<PathBuf> {
session.project.as_ref().map(|p| p.root.join("investigation"))
}
@@ -210,7 +235,74 @@ pub fn load(session: &Session) -> Investigation {
session.ext.get::<Slot>().map(|s| s.lock().unwrap_or_else(PoisonError::into_inner).clone()).unwrap_or_default()
}
-fn save(session: &mut Session, mut inv: Investigation) -> Result<Investigation, ToolError> {
+struct UpdateLock {
+ directory: Option<PathBuf>,
+ _file: Option<std::fs::File>,
+}
+
+impl UpdateLock {
+ fn acquire(session: &Session, cancel: &crate::CancelToken, timeout: Duration) -> Result<Self, ToolError> {
+ cancel.check()?;
+ let directory = dir(session);
+ let Some(path) = directory.as_ref() else { return Ok(Self { directory, _file: None }) };
+ std::fs::create_dir_all(path).map_err(|error| ToolError::io(path.display(), error))?;
+ let lock_path = path.join("update.lock");
+ let file = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(&lock_path)
+ .map_err(|error| ToolError::io(lock_path.display(), error))?;
+ let started = Instant::now();
+ loop {
+ cancel.check()?;
+ match file.try_lock() {
+ Ok(()) => return Ok(Self { directory, _file: Some(file) }),
+ Err(std::fs::TryLockError::WouldBlock) if started.elapsed() < timeout => std::thread::park_timeout(Duration::from_millis(5)),
+ Err(std::fs::TryLockError::WouldBlock) => {
+ return Err(ToolError::new(ErrorCode::TimedOut, "Another process is updating this investigation.")
+ .with_remediation("Wait for the other update, reload the investigation and retry with its current revision."));
+ }
+ Err(std::fs::TryLockError::Error(error)) => return Err(ToolError::io(lock_path.display(), error)),
+ }
+ }
+ }
+}
+
+fn lock_update(session: &Session, cancel: &crate::CancelToken) -> Result<UpdateLock, ToolError> {
+ UpdateLock::acquire(session, cancel, Duration::from_secs(10))
+}
+
+fn load_for_update(session: &Session, guard: &UpdateLock) -> Result<Investigation, ToolError> {
+ let Some(directory) = &guard.directory else { return Ok(load(session)) };
+ let path = directory.join("state.json");
+ match std::fs::read(&path) {
+ Ok(bytes) => serde_json::from_slice(&bytes).map_err(|_| {
+ ToolError::new(ErrorCode::GarbledOutput, "The investigation state could not be read; it was not changed.")
+ .with_remediation("Restore a valid investigation/state.json backup before editing this investigation.")
+ }),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Investigation::default()),
+ Err(error) => Err(ToolError::io(path.display(), error)),
+ }
+}
+
+pub(crate) fn save_new_project(session: &mut Session, inv: Investigation) -> Result<Investigation, ToolError> {
+ let guard = lock_update(session, &crate::CancelToken::default())?;
+ if let Some(directory) = &guard.directory {
+ let path = directory.join("state.json");
+ if path.try_exists().map_err(|error| ToolError::io(path.display(), error))? {
+ return Err(ToolError::new(ErrorCode::StaleRevision, "This project already has an investigation.")
+ .with_remediation("Reload the existing investigation instead of replacing it."));
+ }
+ }
+ save(session, inv, &guard)
+}
+
+fn save(session: &mut Session, mut inv: Investigation, guard: &UpdateLock) -> Result<Investigation, ToolError> {
+ if guard.directory != dir(session) {
+ return Err(ToolError::internal("The investigation changed while its update lock was held."));
+ }
inv.revision = inv.revision.saturating_add(1);
let (_, date, time) = journal::now_utc();
inv.updated = Some(format!("{date}T{time}Z"));
@@ -220,12 +312,8 @@ fn save(session: &mut Session, mut inv: Investigation) -> Result<Investigation,
for (name, body) in render(&inv) {
write_atomic(&d.join(name), body.as_bytes())?;
}
- } else {
- match session.ext.get::<Slot>() {
- Some(slot) => *slot.lock().unwrap_or_else(PoisonError::into_inner) = inv.clone(),
- None => session.ext.insert(Arc::new(Mutex::new(inv.clone()))),
- }
}
+ cache(session, inv.clone());
Ok(inv)
}
@@ -366,9 +454,10 @@ fn core_brief_write(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, ToolError
if p.question.trim().is_empty() {
return Err(ToolError::invalid("The brief needs a question."));
}
- let mut inv = load(ctx.session);
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut inv = load_for_update(ctx.session, &guard)?;
inv.brief = Some(Brief { question: p.question, purpose: p.purpose, targets: p.targets, constraints: p.constraints, done_when: p.done_when });
- let inv = save(ctx.session, inv)?;
+ let inv = save(ctx.session, inv, &guard)?;
Ok(out(&inv, ctx.session))
}
@@ -387,10 +476,11 @@ fn core_plan_update(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, ToolError
if p.steps.len() > 200 {
return Err(ToolError::invalid("A plan can have at most 200 steps."));
}
- let mut inv = load(ctx.session);
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut inv = load_for_update(ctx.session, &guard)?;
check_revision(&inv, p.based_on_revision)?;
inv.plan = p.steps;
- let inv = save(ctx.session, inv)?;
+ let inv = save(ctx.session, inv, &guard)?;
Ok(out(&inv, ctx.session))
}
@@ -415,7 +505,8 @@ fn core_hypothesis_record(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, Too
}
check_ids(ctx.session, &p.evidence_for)?;
check_ids(ctx.session, &p.evidence_against)?;
- let mut inv = load(ctx.session);
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut inv = load_for_update(ctx.session, &guard)?;
let id = format!("hyp_{}", inv.hypotheses.len() + 1);
inv.hypotheses.push(Hypothesis {
id: id.clone(),
@@ -426,7 +517,7 @@ fn core_hypothesis_record(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, Too
contradicting: p.evidence_against,
notes: Vec::new(),
});
- let inv = save(ctx.session, inv)?;
+ let inv = save(ctx.session, inv, &guard)?;
Ok(ToolOutput::Value(json!({"hypothesis_id": id, "revision": inv.revision})))
}
@@ -448,7 +539,8 @@ fn core_hypothesis_update(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, Too
let p: UpdateHypothesisParams = parse_params(p)?;
check_ids(ctx.session, &p.add_supporting_evidence_ids)?;
check_ids(ctx.session, &p.add_contradicting_evidence_ids)?;
- let mut inv = load(ctx.session);
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut inv = load_for_update(ctx.session, &guard)?;
let h = inv
.hypotheses
.iter_mut()
@@ -471,7 +563,7 @@ fn core_hypothesis_update(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, Too
h.notes.push(n);
}
let snapshot = h.clone();
- let inv = save(ctx.session, inv)?;
+ let inv = save(ctx.session, inv, &guard)?;
Ok(ToolOutput::Value(json!({"hypothesis": snapshot, "revision": inv.revision})))
}
@@ -509,7 +601,8 @@ fn core_finding_record(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, ToolEr
.with_remediation("Run the analysis that shows it, then cite the evidence id it returns."));
}
check_ids(ctx.session, &p.evidence_ids)?;
- let mut inv = load(ctx.session);
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut inv = load_for_update(ctx.session, &guard)?;
let id = format!("fnd_{}", inv.findings.len() + 1);
let confidence = match p.confidence {
ConfidenceParam::Observed => Confidence::Observed,
@@ -517,10 +610,54 @@ fn core_finding_record(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, ToolEr
ConfidenceParam::Inferred => Confidence::Inferred,
};
inv.findings.push(Finding { id: id.clone(), statement: p.statement, evidence_ids: p.evidence_ids, confidence });
- let inv = save(ctx.session, inv)?;
+ let inv = save(ctx.session, inv, &guard)?;
Ok(ToolOutput::Value(json!({"finding_id": id, "revision": inv.revision})))
}
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct EditFindingParams {
+ /// An existing finding id from core_investigation_show.
+ pub finding_id: String,
+ /// The corrected settled answer.
+ pub statement: String,
+ /// Evidence ids that establish the corrected answer (at least one).
+ pub evidence_ids: Vec<String>,
+ /// Omit to keep the finding's current confidence.
+ #[serde(default)]
+ pub confidence: Option<ConfidenceParam>,
+ /// The investigation revision read before editing; a stale revision is refused.
+ #[serde(default)]
+ pub based_on_revision: Option<u64>,
+}
+
+fn core_finding_edit(ctx: &mut Ctx<'_>, params: Value) -> Result<ToolOutput, ToolError> {
+ let params: EditFindingParams = parse_params(params)?;
+ if params.statement.trim().is_empty() || params.evidence_ids.is_empty() {
+ return Err(ToolError::invalid("A finding needs a statement and at least one evidence id."));
+ }
+ check_ids(ctx.session, &params.evidence_ids)?;
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut investigation = load_for_update(ctx.session, &guard)?;
+ check_revision(&investigation, params.based_on_revision)?;
+ let finding = investigation
+ .findings
+ .iter_mut()
+ .find(|finding| finding.id == params.finding_id)
+ .ok_or_else(|| ToolError::invalid(format!("Unknown finding {}", params.finding_id)))?;
+ finding.statement = params.statement;
+ finding.evidence_ids = params.evidence_ids;
+ if let Some(confidence) = params.confidence {
+ finding.confidence = match confidence {
+ ConfidenceParam::Observed => Confidence::Observed,
+ ConfidenceParam::Derived => Confidence::Derived,
+ ConfidenceParam::Inferred => Confidence::Inferred,
+ };
+ }
+ let investigation = save(ctx.session, investigation, &guard)?;
+ Ok(ToolOutput::Value(json!({"finding_id": params.finding_id, "revision": investigation.revision})))
+}
+
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct HandoffParams {
@@ -530,9 +667,10 @@ pub struct HandoffParams {
fn core_handoff_write(ctx: &mut Ctx<'_>, p: Value) -> Result<ToolOutput, ToolError> {
let p: HandoffParams = parse_params(p)?;
- let mut inv = load(ctx.session);
+ let guard = lock_update(ctx.session, &ctx.cancel)?;
+ let mut inv = load_for_update(ctx.session, &guard)?;
inv.handoff = Some(p.text);
- let inv = save(ctx.session, inv)?;
+ let inv = save(ctx.session, inv, &guard)?;
Ok(ToolOutput::Value(json!({"revision": inv.revision})))
}
@@ -590,6 +728,207 @@ mod tests {
e.call(id, p, CallOptions::new(Caller::Agent)).map(|o| o.to_json())
}
+ #[test]
+ fn finding_edits_refuse_unbacked_corrections_without_changing_memory() {
+ let engine = Engine::new(crate::testing::session());
+ assert!(engine.registry().get("core_finding_edit").is_some());
+ let before = call(&engine, "core_investigation_show", json!({})).unwrap();
+ for evidence_ids in [json!([]), json!(["ev_missing"])] {
+ assert!(call(&engine, "core_finding_edit", json!({"finding_id":"fnd_1", "statement":"corrected", "evidence_ids":evidence_ids})).is_err());
+ }
+ assert_eq!(call(&engine, "core_investigation_show", json!({})).unwrap(), before);
+ }
+
+ #[test]
+ fn investigation_locks_are_bounded_cancelled_and_released_on_drop() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut session = crate::Session::isolated(directory.path());
+ session.project = Some(Project::create(&directory.path().join("project.cany"), "Test", Purpose::Education).unwrap());
+ let cancel = crate::CancelToken::default();
+ let guard = super::UpdateLock::acquire(&session, &cancel, std::time::Duration::ZERO).unwrap();
+ assert_eq!(super::UpdateLock::acquire(&session, &cancel, std::time::Duration::ZERO).err().unwrap().code, craft_anything_evidence::ErrorCode::TimedOut);
+ cancel.cancel();
+ assert_eq!(
+ super::UpdateLock::acquire(&session, &cancel, std::time::Duration::from_secs(10)).err().unwrap().code,
+ craft_anything_evidence::ErrorCode::Cancelled
+ );
+ drop(guard);
+ assert!(super::UpdateLock::acquire(&session, &crate::CancelToken::default(), std::time::Duration::ZERO).is_ok());
+ }
+
+ #[test]
+ fn investigation_updates_never_replace_unreadable_state() {
+ let directory = tempfile::tempdir().unwrap();
+ let mut session = crate::Session::isolated(directory.path());
+ let project = Project::create(&directory.path().join("project.cany"), "Test", Purpose::Education).unwrap();
+ let path = project.root.join("investigation/state.json");
+ session.open_project(project).unwrap();
+ let engine = Engine::new(session);
+ call(&engine, "core_brief_write", json!({"question":"Keep this"})).unwrap();
+ let rendered = std::fs::read(path.with_file_name("brief.md")).unwrap();
+ std::fs::write(&path, b"not-json").unwrap();
+ assert_eq!(
+ call(&engine, "core_brief_write", json!({"question":"Do not replace"})).unwrap_err().code,
+ craft_anything_evidence::ErrorCode::GarbledOutput
+ );
+ assert_eq!(std::fs::read(&path).unwrap(), b"not-json");
+ assert_eq!(std::fs::read(path.with_file_name("brief.md")).unwrap(), rendered);
+ }
+
+ #[test]
+ fn project_writer_child() {
+ let Ok(root) = std::env::var("CRAFT_TEST_INV_PROJECT") else { return };
+ let label = std::env::var("CRAFT_TEST_INV_LABEL").unwrap();
+ let mode = std::env::var("CRAFT_TEST_INV_MODE").unwrap();
+ let root = std::path::PathBuf::from(root);
+ let mut session = crate::Session::isolated(&root.join(format!("test-config-{label}")));
+ session.open_project(Project::open(&root).unwrap()).unwrap();
+ let engine = Engine::new(session);
+ if mode == "append" {
+ for index in 0..24 {
+ call(&engine, "core_hypothesis_record", json!({"claim":format!("{label}-{index}")})).unwrap();
+ }
+ } else {
+ let result = call(&engine, "core_plan_update", json!({"steps":[{"title":label,"status":"todo"}],"based_on_revision":0}));
+ let outcome = match result {
+ Ok(_) => "ok",
+ Err(error) if error.code == craft_anything_evidence::ErrorCode::StaleRevision => "stale",
+ Err(error) => panic!("{error:?}"),
+ };
+ std::fs::write(root.join(format!("{label}.result")), outcome).unwrap();
+ }
+ }
+
+ #[test]
+ fn project_writers_serialize_across_processes() {
+ let directory = tempfile::tempdir().unwrap();
+ for mode in ["append", "revision"] {
+ let project = Project::create(&directory.path().join(format!("{mode}.cany")), "Test", Purpose::Education).unwrap();
+ let children: Vec<_> = ["first", "second"]
+ .into_iter()
+ .map(|label| {
+ let root = project.root.clone();
+ std::thread::spawn(move || {
+ craft_anything_platform::Process::new(std::env::current_exe().unwrap())
+ .args(["--exact", "tools::investigation_tools::tests::project_writer_child", "--test-threads=1"])
+ .env("CRAFT_TEST_INV_PROJECT", &root)
+ .env("CRAFT_TEST_INV_LABEL", label)
+ .env("CRAFT_TEST_INV_MODE", mode)
+ .timeout(std::time::Duration::from_secs(30))
+ .stdout_cap(64 * 1024)
+ .stderr_cap(64 * 1024)
+ .run_checked()
+ })
+ })
+ .collect();
+ for child in children {
+ child.join().unwrap().unwrap();
+ }
+ let state: super::Investigation = serde_json::from_slice(&std::fs::read(project.root.join("investigation/state.json")).unwrap()).unwrap();
+ if mode == "append" {
+ assert_eq!(state.revision, 48);
+ assert_eq!(state.hypotheses.len(), 48);
+ assert_eq!(state.hypotheses.iter().map(|hypothesis| &hypothesis.id).collect::<std::collections::HashSet<_>>().len(), 48);
+ } else {
+ assert_eq!(state.revision, 1);
+ let mut outcomes: Vec<_> =
+ ["first", "second"].into_iter().map(|label| std::fs::read_to_string(project.root.join(format!("{label}.result"))).unwrap()).collect();
+ outcomes.sort();
+ assert_eq!(outcomes, ["ok", "stale"]);
+ }
+ for (name, body) in super::render(&state) {
+ assert_eq!(std::fs::read_to_string(project.root.join("investigation").join(name)).unwrap(), body);
+ }
+ }
+ }
+
+ #[test]
+ fn finding_corrections_keep_their_id_and_reject_stale_revisions() {
+ use craft_anything_evidence::{Confidence, Environment, EvidenceBuilder, Subject};
+ let engine = Engine::new(crate::testing::session());
+ let evidence = EvidenceBuilder::new("test-observation", Subject { kind: "test".into(), sha256: None, name: None }, Environment::builtin(true))
+ .result(json!({"value": 1}))
+ .summary("Synthetic observation")
+ .confidence(Confidence::Observed)
+ .build()
+ .unwrap();
+ let evidence_id = evidence.id.clone();
+ engine.session().record(evidence).unwrap();
+ call(&engine, "core_finding_record", json!({"statement":"initial", "evidence_ids":[evidence_id]})).unwrap();
+ let edit = json!({"finding_id":"fnd_1", "statement":"corrected", "evidence_ids":[evidence_id], "confidence":"observed", "based_on_revision":1});
+ let result = call(&engine, "core_finding_edit", edit.clone()).unwrap();
+ assert_eq!(result["result"]["finding_id"], "fnd_1");
+ let investigation = call(&engine, "core_investigation_show", json!({})).unwrap();
+ assert_eq!(investigation["result"]["findings"].as_array().unwrap().len(), 1);
+ assert_eq!(investigation["result"]["findings"][0]["statement"], "corrected");
+ assert_eq!(call(&engine, "core_finding_edit", edit).unwrap_err().code, craft_anything_evidence::ErrorCode::StaleRevision);
+ for (confidence, expected) in [("observed", Confidence::Observed), ("derived", Confidence::Derived), ("inferred", Confidence::Inferred)] {
+ call(
+ &engine,
+ "core_finding_edit",
+ json!({"finding_id":"fnd_1", "statement":"reclassified", "evidence_ids":[evidence_id], "confidence":confidence}),
+ )
+ .unwrap();
+ assert_eq!(super::cached(&engine.session()).findings[0].confidence, expected);
+ call(&engine, "core_finding_edit", json!({"finding_id":"fnd_1", "statement":"clarified", "evidence_ids":[evidence_id]})).unwrap();
+ assert_eq!(super::cached(&engine.session()).findings[0].confidence, expected);
+ }
+ }
+
+ #[test]
+ fn shared_projects_preserve_memory_and_refresh_an_external_writers_findings() {
+ use craft_anything_evidence::{Confidence, Environment, EvidenceBuilder, Subject};
+ let directory = tempfile::tempdir().unwrap();
+ let engine = Engine::new(crate::session::Session::isolated(directory.path()));
+ let evidence = EvidenceBuilder::new("test-shared", Subject { kind: "test".into(), sha256: None, name: None }, Environment::builtin(true))
+ .result(json!({"value": 1}))
+ .summary("Synthetic observation")
+ .confidence(Confidence::Observed)
+ .build()
+ .unwrap();
+ let id = evidence.id.clone();
+ engine.session().record(evidence).unwrap();
+ call(&engine, "core_brief_write", json!({"question":"Shared question"})).unwrap();
+ let root = engine.session().ensure_shared_project().unwrap();
+ assert_eq!(engine.session().ensure_shared_project().unwrap(), root);
+ let mut child = crate::session::Session::isolated(&directory.path().join("child"));
+ child.open_project(Project::open(&root).unwrap()).unwrap();
+ let child = Engine::new(child);
+ assert_eq!(call(&child, "core_investigation_show", json!({})).unwrap()["result"]["brief"]["question"], "Shared question");
+ call(&child, "core_finding_record", json!({"statement":"Shared finding", "evidence_ids":[id]})).unwrap();
+ engine.session().open_project(Project::open(&root).unwrap()).unwrap();
+ assert_eq!(super::cached(&engine.session()).findings[0].id, "fnd_1");
+ assert_eq!(super::cached(&engine.session()).findings[0].statement, "Shared finding");
+ let mut reopened = crate::session::Session::isolated(&directory.path().join("reopened"));
+ reopened.open_project(Project::open(&root).unwrap()).unwrap();
+ assert_eq!(super::cached(&reopened).findings[0].id, "fnd_1");
+ }
+
+ #[test]
+ fn shared_targets_are_mode_aware_and_changed_files_are_refused() {
+ use crate::target::{Target, TargetContext};
+ let directory = tempfile::tempdir().unwrap();
+ let path = directory.path().join("sample.bin");
+ std::fs::write(&path, b"sample").unwrap();
+ let target = Target::load(&path).unwrap();
+ let context = TargetContext::from_target(&target);
+ let mut deep = crate::session::Session::isolated(&directory.path().join("deep"));
+ deep.deep_for_run = Some(true);
+ deep.restore_targets(std::slice::from_ref(&context)).unwrap();
+ assert_eq!(deep.active().unwrap().target.id, target.id);
+ assert_eq!(deep.active().unwrap().target.bytes.as_ref(), b"sample");
+ std::fs::write(&path, b"changed").unwrap();
+ let mut other = crate::session::Session::isolated(&directory.path().join("other"));
+ other.deep_for_run = Some(true);
+ assert!(other.restore_targets(std::slice::from_ref(&context)).is_err());
+ assert!(other.active().is_err());
+ std::fs::remove_file(&path).unwrap();
+ let mut clean = crate::session::Session::isolated(&directory.path().join("clean"));
+ clean.restore_targets(&[context]).unwrap();
+ assert_eq!(clean.active().unwrap().target.id, target.id);
+ assert!(clean.active().unwrap().target.bytes.is_empty());
+ }
+
#[test]
fn memory_round_trip_without_project() {
let e = Engine::new(crate::testing::session());
diff --git a/crates/ui-egui/src/builders.rs b/crates/ui-egui/src/builders.rs
index a6076343..ef16d8fd 100644
--- a/crates/ui-egui/src/builders.rs
+++ b/crates/ui-egui/src/builders.rs
@@ -33,10 +33,11 @@ pub fn agent_model_picker(ui: &mut Ui, picker: &mut AgentModelPicker) -> bool {
return false;
}
};
+ let agent = craft_anything_ai::cli_agents::display_for(&picker.context.backend.config.model);
if models.is_empty() {
- ui.label(tr("OpenCode has no visible chat models. Connect a provider in OpenCode, then reload."));
+ ui.label(trf("No chat models are visible in {agent}. Check its setup, then reload.", &[("agent", &agent)]));
}
- let default = tr("OpenCode default");
+ let default = if picker.context.backend.config.model == "opencode" { tr("OpenCode default") } else { tr("Model 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)
@@ -47,18 +48,20 @@ pub fn agent_model_picker(ui: &mut Ui, picker: &mut AgentModelPicker) -> bool {
picker.thinking = None;
}
for model in models {
- let label = format!("{} · {}", model.name, model.id);
+ let label = if model.name == model.id { model.name.clone() } else { 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");
+ widgets::named(response.response, if picker.context.backend.config.model == "opencode" { "OpenCode model" } else { "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));
+ ui.label(
+ RichText::new(trf("The saved model is no longer visible. Choose another model or the {agent} default.", &[("agent", &agent)])).color(t.warning),
+ );
}
let depths = model.map(|m| m.thinking.as_slice()).unwrap_or_default();
ui.label(tr("Thinking depth"));
@@ -178,18 +181,32 @@ impl CraftApp {
return;
}
};
+ let model = context.backend.options.cli_model.clone();
+ let thinking = context
+ .backend
+ .options
+ .cli_thinking
+ .or_else(|| context.backend.options.cli_reasoning_effort.and_then(|value| craft_anything_ai::Effort::parse(value.as_str())));
+ self.load_agent_model_catalog(context, model, thinking);
+ }
+
+ pub fn reload_agent_model(&mut self, name: &str) {
+ if let Some(picker) = self.agent_model_picker.as_ref().filter(|picker| picker.context.backend.config.name == name) {
+ self.load_agent_model_catalog(picker.context.clone(), picker.model.clone(), picker.thinking);
+ } else {
+ self.pick_agent_model(name);
+ }
+ }
+
+ fn load_agent_model_catalog(&mut self, context: craft_anything_ai::ModelContext, model: Option<String>, thinking: Option<craft_anything_ai::Effort>) {
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,
- });
+ self.agent_model_picker = Some(AgentModelPicker { request, model: model.clone(), 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);
+ let mut query = context.clone();
+ query.backend.options.cli_model = model;
+ let result = hub.agent_models(&query);
Ok(crate::Done::AgentModelChoices { request, context, result })
});
}
@@ -207,10 +224,47 @@ impl CraftApp {
/// Use `model` for an AI from now on.
pub fn set_model(&mut self, name: &str, model: &str) {
self.model_picker = None;
+ if let Some(state) = self.model_tuning.get_mut(name) {
+ state.saving = true;
+ }
let (hub, name, model) = (self.hub.clone(), name.to_string(), model.to_string());
self.jobs.spawn(tr("Change an AI's model"), false, move |_| {
- hub.set_model(&name, &model).map_err(|e| e.message)?;
- Ok(crate::backends(&hub))
+ let result = hub.set_model(&name, &model).and_then(|_| {
+ hub.options().get(&name).cloned().ok_or_else(|| craft_anything_engine::evidence::ToolError::invalid("The AI backend was removed."))
+ });
+ Ok(crate::Done::ModelChanged { name, model, result })
+ });
+ }
+
+ /// Populate the persistent model controls on a worker, once for each backend/model pair.
+ pub fn pick_model_options(&mut self, name: &str) {
+ let options = self.backend_options.get(name).cloned().unwrap_or_default();
+ self.model_tuning.insert(
+ name.into(),
+ crate::ModelTuningDraft {
+ backend: name.into(),
+ cli_model: options.cli_model.clone(),
+ choices: None,
+ context: options.cli_context,
+ saving: false,
+ error: None,
+ },
+ );
+ let (hub, name, cli_model) = (self.hub.clone(), name.to_string(), options.cli_model);
+ self.jobs.spawn(tr("Load model options"), false, move |_| {
+ let result = hub.model_tuning(&name);
+ Ok(crate::Done::ModelTuning { name, cli_model, result })
+ });
+ }
+
+ pub fn set_model_options(&mut self, params: craft_anything_ai::model_options::SetModelOptions) {
+ if let Some(state) = self.model_tuning.get_mut(&params.backend) {
+ state.saving = true;
+ }
+ let hub = self.hub.clone();
+ self.jobs.spawn(tr("Set model options"), false, move |_| {
+ let result = hub.set_model_options(&params);
+ Ok(crate::Done::ModelOptionsSaved { params, result })
});
}
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 0a22363b..7790fd67 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -7,6 +7,8 @@ OpenCode model Model v OpenCode
Remote program Vzdálený program
Reload models Znovu načíst modely
Apply Použít
+No chat models are visible in {agent}. Check its setup, then reload. V {agent} nejsou viditelné žádné modely pro chat. Zkontrolujte nastavení a znovu načtěte.
+The saved model is no longer visible. Choose another model or the {agent} default. Uložený model už není vidět. Vyberte jiný model nebo výchozí model v {agent}.
OpenCode has no visible chat models. Connect a provider in OpenCode, then reload. OpenCode nemá žádné viditelné modely pro chat. Připojte v OpenCode poskytovatele a pak znovu načtěte.
The saved model is no longer visible. Choose another model or the OpenCode default. Uložený model už není vidět. Vyberte jiný model nebo výchozí v OpenCode.
The saved thinking depth is unavailable for this model. Choose its default or an offered depth. Uložená hloubka uvažování není pro tento model k dispozici. Vyberte jeho výchozí nebo nabízenou hloubku.
@@ -141,6 +143,7 @@ Answers come from {brain}. To build, set up a coding agent in Settings → AI. N
App Aplikace
App details on device Podrobnosti aplikace v zařízení
Apple apps Aplikace Apple
+Apply model options Použít možnosti modelu
Approve an agent action Schválit akci agenta
Apps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. Aplikace a hry: vylepšovat, dokud nedosáhnou této podobnosti s vašimi obrázky. Při vypnutí se podobnost pouze hlásí.
Architectures Architektury
@@ -281,6 +284,7 @@ Connect to a browser Připojit k prohlížeči
Connect {name} Připojit {name}
Connected devices Připojená zařízení
Connected phone Připojený telefon
+Context window Kontextové okno
Continue Pokračovat
Contradicted Vyvráceno
Control-flow graph: a map of every path a function can take, like a flowchart. Graf toku řízení: mapa všech cest, kterými může funkce projít, podobná vývojovému diagramu.
@@ -330,6 +334,7 @@ Deep Hloubkový
Deep mode now decompiles with Ghidra. The first look at a large program can take several minutes. Hloubkový režim nyní dekompiluje pomocí Ghidra. První průzkum velkého programu může trvat několik minut.
Deep mode on Hloubkový režim zapnutý
Deep: we read its code, files and page source with every tool we have, and with Ghidra when it's installed. Click to switch. Hloubkový režim: čteme kód, soubory i zdrojový kód stránek všemi svými nástroji a také pomocí Ghidra, pokud je nainstalována. Kliknutím přepnete režim.
+Default Výchozí
Delete a project Smazat projekt
Delete it Smazat to
Delete the project Smazat tento projekt
@@ -402,6 +407,7 @@ Export a report (Markdown) Exportovat zprávu (Markdown)
Export captured scripts Exportovat zachycené skripty
Export evidence Exportovat důkazy
Export report Exportovat zprávu
+Extended Rozšířené
Extract an archive Rozbalit archiv
Extract firmware Extrahovat firmware
Extract with this Používat pro extrakci
@@ -630,6 +636,7 @@ List strings Vypsat řetězce
Live: the project's latest build Průběžné: nejnovější sestavení projektu
Load a picture Načíst obrázek
Load a screenshot Načíst snímek obrazovky
+Load model options Načíst možnosti modelu
Loading… Načítání…
Log Protokol
Look again Hledat znovu
@@ -677,6 +684,7 @@ Memory for Ghidra Paměť pro Ghidra
Minimise Minimalizovat
Mode Režim
Model Model AI
+Model options Možnosti modelu
Model: {model} Model AI: {model}
Modules Moduly
More detail Více podrobností
@@ -885,6 +893,7 @@ Read the project Načíst projekt
Reading what's inside… Čtení obsahu…
Ready Hotovo
Ready: {what} is on this computer. Připraveno: {what} je v tomto počítači.
+Reasoning Uvažování
Rebuild status Stav rekonstrukce
Record a finding Zaznamenat zjištění
Record a hypothesis Zaznamenat hypotézu
@@ -989,6 +998,7 @@ Server address Adresa serveru
Session status Stav relace
Set a project's asset budget Nastavit rozpočet podkladů projektu
Set an AI's program Nastavit program AI
+Set model options Nastavit možnosti modelu
Set one up Nastavit
Set up a brain… Nastavit AI asistenta…
Set up a builder Nastavit sestavovacího agenta
@@ -998,6 +1008,7 @@ Show a project Zobrazit projekt
Show folder Zobrazit složku
Show me everything Ukázat vše
Show me the proof Ukázat důkazy
+Show model options Zobrazit možnosti modelu
Show pinned builds Zobrazit připnutá sestavení
Show settings Zobrazit nastavení
Show the answer Zobrazit odpověď
@@ -1021,6 +1032,7 @@ Some plugins couldn't be read: Některé pluginy se nepodařilo načíst:
Something a program borrows from the operating system or a library, like "open a file". Operace, kterou program přebírá z operačního systému nebo knihovny, například „otevřít soubor“.
Something a program or library offers for other programs to use. Funkce, kterou program nebo knihovna nabízí jiným programům.
Source Zdrojový kód
+Standard Standardní
Start Spustit
Start a Frida session Zahájit relaci Frida
Start a GDB session Zahájit relaci GDB
@@ -1152,6 +1164,7 @@ Unreal IoStore Unreal IoStore
Unreal builds games with Apple's Xcode, free in the App Store. Unreal sestavuje hry pomocí Apple Xcode, které je zdarma v App Store.
Unreal is here, but it also needs Visual Studio's C++ tools. Unreal je dostupný, ale potřebuje také nástroje C++ pro Visual Studio.
Unreal pak Unreal pak
+Update a finding Upravit zjištění
Update a hypothesis Aktualizovat hypotézu
Update an open question Aktualizovat otevřenou otázku
Update the checklist Aktualizovat kontrolní seznam
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 21be3a44..5e5b0ec7 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -7,6 +7,8 @@ OpenCode model OpenCode-Modell
Remote program Entferntes Programm
Reload models Modelle neu laden
Apply Übernehmen
+No chat models are visible in {agent}. Check its setup, then reload. In {agent} sind keine Chat-Modelle sichtbar. Prüfe die Einrichtung und lade dann neu.
+The saved model is no longer visible. Choose another model or the {agent} default. Das gespeicherte Modell ist nicht mehr sichtbar. Wähle ein anderes Modell oder den Standard von {agent}.
OpenCode has no visible chat models. Connect a provider in OpenCode, then reload. OpenCode hat keine sichtbaren Chat-Modelle. Verbinde in OpenCode einen Anbieter und lade dann neu.
The saved model is no longer visible. Choose another model or the OpenCode default. Das gespeicherte Modell ist nicht mehr sichtbar. Wähle ein anderes Modell oder den OpenCode-Standard.
The saved thinking depth is unavailable for this model. Choose its default or an offered depth. Die gespeicherte Denktiefe ist für dieses Modell nicht verfügbar. Wähle seinen Standard oder eine angebotene Tiefe.
@@ -141,6 +143,7 @@ Answers come from {brain}. To build, set up a coding agent in Settings → AI. A
App App
App details on device App-Details auf dem Gerät
Apple apps Apple-Apps
+Apply model options Modelloptionen anwenden
Approve an agent action Aktion eines Agenten genehmigen
Apps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. Apps und Spiele: weiter verfeinern, bis sie deinen Bildern so ähnlich sehen. Aus: Die Ähnlichkeit wird nur gemeldet.
Architectures Architekturen
@@ -281,6 +284,7 @@ Connect to a browser Mit einem Browser verbinden
Connect {name} {name} verbinden
Connected devices Verbundene Geräte
Connected phone Verbundenes Handy
+Context window Kontextfenster
Continue Weiter
Contradicted Widerlegt
Control-flow graph: a map of every path a function can take, like a flowchart. Kontrollflussgraph: eine Karte aller Wege, die eine Funktion nehmen kann, wie ein Flussdiagramm.
@@ -330,6 +334,7 @@ Deep Deep
Deep mode now decompiles with Ghidra. The first look at a large program can take several minutes. Der Deep-Modus dekompiliert jetzt mit Ghidra. Der erste Blick auf ein großes Programm kann mehrere Minuten dauern.
Deep mode on Deep-Modus an
Deep: we read its code, files and page source with every tool we have, and with Ghidra when it's installed. Click to switch. Deep: Wir lesen Code, Dateien und Seitenquelltext mit allen Werkzeugen, die wir haben, und mit Ghidra, wenn es installiert ist. Klicke zum Wechseln.
+Default Standard
Delete a project Ein Projekt löschen
Delete it Löschen
Delete the project Das Projekt löschen
@@ -402,6 +407,7 @@ Export a report (Markdown) Einen Bericht exportieren (Markdown)
Export captured scripts Erfasste Skripte exportieren
Export evidence Belege exportieren
Export report Bericht exportieren
+Extended Erweitert
Extract an archive Ein Archiv entpacken
Extract firmware Firmware extrahieren
Extract with this Damit extrahieren
@@ -630,6 +636,7 @@ List strings Strings auflisten
Live: the project's latest build Live: der neueste Build des Projekts
Load a picture Ein Bild laden
Load a screenshot Einen Screenshot laden
+Load model options Modelloptionen laden
Loading… Wird geladen …
Log Protokoll
Look again Noch einmal ansehen
@@ -677,6 +684,7 @@ Memory for Ghidra Speicher für Ghidra
Minimise Minimieren
Mode Modus
Model Modell
+Model options Modelloptionen
Model: {model} Modell: {model}
Modules Module
More detail Mehr Details
@@ -885,6 +893,7 @@ Read the project Das Projekt lesen
Reading what's inside… Es wird gelesen, was darin ist …
Ready Bereit
Ready: {what} is on this computer. Bereit: {what} ist auf diesem Computer.
+Reasoning Schlussfolgern
Rebuild status Nachbau-Status
Record a finding Einen Befund festhalten
Record a hypothesis Eine Hypothese festhalten
@@ -989,6 +998,7 @@ Server address Serveradresse
Session status Sitzungsstatus
Set a project's asset budget Das Asset-Budget eines Projekts festlegen
Set an AI's program Das Programm einer KI festlegen
+Set model options Modelloptionen festlegen
Set one up Eine einrichten
Set up a brain… KI einrichten …
Set up a builder Einen Builder einrichten
@@ -998,6 +1008,7 @@ Show a project Ein Projekt zeigen
Show folder Ordner zeigen
Show me everything Zeig mir alles
Show me the proof Zeig mir den Beweis
+Show model options Modelloptionen anzeigen
Show pinned builds Angepinnte Builds zeigen
Show settings Einstellungen zeigen
Show the answer Die Antwort zeigen
@@ -1021,6 +1032,7 @@ Some plugins couldn't be read: Einige Plugins konnten nicht gelesen werden:
Something a program borrows from the operating system or a library, like "open a file". Etwas, das ein Programm vom Betriebssystem oder einer Bibliothek borgt, etwa „eine Datei öffnen“.
Something a program or library offers for other programs to use. Etwas, das ein Programm oder eine Bibliothek anderen Programmen zur Verfügung stellt.
Source Quelle
+Standard Standard
Start Start
Start a Frida session Eine Frida-Sitzung starten
Start a GDB session Eine GDB-Sitzung starten
@@ -1152,6 +1164,7 @@ Unreal IoStore Unreal IoStore
Unreal builds games with Apple's Xcode, free in the App Store. Unreal baut Spiele mit Apples Xcode, kostenlos im App Store.
Unreal is here, but it also needs Visual Studio's C++ tools. Unreal ist da, braucht aber zusätzlich die C++-Werkzeuge von Visual Studio.
Unreal pak Unreal-Pak
+Update a finding Erkenntnis aktualisieren
Update a hypothesis Eine Hypothese aktualisieren
Update an open question Eine offene Frage aktualisieren
Update the checklist Die Checkliste aktualisieren
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index c89b48b9..13972f85 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -7,6 +7,8 @@ OpenCode model OpenCode 모델
Remote program 원격 프로그램
Reload models 모델 다시 불러오기
Apply 적용
+No chat models are visible in {agent}. Check its setup, then reload. {agent}에 보이는 채팅 모델이 없습니다. 설정을 확인한 다음 다시 불러오세요.
+The saved model is no longer visible. Choose another model or the {agent} default. 저장된 모델이 더 이상 보이지 않습니다. 다른 모델이나 {agent} 기본값을 고르세요.
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. 저장된 생각 깊이는 이 모델에서 쓸 수 없습니다. 기본값이나 제공되는 깊이를 고르세요.
@@ -141,6 +143,7 @@ Answers come from {brain}. To build, set up a coding agent in Settings → AI.
App 앱
App details on device 기기의 앱 정보
Apple apps Apple 앱
+Apply model options 모델 옵션 적용
Approve an agent action 에이전트 작업 승인
Apps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. 앱과 게임: 그림과 이만큼 닮을 때까지 계속 다듬습니다. 끄면 닮은 정도만 알려 줍니다.
Architectures 아키텍처
@@ -281,6 +284,7 @@ Connect to a browser 브라우저에 연결
Connect {name} {name} 연결
Connected devices 연결된 기기
Connected phone 연결된 휴대폰
+Context window 컨텍스트 창
Continue 계속
Contradicted 반박됨
Control-flow graph: a map of every path a function can take, like a flowchart. 제어 흐름 그래프: 순서도처럼 함수가 지날 수 있는 모든 경로를 보여 주는 지도입니다.
@@ -330,6 +334,7 @@ Deep 심층
Deep mode now decompiles with Ghidra. The first look at a large program can take several minutes. 이제 심층 모드에서 Ghidra로 디컴파일합니다. 큰 프로그램은 처음 살펴볼 때 몇 분 걸릴 수 있습니다.
Deep mode on 심층 모드 켜짐
Deep: we read its code, files and page source with every tool we have, and with Ghidra when it's installed. Click to switch. 심층: 가진 모든 도구로 코드, 파일, 페이지 소스를 읽고, Ghidra가 설치되어 있으면 Ghidra도 씁니다. 눌러서 전환합니다.
+Default 기본값
Delete a project 프로젝트 삭제
Delete it 삭제
Delete the project 프로젝트 삭제
@@ -402,6 +407,7 @@ Export a report (Markdown) 보고서 내보내기 (Markdown)
Export captured scripts 캡처한 스크립트 내보내기
Export evidence 근거 내보내기
Export report 보고서 내보내기
+Extended 확장
Extract an archive 압축 파일 풀기
Extract firmware 펌웨어 추출
Extract with this 이걸로 추출
@@ -630,6 +636,7 @@ List strings 문자열 목록
Live: the project's latest build 최신 유지: 프로젝트의 최신 빌드
Load a picture 그림 불러오기
Load a screenshot 스크린샷 불러오기
+Load model options 모델 옵션 불러오기
Loading… 불러오는 중…
Log 로그
Look again 다시 살펴보기
@@ -677,6 +684,7 @@ Memory for Ghidra Ghidra 메모리
Minimise 최소화
Mode 모드
Model 모델
+Model options 모델 옵션
Model: {model} 모델: {model}
Modules 모듈
More detail 더 자세히
@@ -885,6 +893,7 @@ Read the project 프로젝트 읽기
Reading what's inside… 안에 든 것을 읽는 중…
Ready 완성
Ready: {what} is on this computer. 준비됨: {what} 설치되어 있습니다.
+Reasoning 추론
Rebuild status 다시 만들기 상태
Record a finding 발견 기록
Record a hypothesis 가설 기록
@@ -989,6 +998,7 @@ Server address 서버 주소
Session status 세션 상태
Set a project's asset budget 프로젝트 에셋 예산 정하기
Set an AI's program AI 프로그램 정하기
+Set model options 모델 옵션 설정
Set one up 설정하기
Set up a brain… AI 설정…
Set up a builder 빌더 설정
@@ -998,6 +1008,7 @@ Show a project 프로젝트 보기
Show folder 폴더 보기
Show me everything 모두 보여 주기
Show me the proof 근거 보기
+Show model options 모델 옵션 표시
Show pinned builds 고정한 빌드 보기
Show settings 설정 보기
Show the answer 답 보기
@@ -1021,6 +1032,7 @@ Some plugins couldn't be read: 읽지 못한 플러그인이 있습니다:
Something a program borrows from the operating system or a library, like "open a file". 프로그램이 운영체제나 라이브러리에서 빌려 쓰는 기능. "파일 열기" 같은 것입니다.
Something a program or library offers for other programs to use. 프로그램이나 라이브러리가 다른 프로그램이 쓰도록 내놓는 기능.
Source 소스
+Standard 표준
Start 시작
Start a Frida session Frida 세션 시작
Start a GDB session GDB 세션 시작
@@ -1152,6 +1164,7 @@ Unreal IoStore Unreal IoStore
Unreal builds games with Apple's Xcode, free in the App Store. Unreal은 Apple의 Xcode로 게임을 만듭니다. App Store에서 무료로 받을 수 있습니다.
Unreal is here, but it also needs Visual Studio's C++ tools. Unreal은 있지만 Visual Studio의 C++ 도구도 필요합니다.
Unreal pak Unreal pak
+Update a finding 분석 결과 수정
Update a hypothesis 가설 갱신
Update an open question 남은 질문 갱신
Update the checklist 체크리스트 갱신
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index d6fa1350..ce534e28 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -130,6 +130,7 @@ App Приложение
App details on device Сведения о приложении на устройстве
Apple apps Приложения Apple
Apply Применить
+Apply model options Применить параметры модели
Approve an agent action Одобрить действие агента
Apps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. Приложения и игры: продолжать уточнение, пока они не станут похожи на ваши изображения настолько. Выключено — сходство только сообщается.
Architectures Архитектуры
@@ -271,6 +272,7 @@ Connect to a browser Подключиться к браузеру
Connect {name} Подключить {name}
Connected devices Подключённые устройства
Connected phone Подключённый телефон
+Context window Окно контекста
Continue Продолжить
Contradicted Опровергнуто
Control-flow graph: a map of every path a function can take, like a flowchart. Граф потока управления: карта всех путей, по которым может пройти функция, как блок-схема.
@@ -320,6 +322,7 @@ Deep Глубокий
Deep mode now decompiles with Ghidra. The first look at a large program can take several minutes. Режим «Глубокий» теперь декомпилирует с помощью Ghidra. Первый просмотр большой программы может занять несколько минут.
Deep mode on Включён режим «Глубокий»
Deep: we read its code, files and page source with every tool we have, and with Ghidra when it's installed. Click to switch. Глубокий: мы читаем его код, файлы и исходник страницы всеми имеющимися инструментами, а также Ghidra, если он установлен. Нажмите, чтобы переключить.
+Default По умолчанию
Delete a project Удалить проект
Delete it Удалить
Delete the project Удалить проект
@@ -392,6 +395,7 @@ Export a report (Markdown) Экспортировать отчёт (Markdown)
Export captured scripts Экспортировать записанные скрипты
Export evidence Экспортировать доказательства
Export report Экспортировать отчёт
+Extended Расширенный
Extract an archive Распаковать архив
Extract firmware Извлечь прошивку
Extract with this Извлечь с помощью этого
@@ -621,6 +625,7 @@ List strings Список строк
Live: the project's latest build В реальном времени: последняя сборка проекта
Load a picture Загрузить изображение
Load a screenshot Загрузить скриншот
+Load model options Загрузить параметры модели
Loading… Загрузка…
Log Журнал
Look again Искать снова
@@ -669,6 +674,7 @@ Minimise Свернуть
Mode Режим
Model Модель
Model default По умолчанию для модели
+Model options Параметры модели
Model: {model} Модель: {model}
Modules Модули
More detail Подробнее
@@ -778,6 +784,8 @@ Open the installer app Открыть приложение-установщик
Open the website Открыть веб-сайт
Open {name} Открыть {name}
OpenCode default По умолчанию для OpenCode
+No chat models are visible in {agent}. Check its setup, then reload. В {agent} нет доступных моделей для чата. Проверьте настройки и обновите список.
+The saved model is no longer visible. Choose another model or the {agent} default. Сохранённая модель больше не доступна. Выберите другую модель или модель {agent} по умолчанию.
OpenCode has no visible chat models. Connect a provider in OpenCode, then reload. В OpenCode нет доступных моделей для чата. Подключите провайдера в OpenCode и обновите список.
OpenCode model Модель OpenCode
Opened {name} Открыто: {name}
@@ -880,6 +888,7 @@ Read the project Читать проект
Reading what's inside… Чтение того, что внутри…
Ready Готово
Ready: {what} is on this computer. Готово: {what} есть на этом компьютере.
+Reasoning Рассуждение
Rebuild status Состояние пересборки
Record a finding Записать находку
Record a hypothesis Записать гипотезу
@@ -986,6 +995,7 @@ Server address Адрес сервера
Session status Состояние сессии
Set a project's asset budget Установить бюджет ресурсов проекта
Set an AI's program Установить программу ИИ
+Set model options Задать параметры модели
Set one up Настроить
Set up a brain… Настроить «мозг»…
Set up a builder Настроить конструктор
@@ -995,6 +1005,7 @@ Show a project Показать проект
Show folder Показать папку
Show me everything Показать всё
Show me the proof Покажи мне доказательство
+Show model options Показать параметры модели
Show pinned builds Показать закреплённые сборки
Show settings Показать настройки
Show the answer Показать ответ
@@ -1018,6 +1029,7 @@ Some plugins couldn't be read: Некоторые плагины не удало
Something a program borrows from the operating system or a library, like "open a file". То, что программа берёт взаймы у операционной системы или библиотеки, например «открыть файл».
Something a program or library offers for other programs to use. То, что программа или библиотека предлагает другим программам для использования.
Source Источник
+Standard Стандартный
Start Старт
Start a Frida session Запустить сессию Frida
Start a GDB session Запустить сессию GDB
@@ -1152,6 +1164,7 @@ Unreal IoStore IoStore Unreal
Unreal builds games with Apple's Xcode, free in the App Store. Unreal собирает игры с помощью Xcode от Apple, бесплатного в App Store.
Unreal is here, but it also needs Visual Studio's C++ tools. Unreal есть здесь, но ему также нужны инструменты C++ Visual Studio.
Unreal pak Пак Unreal
+Update a finding Обновить вывод
Update a hypothesis Обновить гипотезу
Update an open question Обновить открытый вопрос
Update the checklist Обновить контрольный список
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index d07129cc..398c152f 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -7,6 +7,8 @@ OpenCode model OpenCode 模型
Remote program 远程程序
Reload models 重新加载模型
Apply 应用
+No chat models are visible in {agent}. Check its setup, then reload. {agent} 中没有可见的聊天模型。请检查其设置,然后重新加载。
+The saved model is no longer visible. Choose another model or the {agent} default. 已保存的模型不再可见。请选择其他模型或使用 {agent} 默认设置。
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. 此模型不支持已保存的思考深度。请选择默认设置或可用的深度。
@@ -141,6 +143,7 @@ Answers come from {brain}. To build, set up a coding agent in Settings → AI.
App 应用
App details on device 设备上的应用详情
Apple apps Apple 应用
+Apply model options 应用模型选项
Approve an agent action 批准智能体操作
Apps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. 应用和游戏:持续改进,直到与参考图片达到此相似度。关闭后仅报告相似度。
Architectures 架构
@@ -281,6 +284,7 @@ Connect to a browser 连接浏览器
Connect {name} 连接 {name}
Connected devices 已连接的设备
Connected phone 已连接的手机
+Context window 上下文窗口
Continue 继续
Contradicted 存在矛盾
Control-flow graph: a map of every path a function can take, like a flowchart. 控制流图:像流程图一样,展示函数可能执行的每一条路径。
@@ -330,6 +334,7 @@ Deep 深度
Deep mode now decompiles with Ghidra. The first look at a large program can take several minutes. 深度模式现在会使用 Ghidra 反编译。首次分析大型程序可能需要几分钟。
Deep mode on 深度模式已开启
Deep: we read its code, files and page source with every tool we have, and with Ghidra when it's installed. Click to switch. 深度:使用所有可用工具读取其代码、文件和网页源码;已安装 Ghidra 时也会使用它。点击切换。
+Default 默认
Delete a project 删除项目
Delete it 删除
Delete the project 删除项目
@@ -402,6 +407,7 @@ Export a report (Markdown) 导出报告 (Markdown)
Export captured scripts 导出采集的脚本
Export evidence 导出证据
Export report 导出报告
+Extended 扩展
Extract an archive 解压归档文件
Extract firmware 提取固件
Extract with this 用此工具提取
@@ -630,6 +636,7 @@ List strings 列出字符串
Live: the project's latest build 当前:项目的最新构建
Load a picture 加载图片
Load a screenshot 加载截图
+Load model options 加载模型选项
Loading… 正在加载…
Log 日志
Look again 重新查找
@@ -677,6 +684,7 @@ Memory for Ghidra Ghidra 内存用量
Minimise 最小化
Mode 模式
Model 模型
+Model options 模型选项
Model: {model} 模型:{model}
Modules 模块
More detail 更多详情
@@ -885,6 +893,7 @@ Read the project 读取项目
Reading what's inside… 正在读取内部内容…
Ready 就绪
Ready: {what} is on this computer. 已就绪:此电脑上已有 {what}。
+Reasoning 推理
Rebuild status 重建状态
Record a finding 记录发现
Record a hypothesis 记录假设
@@ -989,6 +998,7 @@ Server address 服务器地址
Session status 会话状态
Set a project's asset budget 设置项目素材预算
Set an AI's program 设置 AI 的程序
+Set model options 设置模型选项
Set one up 设置一个
Set up a brain… 设置 AI 助手…
Set up a builder 配置构建助手
@@ -998,6 +1008,7 @@ Show a project 显示项目
Show folder 显示文件夹
Show me everything 显示全部内容
Show me the proof 查看证据
+Show model options 显示模型选项
Show pinned builds 显示固定的构建
Show settings 显示设置
Show the answer 显示回答
@@ -1021,6 +1032,7 @@ Some plugins couldn't be read: 部分插件无法读取:
Something a program borrows from the operating system or a library, like "open a file". 程序从操作系统或库调用的功能,例如“打开文件”。
Something a program or library offers for other programs to use. 程序或库提供给其他程序使用的功能。
Source 源代码
+Standard 标准
Start 开始
Start a Frida session 启动 Frida 会话
Start a GDB session 启动 GDB 会话
@@ -1152,6 +1164,7 @@ Unreal IoStore Unreal IoStore
Unreal builds games with Apple's Xcode, free in the App Store. Unreal 使用 Apple 的 Xcode 构建游戏,可从 App Store 免费获取。
Unreal is here, but it also needs Visual Studio's C++ tools. 已安装 Unreal,但还需要 Visual Studio 的 C++ 工具。
Unreal pak Unreal pak
+Update a finding 更新发现
Update a hypothesis 更新假设
Update an open question 更新待解答的问题
Update the checklist 更新检查清单
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 5d0c91b7..9b40dbea 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -7,6 +7,8 @@ OpenCode model OpenCode 模型
Remote program 遠端程式
Reload models 重新載入模型
Apply 套用
+No chat models are visible in {agent}. Check its setup, then reload. {agent} 中沒有可見的聊天模型。請檢查其設定,然後重新載入。
+The saved model is no longer visible. Choose another model or the {agent} default. 已儲存的模型不再可見。請選擇其他模型或使用 {agent} 預設設定。
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. 此模型不支援已儲存的思考深度。請選擇預設設定或可用的深度。
@@ -141,6 +143,7 @@ Answers come from {brain}. To build, set up a coding agent in Settings → AI.
App 應用程式
App details on device 裝置上的應用程式詳細資訊
Apple apps Apple 應用程式
+Apply model options 套用模型選項
Approve an agent action 核准代理操作
Apps and games: keep refining until they look this alike to your pictures. Off, the likeness is only reported. 應用程式和遊戲:持續改進,直到與參考圖片達到此相似度。關閉後僅回報相似度。
Architectures 架構
@@ -281,6 +284,7 @@ Connect to a browser 連線至瀏覽器
Connect {name} 連線至 {name}
Connected devices 已連線的裝置
Connected phone 已連線的手機
+Context window 上下文視窗
Continue 繼續
Contradicted 存在矛盾
Control-flow graph: a map of every path a function can take, like a flowchart. 控制流程圖:像流程圖一樣,展示函式可能執行的每一條路徑。
@@ -330,6 +334,7 @@ Deep 深度
Deep mode now decompiles with Ghidra. The first look at a large program can take several minutes. 深度模式現在會使用 Ghidra 反編譯。首次分析大型程式可能需要幾分鐘。
Deep mode on 深度模式已開啟
Deep: we read its code, files and page source with every tool we have, and with Ghidra when it's installed. Click to switch. 深度:使用所有可用工具讀取其程式碼、檔案和網頁原始碼;已安裝 Ghidra 時也會使用它。按一下切換。
+Default 預設
Delete a project 刪除專案
Delete it 刪除
Delete the project 刪除專案
@@ -402,6 +407,7 @@ Export a report (Markdown) 匯出報告 (Markdown)
Export captured scripts 匯出擷取的指令碼
Export evidence 匯出證據
Export report 匯出報告
+Extended 延伸
Extract an archive 解壓縮封存檔
Extract firmware 擷取韌體
Extract with this 用此工具擷取
@@ -630,6 +636,7 @@ List strings 列出字串
Live: the project's latest build 目前:專案的最新建置
Load a picture 載入圖片
Load a screenshot 載入螢幕擷取畫面
+Load model options 載入模型選項
Loading… 正在載入…
Log 記錄
Look again 重新尋找
@@ -677,6 +684,7 @@ Memory for Ghidra Ghidra 記憶體用量
Minimise 最小化
Mode 模式
Model 模型
+Model options 模型選項
Model: {model} 模型:{model}
Modules 模組
More detail 更多詳細資訊
@@ -885,6 +893,7 @@ Read the project 讀取專案
Reading what's inside… 正在讀取內部內容…
Ready 就緒
Ready: {what} is on this computer. 已就緒:此電腦上已有 {what}。
+Reasoning 推理
Rebuild status 重建狀態
Record a finding 記錄發現
Record a hypothesis 記錄假設
@@ -989,6 +998,7 @@ Server address 伺服器位址
Session status 工作階段狀態
Set a project's asset budget 設定專案素材預算
Set an AI's program 設定 AI 的程式
+Set model options 設定模型選項
Set one up 設定一個
Set up a brain… 設定 AI 助手…
Set up a builder 設定建置助手
@@ -998,6 +1008,7 @@ Show a project 顯示專案
Show folder 顯示資料夾
Show me everything 顯示全部內容
Show me the proof 檢視證據
+Show model options 顯示模型選項
Show pinned builds 顯示釘選的建置
Show settings 顯示設定
Show the answer 顯示回答
@@ -1021,6 +1032,7 @@ Some plugins couldn't be read: 部分外掛無法讀取:
Something a program borrows from the operating system or a library, like "open a file". 程式從作業系統或程式庫呼叫的功能,例如「開啟檔案」。
Something a program or library offers for other programs to use. 程式或程式庫提供給其他程式使用的功能。
Source 原始碼
+Standard 標準
Start 開始
Start a Frida session 啟動 Frida 工作階段
Start a GDB session 啟動 GDB 工作階段
@@ -1152,6 +1164,7 @@ Unreal IoStore Unreal IoStore
Unreal builds games with Apple's Xcode, free in the App Store. Unreal 使用 Apple 的 Xcode 建置遊戲,可從 App Store 免費取得。
Unreal is here, but it also needs Visual Studio's C++ tools. 已安裝 Unreal,但還需要 Visual Studio 的 C++ 工具。
Unreal pak Unreal pak
+Update a finding 更新發現
Update a hypothesis 更新假設
Update an open question 更新待解答的問題
Update the checklist 更新檢查清單
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 7ed32e0d..08e520ec 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -165,6 +165,20 @@ pub enum Done {
context: craft_anything_ai::ModelContext,
result: Result<Vec<craft_anything_ai::AgentModel>, ToolError>,
},
+ ModelTuning {
+ name: String,
+ cli_model: Option<String>,
+ result: Result<craft_anything_ai::model_options::ModelTuning, ToolError>,
+ },
+ ModelChanged {
+ name: String,
+ model: String,
+ result: Result<craft_anything_ai::BackendOptions, ToolError>,
+ },
+ ModelOptionsSaved {
+ params: craft_anything_ai::model_options::SetModelOptions,
+ result: Result<(), ToolError>,
+ },
Picked {
pick: Pick,
path: Option<PathBuf>,
@@ -289,6 +303,32 @@ pub struct TargetInfo {
pub bytes: Arc<[u8]>,
}
+/// Cached choices and editable values for one backend/model. Changes save immediately; controls
+/// stay in place while discovery or a save is pending, and failures retain a retryable state.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct ModelTuningDraft {
+ pub backend: String,
+ pub cli_model: Option<String>,
+ pub choices: Option<craft_anything_ai::model_options::ModelTuning>,
+ pub context: Option<craft_anything_ai::config::CliContext>,
+ #[serde(default)]
+ pub saving: bool,
+ #[serde(default)]
+ pub error: Option<String>,
+}
+
+impl ModelTuningDraft {
+ /// Drop an override the selected model does not advertise before presenting its controls.
+ pub fn set_choices(&mut self, choices: craft_anything_ai::model_options::ModelTuning) {
+ self.context = self.context.filter(|value| choices.context.iter().any(|choice| choice.value == *value));
+ self.choices = Some(choices);
+ }
+
+ pub fn params(&self) -> craft_anything_ai::model_options::SetModelOptions {
+ craft_anything_ai::model_options::SetModelOptions { backend: self.backend.clone(), expected_cli_model: self.cli_model.clone(), context: self.context }
+ }
+}
+
/// The last snapshot of the session, refreshed whenever the lock is free and something changed.
#[derive(Debug, Clone, Default)]
pub struct SessionView {
@@ -299,6 +339,8 @@ pub struct SessionView {
pub ledger: Vec<Evidence>,
pub ledger_len: usize,
pub unknowns: Vec<Unknown>,
+ /// Recorded answers (`fnd_*`), distinct from the evidence ledger that supports them.
+ pub findings: Vec<craft_anything_engine::tools::investigation_tools::Finding>,
pub project: Option<String>,
pub project_allows: Vec<String>,
}
@@ -378,6 +420,7 @@ pub struct CraftApp {
pub model_picker: Option<(String, Option<Vec<String>>)>,
pub agent_model_picker: Option<builders::AgentModelPicker>,
model_request: u64,
+ pub model_tuning: std::collections::BTreeMap<String, ModelTuningDraft>,
/// 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.
@@ -485,6 +528,7 @@ impl CraftApp {
model_picker: None,
agent_model_picker: None,
model_request: 0,
+ model_tuning: Default::default(),
picking_program_for: None,
builder: None,
extractor: None,
@@ -764,6 +808,7 @@ impl CraftApp {
},
ledger_len: s.ledger_len(),
unknowns: s.unknowns().take(500).cloned().collect(),
+ findings: craft_anything_engine::tools::investigation_tools::cached(&s).findings,
project: s.project.as_ref().map(|p| p.meta.name.clone()),
project_allows: s.project.as_ref().map(|p| p.meta.allowed_tools.clone()).unwrap_or_default(),
};
@@ -1190,6 +1235,7 @@ impl CraftApp {
match e {
AgentEvent::ToolFinished { .. } => self.view_dirty = true,
AgentEvent::TurnDone { backend, input_tokens, output_tokens, cost_usd, cost_is_estimate } => {
+ self.view_dirty = true;
self.session_usage.add_turn(input_tokens, output_tokens, cost_usd, cost_is_estimate);
let cost = cost_usd.map(|c| format!(", ${c:.4}")).unwrap_or_default();
self.log(false, format!("{backend}: {input_tokens} in / {output_tokens} out{cost}"));
@@ -1356,6 +1402,10 @@ impl CraftApp {
self.builder = builder;
self.extractor = extractor;
self.backend_options = options;
+ self.model_tuning.retain(|name, state| {
+ self.backends.iter().any(|backend| backend.name == *name && craft_anything_ai::model_options::supported(backend))
+ && self.backend_options.get(name).and_then(|options| options.cli_model.as_ref()) == state.cli_model.as_ref()
+ });
}
Done::ModelChoices { name, result } => match result {
// Kept only while the picker is still open for that AI.
@@ -1373,6 +1423,65 @@ impl CraftApp {
picker.result = Some(result.map_err(|e| e.for_people()));
}
}
+ Done::ModelTuning { name, cli_model, result } => {
+ let current = self.backend_options.get(&name).and_then(|options| options.cli_model.clone());
+ if self.model_tuning.get(&name).is_some_and(|state| state.cli_model == cli_model) {
+ if current != cli_model {
+ self.model_tuning.remove(&name);
+ } else {
+ match result {
+ Ok(choices) => {
+ if let Some(draft) = self.model_tuning.get_mut(&name) {
+ draft.set_choices(choices);
+ }
+ }
+ Err(error) => {
+ if let Some(state) = self.model_tuning.get_mut(&name) {
+ state.error = Some(error.for_people());
+ }
+ }
+ }
+ }
+ }
+ }
+ Done::ModelChanged { name, model, result } => match result {
+ Ok(options) => {
+ if let Some(backend) = self.backends.iter_mut().find(|backend| backend.name == name) {
+ if backend.kind != craft_anything_ai::BackendKind::AgentCli {
+ backend.model = model;
+ }
+ self.backend_options.insert(name.clone(), options);
+ }
+ self.model_tuning.remove(&name);
+ }
+ Err(error) => {
+ if let Some(state) = self.model_tuning.get_mut(&name) {
+ state.saving = false;
+ }
+ self.toast(error.for_people(), true);
+ }
+ },
+ Done::ModelOptionsSaved { params, result } => {
+ let current = self.backend_options.get(&params.backend).and_then(|options| options.cli_model.clone());
+ if current == params.expected_cli_model {
+ if result.is_ok()
+ && let Some(options) = self.backend_options.get_mut(&params.backend)
+ {
+ options.cli_context = params.context;
+ }
+ if let Some(state) = self.model_tuning.get_mut(&params.backend) {
+ state.saving = false;
+ if result.is_err()
+ && let Some(options) = self.backend_options.get(&params.backend)
+ {
+ state.context = options.cli_context;
+ }
+ }
+ }
+ if let Err(error) = result {
+ self.toast(error.for_people(), true);
+ }
+ }
Done::BackendAdded { name, result } => match result {
Ok(()) => {
if self.server_form.name.trim() == name {
diff --git a/crates/ui-egui/src/project.rs b/crates/ui-egui/src/project.rs
index 8fbb4498..26c849fe 100644
--- a/crates/ui-egui/src/project.rs
+++ b/crates/ui-egui/src/project.rs
@@ -260,6 +260,9 @@ impl CraftApp {
for (root, e) in &events {
if open.as_ref() == Some(root) {
apply(&mut self.state.feed, e);
+ if matches!(e, RunEvent::Agent(AgentEvent::ToolFinished { .. } | AgentEvent::TurnDone { .. })) {
+ self.view_dirty = true;
+ }
}
// The run saves its usage at each agent turn and when it ends; read it again then.
if matches!(e, RunEvent::Ask(_)) {
diff --git a/crates/ui-egui/src/settings_ui.rs b/crates/ui-egui/src/settings_ui.rs
index 2d372c3e..da6e5e4b 100644
--- a/crates/ui-egui/src/settings_ui.rs
+++ b/crates/ui-egui/src/settings_ui.rs
@@ -305,6 +305,17 @@ fn engines(app: &mut CraftApp, ui: &mut Ui) {
}
}
+/// Keep both selectors in place while their model-specific choices load or fail. Loading is
+/// scheduled after drawing, and a failed lookup stays visible until explicitly retried.
+fn model_options_loading(ui: &mut Ui, backend: &str) {
+ ui.add_enabled_ui(false, |ui| {
+ ui.horizontal_wrapped(|ui| {
+ ui.label(tr("Context window"));
+ egui::ComboBox::from_id_salt(("model-context", backend)).icon(widgets::combo_icon).selected_text(tr("Default")).show_ui(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)) {
@@ -323,6 +334,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
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);
+ let (mut tune_models, mut save_tuning) = (Vec::new(), 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));
@@ -377,12 +389,19 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
// Which model it uses, and the ones it can be set to (#123).
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"));
+ let current = options
+ .and_then(|o| o.cli_model.as_deref())
+ .map(str::to_string)
+ .unwrap_or_else(|| if b.model == "opencode" { tr("OpenCode default") } else { tr("Model default") });
ui.label(trf("Model: {model}", &[("model", &current)]));
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) {
+ let previous = picker.model.clone();
+ let apply = crate::builders::agent_model_picker(ui, picker);
+ if picker.model != previous && craft_anything_ai::cli_agents::adapter_for(&b.model).model_catalog_depends_on_selection() {
+ pick_agent_model = Some(b.name.clone());
+ } else if apply {
chosen_agent_model = Some((b.name.clone(), picker.model.clone(), picker.thinking));
}
ui.horizontal(|ui| {
@@ -438,6 +457,48 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
}
});
}
+ if craft_anything_ai::model_options::supported(b) {
+ if let Some(draft) = app.model_tuning.get_mut(&b.name) {
+ if let Some(choices) = &draft.choices {
+ let mut changed = false;
+ ui.add_enabled_ui(!draft.saving, |ui| {
+ ui.horizontal_wrapped(|ui| {
+ ui.label(tr("Context window"));
+ let label = draft
+ .context
+ .and_then(|value| choices.context.iter().find(|choice| choice.value == value))
+ .map(|choice| tr(&choice.label))
+ .unwrap_or_else(|| tr("Default"));
+ egui::ComboBox::from_id_salt(("model-context", &b.name)).icon(widgets::combo_icon).selected_text(label).show_ui(
+ ui,
+ |ui| {
+ changed |= ui.selectable_value(&mut draft.context, None, tr("Default")).changed();
+ for choice in &choices.context {
+ changed |= ui.selectable_value(&mut draft.context, Some(choice.value), tr(&choice.label)).changed();
+ }
+ },
+ );
+ });
+ });
+ if changed {
+ save_tuning = Some(draft.params());
+ }
+ } else {
+ model_options_loading(ui, &b.name);
+ if let Some(error) = &draft.error {
+ ui.add(egui::Label::new(RichText::new(error).color(t.danger)).wrap());
+ if icons::button(ui, "refresh-cw", 24.0, false, "Load model options").clicked() {
+ tune_models.push(b.name.clone());
+ }
+ } else {
+ ui.spinner();
+ }
+ }
+ } else {
+ model_options_loading(ui, &b.name);
+ tune_models.push(b.name.clone());
+ }
+ }
});
});
ui.add_space(6.0);
@@ -513,7 +574,7 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
app.set_agent_program(&name, Some(program));
}
if let Some(name) = pick_agent_model {
- app.pick_agent_model(&name);
+ app.reload_agent_model(&name);
}
if let Some((name, model, thinking)) = chosen_agent_model {
app.set_agent_model(&name, model, thinking);
@@ -528,6 +589,12 @@ fn ai(app: &mut CraftApp, ui: &mut Ui) {
app.model_picker = None;
app.agent_model_picker = None;
}
+ for name in tune_models {
+ app.pick_model_options(&name);
+ }
+ if let Some(params) = save_tuning {
+ app.set_model_options(params);
+ }
if let Some(name) = remove {
ui.data_mut(|d| d.remove::<String>(confirm_id));
app.remove_backend(&name);
@@ -874,6 +941,77 @@ mod tests {
use crate::{Done, builders::AgentModelPicker, demo, jobs::Finished};
use craft_anything_ai::{BackendConfig, BackendKind};
+ #[test]
+ fn identical_model_names_are_shown_once_in_the_shared_picker() {
+ use craft_anything_ai::{AgentModel, BackendEntry, ModelContext};
+ use egui_kittest::{Harness, kittest::Queryable};
+ let context = ModelContext {
+ backend: BackendEntry {
+ config: BackendConfig {
+ name: "Test agent".into(),
+ kind: BackendKind::AgentCli,
+ model: "copilot".into(),
+ base_url: None,
+ ssh_host: None,
+ enabled: true,
+ },
+ options: Default::default(),
+ },
+ directory: None,
+ };
+ let mut picker = AgentModelPicker {
+ request: 1,
+ context,
+ model: None,
+ thinking: None,
+ result: Some(Ok(vec![
+ AgentModel { id: "auto".into(), name: "auto".into(), thinking: Vec::new() },
+ AgentModel { id: "provider/model".into(), name: "Friendly name".into(), thinking: Vec::new() },
+ ])),
+ };
+ let mut harness = Harness::builder().build_ui(move |ui| {
+ theme::install_fonts(ui.ctx());
+ crate::builders::agent_model_picker(ui, &mut picker);
+ });
+ harness.get_by_label("Model").click();
+ harness.run_steps(3);
+ assert!(harness.query_by_label("auto").is_some());
+ assert!(harness.query_by_label("auto · auto").is_none());
+ assert!(harness.query_by_label("Friendly name · provider/model").is_some());
+ }
+
+ #[test]
+ fn shared_picker_warnings_name_the_configured_agent() {
+ use craft_anything_ai::{BackendEntry, ModelContext};
+ use egui_kittest::{Harness, kittest::Queryable};
+ for (agent, name) in [("copilot", "GitHub Copilot"), ("opencode", "OpenCode")] {
+ let context = ModelContext {
+ backend: BackendEntry {
+ config: BackendConfig {
+ name: "Test".into(),
+ kind: BackendKind::AgentCli,
+ model: agent.into(),
+ base_url: None,
+ ssh_host: None,
+ enabled: true,
+ },
+ options: Default::default(),
+ },
+ directory: None,
+ };
+ let mut picker = AgentModelPicker { request: 1, context, model: Some("missing-model".into()), thinking: None, result: Some(Ok(Vec::new())) };
+ let harness = Harness::builder().build_ui(move |ui| {
+ theme::install_fonts(ui.ctx());
+ crate::builders::agent_model_picker(ui, &mut picker);
+ });
+ harness.get_by_label(format!("No chat models are visible in {name}. Check its setup, then reload.").as_str());
+ harness.get_by_label(format!("The saved model is no longer visible. Choose another model or the {name} default.").as_str());
+ if agent == "copilot" {
+ assert!(harness.query_by_label("The saved model is no longer visible. Choose another model or the OpenCode default.").is_none());
+ }
+ }
+ }
+
/// 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() {
@@ -909,3 +1047,147 @@ mod tests {
assert!(app.agent_model_picker.is_none(), "a confirmed settings change still invalidates the picker");
}
}
+
+#[cfg(test)]
+mod model_options_tests {
+ use super::*;
+ use craft_anything_ai::config::{CliContext, CliReasoningEffort};
+ use craft_anything_ai::model_options::{ModelOption, ModelTuning};
+
+ fn app_with_backend() -> CraftApp {
+ let mut app = crate::demo::app(crate::demo::engine(craft_anything_engine::Mode::Beginner, false));
+ app.engine.session().settings.ai = Default::default();
+ app.backends = vec![craft_anything_ai::BackendConfig {
+ name: "Copilot test".into(),
+ kind: BackendKind::AgentCli,
+ model: "copilot".into(),
+ base_url: None,
+ ssh_host: None,
+ enabled: true,
+ }];
+ app
+ }
+
+ fn render(app: &mut CraftApp) -> String {
+ let context = egui::Context::default();
+ crate::theme::install_fonts(&context);
+ let mut output = context.run_ui(egui::RawInput::default(), |ui| ai(app, ui));
+ output.textures_delta.clear();
+ output
+ .shapes
+ .iter()
+ .filter_map(|shape| match &shape.shape {
+ egui::epaint::Shape::Text(text) => Some(text.galley.text().to_string()),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ #[test]
+ fn model_controls_use_shared_thinking_and_separate_context_without_loading_a_cli() {
+ let mut app = app_with_backend();
+ let mut draft = crate::ModelTuningDraft {
+ backend: "Copilot test".into(),
+ cli_model: Some("test-model".into()),
+ choices: None,
+ context: Some(CliContext::Long),
+ saving: false,
+ error: None,
+ };
+ draft.set_choices(ModelTuning {
+ model: "test-model".into(),
+ context: vec![ModelOption { value: CliContext::Long, label: "1M".into(), description: None }],
+ reasoning: vec![ModelOption { value: CliReasoningEffort::High, label: "high".into(), description: None }],
+ });
+ app.model_tuning.insert(draft.backend.clone(), draft);
+ let text = render(&mut app);
+ assert!(text.contains("Context window") && text.contains("Thinking depth") && text.contains("1M") && !text.contains("Reasoning"), "{text}");
+ assert_eq!(app.model_tuning["Copilot test"].params().context, Some(CliContext::Long));
+ }
+
+ #[test]
+ fn model_controls_are_always_visible_and_discovery_is_not_requeued_each_frame() {
+ let mut app = app_with_backend();
+ let text = render(&mut app);
+ assert!(text.contains("Context window") && text.contains("Thinking depth"), "{text}");
+ let jobs = app.jobs.list.len();
+ assert!(app.model_tuning.contains_key("Copilot test"));
+ render(&mut app);
+ assert_eq!(app.jobs.list.len(), jobs);
+ app.model_tuning.get_mut("Copilot test").unwrap().error = Some("Discovery unavailable".into());
+ let text = render(&mut app);
+ assert!(text.contains("Context window") && text.contains("Thinking depth") && text.contains("Discovery unavailable"), "{text}");
+ assert_eq!(app.jobs.list.len(), jobs, "failed discovery waits for an explicit retry");
+ }
+
+ #[test]
+ fn model_option_changes_save_without_closing_the_controls() {
+ let mut app = app_with_backend();
+ app.hub.add_backend(app.backends[0].clone(), None).unwrap();
+ app.backend_options = app.hub.options();
+ let state = crate::ModelTuningDraft {
+ backend: "Copilot test".into(),
+ cli_model: None,
+ choices: None,
+ context: Some(CliContext::Long),
+ saving: false,
+ error: None,
+ };
+ let params = state.params();
+ app.model_tuning.insert(state.backend.clone(), state);
+ app.set_model_options(params);
+ assert!(app.model_tuning["Copilot test"].saving);
+ let started = std::time::Instant::now();
+ while app.model_tuning["Copilot test"].saving && started.elapsed() < std::time::Duration::from_secs(3) {
+ for finished in app.jobs.poll() {
+ app.handle_done(finished);
+ }
+ std::thread::park_timeout(std::time::Duration::from_millis(5));
+ }
+ assert!(!app.model_tuning["Copilot test"].saving);
+ assert_eq!(app.hub.options()["Copilot test"].cli_context, Some(CliContext::Long));
+ assert_eq!(app.backend_options["Copilot test"].cli_thinking, None);
+ }
+
+ #[test]
+ fn choosing_a_model_automatically_repopulates_its_options() {
+ let mut app = app_with_backend();
+ app.hub
+ .add_backend_with(
+ craft_anything_ai::BackendEntry {
+ config: app.backends[0].clone(),
+ options: craft_anything_ai::BackendOptions {
+ cli_model: Some("old-model".into()),
+ command: Some("craft-anything-no-such-test-agent".into()),
+ ..Default::default()
+ },
+ },
+ None,
+ )
+ .unwrap();
+ app.backend_options = app.hub.options();
+ app.model_tuning.insert(
+ "Copilot test".into(),
+ crate::ModelTuningDraft {
+ backend: "Copilot test".into(),
+ cli_model: Some("old-model".into()),
+ choices: None,
+ context: None,
+ saving: false,
+ error: Some("Old choices".into()),
+ },
+ );
+ let mut options = app.backend_options["Copilot test"].clone();
+ options.cli_model = Some("new-model".into());
+ app.hub.add_backend_with(craft_anything_ai::BackendEntry { config: app.backends[0].clone(), options }, None).unwrap();
+ let result = crate::backends(&app.hub);
+ app.handle_done(crate::jobs::Finished { job: 0, result: Ok(result) });
+ assert_eq!(app.backend_options["Copilot test"].cli_model.as_deref(), Some("new-model"));
+ assert!(!app.model_tuning.contains_key("Copilot test"));
+ let text = render(&mut app);
+ assert!(text.contains("new-model") && text.contains("Context window") && text.contains("Thinking depth"), "{text}");
+ assert_eq!(app.model_tuning["Copilot test"].cli_model.as_deref(), Some("new-model"));
+ assert_eq!(app.model_tuning["Copilot test"].error, None);
+ }
+}
diff --git a/crates/ui-egui/src/workbench.rs b/crates/ui-egui/src/workbench.rs
index d24ca533..79021a16 100644
--- a/crates/ui-egui/src/workbench.rs
+++ b/crates/ui-egui/src/workbench.rs
@@ -805,12 +805,27 @@ fn ledger(app: &mut CraftApp, ui: &mut Ui) {
panel_title(ui, "Evidence ledger", Some(app.view.ledger_len));
});
ui.add_space(4.0);
- if app.view.ledger.is_empty() {
+ if app.view.ledger.is_empty() && app.view.findings.is_empty() {
widgets::empty_state(ui, "shield-check", "No evidence yet", "Every finding is saved here with how sure we are.");
return;
}
let mut pick = None;
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
+ if !app.view.findings.is_empty() {
+ panel_title(ui, "findings", Some(app.view.findings.len()));
+ for finding in &app.view.findings {
+ ui.add_space(6.0);
+ ui.label(RichText::new(&finding.id).font(theme::mono(12.0)).color(t.accent));
+ ui.add(egui::Label::new(&finding.statement).wrap());
+ ui.label(RichText::new(finding.confidence.plain_label()).color(t.text_dim).size(theme::CAPTION));
+ for id in &finding.evidence_ids {
+ if widgets::link(ui, id).clicked() {
+ pick = Some(id.clone());
+ }
+ }
+ ui.separator();
+ }
+ }
for e in &app.view.ledger {
let selected = app.state.selected_evidence.as_ref() == Some(&e.id);
if evidence_ui::ledger_row(ui, e, selected) {
@@ -867,7 +882,7 @@ fn status_line(app: &CraftApp, ui: &mut Ui) {
let n = app.jobs.running().filter(|j| j.visible).count();
let text = if n > 0 { crate::i18n::trf("{n} job(s) running", &[("n", &n.to_string())]) } else { tr("Ready") };
ui.label(RichText::new(text).color(t.text_faint).size(theme::CAPTION));
- ui.label(RichText::new(format!("· {} {}", app.view.ledger_len, tr("findings"))).color(t.text_faint).size(theme::CAPTION));
+ ui.label(RichText::new(format!("· {} {}", app.view.findings.len(), tr("findings"))).color(t.text_faint).size(theme::CAPTION));
}
fn bottom(app: &mut CraftApp, ui: &mut Ui) {
@@ -972,6 +987,32 @@ fn log_view(app: &CraftApp, ui: &mut Ui) {
mod tests {
use super::*;
+ #[test]
+ fn recorded_findings_render_even_without_evidence_rows() {
+ let mut app = crate::demo::app(crate::demo::engine(craft_anything_engine::Mode::Beginner, false));
+ app.view.findings = vec![craft_anything_engine::tools::investigation_tools::Finding {
+ id: "fnd_1".into(),
+ statement: "A recorded answer from the shared investigation".into(),
+ evidence_ids: Vec::new(),
+ confidence: craft_anything_engine::evidence::Confidence::Observed,
+ }];
+ app.view.ledger.clear();
+ let context = egui::Context::default();
+ crate::theme::install_fonts(&context);
+ let mut output = context.run_ui(egui::RawInput::default(), |ui| ledger(&mut app, ui));
+ output.textures_delta.clear();
+ let text = output
+ .shapes
+ .iter()
+ .filter_map(|shape| match &shape.shape {
+ egui::epaint::Shape::Text(text) => Some(text.galley.text().to_string()),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(text.contains("fnd_1") && text.contains("A recorded answer"), "{text}");
+ }
+
#[test]
fn rows_are_found_in_common_shapes() {
assert_eq!(rows(&json!([1, 2])).len(), 2);
diff --git a/crates/ui-egui/tests/headless_parity.rs b/crates/ui-egui/tests/headless_parity.rs
index 4f0801b8..31d12d8f 100644
--- a/crates/ui-egui/tests/headless_parity.rs
+++ b/crates/ui-egui/tests/headless_parity.rs
@@ -112,7 +112,10 @@ const ACTIONS: &[Action] = &[
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("reload_agent_model", "reload model-specific thinking choices", Tool(&["ai_models_list"])),
a("set_agent_model", "choose an agent's model and thinking depth", Tool(&["ai_model_set"])),
+ a("pick_model_options", "discover context and reasoning for a model", Tool(&["ai_model_options_show"])),
+ a("set_model_options", "save a model's context and reasoning choices", Tool(&["ai_model_options_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>")),
@@ -137,6 +140,7 @@ const ACTIONS: &[Action] = &[
/// `CraftApp` methods that aren't person-facing actions: callbacks, polling, drawing, helpers.
#[rustfmt::skip]
const PLUMBING: &[(&str, &str)] = &[
+ ("load_agent_model_catalog", "worker dispatch shared by the model picker and its reload action"),
("stuck_banner", "draws what the lock watchdog found; `sync::problems` and its log are the headless side"),
("act", "runs a button's tool on a worker (play, preview, open folder)"),
("waiting_question", "finds the question an answer is for"),
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index d302dae5..df5e7095 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -359,6 +359,26 @@ Owner: maintainers · Status: in progress
### R2.2 More coding agents
Owner: open · Status: in progress
+- [x] GitHub Copilot through its own CLI login and ACP, without credential import:
+ discovery, MCP-only tool restrictions, model selection and fresh read-only questions;
+ unit tests and CLI 1.0.105 with an isolated home and loopback model, all five access modes
+ — claimed: qu-gg, branch `feature/r2.2-copilot-integration` (recorded during PR preparation)
+- [x] Review hardening: cap target handoff at 128 while preserving the active target; propagate
+ context-discovery cancellation, normalize CLI-only efforts for Claude requests, and name
+ the configured agent in shared picker warnings, with focused regressions and translations
+- [x] Local agent chats share a saved investigation and open-target metadata with MCP; background
+ refresh makes recorded findings visible in the workbench Evidence pane. `core_finding_edit`
+ corrects a finding with checked evidence and an optional revision guard, preserving confidence
+ when omitted. Builder refresh failures warn instead of ending the turn; shared ACP errors
+ use the current agent and its sign-in guidance. Engine, process-level MCP and headless
+ rendering tests cover sharing, mode boundaries and finding ids; regressions cover confidence
+ preservation, explicit overrides and agent-specific errors
+- [x] Serialize project-backed investigation load, revision check, mutation and all rendered
+ writes under one bounded, cancellable interprocess lock. Refuse malformed state rather
+ than replacing it; separate-process regressions retain concurrent appends and reject one
+ of two updates based on the same revision
+- [ ] Refresh externally changed investigation/evidence records incrementally, avoiding repeated
+ full reloads under the session lock while retaining mid-turn findings visibility
- [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.
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 5c955ca7..29a1304d 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -15,7 +15,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| 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 | 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 |
+| Engine | 300 engine tools (320 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 |
| German UI | German (`de`, informal "du") in Settings → General → Language; System picks it for a German OS language. The catalog has the same keys as the Chinese ones. Drafted with an AI, not yet reviewed by a native speaker. Requests such as "Ein einfaches Snake-Spiel" or "Eine Website für …" keep their project kind. See [localisation](localization.md). | Catalog and locale tests, key-set comparison with the Chinese catalogs, the isolated language-switch test, a kind-detection test; fmt, clippy, layers, locks and secrets are clean. Not checked: how the German texts look in the running window (length, line breaks), and the `de.tsv` wording by a native speaker. |
| 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 |
@@ -35,6 +35,10 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Generated assets | Off until the person turns them on for a game (the switch on Make and on the project, `project_assets_allow`, `rebuild --generate-assets`, saved in craft.json; turning it on without a fal.ai key asks for one); the brief and the asset tools need both that and a key. `assets_image_generate` (Nano Banana Pro by default) and `assets_model_generate` (picture → Tripo P1 low-poly GLB with a face limit) through the person's key for each asset provider (fal.ai today); per-project budget, $5 by default (`[assets] budget_usd` in config.toml); models and prices from the `assets.toml` table (picture model selectable: Nano Banana Pro, FLUX dev or schnell; priced per picture or per megapixel); every call reports its cost | Unit tests; a live 3D generation with a real key (picture, then model) with FLUX dev; Nano Banana Pro not yet run with a real key |
| Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) |
| Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode, goose, Hermes and Maki in their ACP mode, one agent process per chat or build with our MCP server; Maki's ACP mode takes the backend's model (`cli_model`). In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode). While a saved session loads, replayed updates are withheld from the new turn | Protocol unit tests against scripted agent messages and an approval-policy test. Run live with Maki 0.7.0 only (2026-11-02, Linux, headless CLI): a static page built to Ready in 38 s, a follow-up continued the same session with `session/load`, and with Auto mode off its command and tool requests were refused in an unattended run. Replay suppression passes scripted load-history, success/error and cancellation tests; this correction has not been rerun with a live agent. Turns report 0 tokens over ACP |
+| GitHub Copilot | Installed `copilot` through ACP by default, with CLI-owned login (no credential import), explicit Craft Anything MCP tool allowlist, model selection and fresh read-only build questions. Target handoff retains the last 128 entries with the active target last; context discovery respects tool cancellation and shared picker warnings name the agent | Authenticated builds, model discovery and real-account session resume confirmed by the person using the app. Target-boundary, cancellation and agent-warning regressions supplement unit tests and an offline CLI 1.0.105 compatibility test covering all five access modes. See [copilot.md](copilot.md) |
+| Shared investigation for local agents | A worker saves session-only investigations before starting MCP, shares open targets in a mode-aware handoff, and reloads externally recorded evidence/findings. Builder refresh failures warn rather than ending the turn. The workbench Evidence pane shows `fnd_*` records with proof links; `core_finding_edit` preserves ids and omitted confidence while checking evidence and stale revisions | Engine persistence/correction tests, process-level MCP target tests in both modes, and headless findings-rendering test; live authenticated target-to-finding workflow confirmed by the person using the app |
+| Copilot model options | Shared agent catalogue, model/thinking picker, `cli_model`/`cli_thinking` and `ai_models_list`/`ai_model_set`; selected-model reasoning metadata reloads without a prompt. Context tiers remain separate through `ai_model_options_show`/`ai_model_options_set`, preserving thinking. Legacy reasoning settings remain readable | Isolated catalogue/validation, flags, persistence, stale-result and headless UI tests. Previous authenticated metadata checks used CLI 1.0.105; no new live-account run after the shared-picker rework. Numeric context limits are not advertised in its initial ACP metadata |
+| Investigation writer coordination | Every project-backed mutation holds one OS file lock over load, revision validation, mutation and state/Markdown writes. Waits are bounded and cancellable; unreadable state is not overwritten | Separate-process append/revision-race tests, matching Markdown renders, lock timeout/cancellation/release and malformed-state regressions |
| WASM plugins | With `--features wasm-plugins`: `[[plugins.wasm]]` components exporting `craft-anything:plugin/tools` add tools, and ones exporting `craft-anything:plugin/checks` add checks run after each kind's own (they get the build's file list as JSON) (added, listed, turned on or off and removed in Settings → Plugins or with `plugins_add`/`plugins_remove`/`plugins_list`); no imports, fresh instance per call, fuel and memory limits | Tests with components written in WAT (describe, call, checks, a looping call stopped, imports refused, end to end through the engine); `examples/wasm-plugin-wordcount` built from Rust and loaded |
| WebAssembly tag interfaces | `formats_wasm_compare` resolves retained imported and defined tag exports to their declared parameter types. Identical unresolved or invalid diagnostics may still count as unchanged; those counts do not establish interface compatibility, and invalid/partial limitations remain present | Synthetic core modules with tag changes and re-exports, mixed index spaces, import/tag limits, and missing or non-function type references; formats and engine tests. No real module corpus or WebAssembly execution was used for this correction |
| Questions and approvals | A file inbox per project; `core_person_ask`, `core_action_approve` and MCP consent requests become cards in the app | Cross-handle round-trip tests, a full approval round trip through the engine |
@@ -231,7 +235,10 @@ laptops are covered by unit tests on fake `/sys/class/drm` folders only.
that would ask (an MCP server's tools, in subagents too) unless the person allowed it in Maki's
own permissions. It hasn't been run as a `maki -p` builder here.
- Claude Code is fully wired as a builder; Codex works through its own flags (our tools are pre-approved for
- `codex exec`, see `docs/codex.md`) but is unverified on a real install and doesn't resume; other agent programs get plain text in and out. API-key
+ `codex exec`, see `docs/codex.md`) but is unverified on a real install and doesn't resume;
+ Copilot builds, model discovery and real-account session
+ resume were confirmed by the person using the app. Other agent programs
+ without an adapter get plain text in and out. API-key
backends (Anthropic, OpenRouter, OpenAI, Gemini through a Google AI Studio key, local; Kimi K3.1 Pro through OpenRouter is offered by Detect; a backend chosen as the Extractor takes a Deep-mode game's own files out into `app/Original/` after the study) build with our own loop and the Build tools,
trim and summarise long conversations and keep them in `transcript.json`; no live API build has
been run yet.
diff --git a/docs/copilot.md b/docs/copilot.md
new file mode 100644
index 00000000..5d872496
--- /dev/null
+++ b/docs/copilot.md
@@ -0,0 +1,174 @@
+# GitHub Copilot
+
+Craft Anything can use the installed GitHub Copilot CLI for analysis and building through the
+Agent Client Protocol (ACP).
+
+## Setup
+
+1. Install the standalone Copilot CLI using GitHub's
+ [installation instructions](https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli).
+2. In your own terminal, run `copilot login` and complete GitHub's sign-in flow. The CLI owns
+ authentication, credential storage and refresh. Craft Anything does not read its credential
+ store, collect a Copilot key or provide a login flow. Retry after login; if authentication
+ still fails, restart Craft Anything.
+3. In Settings > AI, detect and add **GitHub Copilot**, then choose it for chat or **Build with this**.
+ If it is installed outside the searched locations, use **Choose...** to select the executable.
+
+The equivalent backend entry in `config.toml` is:
+
+```toml
+[[ai.backends]]
+name = "GitHub Copilot"
+kind = "agent_cli"
+model = "copilot"
+enabled = true
+```
+
+ACP is enabled automatically for this provider. Do not set `acp = false` or an SSH host: those
+configurations are refused rather than falling back to an interactive CLI. Extra `args` are also
+refused because they could override the integration's tool or authentication configuration.
+
+The `model` field identifies the agent. To select a model, use the app's model picker or set
+`cli_model` on the same backend entry. With no override, the app shows **Model default**
+and respects the CLI's own model configuration. The picker offers `auto` and models advertised
+by a fresh ACP session. Model discovery has a deadline and requires the CLI to be ready and
+authenticated. Account entitlement, model access, organization policies and billing remain
+GitHub's responsibility; a Copilot subscription is not an unlimited API allowance.
+
+## Context and Reasoning
+
+Copilot uses the same model and **Thinking depth** picker as OpenCode. In Settings > AI, choose
+**Change...**, select a model and its advertised thinking depth, then **Apply**. Model changes
+reload model-specific metadata on a worker; stale results and unsupported choices are refused.
+The shared catalogue and validated save use `AgentModel`, `ModelContext`, `cli_thinking`,
+`ai_models_list` and `ai_model_set`, rather than a second Copilot model-selection path.
+
+**Context window** remains a separate, always-visible Copilot control. It loads automatically
+and saves immediately, without changing thinking depth. Loading and retryable errors keep the
+control visible. Changing the model clears the old context override.
+
+- **Default** inherits Copilot CLI's own setting. It is not the same as an explicit `none` effort.
+- **Standard** passes `--context default`; **Extended** passes `--context long_context`.
+ Token limits depend on the model. The picker preserves reported window labels when available;
+ CLI 1.0.105 does not advertise numeric window limits in its initial ACP metadata, so this
+ version uses tier labels rather than guessing a token count.
+- Reasoning choices come from the selected model's ACP `reasoning_effort` options. For example,
+ GPT-6 Luna advertised `none`, `low`, `medium`, `high`, `xhigh` and `max` during verification.
+ The CLI accepts a wider overall range, but the picker does not offer levels the model omits.
+ These are named effort levels, not a configurable numeric thinking-token budget.
+
+The saved options are typed backend fields, not unrestricted extra arguments:
+
+```toml
+cli_model = "gpt-6-luna"
+cli_context = "long_context"
+cli_thinking = "xhigh"
+```
+
+Place these on the same backend entry. Older `cli_reasoning_effort` and `effort` settings remain
+fallbacks until the shared model/thinking picker is saved; that save clears the old overrides.
+An explicit `cli_thinking = "none"` is different from omitting `cli_thinking`. GUI changes take
+effect on the next chat turn, or the next build/continue run, not midway through a running turn.
+Model discovery sends no model prompt and runs off the UI thread.
+
+The same capability is available headlessly:
+
+```sh
+craft-anything-cli ai-models-list --name "GitHub Copilot"
+craft-anything-cli ai-model-set --name "GitHub Copilot" --model gpt-6-luna --thinking xhigh
+craft-anything-cli ai-model-options-show --backend "GitHub Copilot"
+craft-anything-cli ai-model-options-set --backend "GitHub Copilot" --expected-cli-model gpt-6-luna --context long_context
+```
+
+The context show tool returns the current `cli_model` and supported choices. Supply that model as
+`expected_cli_model` when saving; a changed model is refused instead of applying stale choices.
+For a backend inheriting the CLI's model, the guard is null. The write tool also accepts null
+context to restore its default. Model and thinking changes go through the shared `ai_model_set`
+validation path; the context-only tool never changes thinking.
+Context-option discovery follows the calling tool's cancellation token, including before the
+CLI starts. Shared picker warnings name the configured agent rather than assuming OpenCode.
+
+## Tools and Permissions
+
+Chat and builds use an explicit allowlist of Craft Anything's built-in engine and AI MCP tools.
+Copilot's native file, shell, web and delegation tools are not exposed. The MCP server enforces
+Clean room or Deep mode, and build tools retain Craft Anything's approval policy and inbox.
+Copilot's built-in MCP servers and custom-instruction loading are disabled for these runs;
+the person's own CLI configuration and credentials are not rewritten.
+
+The adapter passes a session-only `--additional-mcp-config` with the installed
+`craft-anything-cli mcp` command, investigation and inbox. CLI 1.0.105 did not expose the test
+server when it was supplied only through ACP's `session/new`, so both forms are supplied.
+
+Questions about a build start a fresh session, never load or change the builder's session, and
+attach no MCP server. Deep-mode questions can use only `view`, `glob` and `grep`. Clean-room
+questions have no tools. The empty `--available-tools=` value restores the CLI's defaults, so
+the tool-free case instead allowlists `ask_user` and disables it with `--no-ask-user`.
+
+Processes run through the platform supervisor with bounded output and a wall-clock deadline;
+the app's stop action sends ACP cancellation and dropping the conversation terminates its
+process group. Builds preflight the companion CLI before starting. Session loading is used
+only when the agent advertises that capability; failed ACP startup can be retried after login.
+
+## Targets and Findings
+
+Local agent chats use the same saved investigation as the app. If no `.cany` project is open,
+the conversation worker creates one under the app's configuration directory and preserves the
+current evidence, unknowns and investigation memory before starting MCP. Open target metadata
+is handed to the child, keeping at most the last 128 targets with the active target restored
+last, matching the receiver's limit. Deep mode reopens and verifies
+the files; Clean room shares metadata without reading their contents.
+
+At a turn boundary, changing the project, open targets, active target or analysis mode refreshes
+the MCP connection. A saved agent session is carried across only within the same project.
+Tool completion and turn completion reload the shared evidence and findings on a worker; the
+UI renders the cached snapshot without reading files while drawing.
+Rebuild agents receive the same target handoff at startup and refresh their project's shared
+investigation before completed tool and turn events reach the app. A refresh error is logged
+without ending the builder's turn.
+
+The workbench's **Evidence** pane now lists recorded findings (`fnd_1`, `fnd_2`, ...), their
+statements, confidence and links to supporting evidence. These are separate from evidence
+records (`ev_...`). Agents read them with `core_investigation_show`, record a settled answer
+with `core_finding_record`, and correct one with `core_finding_edit`. Corrections keep the id,
+require valid evidence and can refuse a stale `based_on_revision`. Omitting `confidence` keeps
+the existing confidence; supplying it explicitly replaces it.
+
+Every project-backed investigation writer holds the same OS file lock across loading state,
+checking its revision, applying the change and writing structured state plus Markdown renders.
+The wait is cancellable and times out after ten seconds. Concurrent edits based on the same
+revision cannot both succeed; malformed state is refused rather than replaced with an empty
+investigation. The lock is released when its handle closes, including after process exit.
+
+An older MCP process that started without a project may still hold its findings only in memory.
+Before closing that conversation, ask it to export its investigation or a report to a file.
+Those session-only records are not automatically recovered by the new shared-project path.
+
+## Verification and Limits
+
+- Unit tests cover discovery/routing, model settings and catalogue parsing, permissions,
+ session loading, cancellation, external sign-in guidance and refusal of unsafe options.
+- Copilot CLI 1.0.105 was checked with an isolated home, a synthetic MCP server and a fake
+ OpenAI-compatible model on loopback. The model received exactly the allowed tools for
+ analysis, both build modes and both question modes. No real account or hosted model was used.
+- The opt-in compatibility test needs Node.js for its synthetic MCP fixture, not for the
+ application itself. Run it with
+ `cargo test -p craft-anything-ai copilot_cli_enforces_mcp_only_and_empty_tool_filters -- --ignored`.
+- Authenticated builds, account-specific model discovery and real-account session resume were
+ confirmed by the person using the app. GitHub documents ACP as public preview.
+- The target handoff has process-level MCP tests in both modes. Finding correction/persistence
+ has engine tests, and a headless UI test checks that recorded ids and statements render.
+ The live authenticated target-to-finding workflow was confirmed by the person using the app.
+- Separate-process regressions verify concurrent appends, stale revision refusal and matching
+ rendered files. Lock cancellation/timeouts and preservation of malformed state have tests.
+ The shared-picker rework has isolated catalogue, persistence and headless GUI tests; it has
+ not received a new live-account run after this rebase.
+- ACP usage totals are unavailable here. The activity stream says so, and no dollar cost is
+ fabricated. Consult Copilot CLI for usage and billing.
+- Questions use current project context rather than a fork of the builder's conversation.
+ Follow-up notes wait for a turn boundary; Claude Code's mid-tool notes hook has no equivalent
+ in this integration yet.
+- The explicit tool allowlist covers built-in engine and AI tools, not runtime plugin tools.
+ An expansion needs an end-to-end restriction test before those tools are enabled.
+
+Reference: [GitHub's ACP server documentation](https://docs.github.com/en/copilot/reference/copilot-cli-reference/acp-server).
diff --git a/docs/extending.md b/docs/extending.md
index 90ade445..1b337d0a 100644
--- a/docs/extending.md
+++ b/docs/extending.md
@@ -11,7 +11,7 @@ place to add yours. Follow `AGENTS.md` (never crash, layers, external programs t
| A kind of thing to make | `crates/ai/src/rebuild/kinds/` | Implement `TargetKind` (detection score, default stack, brief sections, checks, refine message, the app's words) and `KindRegistry::register` it. |
| A way to judge a build | `crates/ai/src/rebuild/kinds/` | Implement `Check` (`run(&mut CheckCx) -> CheckResult`; `applies` to skip it in some runs, or wrap it in `DeepOnly`); return it from your kind's `checks`. Decide on `passed`/`similarity`, never on text. |
| A stack | `crates/ai/src/rebuild/stacks.toml` | One `[[stack]]` entry: name, the builder's steps, the phrases that ask for it, its engine, the package.json dependencies that show a build uses it. A component or styling library is a `[[library]]` entry (name, phrases, the stacks it works with, steps). |
-| A coding agent | `crates/ai/src/cli_agents/adapters.rs` | Implement `AgentAdapter` (args, required flags, stream parsing, resume, sign-in check) and register it in `AgentAdapters`. Agents it doesn't know run with the plain adapter. An agent that speaks ACP needs only a row in `cli_agents::acp::ACP_AGENTS` (its id and the arguments that start ACP mode); if its ACP mode takes the backend's model, a row in `ACP_MODEL_FLAGS` too. |
+| A coding agent | `crates/ai/src/cli_agents/adapters.rs` | Implement `AgentAdapter` (args, required flags, stream parsing, resume, sign-in check) and register it in `AgentAdapters`. Use `has_model_catalog`, `model_catalog`, `validate_model` and the shared `AgentModel`/`ModelContext` picker and tools for model/thinking selection; set `model_catalog_depends_on_selection` when metadata depends on the selected model. ACP agents also get a row in `cli_agents::acp::ACP_AGENTS`; if their ACP mode takes the backend's model, a row in `ACP_MODEL_FLAGS` too. Override ACP startup options, process setup or `requires_acp` when needed; verify actual tool exposure, not only startup. |
| An asset provider | `crates/engines/src/assets/` | Implement `AssetProvider` (`key_env` names its environment variable); add its models and prices to `assets.toml`. Its key is its own: `assets_key_set` with `provider`, kept as `assets:<id>`. |
| An external engine | `crates/engines/src/table.rs` | One `ExternalEngine` entry (exes, known paths, what it's for, install pins with SHA-256 checked against the publisher), plus a `tool_paths!` id in `settings.rs` if people can point at their own install. |
| A front end for builds | anywhere above L5 | Hold a `rebuild::RunSet` (it queues past its limit) and `poll` it; test it with `RunSet::with_starter(StandIns::starter())`, whose runs report only what the test sends. |
diff --git a/docs/pitfalls.md b/docs/pitfalls.md
index 73f9df14..6f7560fc 100644
--- a/docs/pitfalls.md
+++ b/docs/pitfalls.md
@@ -6,6 +6,11 @@ Keep entries short: what happened, then the rule.
## Git and pull requests
+**Work began before its roadmap claim, on a branch without the required prefix.** Renaming the
+branch and recording the claim during PR preparation fixes coordination going forward, not the
+missed order. Create and publish the claim on a correctly named branch before implementation;
+never describe a late claim as compliance with the claim-before-work rule.
+
**A commit landed on `main` without a PR.** `git switch main && git pull` was run with uncommitted
changes: the switch succeeded, the pull refused, and the failure was read as "still on my branch".
The next commit and `git push --force-with-lease` went to `main`.
@@ -548,6 +553,41 @@ points to as well (`agent-session.jsonl`), tell "not here" apart from a failure
## Agent tooling
+**Shared CLI efforts reached Claude unchanged.** Keep CLI-only levels available for agents, but
+normalize at the provider boundary; test serialized requests for known and unknown model families.
+
+**A sender could exceed its MCP receiver's target limit.** Bound the handoff to the receiver's
+accepted count and retain the active target; test the boundary, truncation order and remote mode.
+
+**A finding correction reset omitted confidence to inferred.** Edit defaults must preserve existing
+values unless explicitly changed; test omitted fields and every supplied confidence level.
+
+**Atomic replacements still lost concurrent investigation updates.** A process-local mutex and
+rename protect neither a cross-process revision check nor the whole read/modify/write sequence.
+Hold one OS file lock from load through every rendered write, use it for all writers, bound and
+cancel the wait, and test with separate processes. Never treat malformed state as an empty update.
+
+**An optional view refresh could fail the builder's turn.** Log cache-refresh errors and continue
+relaying agent events; only failures of the actual build belong on its fatal path.
+
+**Generic ACP errors named Copilot for every adapter.** Use the current agent's display name and
+the adapter's sign-in guidance; test an ACP-only adapter with and without that guidance.
+
+**An agent's findings existed only in its own session.** A separate MCP process started without
+the desktop's targets or a saved project, so its `fnd_*` records never reached the app. Local
+agent chats now attach a shared investigation, hand over target metadata and refresh snapshots
+after tool results. Test the child process's targets and the UI's finding ids, not only tool calls.
+
+**A headless egui check reached rendering and then failed in teardown.** The app's named fonts
+must be installed, and a test without a renderer must explicitly clear `output.textures_delta`.
+Use the repository's `run_ui` API and its font setup instead of assuming an older egui harness.
+
+**An ACP handshake passed while the tools were missing, and an empty tool list enabled them all.**
+Copilot CLI 1.0.105 initialized successfully but did not expose a server supplied only through
+ACP's `session/new`; explicit `--additional-mcp-config` made it available. An empty
+`--available-tools=` restored native tools instead of disabling them. Verify the tools actually
+sent to a fake local model, including the no-tools case, before trusting startup or argument tests.
+
**Shell quoting breaks generated edits.** Heredocs carrying Python with quotes, `'''` or `\n` were
mangled by the shell several times. Write multi-line edit scripts to a file and run the file.
diff --git a/docs/tools.md b/docs/tools.md
index 49a8f612..7468f56c 100644
--- a/docs/tools.md
+++ b/docs/tools.md
@@ -2,9 +2,9 @@
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_*`, `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.
+**300 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)
+## Essentials (`core`, 35)
- `core_target_open`: Open
- `core_target_close`: Close
@@ -31,6 +31,7 @@ Generated by `cargo xtask tools`. Do not edit by hand.
- `core_hypothesis_record`: Record a hypothesis
- `core_hypothesis_update`: Update a hypothesis
- `core_finding_record`: Record a finding
+- `core_finding_edit`: Update a finding
- `core_handoff_write`: Write the handoff
- `core_journal_read`: Read the journal
- `core_report_save`: Save a report