BlueGit

ict rusty-teams

Files

rusty-teams / crates / agents / src / settings.rs

settings.rs

settings.rs 11.1 KiB Download Raw
1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::action::AgentAction;
6use crate::profile::{AgentBackend, AgentProfile};
7use crate::template::{is_known_placeholder, placeholders_in};
8
9pub const SETTINGS_KEY: &str = "agents.settings";
10pub const RECENT_WORKING_DIR_LIMIT: usize = 5;
11
12#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
13pub enum SettingsProblem {
14 #[error("action {action_id} references unknown agent {agent_id}")]
15 UnknownAgent { action_id: String, agent_id: String },
16 #[error("agent {agent_id} has an empty command")]
17 EmptyCommand { agent_id: String },
18 #[error("{item_id} uses unknown placeholder {{{placeholder}}}")]
19 UnknownPlaceholder {
20 item_id: String,
21 placeholder: String,
22 },
23 #[error("agent {agent_id} has an empty model")]
24 EmptyModel { agent_id: String },
25}
26
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(default)]
29pub struct AgentSettings {
30 pub agents: Vec<AgentProfile>,
31 pub actions: Vec<AgentAction>,
32 pub resume_interrupted_runs: bool,
33 pub recent_working_dirs: HashMap<String, Vec<String>>,
34 /// Empty means Microsoft Copilot. Otherwise the id of a chat profile.
35 pub write_with: String,
36}
37
38impl Default for AgentSettings {
39 fn default() -> Self {
40 Self {
41 agents: vec![AgentProfile::claude_wsl(), AgentProfile::copilot_wsl()],
42 actions: vec![
43 AgentAction::answer_this("claude"),
44 AgentAction::build_this("claude"),
45 ],
46 resume_interrupted_runs: true,
47 recent_working_dirs: HashMap::new(),
48 write_with: String::new(),
49 }
50 }
51}
52
53fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec<SettingsProblem>) {
54 for text in texts {
55 for placeholder in placeholders_in(text) {
56 if !is_known_placeholder(&placeholder) {
57 problems.push(SettingsProblem::UnknownPlaceholder {
58 item_id: item_id.to_string(),
59 placeholder,
60 });
61 }
62 }
63 }
64}
65
66impl AgentSettings {
67 /// Chat profile chosen under «Write with», or `None` for Microsoft Copilot.
68 pub fn write_with_profile(&self) -> Option<&AgentProfile> {
69 if self.write_with.is_empty() {
70 return None;
71 }
72 self.agents
73 .iter()
74 .find(|agent| agent.id == self.write_with && agent.is_chat())
75 }
76
77 pub fn to_json(&self) -> String {
78 serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
79 }
80
81 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
82 let mut settings: Self = serde_json::from_str(json)?;
83 for agent in &mut settings.agents {
84 agent.migrate_open_session_command();
85 }
86 Ok(settings)
87 }
88
89 pub fn recent_working_dirs_of(&self, agent_id: &str) -> &[String] {
90 self.recent_working_dirs
91 .get(agent_id)
92 .map_or(&[], Vec::as_slice)
93 }
94
95 pub fn remember_working_dir(&mut self, agent_id: &str, working_dir: &str) {
96 let recent = self
97 .recent_working_dirs
98 .entry(agent_id.to_owned())
99 .or_default();
100 recent.retain(|existing| existing != working_dir);
101 recent.insert(0, working_dir.to_owned());
102 recent.truncate(RECENT_WORKING_DIR_LIMIT);
103 }
104
105 pub fn validate(&self) -> Vec<SettingsProblem> {
106 let mut problems = Vec::new();
107 for agent in &self.agents {
108 if agent.is_command() && agent.command.trim().is_empty() {
109 problems.push(SettingsProblem::EmptyCommand {
110 agent_id: agent.id.clone(),
111 });
112 }
113 let model = match &agent.backend {
114 AgentBackend::OpenAi { model, .. } | AgentBackend::Anthropic { model, .. } => {
115 model.as_str()
116 }
117 AgentBackend::Command => "",
118 };
119 if agent.is_chat() && model.trim().is_empty() {
120 problems.push(SettingsProblem::EmptyModel {
121 agent_id: agent.id.clone(),
122 });
123 }
124 check_placeholders(
125 &agent.id,
126 &[&agent.command, &agent.open_session_command],
127 &mut problems,
128 );
129 }
130 for action in &self.actions {
131 if !self.agents.iter().any(|agent| agent.id == action.agent_id) {
132 problems.push(SettingsProblem::UnknownAgent {
133 action_id: action.id.clone(),
134 agent_id: action.agent_id.clone(),
135 });
136 }
137 check_placeholders(
138 &action.id,
139 &[&action.prompt_template, &action.extra_args],
140 &mut problems,
141 );
142 }
143 problems
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150
151 #[test]
152 fn default_round_trips_and_is_valid() {
153 let settings = AgentSettings::default();
154 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
155 assert_eq!(loaded, settings);
156 assert!(settings.validate().is_empty());
157 }
158
159 #[test]
160 fn from_json_migrates_legacy_wsl_open_session_commands_only() {
161 let legacy = AgentSettings::from_json(&format!(
162 r#"{{"agents":[{{"id":"claude","open_session_command":"{}"}},{{"id":"copilot","open_session_command":"{}"}},{{"id":"mine","open_session_command":"wt.exe wsl.exe -e claude --resume {{session_id}}"}}]}}"#,
163 crate::profile::LEGACY_CLAUDE_WSL_OPEN_SESSION,
164 crate::profile::LEGACY_COPILOT_WSL_OPEN_SESSION,
165 ))
166 .unwrap();
167 assert_eq!(
168 legacy.agents[0].open_session_command,
169 AgentProfile::claude_wsl().open_session_command
170 );
171 assert_eq!(
172 legacy.agents[1].open_session_command,
173 AgentProfile::copilot_wsl().open_session_command
174 );
175 assert_eq!(
176 legacy.agents[2].open_session_command,
177 "wt.exe wsl.exe -e claude --resume {session_id}"
178 );
179 }
180
181 #[test]
182 fn recent_working_dirs_are_newest_first_deduped_limited_and_per_agent() {
183 let mut settings = AgentSettings::default();
184 assert!(settings.recent_working_dirs_of("claude").is_empty());
185 for index in 0..7 {
186 settings.remember_working_dir("claude", &format!("/repo/{index}"));
187 }
188 settings.remember_working_dir("claude", "/repo/4");
189 settings.remember_working_dir("copilot", "/other");
190 assert_eq!(
191 settings.recent_working_dirs_of("claude"),
192 ["/repo/4", "/repo/6", "/repo/5", "/repo/3", "/repo/2"]
193 );
194 assert_eq!(settings.recent_working_dirs_of("copilot"), ["/other"]);
195 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
196 assert_eq!(loaded, settings);
197 assert!(
198 AgentSettings::from_json("{}")
199 .unwrap()
200 .recent_working_dirs
201 .is_empty()
202 );
203 }
204
205 #[test]
206 fn empty_object_loads_defaults() {
207 assert_eq!(
208 AgentSettings::from_json("{}").unwrap(),
209 AgentSettings::default()
210 );
211 }
212
213 #[test]
214 fn resume_defaults_on_and_can_be_switched_off() {
215 assert!(
216 AgentSettings::from_json("{}")
217 .unwrap()
218 .resume_interrupted_runs
219 );
220 let off = AgentSettings::from_json(r#"{"resume_interrupted_runs":false}"#).unwrap();
221 assert!(!off.resume_interrupted_runs);
222 }
223
224 #[test]
225 fn partial_json_fills_missing_fields() {
226 let loaded = AgentSettings::from_json(
227 r#"{"agents":[{"id":"x","command":"x {session_id}"}],"actions":[{"id":"a","agent_id":"x"}]}"#,
228 )
229 .unwrap();
230 assert_eq!(loaded.agents.len(), 1);
231 assert_eq!(
232 loaded.agents[0].output,
233 crate::OutputFormat::ClaudeStreamJson
234 );
235 assert_eq!(loaded.actions[0].working_dir, "");
236 let only_actions = AgentSettings::from_json(r#"{"actions":[]}"#).unwrap();
237 assert_eq!(only_actions.agents.len(), 2);
238 }
239
240 #[test]
241 fn validate_finds_problems() {
242 let mut settings = AgentSettings::default();
243 settings.actions[0].agent_id = "ghost".to_string();
244 settings.agents[1].command = String::new();
245 settings.agents[0].command.push_str(" {bogus}");
246 settings.actions[1].prompt_template.push_str(" {nope}");
247 let problems = settings.validate();
248 assert!(problems.contains(&SettingsProblem::UnknownAgent {
249 action_id: "answer-this".to_string(),
250 agent_id: "ghost".to_string(),
251 }));
252 assert!(problems.contains(&SettingsProblem::EmptyCommand {
253 agent_id: "copilot".to_string(),
254 }));
255 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
256 item_id: "claude".to_string(),
257 placeholder: "bogus".to_string(),
258 }));
259 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
260 item_id: "build-this".to_string(),
261 placeholder: "nope".to_string(),
262 }));
263 }
264
265 #[test]
266 fn a_profile_without_backend_stays_a_command() {
267 let loaded = AgentSettings::from_json(
268 r#"{"agents":[{"id":"legacy","name":"Legacy","command":"claude -p"}]}"#,
269 )
270 .unwrap();
271 assert!(loaded.agents[0].is_command());
272 assert!(loaded.write_with.is_empty());
273 }
274
275 #[test]
276 fn chat_profiles_need_a_model_and_write_with_round_trips() {
277 let mut settings = AgentSettings::default();
278 settings.agents.push(AgentProfile::ollama());
279 assert!(settings.validate().contains(&SettingsProblem::EmptyModel {
280 agent_id: "ollama".to_string(),
281 }));
282 settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {
283 base_url: "http://127.0.0.1:11434/v1".to_owned(),
284 model: "qwen3.5:9b".to_owned(),
285 api_key: String::new(),
286 };
287 settings.write_with = "ollama".to_owned();
288 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
289 assert_eq!(loaded.write_with, "ollama");
290 assert!(loaded.validate().is_empty());
291 }
292
293 #[test]
294 fn write_with_profile_is_none_for_microsoft_and_missing_ids() {
295 let mut settings = AgentSettings::default();
296 assert!(settings.write_with_profile().is_none());
297 settings.write_with = "missing".to_owned();
298 assert!(settings.write_with_profile().is_none());
299 settings.agents.push(AgentProfile::ollama());
300 settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi {
301 base_url: "http://127.0.0.1:11434/v1".to_owned(),
302 model: "qwen3.5:9b".to_owned(),
303 api_key: String::new(),
304 };
305 settings.write_with = "ollama".to_owned();
306 assert_eq!(
307 settings
308 .write_with_profile()
309 .map(|profile| profile.name.as_str()),
310 Some("Ollama")
311 );
312 settings.write_with = "claude".to_owned();
313 assert!(settings.write_with_profile().is_none());
314 }
315}