BlueGit

ict rusty-teams

Files

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

invocation.rs

invocation.rs 30.3 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 // copilot runs under WSL on Windows hosts and gets the /mnt/... form there;
584 // wsl_path leaves other platforms' paths alone.
585 assert_eq!(
586 plan.run.args[flag_position + 1],
587 format!(
588 "@{}",
589 wsl_path(&directory.path().join("mcp-sid.json").to_string_lossy())
590 )
591 );
592 }
593
594 #[test]
595 fn windows_paths_translate_to_the_wsl_mount() {
596 assert_eq!(
597 wsl_path(r"C:\Users\x\AppData\mcp-1.json"),
598 "/mnt/c/Users/x/AppData/mcp-1.json"
599 );
600 assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json");
601 assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json");
602 assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json");
603 }
604
605 #[test]
606 fn agent_placeholder_renders_profile_id() {
607 let mut profile = AgentProfile::claude_host();
608 profile.command = "tool --agent {agent}".to_string();
609 let mut action = AgentAction::build_this("x");
610 action.extra_args = String::new();
611 let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap();
612 assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from));
613 }
614
615 #[test]
616 fn empty_command_is_an_error() {
617 let mut profile = AgentProfile::claude_host();
618 profile.command = String::new();
619 let mut action = AgentAction::build_this("x");
620 action.extra_args = String::new();
621 assert_eq!(
622 build_invocation(&profile, &action, "p", "s", None, None),
623 Err(InvocationError::EmptyCommand)
624 );
625 }
626
627 #[test]
628 fn open_session_renders_cwd_and_session() {
629 let action = AgentAction::build_this("claude");
630 let invocation =
631 open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap();
632 assert_eq!(invocation.program, "wt.exe");
633 assert_eq!(
634 invocation.args,
635 [
636 "wsl.exe",
637 "--cd",
638 "~",
639 "-e",
640 "sh",
641 "-lc",
642 "exec claude --resume sid-4"
643 ]
644 .map(String::from)
645 );
646 }
647
648 #[test]
649 fn version_check_runs_the_first_token_in_the_same_environment() {
650 let host = version_check_invocation(&AgentProfile::claude_host());
651 assert_eq!(host.program, "claude");
652 assert_eq!(host.args, ["--version"].map(String::from));
653 let mut wsl_profile = AgentProfile::claude_wsl();
654 wsl_profile.environment = Environment::Wsl {
655 distro: Some("Ubuntu".to_string()),
656 };
657 let wsl = version_check_invocation(&wsl_profile);
658 assert_eq!(wsl.program, "wsl.exe");
659 assert_eq!(
660 wsl.args,
661 [
662 "-d",
663 "Ubuntu",
664 "-e",
665 "sh",
666 "-lc",
667 WSL_SCRIPT,
668 "sh",
669 "~",
670 "claude",
671 "--version"
672 ]
673 .map(String::from)
674 );
675 }
676
677 #[test]
678 fn resume_swaps_the_session_flag_and_keeps_the_extra_args() {
679 let mut profile = AgentProfile::claude_wsl();
680 profile.environment = Environment::Wsl {
681 distro: Some("Ubuntu".to_string()),
682 };
683 let action = AgentAction::answer_this("claude");
684 let plan = resume_invocation(&profile, &action, "go on", "sid-9", None, None).unwrap();
685 let expected_args: Vec<String> = [
686 "-d",
687 "Ubuntu",
688 "-e",
689 "sh",
690 "-lc",
691 WSL_SCRIPT,
692 "sh",
693 "~",
694 "claude",
695 "-p",
696 "--output-format",
697 "stream-json",
698 "--verbose",
699 "--resume",
700 "sid-9",
701 "--allowedTools",
702 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
703 ]
704 .map(String::from)
705 .to_vec();
706 assert_eq!(plan.run.args, expected_args);
707 assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
708 assert_eq!(
709 plan.stop.unwrap().args,
710 [
711 "-d",
712 "Ubuntu",
713 "-e",
714 "sh",
715 "-c",
716 APP_STOP_SCRIPT,
717 "sh",
718 "sid-9"
719 ]
720 .map(String::from)
721 );
722 }
723
724 #[test]
725 fn resume_on_the_host_keeps_the_permission_mode() {
726 let action = AgentAction::build_this("claude-host");
727 let plan = resume_invocation(
728 &AgentProfile::claude_host(),
729 &action,
730 "go on",
731 "sid-8",
732 None,
733 None,
734 )
735 .unwrap();
736 assert_eq!(plan.run.program, "claude");
737 assert!(!plan.run.args.contains(&"--session-id".to_string()));
738 assert!(
739 plan.run
740 .args
741 .windows(2)
742 .any(|pair| pair == ["--resume", "sid-8"])
743 );
744 assert!(
745 plan.run
746 .args
747 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
748 );
749 assert_eq!(plan.stop, None);
750 }
751
752 #[test]
753 fn resume_rejects_a_session_id_that_is_not_plain() {
754 let action = AgentAction::answer_this("claude");
755 assert!(matches!(
756 resume_invocation(
757 &AgentProfile::claude_wsl(),
758 &action,
759 "x",
760 "a b; rm",
761 None,
762 None
763 ),
764 Err(InvocationError::InvalidSessionId)
765 ));
766 }
767
768 #[test]
769 fn linux_path_maps_drives_and_wsl_unc_paths() {
770 assert_eq!(linux_path(r"C:\Users\dd\repo"), "/mnt/c/Users/dd/repo");
771 assert_eq!(
772 linux_path(r"\\wsl.localhost\Ubuntu\home\daniel\repo"),
773 "/home/daniel/repo"
774 );
775 assert_eq!(linux_path(r"\\wsl$\Ubuntu\home"), "/home");
776 assert_eq!(linux_path(r"\\wsl.localhost\Ubuntu"), "/");
777 assert_eq!(
778 wsl_unc_distro(r"\\wsl.localhost\Ubuntu\home"),
779 Some("Ubuntu")
780 );
781 assert_eq!(wsl_unc_distro(r"\\wsl$\Debian"), Some("Debian"));
782 assert_eq!(wsl_unc_distro(r"C:\Users"), None);
783 assert_eq!(linux_path("/home/daniel"), "/home/daniel");
784 }
785
786 #[test]
787 fn copilot_resumes_with_the_prompt_in_its_args() {
788 let action = AgentAction::answer_this("copilot");
789 let plan = resume_invocation(
790 &AgentProfile::copilot_wsl(),
791 &action,
792 "go on",
793 "sid-7",
794 None,
795 None,
796 )
797 .unwrap();
798 assert_eq!(plan.run.stdin, None);
799 assert!(
800 plan.run
801 .args
802 .windows(2)
803 .any(|pair| pair == ["--resume", "sid-7"])
804 );
805 assert!(plan.run.args.contains(&"go on".to_string()));
806 }
807
808 #[test]
809 fn kill_refuses_a_session_id_that_is_not_plain() {
810 assert_eq!(kill_process_invocation(1, ""), None);
811 assert_eq!(kill_process_invocation(1, "a'; rm -rf /; '"), None);
812 assert_eq!(kill_process_invocation(1, "a b"), None);
813 }
814
815 #[cfg(windows)]
816 #[test]
817 fn kill_checks_the_command_line_before_taskkill() {
818 let invocation = kill_process_invocation(4242, "abc-123").unwrap();
819 assert_eq!(invocation.program, "powershell");
820 assert_eq!(
821 invocation.args[..2],
822 ["-NoProfile", "-Command"].map(String::from)
823 );
824 let script = &invocation.args[2];
825 assert!(script.contains("ProcessId=4242"));
826 assert!(script.contains("-like '*abc-123*'"));
827 assert!(script.contains("taskkill /PID 4242 /T /F"));
828 }
829
830 #[cfg(unix)]
831 mod unix_kill {
832 use super::super::*;
833
834 fn spawn_agent_like(arguments: &[&str]) -> std::process::Child {
835 std::process::Command::new("sh")
836 .args(["-c", "sleep 30", "claude"])
837 .args(arguments)
838 .spawn()
839 .unwrap()
840 }
841
842 fn run_app_stop(session_id: &str) {
843 std::process::Command::new("sh")
844 .args(["-c", APP_STOP_SCRIPT, "sh", session_id])
845 .status()
846 .unwrap();
847 }
848
849 fn is_running(child: &mut std::process::Child) -> bool {
850 child.try_wait().unwrap().is_none()
851 }
852
853 #[cfg_attr(target_os = "macos", ignore = "the stop script reads /proc cmdline")]
854 #[test]
855 fn the_app_stop_matches_by_the_role_of_the_session_id() {
856 let session = uuid::Uuid::new_v4().to_string();
857 let fork_id = uuid::Uuid::new_v4().to_string();
858 let mut headless = spawn_agent_like(&[
859 "--print",
860 "--resume",
861 &session,
862 "--output-format",
863 "stream-json",
864 ]);
865 let mut fork = spawn_agent_like(&[
866 "-p",
867 "--output-format",
868 "stream-json",
869 "--resume",
870 &session,
871 "--fork-session",
872 "--session-id",
873 &fork_id,
874 ]);
875 let mut terminal = spawn_agent_like(&["--resume", &session]);
876 std::thread::sleep(std::time::Duration::from_millis(200));
877 run_app_stop(&session);
878 assert!(headless.wait().is_ok_and(|status| !status.success()));
879 assert!(is_running(&mut fork));
880 assert!(is_running(&mut terminal));
881 run_app_stop(&fork_id);
882 assert!(fork.wait().is_ok_and(|status| !status.success()));
883 assert!(is_running(&mut terminal));
884 terminal.kill().unwrap();
885 terminal.wait().unwrap();
886 }
887
888 #[test]
889 fn a_running_stop_script_is_never_killed_by_another() {
890 let session = uuid::Uuid::new_v4().to_string();
891 let mut lookalike = std::process::Command::new("sh")
892 .args([
893 "-c",
894 &format!("sleep 30 # {APP_STOP_SCRIPT}"),
895 "sh",
896 "-p",
897 "--output-format",
898 "--resume",
899 &session,
900 ])
901 .spawn()
902 .unwrap();
903 std::thread::sleep(std::time::Duration::from_millis(200));
904 run_app_stop(&session);
905 assert!(is_running(&mut lookalike));
906 lookalike.kill().unwrap();
907 lookalike.wait().unwrap();
908 }
909
910 fn spawn_sleeper(label: &str) -> std::process::Child {
911 std::process::Command::new("sh")
912 .args(["-c", "sleep 30", label])
913 .spawn()
914 .unwrap()
915 }
916
917 fn run_kill(process_id: u32, session_id: &str) {
918 let invocation = kill_process_invocation(process_id, session_id).unwrap();
919 std::process::Command::new(invocation.program)
920 .args(invocation.args)
921 .status()
922 .unwrap();
923 }
924
925 #[cfg_attr(target_os = "macos", ignore = "the stop script reads /proc cmdline")]
926 #[test]
927 fn kills_a_process_whose_command_line_has_the_session_id() {
928 let mut child = spawn_sleeper("fake-session-1");
929 run_kill(child.id(), "fake-session-1");
930 let status = child.wait().unwrap();
931 assert!(!status.success());
932 }
933
934 #[test]
935 fn leaves_a_process_without_the_session_id_alone() {
936 let mut child = spawn_sleeper("other-session");
937 run_kill(child.id(), "fake-session-2");
938 assert!(child.try_wait().unwrap().is_none());
939 child.kill().unwrap();
940 child.wait().unwrap();
941 }
942 }
943
944 #[test]
945 fn a_command_without_the_session_flag_cannot_resume() {
946 let mut profile = AgentProfile::claude_host();
947 profile.command = "tool -p".to_string();
948 let action = AgentAction::build_this("claude-host");
949 assert!(!supports_resume(&profile));
950 assert_eq!(
951 resume_invocation(&profile, &action, "go on", "sid", None, None),
952 Err(InvocationError::CannotResume)
953 );
954 }
955}