BlueGit

ict rusty-teams

Files

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

invocation.rs

invocation.rs 30.0 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 APP_STOP_SCRIPT: &str = r#"for p in $(pgrep -f -- "$1"); do c=$(tr '\0' ' ' </proc/$p/cmdline 2>/dev/null) || continue; case "$c" in *app-stop-marker*) continue;; esac; case "$c" in *" -p "*|*" --print "*) ;; *) continue;; esac; case "$c" in *--output-format*) ;; *) continue;; esac; case "$c" in *"--session-id $1 "*) kill -9 "$p";; *"--resume $1 "*) case "$c" in *--fork-session*) ;; *) kill -9 "$p";; esac;; esac; done"#;
9const SESSION_FLAG: &str = "--session-id {session_id}";
10const RESUME_FLAG: &str = "--resume {session_id}";
11const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;
12
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Invocation {
15 pub program: String,
16 pub args: Vec<String>,
17 pub cwd: Option<PathBuf>,
18 pub stdin: Option<String>,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct McpEndpoint {
23 pub url: String,
24 pub token: String,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct RunPlan {
29 pub run: Invocation,
30 pub stop: Option<Invocation>,
31 pub cleanup: Vec<PathBuf>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
35pub enum InvocationError {
36 #[error("the command is empty")]
37 EmptyCommand,
38 #[error(transparent)]
39 UnknownPlaceholder(#[from] UnknownPlaceholder),
40 #[error("cannot write the MCP config: {0}")]
41 McpConfig(String),
42 #[error("the agent command has no \"{SESSION_FLAG}\" to resume with")]
43 CannotResume,
44 #[error("the session id is not valid")]
45 InvalidSessionId,
46}
47
48fn expand_home(path: &str) -> String {
49 let remainder = match path.strip_prefix('~') {
50 Some(remainder) if remainder.is_empty() || remainder.starts_with(['/', '\\']) => remainder,
51 _ => return path.to_string(),
52 };
53 match std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")) {
54 Ok(home) => format!("{home}{remainder}"),
55 Err(_) => path.to_string(),
56 }
57}
58
59fn mcp_config_json(endpoint: &McpEndpoint) -> String {
60 serde_json::json!({
61 "mcpServers": {
62 "teams": {
63 "type": "http",
64 "url": endpoint.url,
65 "headers": {"Authorization": format!("Bearer {}", endpoint.token)},
66 }
67 }
68 })
69 .to_string()
70}
71
72fn wsl_unc_rest(path: &str) -> Option<&str> {
73 path.strip_prefix(r"\\wsl.localhost\")
74 .or_else(|| path.strip_prefix(r"\\wsl$\"))
75}
76
77pub fn wsl_unc_distro(path: &str) -> Option<&str> {
78 wsl_unc_rest(path).map(|rest| rest.split('\\').next().unwrap_or(rest))
79}
80
81pub fn linux_path(path: &str) -> String {
82 match wsl_unc_rest(path) {
83 Some(rest) => match rest.split_once('\\') {
84 Some((_, relative)) => format!("/{}", relative.replace('\\', "/")),
85 None => "/".to_owned(),
86 },
87 None => wsl_path(path),
88 }
89}
90
91pub fn wsl_path(path: &str) -> String {
92 let mut characters = path.chars();
93 match (characters.next(), characters.next(), characters.next()) {
94 (Some(drive), Some(':'), Some('/' | '\\')) if drive.is_ascii_alphabetic() => format!(
95 "/mnt/{}/{}",
96 drive.to_ascii_lowercase(),
97 path[3..].replace('\\', "/")
98 ),
99 _ => path.to_string(),
100 }
101}
102
103fn write_mcp_config(
104 directory: &Path,
105 session_id: &str,
106 endpoint: &McpEndpoint,
107) -> Result<PathBuf, InvocationError> {
108 let to_error = |error: std::io::Error| InvocationError::McpConfig(error.to_string());
109 std::fs::create_dir_all(directory).map_err(to_error)?;
110 let path = directory.join(format!("mcp-{session_id}.json"));
111 let mut options = std::fs::OpenOptions::new();
112 options.write(true).create(true).truncate(true);
113 #[cfg(unix)]
114 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
115 let mut file = options.open(&path).map_err(to_error)?;
116 std::io::Write::write_all(&mut file, mcp_config_json(endpoint).as_bytes()).map_err(to_error)?;
117 Ok(path)
118}
119
120fn mcp_config_argument(flag: &str, path: &Path, environment: &Environment) -> String {
121 let text = path.to_string_lossy();
122 let text = match environment {
123 Environment::Wsl { .. } if cfg!(windows) => wsl_path(&text),
124 _ => text.into_owned(),
125 };
126 if flag.ends_with("additional-mcp-config") {
127 format!("@{text}")
128 } else {
129 text
130 }
131}
132
133fn wsl_prefix(environment: &Environment) -> Vec<String> {
134 match environment {
135 Environment::Wsl {
136 distro: Some(distro),
137 } => vec!["-d".to_string(), distro.clone()],
138 _ => Vec::new(),
139 }
140}
141
142fn working_directory(profile: &AgentProfile, action: &AgentAction) -> String {
143 match profile.environment {
144 Environment::Host => expand_home(&action.working_dir),
145 Environment::Wsl { .. } => action.working_dir.clone(),
146 }
147}
148
149pub fn build_invocation(
150 profile: &AgentProfile,
151 action: &AgentAction,
152 prompt: &str,
153 session_id: &str,
154 mcp: Option<&McpEndpoint>,
155 mcp_config_directory: Option<&Path>,
156) -> Result<RunPlan, InvocationError> {
157 let working_dir = working_directory(profile, action);
158 let values = Values {
159 session_id: session_id.to_string(),
160 agent: profile.id.clone(),
161 prompt: prompt.to_string(),
162 cwd: working_dir.clone(),
163 ..Values::default()
164 };
165 let raw_tokens: Vec<String> = split_command(&profile.command)
166 .into_iter()
167 .chain(split_command(&action.extra_args))
168 .collect();
169 if raw_tokens.is_empty() {
170 return Err(InvocationError::EmptyCommand);
171 }
172 let uses_prompt_placeholder = raw_tokens
173 .iter()
174 .any(|token| placeholders_in(token).iter().any(|name| name == "prompt"));
175 let mut tokens = raw_tokens
176 .iter()
177 .map(|token| render(token, &values))
178 .collect::<Result<Vec<_>, _>>()?;
179 let mut cleanup = Vec::new();
180 if let Some(endpoint) = mcp
181 && let Some(directory) = mcp_config_directory
182 && !profile.mcp_config_flag.is_empty()
183 {
184 let path = write_mcp_config(directory, session_id, endpoint)?;
185 tokens.push(profile.mcp_config_flag.clone());
186 tokens.push(mcp_config_argument(
187 &profile.mcp_config_flag,
188 &path,
189 &profile.environment,
190 ));
191 cleanup.push(path);
192 }
193 let stdin = (!uses_prompt_placeholder).then(|| prompt.to_string());
194
195 match &profile.environment {
196 Environment::Host => {
197 let mut tokens = tokens.into_iter();
198 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
199 Ok(RunPlan {
200 run: Invocation {
201 program,
202 args: tokens.collect(),
203 cwd: Some(PathBuf::from(working_dir)),
204 stdin,
205 },
206 stop: None,
207 cleanup,
208 })
209 }
210 Environment::Wsl { .. } => {
211 let mut args = wsl_prefix(&profile.environment);
212 args.extend(
213 ["-e", "sh", "-lc", WSL_SCRIPT, "sh"]
214 .into_iter()
215 .map(String::from),
216 );
217 args.push(working_dir);
218 args.extend(tokens);
219 Ok(RunPlan {
220 run: Invocation {
221 program: WSL_PROGRAM.to_string(),
222 args,
223 cwd: None,
224 stdin,
225 },
226 stop: Some(app_stop_invocation(&profile.environment, session_id)),
227 cleanup,
228 })
229 }
230 }
231}
232
233fn app_stop_invocation(environment: &Environment, session_id: &str) -> Invocation {
234 let mut args = wsl_prefix(environment);
235 args.extend(["-e", "sh", "-c", APP_STOP_SCRIPT, "sh", session_id].map(String::from));
236 Invocation {
237 program: WSL_PROGRAM.to_string(),
238 args,
239 cwd: None,
240 stdin: None,
241 }
242}
243
244pub fn wsl_stop_invocation(environment: &Environment, session_id: &str) -> Option<Invocation> {
245 (matches!(environment, Environment::Wsl { .. }) && is_plain_session_id(session_id))
246 .then(|| app_stop_invocation(environment, session_id))
247}
248
249fn is_plain_session_id(session_id: &str) -> bool {
250 !session_id.is_empty()
251 && session_id
252 .chars()
253 .all(|character| character.is_ascii_alphanumeric() || character == '-')
254}
255
256pub fn kill_process_invocation(process_id: u32, session_id: &str) -> Option<Invocation> {
257 if !is_plain_session_id(session_id) {
258 return None;
259 }
260 if cfg!(windows) {
261 let script = format!(
262 "$p = Get-CimInstance Win32_Process -Filter 'ProcessId={process_id}'; if ($p -and $p.CommandLine -like '*{session_id}*') {{ taskkill /PID {process_id} /T /F }}"
263 );
264 return Some(Invocation {
265 program: "powershell".to_string(),
266 args: ["-NoProfile", "-Command", &script]
267 .map(String::from)
268 .to_vec(),
269 cwd: None,
270 stdin: None,
271 });
272 }
273 Some(Invocation {
274 program: "sh".to_string(),
275 args: [
276 "-c",
277 r#"grep -qaF -- "$2" "/proc/$1/cmdline" && kill -9 "$1""#,
278 "sh",
279 &process_id.to_string(),
280 session_id,
281 ]
282 .map(String::from)
283 .to_vec(),
284 cwd: None,
285 stdin: None,
286 })
287}
288
289pub fn supports_resume(profile: &AgentProfile) -> bool {
290 profile.command.contains(SESSION_FLAG)
291}
292
293pub fn resume_invocation(
294 profile: &AgentProfile,
295 action: &AgentAction,
296 prompt: &str,
297 session_id: &str,
298 mcp: Option<&McpEndpoint>,
299 mcp_config_directory: Option<&Path>,
300) -> Result<RunPlan, InvocationError> {
301 resume_with_flag(
302 profile,
303 action,
304 prompt,
305 session_id,
306 RESUME_FLAG,
307 mcp,
308 mcp_config_directory,
309 )
310}
311
312fn resume_with_flag(
313 profile: &AgentProfile,
314 action: &AgentAction,
315 prompt: &str,
316 session_id: &str,
317 flag: &str,
318 mcp: Option<&McpEndpoint>,
319 mcp_config_directory: Option<&Path>,
320) -> Result<RunPlan, InvocationError> {
321 if !supports_resume(profile) {
322 return Err(InvocationError::CannotResume);
323 }
324 if !is_plain_session_id(session_id) {
325 return Err(InvocationError::InvalidSessionId);
326 }
327 let resuming_profile = AgentProfile {
328 command: profile.command.replace(SESSION_FLAG, flag),
329 ..profile.clone()
330 };
331 build_invocation(
332 &resuming_profile,
333 action,
334 prompt,
335 session_id,
336 mcp,
337 mcp_config_directory,
338 )
339}
340
341pub fn open_session_invocation(
342 profile: &AgentProfile,
343 action: &AgentAction,
344 session_id: &str,
345) -> Result<Invocation, InvocationError> {
346 let values = Values {
347 session_id: session_id.to_string(),
348 agent: profile.id.clone(),
349 cwd: working_directory(profile, action),
350 ..Values::default()
351 };
352 let mut tokens = split_command(&profile.open_session_command)
353 .iter()
354 .map(|token| render(token, &values))
355 .collect::<Result<Vec<_>, _>>()?
356 .into_iter();
357 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
358 Ok(Invocation {
359 program,
360 args: tokens.collect(),
361 cwd: None,
362 stdin: None,
363 })
364}
365
366pub fn version_check_invocation(profile: &AgentProfile) -> Invocation {
367 let program = split_command(&profile.command)
368 .into_iter()
369 .next()
370 .unwrap_or_default();
371 match &profile.environment {
372 Environment::Host => Invocation {
373 program,
374 args: vec!["--version".to_string()],
375 cwd: None,
376 stdin: None,
377 },
378 Environment::Wsl { .. } => {
379 let mut args = wsl_prefix(&profile.environment);
380 args.extend(
381 ["-e", "sh", "-lc", WSL_SCRIPT, "sh", "~"]
382 .into_iter()
383 .map(String::from),
384 );
385 args.push(program);
386 args.push("--version".to_string());
387 Invocation {
388 program: WSL_PROGRAM.to_string(),
389 args,
390 cwd: None,
391 stdin: None,
392 }
393 }
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400
401 #[test]
402 fn wsl_invocation_has_exact_args() {
403 let mut profile = AgentProfile::claude_wsl();
404 profile.environment = Environment::Wsl {
405 distro: Some("Ubuntu".to_string()),
406 };
407 let action = AgentAction::answer_this("claude");
408 let plan = build_invocation(&profile, &action, "hi there", "sid-1", None, None).unwrap();
409 let expected_args: Vec<String> = [
410 "-d",
411 "Ubuntu",
412 "-e",
413 "sh",
414 "-lc",
415 WSL_SCRIPT,
416 "sh",
417 "~",
418 "claude",
419 "-p",
420 "--output-format",
421 "stream-json",
422 "--verbose",
423 "--session-id",
424 "sid-1",
425 "--allowedTools",
426 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
427 ]
428 .map(String::from)
429 .to_vec();
430 assert_eq!(plan.run.program, "wsl.exe");
431 assert_eq!(plan.run.args, expected_args);
432 assert_eq!(plan.run.cwd, None);
433 assert_eq!(plan.run.stdin.as_deref(), Some("hi there"));
434 let stop = plan.stop.unwrap();
435 assert_eq!(stop.program, "wsl.exe");
436 assert_eq!(
437 stop.args,
438 [
439 "-d",
440 "Ubuntu",
441 "-e",
442 "sh",
443 "-c",
444 APP_STOP_SCRIPT,
445 "sh",
446 "sid-1"
447 ]
448 .map(String::from)
449 );
450 }
451
452 #[test]
453 fn prompt_placeholder_goes_in_args_without_stdin() {
454 let profile = AgentProfile::copilot_wsl();
455 let action = AgentAction::answer_this("copilot");
456 let plan = build_invocation(&profile, &action, "a b\nc", "sid-2", None, None).unwrap();
457 assert_eq!(plan.run.stdin, None);
458 assert_eq!(plan.run.args[..2], ["-e".to_string(), "sh".to_string()]);
459 let prompt_position = plan.run.args.iter().position(|arg| arg == "-p").unwrap() + 1;
460 assert_eq!(plan.run.args[prompt_position], "a b\nc");
461 }
462
463 #[test]
464 fn host_invocation_expands_home() {
465 let mut action = AgentAction::build_this("claude-host");
466 action.working_dir = "~/work".to_string();
467 let plan = build_invocation(
468 &AgentProfile::claude_host(),
469 &action,
470 "p",
471 "sid-3",
472 None,
473 None,
474 )
475 .unwrap();
476 let home = std::env::var("HOME")
477 .or_else(|_| std::env::var("USERPROFILE"))
478 .unwrap();
479 assert_eq!(plan.run.program, "claude");
480 assert_eq!(plan.run.cwd, Some(PathBuf::from(format!("{home}/work"))));
481 assert_eq!(plan.run.stdin.as_deref(), Some("p"));
482 assert!(
483 plan.run
484 .args
485 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
486 );
487 assert_eq!(plan.stop, None);
488 }
489
490 fn endpoint() -> McpEndpoint {
491 McpEndpoint {
492 url: "http://127.0.0.1:9/mcp".to_string(),
493 token: "tok".to_string(),
494 }
495 }
496
497 #[test]
498 fn mcp_endpoint_writes_a_config_file_and_passes_its_path() {
499 let directory = tempfile::tempdir().unwrap();
500 let action = AgentAction::answer_this("claude");
501 let plan = build_invocation(
502 &AgentProfile::claude_host(),
503 &action,
504 "p",
505 "sid",
506 Some(&endpoint()),
507 Some(directory.path()),
508 )
509 .unwrap();
510 let flag_position = plan
511 .run
512 .args
513 .iter()
514 .position(|arg| arg == "--mcp-config")
515 .unwrap();
516 let expected_path = directory.path().join("mcp-sid.json");
517 assert_eq!(
518 plan.run.args[flag_position + 1],
519 expected_path.to_string_lossy()
520 );
521 assert_eq!(plan.cleanup, vec![expected_path.clone()]);
522 assert!(!plan.run.args.iter().any(|arg| arg.contains("tok")));
523 let json: serde_json::Value =
524 serde_json::from_str(&std::fs::read_to_string(&expected_path).unwrap()).unwrap();
525 let server = &json["mcpServers"]["teams"];
526 assert_eq!(server["type"], "http");
527 assert_eq!(server["url"], "http://127.0.0.1:9/mcp");
528 assert_eq!(server["headers"]["Authorization"], "Bearer tok");
529 #[cfg(unix)]
530 assert_eq!(
531 std::os::unix::fs::PermissionsExt::mode(
532 &std::fs::metadata(&expected_path).unwrap().permissions()
533 ) & 0o777,
534 0o600
535 );
536 }
537
538 #[test]
539 fn mcp_flag_is_omitted_without_endpoint_or_directory() {
540 let directory = tempfile::tempdir().unwrap();
541 let action = AgentAction::answer_this("claude");
542 let profile = AgentProfile::claude_host();
543 let without_endpoint =
544 build_invocation(&profile, &action, "p", "sid", None, Some(directory.path())).unwrap();
545 assert!(
546 !without_endpoint
547 .run
548 .args
549 .iter()
550 .any(|arg| arg == "--mcp-config")
551 );
552 let without_directory =
553 build_invocation(&profile, &action, "p", "sid", Some(&endpoint()), None).unwrap();
554 assert!(
555 !without_directory
556 .run
557 .args
558 .iter()
559 .any(|arg| arg == "--mcp-config")
560 );
561 assert!(without_directory.cleanup.is_empty());
562 }
563
564 #[test]
565 fn copilot_takes_the_config_path_with_an_at_prefix() {
566 let directory = tempfile::tempdir().unwrap();
567 let action = AgentAction::answer_this("copilot");
568 let plan = build_invocation(
569 &AgentProfile::copilot_wsl(),
570 &action,
571 "p",
572 "sid",
573 Some(&endpoint()),
574 Some(directory.path()),
575 )
576 .unwrap();
577 let flag_position = plan
578 .run
579 .args
580 .iter()
581 .position(|arg| arg == "--additional-mcp-config")
582 .unwrap();
583 assert_eq!(
584 plan.run.args[flag_position + 1],
585 format!(
586 "@{}",
587 directory.path().join("mcp-sid.json").to_string_lossy()
588 )
589 );
590 }
591
592 #[test]
593 fn windows_paths_translate_to_the_wsl_mount() {
594 assert_eq!(
595 wsl_path(r"C:\Users\x\AppData\mcp-1.json"),
596 "/mnt/c/Users/x/AppData/mcp-1.json"
597 );
598 assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json");
599 assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json");
600 assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json");
601 }
602
603 #[test]
604 fn agent_placeholder_renders_profile_id() {
605 let mut profile = AgentProfile::claude_host();
606 profile.command = "tool --agent {agent}".to_string();
607 let mut action = AgentAction::build_this("x");
608 action.extra_args = String::new();
609 let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap();
610 assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from));
611 }
612
613 #[test]
614 fn empty_command_is_an_error() {
615 let mut profile = AgentProfile::claude_host();
616 profile.command = String::new();
617 let mut action = AgentAction::build_this("x");
618 action.extra_args = String::new();
619 assert_eq!(
620 build_invocation(&profile, &action, "p", "s", None, None),
621 Err(InvocationError::EmptyCommand)
622 );
623 }
624
625 #[test]
626 fn open_session_renders_cwd_and_session() {
627 let action = AgentAction::build_this("claude");
628 let invocation =
629 open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap();
630 assert_eq!(invocation.program, "wt.exe");
631 assert_eq!(
632 invocation.args,
633 [
634 "wsl.exe",
635 "--cd",
636 "~",
637 "-e",
638 "sh",
639 "-lc",
640 "exec claude --resume sid-4"
641 ]
642 .map(String::from)
643 );
644 }
645
646 #[test]
647 fn version_check_runs_the_first_token_in_the_same_environment() {
648 let host = version_check_invocation(&AgentProfile::claude_host());
649 assert_eq!(host.program, "claude");
650 assert_eq!(host.args, ["--version"].map(String::from));
651 let mut wsl_profile = AgentProfile::claude_wsl();
652 wsl_profile.environment = Environment::Wsl {
653 distro: Some("Ubuntu".to_string()),
654 };
655 let wsl = version_check_invocation(&wsl_profile);
656 assert_eq!(wsl.program, "wsl.exe");
657 assert_eq!(
658 wsl.args,
659 [
660 "-d",
661 "Ubuntu",
662 "-e",
663 "sh",
664 "-lc",
665 WSL_SCRIPT,
666 "sh",
667 "~",
668 "claude",
669 "--version"
670 ]
671 .map(String::from)
672 );
673 }
674
675 #[test]
676 fn resume_swaps_the_session_flag_and_keeps_the_extra_args() {
677 let mut profile = AgentProfile::claude_wsl();
678 profile.environment = Environment::Wsl {
679 distro: Some("Ubuntu".to_string()),
680 };
681 let action = AgentAction::answer_this("claude");
682 let plan = resume_invocation(&profile, &action, "go on", "sid-9", None, None).unwrap();
683 let expected_args: Vec<String> = [
684 "-d",
685 "Ubuntu",
686 "-e",
687 "sh",
688 "-lc",
689 WSL_SCRIPT,
690 "sh",
691 "~",
692 "claude",
693 "-p",
694 "--output-format",
695 "stream-json",
696 "--verbose",
697 "--resume",
698 "sid-9",
699 "--allowedTools",
700 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
701 ]
702 .map(String::from)
703 .to_vec();
704 assert_eq!(plan.run.args, expected_args);
705 assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
706 assert_eq!(
707 plan.stop.unwrap().args,
708 [
709 "-d",
710 "Ubuntu",
711 "-e",
712 "sh",
713 "-c",
714 APP_STOP_SCRIPT,
715 "sh",
716 "sid-9"
717 ]
718 .map(String::from)
719 );
720 }
721
722 #[test]
723 fn resume_on_the_host_keeps_the_permission_mode() {
724 let action = AgentAction::build_this("claude-host");
725 let plan = resume_invocation(
726 &AgentProfile::claude_host(),
727 &action,
728 "go on",
729 "sid-8",
730 None,
731 None,
732 )
733 .unwrap();
734 assert_eq!(plan.run.program, "claude");
735 assert!(!plan.run.args.contains(&"--session-id".to_string()));
736 assert!(
737 plan.run
738 .args
739 .windows(2)
740 .any(|pair| pair == ["--resume", "sid-8"])
741 );
742 assert!(
743 plan.run
744 .args
745 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
746 );
747 assert_eq!(plan.stop, None);
748 }
749
750 #[test]
751 fn resume_rejects_a_session_id_that_is_not_plain() {
752 let action = AgentAction::answer_this("claude");
753 assert!(matches!(
754 resume_invocation(
755 &AgentProfile::claude_wsl(),
756 &action,
757 "x",
758 "a b; rm",
759 None,
760 None
761 ),
762 Err(InvocationError::InvalidSessionId)
763 ));
764 }
765
766 #[test]
767 fn linux_path_maps_drives_and_wsl_unc_paths() {
768 assert_eq!(linux_path(r"C:\Users\dd\repo"), "/mnt/c/Users/dd/repo");
769 assert_eq!(
770 linux_path(r"\\wsl.localhost\Ubuntu\home\daniel\repo"),
771 "/home/daniel/repo"
772 );
773 assert_eq!(linux_path(r"\\wsl$\Ubuntu\home"), "/home");
774 assert_eq!(linux_path(r"\\wsl.localhost\Ubuntu"), "/");
775 assert_eq!(
776 wsl_unc_distro(r"\\wsl.localhost\Ubuntu\home"),
777 Some("Ubuntu")
778 );
779 assert_eq!(wsl_unc_distro(r"\\wsl$\Debian"), Some("Debian"));
780 assert_eq!(wsl_unc_distro(r"C:\Users"), None);
781 assert_eq!(linux_path("/home/daniel"), "/home/daniel");
782 }
783
784 #[test]
785 fn copilot_resumes_with_the_prompt_in_its_args() {
786 let action = AgentAction::answer_this("copilot");
787 let plan = resume_invocation(
788 &AgentProfile::copilot_wsl(),
789 &action,
790 "go on",
791 "sid-7",
792 None,
793 None,
794 )
795 .unwrap();
796 assert_eq!(plan.run.stdin, None);
797 assert!(
798 plan.run
799 .args
800 .windows(2)
801 .any(|pair| pair == ["--resume", "sid-7"])
802 );
803 assert!(plan.run.args.contains(&"go on".to_string()));
804 }
805
806 #[test]
807 fn kill_refuses_a_session_id_that_is_not_plain() {
808 assert_eq!(kill_process_invocation(1, ""), None);
809 assert_eq!(kill_process_invocation(1, "a'; rm -rf /; '"), None);
810 assert_eq!(kill_process_invocation(1, "a b"), None);
811 }
812
813 #[cfg(windows)]
814 #[test]
815 fn kill_checks_the_command_line_before_taskkill() {
816 let invocation = kill_process_invocation(4242, "abc-123").unwrap();
817 assert_eq!(invocation.program, "powershell");
818 assert_eq!(
819 invocation.args[..2],
820 ["-NoProfile", "-Command"].map(String::from)
821 );
822 let script = &invocation.args[2];
823 assert!(script.contains("ProcessId=4242"));
824 assert!(script.contains("-like '*abc-123*'"));
825 assert!(script.contains("taskkill /PID 4242 /T /F"));
826 }
827
828 #[cfg(unix)]
829 mod unix_kill {
830 use super::super::*;
831
832 fn spawn_agent_like(arguments: &[&str]) -> std::process::Child {
833 std::process::Command::new("sh")
834 .args(["-c", "sleep 30", "claude"])
835 .args(arguments)
836 .spawn()
837 .unwrap()
838 }
839
840 fn run_app_stop(session_id: &str) {
841 std::process::Command::new("sh")
842 .args(["-c", APP_STOP_SCRIPT, "sh", session_id])
843 .status()
844 .unwrap();
845 }
846
847 fn is_running(child: &mut std::process::Child) -> bool {
848 child.try_wait().unwrap().is_none()
849 }
850
851 #[test]
852 fn the_app_stop_matches_by_the_role_of_the_session_id() {
853 let session = uuid::Uuid::new_v4().to_string();
854 let fork_id = uuid::Uuid::new_v4().to_string();
855 let mut headless = spawn_agent_like(&[
856 "--print",
857 "--resume",
858 &session,
859 "--output-format",
860 "stream-json",
861 ]);
862 let mut fork = spawn_agent_like(&[
863 "-p",
864 "--output-format",
865 "stream-json",
866 "--resume",
867 &session,
868 "--fork-session",
869 "--session-id",
870 &fork_id,
871 ]);
872 let mut terminal = spawn_agent_like(&["--resume", &session]);
873 std::thread::sleep(std::time::Duration::from_millis(200));
874 run_app_stop(&session);
875 assert!(headless.wait().is_ok_and(|status| !status.success()));
876 assert!(is_running(&mut fork));
877 assert!(is_running(&mut terminal));
878 run_app_stop(&fork_id);
879 assert!(fork.wait().is_ok_and(|status| !status.success()));
880 assert!(is_running(&mut terminal));
881 terminal.kill().unwrap();
882 terminal.wait().unwrap();
883 }
884
885 #[test]
886 fn a_running_stop_script_is_never_killed_by_another() {
887 let session = uuid::Uuid::new_v4().to_string();
888 let mut lookalike = std::process::Command::new("sh")
889 .args([
890 "-c",
891 &format!("sleep 30 # {APP_STOP_SCRIPT}"),
892 "sh",
893 "-p",
894 "--output-format",
895 "--resume",
896 &session,
897 ])
898 .spawn()
899 .unwrap();
900 std::thread::sleep(std::time::Duration::from_millis(200));
901 run_app_stop(&session);
902 assert!(is_running(&mut lookalike));
903 lookalike.kill().unwrap();
904 lookalike.wait().unwrap();
905 }
906
907 fn spawn_sleeper(label: &str) -> std::process::Child {
908 std::process::Command::new("sh")
909 .args(["-c", "sleep 30", label])
910 .spawn()
911 .unwrap()
912 }
913
914 fn run_kill(process_id: u32, session_id: &str) {
915 let invocation = kill_process_invocation(process_id, session_id).unwrap();
916 std::process::Command::new(invocation.program)
917 .args(invocation.args)
918 .status()
919 .unwrap();
920 }
921
922 #[test]
923 fn kills_a_process_whose_command_line_has_the_session_id() {
924 let mut child = spawn_sleeper("fake-session-1");
925 run_kill(child.id(), "fake-session-1");
926 let status = child.wait().unwrap();
927 assert!(!status.success());
928 }
929
930 #[test]
931 fn leaves_a_process_without_the_session_id_alone() {
932 let mut child = spawn_sleeper("other-session");
933 run_kill(child.id(), "fake-session-2");
934 assert!(child.try_wait().unwrap().is_none());
935 child.kill().unwrap();
936 child.wait().unwrap();
937 }
938 }
939
940 #[test]
941 fn a_command_without_the_session_flag_cannot_resume() {
942 let mut profile = AgentProfile::claude_host();
943 profile.command = "tool -p".to_string();
944 let action = AgentAction::build_this("claude-host");
945 assert!(!supports_resume(&profile));
946 assert_eq!(
947 resume_invocation(&profile, &action, "go on", "sid", None, None),
948 Err(InvocationError::CannotResume)
949 );
950 }
951}