BlueGit

ict rusty-teams

Files

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

invocation.rs

invocation.rs 16.8 KiB Download Raw
1use std::path::{Path, PathBuf};
2
3use crate::action::AgentAction;
4use crate::profile::{AgentProfile, Environment};
5use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
6
7const WSL_PROGRAM: &str = "wsl.exe";
8const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Invocation {
12 pub program: String,
13 pub args: Vec<String>,
14 pub cwd: Option<PathBuf>,
15 pub stdin: Option<String>,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct McpEndpoint {
20 pub url: String,
21 pub token: String,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct RunPlan {
26 pub run: Invocation,
27 pub stop: Option<Invocation>,
28 pub cleanup: Vec<PathBuf>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
32pub enum InvocationError {
33 #[error("the command is empty")]
34 EmptyCommand,
35 #[error(transparent)]
36 UnknownPlaceholder(#[from] UnknownPlaceholder),
37 #[error("cannot write the MCP config: {0}")]
38 McpConfig(String),
39}
40
41fn expand_home(path: &str) -> String {
42 let remainder = match path.strip_prefix('~') {
43 Some(remainder) if remainder.is_empty() || remainder.starts_with(['/', '\\']) => remainder,
44 _ => return path.to_string(),
45 };
46 match std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")) {
47 Ok(home) => format!("{home}{remainder}"),
48 Err(_) => path.to_string(),
49 }
50}
51
52fn mcp_config_json(endpoint: &McpEndpoint) -> String {
53 serde_json::json!({
54 "mcpServers": {
55 "teams": {
56 "type": "http",
57 "url": endpoint.url,
58 "headers": {"Authorization": format!("Bearer {}", endpoint.token)},
59 }
60 }
61 })
62 .to_string()
63}
64
65pub fn wsl_path(path: &str) -> String {
66 let mut characters = path.chars();
67 match (characters.next(), characters.next(), characters.next()) {
68 (Some(drive), Some(':'), Some('/' | '\\')) if drive.is_ascii_alphabetic() => format!(
69 "/mnt/{}/{}",
70 drive.to_ascii_lowercase(),
71 path[3..].replace('\\', "/")
72 ),
73 _ => path.to_string(),
74 }
75}
76
77fn write_mcp_config(
78 directory: &Path,
79 session_id: &str,
80 endpoint: &McpEndpoint,
81) -> Result<PathBuf, InvocationError> {
82 let to_error = |error: std::io::Error| InvocationError::McpConfig(error.to_string());
83 std::fs::create_dir_all(directory).map_err(to_error)?;
84 let path = directory.join(format!("mcp-{session_id}.json"));
85 let mut options = std::fs::OpenOptions::new();
86 options.write(true).create(true).truncate(true);
87 #[cfg(unix)]
88 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
89 let mut file = options.open(&path).map_err(to_error)?;
90 std::io::Write::write_all(&mut file, mcp_config_json(endpoint).as_bytes()).map_err(to_error)?;
91 Ok(path)
92}
93
94fn mcp_config_argument(flag: &str, path: &Path, environment: &Environment) -> String {
95 let text = path.to_string_lossy();
96 let text = match environment {
97 Environment::Wsl { .. } if cfg!(windows) => wsl_path(&text),
98 _ => text.into_owned(),
99 };
100 if flag.ends_with("additional-mcp-config") {
101 format!("@{text}")
102 } else {
103 text
104 }
105}
106
107fn wsl_prefix(environment: &Environment) -> Vec<String> {
108 match environment {
109 Environment::Wsl {
110 distro: Some(distro),
111 } => vec!["-d".to_string(), distro.clone()],
112 _ => Vec::new(),
113 }
114}
115
116fn working_directory(profile: &AgentProfile, action: &AgentAction) -> String {
117 match profile.environment {
118 Environment::Host => expand_home(&action.working_dir),
119 Environment::Wsl { .. } => action.working_dir.clone(),
120 }
121}
122
123pub fn build_invocation(
124 profile: &AgentProfile,
125 action: &AgentAction,
126 prompt: &str,
127 session_id: &str,
128 mcp: Option<&McpEndpoint>,
129 mcp_config_directory: Option<&Path>,
130) -> Result<RunPlan, InvocationError> {
131 let working_dir = working_directory(profile, action);
132 let values = Values {
133 session_id: session_id.to_string(),
134 agent: profile.id.clone(),
135 prompt: prompt.to_string(),
136 cwd: working_dir.clone(),
137 ..Values::default()
138 };
139 let raw_tokens: Vec<String> = split_command(&profile.command)
140 .into_iter()
141 .chain(split_command(&action.extra_args))
142 .collect();
143 if raw_tokens.is_empty() {
144 return Err(InvocationError::EmptyCommand);
145 }
146 let uses_prompt_placeholder = raw_tokens
147 .iter()
148 .any(|token| placeholders_in(token).iter().any(|name| name == "prompt"));
149 let mut tokens = raw_tokens
150 .iter()
151 .map(|token| render(token, &values))
152 .collect::<Result<Vec<_>, _>>()?;
153 let mut cleanup = Vec::new();
154 if let Some(endpoint) = mcp
155 && let Some(directory) = mcp_config_directory
156 && !profile.mcp_config_flag.is_empty()
157 {
158 let path = write_mcp_config(directory, session_id, endpoint)?;
159 tokens.push(profile.mcp_config_flag.clone());
160 tokens.push(mcp_config_argument(
161 &profile.mcp_config_flag,
162 &path,
163 &profile.environment,
164 ));
165 cleanup.push(path);
166 }
167 let stdin = (!uses_prompt_placeholder).then(|| prompt.to_string());
168
169 match &profile.environment {
170 Environment::Host => {
171 let mut tokens = tokens.into_iter();
172 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
173 Ok(RunPlan {
174 run: Invocation {
175 program,
176 args: tokens.collect(),
177 cwd: Some(PathBuf::from(working_dir)),
178 stdin,
179 },
180 stop: None,
181 cleanup,
182 })
183 }
184 Environment::Wsl { .. } => {
185 let mut args = wsl_prefix(&profile.environment);
186 let mut stop_args = args.clone();
187 args.extend(
188 ["-e", "sh", "-lc", WSL_SCRIPT, "sh"]
189 .into_iter()
190 .map(String::from),
191 );
192 args.push(working_dir);
193 args.extend(tokens);
194 stop_args.extend(["-e", "pkill", "-f", session_id].map(String::from));
195 Ok(RunPlan {
196 run: Invocation {
197 program: WSL_PROGRAM.to_string(),
198 args,
199 cwd: None,
200 stdin,
201 },
202 stop: Some(Invocation {
203 program: WSL_PROGRAM.to_string(),
204 args: stop_args,
205 cwd: None,
206 stdin: None,
207 }),
208 cleanup,
209 })
210 }
211 }
212}
213
214pub fn open_session_invocation(
215 profile: &AgentProfile,
216 action: &AgentAction,
217 session_id: &str,
218) -> Result<Invocation, InvocationError> {
219 let values = Values {
220 session_id: session_id.to_string(),
221 agent: profile.id.clone(),
222 cwd: working_directory(profile, action),
223 ..Values::default()
224 };
225 let mut tokens = split_command(&profile.open_session_command)
226 .iter()
227 .map(|token| render(token, &values))
228 .collect::<Result<Vec<_>, _>>()?
229 .into_iter();
230 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
231 Ok(Invocation {
232 program,
233 args: tokens.collect(),
234 cwd: None,
235 stdin: None,
236 })
237}
238
239pub fn version_check_invocation(profile: &AgentProfile) -> Invocation {
240 let program = split_command(&profile.command)
241 .into_iter()
242 .next()
243 .unwrap_or_default();
244 match &profile.environment {
245 Environment::Host => Invocation {
246 program,
247 args: vec!["--version".to_string()],
248 cwd: None,
249 stdin: None,
250 },
251 Environment::Wsl { .. } => {
252 let mut args = wsl_prefix(&profile.environment);
253 args.extend(
254 ["-e", "sh", "-lc", WSL_SCRIPT, "sh", "~"]
255 .into_iter()
256 .map(String::from),
257 );
258 args.push(program);
259 args.push("--version".to_string());
260 Invocation {
261 program: WSL_PROGRAM.to_string(),
262 args,
263 cwd: None,
264 stdin: None,
265 }
266 }
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 #[test]
275 fn wsl_invocation_has_exact_args() {
276 let mut profile = AgentProfile::claude_wsl();
277 profile.environment = Environment::Wsl {
278 distro: Some("Ubuntu".to_string()),
279 };
280 let action = AgentAction::answer_this("claude");
281 let plan = build_invocation(&profile, &action, "hi there", "sid-1", None, None).unwrap();
282 let expected_args: Vec<String> = [
283 "-d",
284 "Ubuntu",
285 "-e",
286 "sh",
287 "-lc",
288 WSL_SCRIPT,
289 "sh",
290 "~",
291 "claude",
292 "-p",
293 "--output-format",
294 "stream-json",
295 "--verbose",
296 "--session-id",
297 "sid-1",
298 "--allowedTools",
299 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
300 ]
301 .map(String::from)
302 .to_vec();
303 assert_eq!(plan.run.program, "wsl.exe");
304 assert_eq!(plan.run.args, expected_args);
305 assert_eq!(plan.run.cwd, None);
306 assert_eq!(plan.run.stdin.as_deref(), Some("hi there"));
307 let stop = plan.stop.unwrap();
308 assert_eq!(stop.program, "wsl.exe");
309 assert_eq!(
310 stop.args,
311 ["-d", "Ubuntu", "-e", "pkill", "-f", "sid-1"].map(String::from)
312 );
313 }
314
315 #[test]
316 fn prompt_placeholder_goes_in_args_without_stdin() {
317 let profile = AgentProfile::copilot_wsl();
318 let action = AgentAction::answer_this("copilot");
319 let plan = build_invocation(&profile, &action, "a b\nc", "sid-2", None, None).unwrap();
320 assert_eq!(plan.run.stdin, None);
321 assert_eq!(plan.run.args[..2], ["-e".to_string(), "sh".to_string()]);
322 let prompt_position = plan.run.args.iter().position(|arg| arg == "-p").unwrap() + 1;
323 assert_eq!(plan.run.args[prompt_position], "a b\nc");
324 }
325
326 #[test]
327 fn host_invocation_expands_home() {
328 let mut action = AgentAction::build_this("claude-host");
329 action.working_dir = "~/work".to_string();
330 let plan = build_invocation(
331 &AgentProfile::claude_host(),
332 &action,
333 "p",
334 "sid-3",
335 None,
336 None,
337 )
338 .unwrap();
339 let home = std::env::var("HOME")
340 .or_else(|_| std::env::var("USERPROFILE"))
341 .unwrap();
342 assert_eq!(plan.run.program, "claude");
343 assert_eq!(plan.run.cwd, Some(PathBuf::from(format!("{home}/work"))));
344 assert_eq!(plan.run.stdin.as_deref(), Some("p"));
345 assert!(
346 plan.run
347 .args
348 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
349 );
350 assert_eq!(plan.stop, None);
351 }
352
353 fn endpoint() -> McpEndpoint {
354 McpEndpoint {
355 url: "http://127.0.0.1:9/mcp".to_string(),
356 token: "tok".to_string(),
357 }
358 }
359
360 #[test]
361 fn mcp_endpoint_writes_a_config_file_and_passes_its_path() {
362 let directory = tempfile::tempdir().unwrap();
363 let action = AgentAction::answer_this("claude");
364 let plan = build_invocation(
365 &AgentProfile::claude_host(),
366 &action,
367 "p",
368 "sid",
369 Some(&endpoint()),
370 Some(directory.path()),
371 )
372 .unwrap();
373 let flag_position = plan
374 .run
375 .args
376 .iter()
377 .position(|arg| arg == "--mcp-config")
378 .unwrap();
379 let expected_path = directory.path().join("mcp-sid.json");
380 assert_eq!(
381 plan.run.args[flag_position + 1],
382 expected_path.to_string_lossy()
383 );
384 assert_eq!(plan.cleanup, vec![expected_path.clone()]);
385 assert!(!plan.run.args.iter().any(|arg| arg.contains("tok")));
386 let json: serde_json::Value =
387 serde_json::from_str(&std::fs::read_to_string(&expected_path).unwrap()).unwrap();
388 let server = &json["mcpServers"]["teams"];
389 assert_eq!(server["type"], "http");
390 assert_eq!(server["url"], "http://127.0.0.1:9/mcp");
391 assert_eq!(server["headers"]["Authorization"], "Bearer tok");
392 #[cfg(unix)]
393 assert_eq!(
394 std::os::unix::fs::PermissionsExt::mode(
395 &std::fs::metadata(&expected_path).unwrap().permissions()
396 ) & 0o777,
397 0o600
398 );
399 }
400
401 #[test]
402 fn mcp_flag_is_omitted_without_endpoint_or_directory() {
403 let directory = tempfile::tempdir().unwrap();
404 let action = AgentAction::answer_this("claude");
405 let profile = AgentProfile::claude_host();
406 let without_endpoint =
407 build_invocation(&profile, &action, "p", "sid", None, Some(directory.path())).unwrap();
408 assert!(
409 !without_endpoint
410 .run
411 .args
412 .iter()
413 .any(|arg| arg == "--mcp-config")
414 );
415 let without_directory =
416 build_invocation(&profile, &action, "p", "sid", Some(&endpoint()), None).unwrap();
417 assert!(
418 !without_directory
419 .run
420 .args
421 .iter()
422 .any(|arg| arg == "--mcp-config")
423 );
424 assert!(without_directory.cleanup.is_empty());
425 }
426
427 #[test]
428 fn copilot_takes_the_config_path_with_an_at_prefix() {
429 let directory = tempfile::tempdir().unwrap();
430 let action = AgentAction::answer_this("copilot");
431 let plan = build_invocation(
432 &AgentProfile::copilot_wsl(),
433 &action,
434 "p",
435 "sid",
436 Some(&endpoint()),
437 Some(directory.path()),
438 )
439 .unwrap();
440 let flag_position = plan
441 .run
442 .args
443 .iter()
444 .position(|arg| arg == "--additional-mcp-config")
445 .unwrap();
446 assert_eq!(
447 plan.run.args[flag_position + 1],
448 format!(
449 "@{}",
450 directory.path().join("mcp-sid.json").to_string_lossy()
451 )
452 );
453 }
454
455 #[test]
456 fn windows_paths_translate_to_the_wsl_mount() {
457 assert_eq!(
458 wsl_path(r"C:\Users\x\AppData\mcp-1.json"),
459 "/mnt/c/Users/x/AppData/mcp-1.json"
460 );
461 assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json");
462 assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json");
463 assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json");
464 }
465
466 #[test]
467 fn agent_placeholder_renders_profile_id() {
468 let mut profile = AgentProfile::claude_host();
469 profile.command = "tool --agent {agent}".to_string();
470 let mut action = AgentAction::build_this("x");
471 action.extra_args = String::new();
472 let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap();
473 assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from));
474 }
475
476 #[test]
477 fn empty_command_is_an_error() {
478 let mut profile = AgentProfile::claude_host();
479 profile.command = String::new();
480 let mut action = AgentAction::build_this("x");
481 action.extra_args = String::new();
482 assert_eq!(
483 build_invocation(&profile, &action, "p", "s", None, None),
484 Err(InvocationError::EmptyCommand)
485 );
486 }
487
488 #[test]
489 fn open_session_renders_cwd_and_session() {
490 let action = AgentAction::build_this("claude");
491 let invocation =
492 open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap();
493 assert_eq!(invocation.program, "wt.exe");
494 assert_eq!(
495 invocation.args,
496 ["wsl.exe", "--cd", "~", "-e", "claude", "--resume", "sid-4"].map(String::from)
497 );
498 }
499
500 #[test]
501 fn version_check_runs_the_first_token_in_the_same_environment() {
502 let host = version_check_invocation(&AgentProfile::claude_host());
503 assert_eq!(host.program, "claude");
504 assert_eq!(host.args, ["--version"].map(String::from));
505 let mut wsl_profile = AgentProfile::claude_wsl();
506 wsl_profile.environment = Environment::Wsl {
507 distro: Some("Ubuntu".to_string()),
508 };
509 let wsl = version_check_invocation(&wsl_profile);
510 assert_eq!(wsl.program, "wsl.exe");
511 assert_eq!(
512 wsl.args,
513 [
514 "-d",
515 "Ubuntu",
516 "-e",
517 "sh",
518 "-lc",
519 WSL_SCRIPT,
520 "sh",
521 "~",
522 "claude",
523 "--version"
524 ]
525 .map(String::from)
526 );
527 }
528}