BlueGit

ict rusty-teams

Files

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

invocation.rs

invocation.rs 31.6 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
312pub fn fork_invocation(
313 profile: &AgentProfile,
314 action: &AgentAction,
315 prompt: &str,
316 original_session_id: &str,
317 fork_session_id: &str,
318 mcp: Option<&McpEndpoint>,
319 mcp_config_directory: Option<&Path>,
320) -> Result<RunPlan, InvocationError> {
321 if !is_plain_session_id(original_session_id) {
322 return Err(InvocationError::InvalidSessionId);
323 }
324 resume_with_flag(
325 profile,
326 action,
327 prompt,
328 fork_session_id,
329 &format!("--resume {original_session_id} --fork-session {SESSION_FLAG}"),
330 mcp,
331 mcp_config_directory,
332 )
333}
334
335fn resume_with_flag(
336 profile: &AgentProfile,
337 action: &AgentAction,
338 prompt: &str,
339 session_id: &str,
340 flag: &str,
341 mcp: Option<&McpEndpoint>,
342 mcp_config_directory: Option<&Path>,
343) -> Result<RunPlan, InvocationError> {
344 if !supports_resume(profile) {
345 return Err(InvocationError::CannotResume);
346 }
347 if !is_plain_session_id(session_id) {
348 return Err(InvocationError::InvalidSessionId);
349 }
350 let resuming_profile = AgentProfile {
351 command: profile.command.replace(SESSION_FLAG, flag),
352 ..profile.clone()
353 };
354 build_invocation(
355 &resuming_profile,
356 action,
357 prompt,
358 session_id,
359 mcp,
360 mcp_config_directory,
361 )
362}
363
364pub fn open_session_invocation(
365 profile: &AgentProfile,
366 action: &AgentAction,
367 session_id: &str,
368) -> Result<Invocation, InvocationError> {
369 let values = Values {
370 session_id: session_id.to_string(),
371 agent: profile.id.clone(),
372 cwd: working_directory(profile, action),
373 ..Values::default()
374 };
375 let mut tokens = split_command(&profile.open_session_command)
376 .iter()
377 .map(|token| render(token, &values))
378 .collect::<Result<Vec<_>, _>>()?
379 .into_iter();
380 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
381 Ok(Invocation {
382 program,
383 args: tokens.collect(),
384 cwd: None,
385 stdin: None,
386 })
387}
388
389pub fn version_check_invocation(profile: &AgentProfile) -> Invocation {
390 let program = split_command(&profile.command)
391 .into_iter()
392 .next()
393 .unwrap_or_default();
394 match &profile.environment {
395 Environment::Host => Invocation {
396 program,
397 args: vec!["--version".to_string()],
398 cwd: None,
399 stdin: None,
400 },
401 Environment::Wsl { .. } => {
402 let mut args = wsl_prefix(&profile.environment);
403 args.extend(
404 ["-e", "sh", "-lc", WSL_SCRIPT, "sh", "~"]
405 .into_iter()
406 .map(String::from),
407 );
408 args.push(program);
409 args.push("--version".to_string());
410 Invocation {
411 program: WSL_PROGRAM.to_string(),
412 args,
413 cwd: None,
414 stdin: None,
415 }
416 }
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use super::*;
423
424 #[test]
425 fn wsl_invocation_has_exact_args() {
426 let mut profile = AgentProfile::claude_wsl();
427 profile.environment = Environment::Wsl {
428 distro: Some("Ubuntu".to_string()),
429 };
430 let action = AgentAction::answer_this("claude");
431 let plan = build_invocation(&profile, &action, "hi there", "sid-1", None, None).unwrap();
432 let expected_args: Vec<String> = [
433 "-d",
434 "Ubuntu",
435 "-e",
436 "sh",
437 "-lc",
438 WSL_SCRIPT,
439 "sh",
440 "~",
441 "claude",
442 "-p",
443 "--output-format",
444 "stream-json",
445 "--verbose",
446 "--session-id",
447 "sid-1",
448 "--allowedTools",
449 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
450 ]
451 .map(String::from)
452 .to_vec();
453 assert_eq!(plan.run.program, "wsl.exe");
454 assert_eq!(plan.run.args, expected_args);
455 assert_eq!(plan.run.cwd, None);
456 assert_eq!(plan.run.stdin.as_deref(), Some("hi there"));
457 let stop = plan.stop.unwrap();
458 assert_eq!(stop.program, "wsl.exe");
459 assert_eq!(
460 stop.args,
461 [
462 "-d",
463 "Ubuntu",
464 "-e",
465 "sh",
466 "-c",
467 APP_STOP_SCRIPT,
468 "sh",
469 "sid-1"
470 ]
471 .map(String::from)
472 );
473 }
474
475 #[test]
476 fn prompt_placeholder_goes_in_args_without_stdin() {
477 let profile = AgentProfile::copilot_wsl();
478 let action = AgentAction::answer_this("copilot");
479 let plan = build_invocation(&profile, &action, "a b\nc", "sid-2", None, None).unwrap();
480 assert_eq!(plan.run.stdin, None);
481 assert_eq!(plan.run.args[..2], ["-e".to_string(), "sh".to_string()]);
482 let prompt_position = plan.run.args.iter().position(|arg| arg == "-p").unwrap() + 1;
483 assert_eq!(plan.run.args[prompt_position], "a b\nc");
484 }
485
486 #[test]
487 fn host_invocation_expands_home() {
488 let mut action = AgentAction::build_this("claude-host");
489 action.working_dir = "~/work".to_string();
490 let plan = build_invocation(
491 &AgentProfile::claude_host(),
492 &action,
493 "p",
494 "sid-3",
495 None,
496 None,
497 )
498 .unwrap();
499 let home = std::env::var("HOME")
500 .or_else(|_| std::env::var("USERPROFILE"))
501 .unwrap();
502 assert_eq!(plan.run.program, "claude");
503 assert_eq!(plan.run.cwd, Some(PathBuf::from(format!("{home}/work"))));
504 assert_eq!(plan.run.stdin.as_deref(), Some("p"));
505 assert!(
506 plan.run
507 .args
508 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
509 );
510 assert_eq!(plan.stop, None);
511 }
512
513 fn endpoint() -> McpEndpoint {
514 McpEndpoint {
515 url: "http://127.0.0.1:9/mcp".to_string(),
516 token: "tok".to_string(),
517 }
518 }
519
520 #[test]
521 fn mcp_endpoint_writes_a_config_file_and_passes_its_path() {
522 let directory = tempfile::tempdir().unwrap();
523 let action = AgentAction::answer_this("claude");
524 let plan = build_invocation(
525 &AgentProfile::claude_host(),
526 &action,
527 "p",
528 "sid",
529 Some(&endpoint()),
530 Some(directory.path()),
531 )
532 .unwrap();
533 let flag_position = plan
534 .run
535 .args
536 .iter()
537 .position(|arg| arg == "--mcp-config")
538 .unwrap();
539 let expected_path = directory.path().join("mcp-sid.json");
540 assert_eq!(
541 plan.run.args[flag_position + 1],
542 expected_path.to_string_lossy()
543 );
544 assert_eq!(plan.cleanup, vec![expected_path.clone()]);
545 assert!(!plan.run.args.iter().any(|arg| arg.contains("tok")));
546 let json: serde_json::Value =
547 serde_json::from_str(&std::fs::read_to_string(&expected_path).unwrap()).unwrap();
548 let server = &json["mcpServers"]["teams"];
549 assert_eq!(server["type"], "http");
550 assert_eq!(server["url"], "http://127.0.0.1:9/mcp");
551 assert_eq!(server["headers"]["Authorization"], "Bearer tok");
552 #[cfg(unix)]
553 assert_eq!(
554 std::os::unix::fs::PermissionsExt::mode(
555 &std::fs::metadata(&expected_path).unwrap().permissions()
556 ) & 0o777,
557 0o600
558 );
559 }
560
561 #[test]
562 fn mcp_flag_is_omitted_without_endpoint_or_directory() {
563 let directory = tempfile::tempdir().unwrap();
564 let action = AgentAction::answer_this("claude");
565 let profile = AgentProfile::claude_host();
566 let without_endpoint =
567 build_invocation(&profile, &action, "p", "sid", None, Some(directory.path())).unwrap();
568 assert!(
569 !without_endpoint
570 .run
571 .args
572 .iter()
573 .any(|arg| arg == "--mcp-config")
574 );
575 let without_directory =
576 build_invocation(&profile, &action, "p", "sid", Some(&endpoint()), None).unwrap();
577 assert!(
578 !without_directory
579 .run
580 .args
581 .iter()
582 .any(|arg| arg == "--mcp-config")
583 );
584 assert!(without_directory.cleanup.is_empty());
585 }
586
587 #[test]
588 fn copilot_takes_the_config_path_with_an_at_prefix() {
589 let directory = tempfile::tempdir().unwrap();
590 let action = AgentAction::answer_this("copilot");
591 let plan = build_invocation(
592 &AgentProfile::copilot_wsl(),
593 &action,
594 "p",
595 "sid",
596 Some(&endpoint()),
597 Some(directory.path()),
598 )
599 .unwrap();
600 let flag_position = plan
601 .run
602 .args
603 .iter()
604 .position(|arg| arg == "--additional-mcp-config")
605 .unwrap();
606 assert_eq!(
607 plan.run.args[flag_position + 1],
608 format!(
609 "@{}",
610 directory.path().join("mcp-sid.json").to_string_lossy()
611 )
612 );
613 }
614
615 #[test]
616 fn windows_paths_translate_to_the_wsl_mount() {
617 assert_eq!(
618 wsl_path(r"C:\Users\x\AppData\mcp-1.json"),
619 "/mnt/c/Users/x/AppData/mcp-1.json"
620 );
621 assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json");
622 assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json");
623 assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json");
624 }
625
626 #[test]
627 fn agent_placeholder_renders_profile_id() {
628 let mut profile = AgentProfile::claude_host();
629 profile.command = "tool --agent {agent}".to_string();
630 let mut action = AgentAction::build_this("x");
631 action.extra_args = String::new();
632 let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap();
633 assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from));
634 }
635
636 #[test]
637 fn empty_command_is_an_error() {
638 let mut profile = AgentProfile::claude_host();
639 profile.command = String::new();
640 let mut action = AgentAction::build_this("x");
641 action.extra_args = String::new();
642 assert_eq!(
643 build_invocation(&profile, &action, "p", "s", None, None),
644 Err(InvocationError::EmptyCommand)
645 );
646 }
647
648 #[test]
649 fn open_session_renders_cwd_and_session() {
650 let action = AgentAction::build_this("claude");
651 let invocation =
652 open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap();
653 assert_eq!(invocation.program, "wt.exe");
654 assert_eq!(
655 invocation.args,
656 [
657 "wsl.exe",
658 "--cd",
659 "~",
660 "-e",
661 "sh",
662 "-lc",
663 "exec claude --resume sid-4"
664 ]
665 .map(String::from)
666 );
667 }
668
669 #[test]
670 fn version_check_runs_the_first_token_in_the_same_environment() {
671 let host = version_check_invocation(&AgentProfile::claude_host());
672 assert_eq!(host.program, "claude");
673 assert_eq!(host.args, ["--version"].map(String::from));
674 let mut wsl_profile = AgentProfile::claude_wsl();
675 wsl_profile.environment = Environment::Wsl {
676 distro: Some("Ubuntu".to_string()),
677 };
678 let wsl = version_check_invocation(&wsl_profile);
679 assert_eq!(wsl.program, "wsl.exe");
680 assert_eq!(
681 wsl.args,
682 [
683 "-d",
684 "Ubuntu",
685 "-e",
686 "sh",
687 "-lc",
688 WSL_SCRIPT,
689 "sh",
690 "~",
691 "claude",
692 "--version"
693 ]
694 .map(String::from)
695 );
696 }
697
698 #[test]
699 fn resume_swaps_the_session_flag_and_keeps_the_extra_args() {
700 let mut profile = AgentProfile::claude_wsl();
701 profile.environment = Environment::Wsl {
702 distro: Some("Ubuntu".to_string()),
703 };
704 let action = AgentAction::answer_this("claude");
705 let plan = resume_invocation(&profile, &action, "go on", "sid-9", None, None).unwrap();
706 let expected_args: Vec<String> = [
707 "-d",
708 "Ubuntu",
709 "-e",
710 "sh",
711 "-lc",
712 WSL_SCRIPT,
713 "sh",
714 "~",
715 "claude",
716 "-p",
717 "--output-format",
718 "stream-json",
719 "--verbose",
720 "--resume",
721 "sid-9",
722 "--allowedTools",
723 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
724 ]
725 .map(String::from)
726 .to_vec();
727 assert_eq!(plan.run.args, expected_args);
728 assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
729 assert_eq!(
730 plan.stop.unwrap().args,
731 [
732 "-d",
733 "Ubuntu",
734 "-e",
735 "sh",
736 "-c",
737 APP_STOP_SCRIPT,
738 "sh",
739 "sid-9"
740 ]
741 .map(String::from)
742 );
743 }
744
745 #[test]
746 fn resume_on_the_host_keeps_the_permission_mode() {
747 let action = AgentAction::build_this("claude-host");
748 let plan = resume_invocation(
749 &AgentProfile::claude_host(),
750 &action,
751 "go on",
752 "sid-8",
753 None,
754 None,
755 )
756 .unwrap();
757 assert_eq!(plan.run.program, "claude");
758 assert!(!plan.run.args.contains(&"--session-id".to_string()));
759 assert!(
760 plan.run
761 .args
762 .windows(2)
763 .any(|pair| pair == ["--resume", "sid-8"])
764 );
765 assert!(
766 plan.run
767 .args
768 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
769 );
770 assert_eq!(plan.stop, None);
771 }
772
773 #[test]
774 fn fork_resumes_the_original_into_a_fresh_session_id_and_keeps_the_stop() {
775 let action = AgentAction::answer_this("claude");
776 let plan = fork_invocation(
777 &AgentProfile::claude_wsl(),
778 &action,
779 "go on",
780 "old-6",
781 "new-6",
782 None,
783 None,
784 )
785 .unwrap();
786 assert!(plan.run.args.windows(5).any(|window| window
787 == [
788 "--resume",
789 "old-6",
790 "--fork-session",
791 "--session-id",
792 "new-6"
793 ]));
794 assert_eq!(plan.run.stdin.as_deref(), Some("go on"));
795 assert_eq!(
796 plan.stop.unwrap().args,
797 ["-e", "sh", "-c", APP_STOP_SCRIPT, "sh", "new-6"].map(String::from)
798 );
799 assert!(
800 fork_invocation(
801 &AgentProfile::claude_wsl(),
802 &action,
803 "x",
804 "bad id; rm",
805 "new",
806 None,
807 None
808 )
809 .is_err()
810 );
811 }
812
813 #[test]
814 fn resume_rejects_a_session_id_that_is_not_plain() {
815 let action = AgentAction::answer_this("claude");
816 assert!(matches!(
817 resume_invocation(
818 &AgentProfile::claude_wsl(),
819 &action,
820 "x",
821 "a b; rm",
822 None,
823 None
824 ),
825 Err(InvocationError::InvalidSessionId)
826 ));
827 }
828
829 #[test]
830 fn linux_path_maps_drives_and_wsl_unc_paths() {
831 assert_eq!(linux_path(r"C:\Users\dd\repo"), "/mnt/c/Users/dd/repo");
832 assert_eq!(
833 linux_path(r"\\wsl.localhost\Ubuntu\home\daniel\repo"),
834 "/home/daniel/repo"
835 );
836 assert_eq!(linux_path(r"\\wsl$\Ubuntu\home"), "/home");
837 assert_eq!(linux_path(r"\\wsl.localhost\Ubuntu"), "/");
838 assert_eq!(
839 wsl_unc_distro(r"\\wsl.localhost\Ubuntu\home"),
840 Some("Ubuntu")
841 );
842 assert_eq!(wsl_unc_distro(r"\\wsl$\Debian"), Some("Debian"));
843 assert_eq!(wsl_unc_distro(r"C:\Users"), None);
844 assert_eq!(linux_path("/home/daniel"), "/home/daniel");
845 }
846
847 #[test]
848 fn copilot_resumes_with_the_prompt_in_its_args() {
849 let action = AgentAction::answer_this("copilot");
850 let plan = resume_invocation(
851 &AgentProfile::copilot_wsl(),
852 &action,
853 "go on",
854 "sid-7",
855 None,
856 None,
857 )
858 .unwrap();
859 assert_eq!(plan.run.stdin, None);
860 assert!(
861 plan.run
862 .args
863 .windows(2)
864 .any(|pair| pair == ["--resume", "sid-7"])
865 );
866 assert!(plan.run.args.contains(&"go on".to_string()));
867 }
868
869 #[test]
870 fn kill_refuses_a_session_id_that_is_not_plain() {
871 assert_eq!(kill_process_invocation(1, ""), None);
872 assert_eq!(kill_process_invocation(1, "a'; rm -rf /; '"), None);
873 assert_eq!(kill_process_invocation(1, "a b"), None);
874 }
875
876 #[cfg(windows)]
877 #[test]
878 fn kill_checks_the_command_line_before_taskkill() {
879 let invocation = kill_process_invocation(4242, "abc-123").unwrap();
880 assert_eq!(invocation.program, "powershell");
881 assert_eq!(
882 invocation.args[..2],
883 ["-NoProfile", "-Command"].map(String::from)
884 );
885 let script = &invocation.args[2];
886 assert!(script.contains("ProcessId=4242"));
887 assert!(script.contains("-like '*abc-123*'"));
888 assert!(script.contains("taskkill /PID 4242 /T /F"));
889 }
890
891 #[cfg(unix)]
892 mod unix_kill {
893 use super::super::*;
894
895 fn spawn_agent_like(arguments: &[&str]) -> std::process::Child {
896 std::process::Command::new("sh")
897 .args(["-c", "sleep 30", "claude"])
898 .args(arguments)
899 .spawn()
900 .unwrap()
901 }
902
903 fn run_app_stop(session_id: &str) {
904 std::process::Command::new("sh")
905 .args(["-c", APP_STOP_SCRIPT, "sh", session_id])
906 .status()
907 .unwrap();
908 }
909
910 fn is_running(child: &mut std::process::Child) -> bool {
911 child.try_wait().unwrap().is_none()
912 }
913
914 #[test]
915 fn the_app_stop_matches_by_the_role_of_the_session_id() {
916 let session = uuid::Uuid::new_v4().to_string();
917 let fork_id = uuid::Uuid::new_v4().to_string();
918 let mut headless = spawn_agent_like(&[
919 "--print",
920 "--resume",
921 &session,
922 "--output-format",
923 "stream-json",
924 ]);
925 let mut fork = spawn_agent_like(&[
926 "-p",
927 "--output-format",
928 "stream-json",
929 "--resume",
930 &session,
931 "--fork-session",
932 "--session-id",
933 &fork_id,
934 ]);
935 let mut terminal = spawn_agent_like(&["--resume", &session]);
936 std::thread::sleep(std::time::Duration::from_millis(200));
937 run_app_stop(&session);
938 assert!(headless.wait().is_ok_and(|status| !status.success()));
939 assert!(is_running(&mut fork));
940 assert!(is_running(&mut terminal));
941 run_app_stop(&fork_id);
942 assert!(fork.wait().is_ok_and(|status| !status.success()));
943 assert!(is_running(&mut terminal));
944 terminal.kill().unwrap();
945 terminal.wait().unwrap();
946 }
947
948 #[test]
949 fn a_running_stop_script_is_never_killed_by_another() {
950 let session = uuid::Uuid::new_v4().to_string();
951 let mut lookalike = std::process::Command::new("sh")
952 .args([
953 "-c",
954 &format!("sleep 30 # {APP_STOP_SCRIPT}"),
955 "sh",
956 "-p",
957 "--output-format",
958 "--resume",
959 &session,
960 ])
961 .spawn()
962 .unwrap();
963 std::thread::sleep(std::time::Duration::from_millis(200));
964 run_app_stop(&session);
965 assert!(is_running(&mut lookalike));
966 lookalike.kill().unwrap();
967 lookalike.wait().unwrap();
968 }
969
970 fn spawn_sleeper(label: &str) -> std::process::Child {
971 std::process::Command::new("sh")
972 .args(["-c", "sleep 30", label])
973 .spawn()
974 .unwrap()
975 }
976
977 fn run_kill(process_id: u32, session_id: &str) {
978 let invocation = kill_process_invocation(process_id, session_id).unwrap();
979 std::process::Command::new(invocation.program)
980 .args(invocation.args)
981 .status()
982 .unwrap();
983 }
984
985 #[test]
986 fn kills_a_process_whose_command_line_has_the_session_id() {
987 let mut child = spawn_sleeper("fake-session-1");
988 run_kill(child.id(), "fake-session-1");
989 let status = child.wait().unwrap();
990 assert!(!status.success());
991 }
992
993 #[test]
994 fn leaves_a_process_without_the_session_id_alone() {
995 let mut child = spawn_sleeper("other-session");
996 run_kill(child.id(), "fake-session-2");
997 assert!(child.try_wait().unwrap().is_none());
998 child.kill().unwrap();
999 child.wait().unwrap();
1000 }
1001 }
1002
1003 #[test]
1004 fn a_command_without_the_session_flag_cannot_resume() {
1005 let mut profile = AgentProfile::claude_host();
1006 profile.command = "tool -p".to_string();
1007 let action = AgentAction::build_this("claude-host");
1008 assert!(!supports_resume(&profile));
1009 assert_eq!(
1010 resume_invocation(&profile, &action, "go on", "sid", None, None),
1011 Err(InvocationError::CannotResume)
1012 );
1013 }
1014}