BlueGit

ict rusty-teams

Files

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

settings.rs

settings.rs 8.1 KiB Download Raw
1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::action::AgentAction;
6use crate::profile::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}
24
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(default)]
27pub struct AgentSettings {
28 pub agents: Vec<AgentProfile>,
29 pub actions: Vec<AgentAction>,
30 pub resume_interrupted_runs: bool,
31 pub recent_working_dirs: HashMap<String, Vec<String>>,
32}
33
34impl Default for AgentSettings {
35 fn default() -> Self {
36 Self {
37 agents: vec![AgentProfile::claude_wsl(), AgentProfile::copilot_wsl()],
38 actions: vec![
39 AgentAction::answer_this("claude"),
40 AgentAction::build_this("claude"),
41 ],
42 resume_interrupted_runs: true,
43 recent_working_dirs: HashMap::new(),
44 }
45 }
46}
47
48fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec<SettingsProblem>) {
49 for text in texts {
50 for placeholder in placeholders_in(text) {
51 if !is_known_placeholder(&placeholder) {
52 problems.push(SettingsProblem::UnknownPlaceholder {
53 item_id: item_id.to_string(),
54 placeholder,
55 });
56 }
57 }
58 }
59}
60
61impl AgentSettings {
62 pub fn to_json(&self) -> String {
63 serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
64 }
65
66 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
67 let mut settings: Self = serde_json::from_str(json)?;
68 for agent in &mut settings.agents {
69 agent.migrate_open_session_command();
70 }
71 Ok(settings)
72 }
73
74 pub fn recent_working_dirs_of(&self, agent_id: &str) -> &[String] {
75 self.recent_working_dirs
76 .get(agent_id)
77 .map_or(&[], Vec::as_slice)
78 }
79
80 pub fn remember_working_dir(&mut self, agent_id: &str, working_dir: &str) {
81 let recent = self
82 .recent_working_dirs
83 .entry(agent_id.to_owned())
84 .or_default();
85 recent.retain(|existing| existing != working_dir);
86 recent.insert(0, working_dir.to_owned());
87 recent.truncate(RECENT_WORKING_DIR_LIMIT);
88 }
89
90 pub fn validate(&self) -> Vec<SettingsProblem> {
91 let mut problems = Vec::new();
92 for agent in &self.agents {
93 if agent.command.trim().is_empty() {
94 problems.push(SettingsProblem::EmptyCommand {
95 agent_id: agent.id.clone(),
96 });
97 }
98 check_placeholders(
99 &agent.id,
100 &[&agent.command, &agent.open_session_command],
101 &mut problems,
102 );
103 }
104 for action in &self.actions {
105 if !self.agents.iter().any(|agent| agent.id == action.agent_id) {
106 problems.push(SettingsProblem::UnknownAgent {
107 action_id: action.id.clone(),
108 agent_id: action.agent_id.clone(),
109 });
110 }
111 check_placeholders(
112 &action.id,
113 &[&action.prompt_template, &action.extra_args],
114 &mut problems,
115 );
116 }
117 problems
118 }
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
126 fn default_round_trips_and_is_valid() {
127 let settings = AgentSettings::default();
128 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
129 assert_eq!(loaded, settings);
130 assert!(settings.validate().is_empty());
131 }
132
133 #[test]
134 fn from_json_migrates_legacy_wsl_open_session_commands_only() {
135 let legacy = AgentSettings::from_json(&format!(
136 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}}"}}]}}"#,
137 crate::profile::LEGACY_CLAUDE_WSL_OPEN_SESSION,
138 crate::profile::LEGACY_COPILOT_WSL_OPEN_SESSION,
139 ))
140 .unwrap();
141 assert_eq!(
142 legacy.agents[0].open_session_command,
143 AgentProfile::claude_wsl().open_session_command
144 );
145 assert_eq!(
146 legacy.agents[1].open_session_command,
147 AgentProfile::copilot_wsl().open_session_command
148 );
149 assert_eq!(
150 legacy.agents[2].open_session_command,
151 "wt.exe wsl.exe -e claude --resume {session_id}"
152 );
153 }
154
155 #[test]
156 fn recent_working_dirs_are_newest_first_deduped_limited_and_per_agent() {
157 let mut settings = AgentSettings::default();
158 assert!(settings.recent_working_dirs_of("claude").is_empty());
159 for index in 0..7 {
160 settings.remember_working_dir("claude", &format!("/repo/{index}"));
161 }
162 settings.remember_working_dir("claude", "/repo/4");
163 settings.remember_working_dir("copilot", "/other");
164 assert_eq!(
165 settings.recent_working_dirs_of("claude"),
166 ["/repo/4", "/repo/6", "/repo/5", "/repo/3", "/repo/2"]
167 );
168 assert_eq!(settings.recent_working_dirs_of("copilot"), ["/other"]);
169 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
170 assert_eq!(loaded, settings);
171 assert!(
172 AgentSettings::from_json("{}")
173 .unwrap()
174 .recent_working_dirs
175 .is_empty()
176 );
177 }
178
179 #[test]
180 fn empty_object_loads_defaults() {
181 assert_eq!(
182 AgentSettings::from_json("{}").unwrap(),
183 AgentSettings::default()
184 );
185 }
186
187 #[test]
188 fn resume_defaults_on_and_can_be_switched_off() {
189 assert!(
190 AgentSettings::from_json("{}")
191 .unwrap()
192 .resume_interrupted_runs
193 );
194 let off = AgentSettings::from_json(r#"{"resume_interrupted_runs":false}"#).unwrap();
195 assert!(!off.resume_interrupted_runs);
196 }
197
198 #[test]
199 fn partial_json_fills_missing_fields() {
200 let loaded = AgentSettings::from_json(
201 r#"{"agents":[{"id":"x","command":"x {session_id}"}],"actions":[{"id":"a","agent_id":"x"}]}"#,
202 )
203 .unwrap();
204 assert_eq!(loaded.agents.len(), 1);
205 assert_eq!(
206 loaded.agents[0].output,
207 crate::OutputFormat::ClaudeStreamJson
208 );
209 assert_eq!(loaded.actions[0].working_dir, "");
210 let only_actions = AgentSettings::from_json(r#"{"actions":[]}"#).unwrap();
211 assert_eq!(only_actions.agents.len(), 2);
212 }
213
214 #[test]
215 fn validate_finds_problems() {
216 let mut settings = AgentSettings::default();
217 settings.actions[0].agent_id = "ghost".to_string();
218 settings.agents[1].command = String::new();
219 settings.agents[0].command.push_str(" {bogus}");
220 settings.actions[1].prompt_template.push_str(" {nope}");
221 let problems = settings.validate();
222 assert!(problems.contains(&SettingsProblem::UnknownAgent {
223 action_id: "answer-this".to_string(),
224 agent_id: "ghost".to_string(),
225 }));
226 assert!(problems.contains(&SettingsProblem::EmptyCommand {
227 agent_id: "copilot".to_string(),
228 }));
229 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
230 item_id: "claude".to_string(),
231 placeholder: "bogus".to_string(),
232 }));
233 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
234 item_id: "build-this".to_string(),
235 placeholder: "nope".to_string(),
236 }));
237 }
238}