1use super::*;
13use std::collections::HashMap;
14use std::sync::{LazyLock, Mutex};
15use std::time::{Duration, Instant};
16
17pub(super) const ACTIONS: &[&str] = &["open", "type", "read", "wait", "run", "close", "connections"];
18
19#[derive(Clone, Debug, PartialEq)]
21enum Kind {
22 Pty,
23 Background,
24}
25
26#[derive(Clone, Debug)]
27struct Known {
28 kind: Kind,
29 connection: Option<String>,
30 family: Option<ShellFamily>,
33}
34
35#[derive(Default)]
36struct State {
37 known: HashMap<String, Known>,
38 drawer: Option<String>,
39}
40
41static STATE: LazyLock<Mutex<State>> = LazyLock::new(Default::default);
42
43static CAPTURES: LazyLock<Mutex<std::collections::HashSet<String>>> = LazyLock::new(Default::default);
46
47fn captures(arguments: &Value) -> bool {
48 arguments.get("capture").and_then(Value::as_array).is_some_and(|a| !a.is_empty())
49}
50
51async fn add_capture_outcome(cx: &ToolCtx<'_>, id: &str, out: &mut Value) {
55 if !CAPTURES.lock().unwrap_or_else(|p| p.into_inner()).contains(id) {
56 return;
57 }
58 let Ok(auth) = sign_ui_automation_auth() else { return };
59 let Ok(body) = serde_json::to_value(agentmux_common::api_types::ShellOutputRequest { shell_id: id.to_string(), auth }) else { return };
60 let base = cx.local_url.trim_end_matches('/');
61 let Ok(v) = srv_post_json(cx.client, &format!("{base}/api/v1/shell/output"), cx.auth_key, &body, "Terminal output").await else { return };
62 let Ok(r) = serde_json::from_value::<agentmux_common::api_types::ShellOutputResponse>(v) else { return };
63 if r.running {
64 return;
65 }
66 out["captured"] = json!(r.captured);
67 if let Some(why) = r.withheld {
68 out["withheld"] = json!(why);
69 }
70}
71
72const CHUNK_CHARS: usize = 400;
75const CHUNK_GAP: Duration = Duration::from_millis(15);
76const POLL: Duration = Duration::from_millis(200);
77const DEFAULT_TIMEOUT_MS: u64 = 30_000;
78const MAX_TIMEOUT_MS: u64 = 600_000;
79const READ_ALL_LINES: u32 = 20_000;
81const MAX_RUN_LINES: usize = 400;
82
83pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
84 match name {
85 "Terminal" => {
86 let action = arguments.get("action").and_then(|v| v.as_str()).unwrap_or("");
87 let out = match action {
88 "open" => open(arguments, cx).await?,
89 "type" => type_action(arguments, cx).await?,
90 "read" => read_action(arguments, cx).await?,
91 "wait" => wait_action(arguments, cx).await?,
92 "run" => run_action(arguments, cx).await?,
93 "close" => close(arguments, cx).await?,
94 "connections" => return shell::call("ConnList", arguments, cx).await,
95 "" => anyhow::bail!("missing required parameter: action (one of {})", ACTIONS.join(", ")),
96 other => anyhow::bail!("unknown action {other:?}: use one of {}", ACTIONS.join(", ")),
97 };
98 Ok(serde_json::to_string_pretty(&out)?)
99 }
100 _ => Err(not_in_family()),
101 }
102}
103
104fn target(connection: Option<&str>) -> Value {
110 match connection.filter(|c| *c != "local") {
111 None => {
112 let shell = if cfg!(windows) {
113 "cmd".to_string()
114 } else {
115 std::env::var("SHELL")
116 .ok()
117 .and_then(|s| std::path::Path::new(&s).file_name().map(|f| f.to_string_lossy().into_owned()))
118 .unwrap_or_else(|| "sh".to_string())
119 };
120 json!({ "platform": std::env::consts::OS, "shell": shell, "connection": "local" })
121 }
122 Some(c) if c.starts_with("wsl://") => json!({ "platform": "linux", "shell": "login shell", "connection": c }),
123 Some(c) => json!({ "platform": "remote", "shell": "login shell", "connection": c }),
124 }
125}
126
127#[derive(Clone, Copy, Debug, PartialEq)]
128pub(super) enum ShellFamily {
129 Cmd,
130 Posix,
131 Fish,
133 Pwsh,
135}
136
137fn local_family(connection: Option<&str>) -> Option<ShellFamily> {
140 match connection.filter(|c| *c != "local") {
141 None if cfg!(windows) => Some(ShellFamily::Cmd),
142 None if target(None)["shell"] == "fish" => Some(ShellFamily::Fish),
143 None => Some(ShellFamily::Posix),
144 Some(_) => None,
145 }
146}
147
148fn remember(id: &str, kind: Kind, connection: Option<String>) {
149 let mut st = STATE.lock().unwrap();
150 let family = local_family(connection.as_deref());
151 st.known.insert(id.to_string(), Known { kind: kind.clone(), connection, family });
152 if kind == Kind::Pty {
153 st.drawer = Some(id.to_string());
154 }
155}
156
157fn known(id: &str) -> Known {
158 STATE
159 .lock()
160 .unwrap()
161 .known
162 .get(id)
163 .cloned()
164 .unwrap_or(Known { kind: Kind::Pty, connection: None, family: local_family(None) })
165}
166
167async fn family_of(cx: &ToolCtx<'_>, id: &str) -> Result<ShellFamily> {
171 if let Some(f) = known(id).family {
172 return Ok(f);
173 }
174 let family = probe_family(cx, id).await.unwrap_or(ShellFamily::Posix);
175 if let Some(k) = STATE.lock().unwrap().known.get_mut(id) {
176 k.family = Some(family);
177 }
178 Ok(family)
179}
180
181pub(super) fn probe_line(nonce: &str) -> String {
184 format!("echo __AMX_FAM_{nonce}_{PROBE_EXPR}.end")
185}
186
187const PROBE_EXPR: &str = "%COMSPEC%_$FISH_VERSION.$PSVersionTable";
189
190pub(super) fn classify_probe(text: &str, nonce: &str) -> Option<ShellFamily> {
193 let re = regex::Regex::new(&format!(r"__AMX_FAM_{}_(.*?)\.end", regex::escape(nonce))).ok()?;
194 let got = re
197 .captures_iter(text)
198 .filter_map(|c| c.get(1).map(|g| g.as_str().to_string()))
199 .find(|g| g != PROBE_EXPR)?;
200 let lower = got.to_ascii_lowercase();
201 Some(if lower.contains("cmd.exe") {
202 ShellFamily::Cmd
203 } else if got.contains("PSVersionHashTable") {
204 ShellFamily::Pwsh
205 } else if got.starts_with("%COMSPEC%_") && got[10..].starts_with(|c: char| c.is_ascii_digit()) {
206 ShellFamily::Fish
207 } else {
208 ShellFamily::Posix
209 })
210}
211
212async fn probe_family(cx: &ToolCtx<'_>, id: &str) -> Result<ShellFamily> {
213 let nonce = uuid::Uuid::new_v4().simple().to_string()[..8].to_string();
214 let start = read_log(cx, id, None, 1).await?.end;
215 write(cx, id, &format!("{}\r", probe_line(&nonce))).await?;
216 let deadline = Instant::now() + Duration::from_secs(5);
217 while Instant::now() < deadline {
218 tokio::time::sleep(POLL).await;
219 let text = strip_ansi(&read_log(cx, id, Some(start), READ_ALL_LINES).await?.content);
220 if let Some(f) = classify_probe(&text, &nonce) {
221 return Ok(f);
222 }
223 }
224 anyhow::bail!("the shell didn't answer the probe")
225}
226
227async fn resolve(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
230 if let Some(id) = arg_str(arguments, "terminal").or_else(|| arg_str(arguments, "shell_id")) {
231 return Ok(id.to_string());
232 }
233 if let Some(id) = STATE.lock().unwrap().drawer.clone() {
234 return Ok(id);
235 }
236 let opened = open(arguments, cx).await?;
237 Ok(opened["terminal"].as_str().unwrap_or_default().to_string())
238}
239
240async fn open(arguments: &Value, cx: &ToolCtx<'_>) -> Result<Value> {
243 let id = pty_shell::call("PtyShell", arguments, cx).await?;
244 let connection = arg_str(arguments, "connection").map(str::to_string);
245 remember(&id, Kind::Pty, connection.clone());
246 if known(&id).family.is_none() {
250 tokio::time::sleep(Duration::from_millis(500)).await;
251 let tail = strip_ansi(&read_log(cx, &id, None, 5).await?.content);
252 if at_any_prompt(&tail, None) {
253 family_of(cx, &id).await?;
254 }
255 }
256 let mut out = target(connection.as_deref());
257 out["terminal"] = json!(id);
258 out["kind"] = json!("drawer");
259 out["note"] = json!("Your pane's shell drawer: the same terminal the user sees there.");
260 Ok(out)
261}
262
263async fn close(arguments: &Value, cx: &ToolCtx<'_>) -> Result<Value> {
264 let id = resolve(arguments, cx).await?;
265 let args = json!({ "shell_id": id });
266 let message = match known(&id).kind {
267 Kind::Background => shell::call("ShellStop", &args, cx).await?,
268 Kind::Pty => pty_shell::call("PtyShellStop", &args, cx).await?,
269 };
270 Ok(json!({ "terminal": id, "result": message }))
271}
272
273async fn type_action(arguments: &Value, cx: &ToolCtx<'_>) -> Result<Value> {
276 let id = resolve(arguments, cx).await?;
277 let text = arguments.get("text").and_then(|v| v.as_str()).unwrap_or("");
278 let keys = key_list(arguments)?;
279 let submit = arguments.get("submit").and_then(|v| v.as_bool()).unwrap_or(false);
280 if text.is_empty() && keys.is_empty() && !submit {
281 anyhow::bail!("type needs text, keys or submit");
282 }
283
284 if known(&id).kind == Kind::Background {
285 if !keys.is_empty() {
286 anyhow::bail!("keys go to a terminal; a background job takes text on stdin only");
287 }
288 if !submit {
291 anyhow::bail!("a background job's stdin takes whole lines: pass submit: true to send text as a line");
292 }
293 let result = shell::call("ShellInput", &json!({ "shell_id": id, "text": text }), cx).await?;
294 return Ok(json!({ "terminal": id, "result": result }));
295 }
296
297 if let (Some(rows), Some(cols)) = (arguments.get("rows"), arguments.get("cols")) {
298 pty_shell::call("PtyShellResize", &json!({ "shell_id": id, "rows": rows, "cols": cols }), cx).await?;
299 }
300 let start = read_log(cx, &id, None, 1).await?.end;
301 let mut bytes = to_cr(text);
302 for k in &keys {
303 bytes.push_str(k);
304 }
305 if submit {
306 bytes.push('\r');
307 }
308 write(cx, &id, &bytes).await?;
309
310 let mut out = json!({ "terminal": id, "since": start });
311 if arguments.get("until").is_some() {
312 let waited = wait_on(arguments, cx, &id, start, text.lines().count()).await?;
316 out["wait"] = waited;
317 } else {
318 tokio::time::sleep(Duration::from_millis(300)).await;
319 }
320 let tail_lines = arguments.get("tail_lines").and_then(|v| v.as_u64()).unwrap_or(15) as u32;
321 if tail_lines > 0 {
322 let log = read_log(cx, &id, Some(start), tail_lines).await?;
323 out["output"] = json!(strip_ansi(&log.content));
324 out["since"] = json!(log.end);
325 }
326 Ok(out)
327}
328
329fn key_list(arguments: &Value) -> Result<Vec<String>> {
331 let Some(list) = arguments.get("keys") else { return Ok(vec![]) };
332 let names: Vec<&str> = match list {
333 Value::String(s) => vec![s.as_str()],
334 Value::Array(a) => a.iter().filter_map(|v| v.as_str()).collect(),
335 _ => anyhow::bail!("keys is a list of key names, e.g. [\"Ctrl+C\"] or [\"Down\", \"Enter\"]"),
336 };
337 names
338 .iter()
339 .map(|n| {
340 key_bytes(n).ok_or_else(|| {
341 anyhow::anyhow!(
342 "unknown key {n:?}: use Enter, Tab, Shift+Tab, Esc, Backspace, Delete, Insert, Space, \
343 Up, Down, Left, Right, Home, End, PageUp, PageDown, F1-F12, Ctrl+<letter>, Alt+<key>"
344 )
345 })
346 })
347 .collect()
348}
349
350pub(super) fn key_bytes(name: &str) -> Option<String> {
354 let trimmed = name.trim();
355 let lower = trimmed.to_ascii_lowercase();
356 let fixed = match lower.as_str() {
357 "enter" | "return" => "\r",
358 "tab" => "\t",
359 "shift+tab" => "\x1b[Z",
360 "esc" | "escape" => "\x1b",
361 "backspace" => "\x7f",
362 "delete" | "del" => "\x1b[3~",
363 "insert" => "\x1b[2~",
364 "space" => " ",
365 "up" => "\x1b[A",
366 "down" => "\x1b[B",
367 "right" => "\x1b[C",
368 "left" => "\x1b[D",
369 "home" => "\x1b[H",
370 "end" => "\x1b[F",
371 "pageup" => "\x1b[5~",
372 "pagedown" => "\x1b[6~",
373 "f1" => "\x1bOP",
374 "f2" => "\x1bOQ",
375 "f3" => "\x1bOR",
376 "f4" => "\x1bOS",
377 "f5" => "\x1b[15~",
378 "f6" => "\x1b[17~",
379 "f7" => "\x1b[18~",
380 "f8" => "\x1b[19~",
381 "f9" => "\x1b[20~",
382 "f10" => "\x1b[21~",
383 "f11" => "\x1b[23~",
384 "f12" => "\x1b[24~",
385 _ => "",
386 };
387 if !fixed.is_empty() {
388 return Some(fixed.to_string());
389 }
390 if let Some(rest) = lower.strip_prefix("ctrl+") {
391 let mut chars = rest.chars();
392 if let (Some(c), None) = (chars.next(), chars.next()) {
393 return match c {
394 'a'..='z' => Some(((c as u8 - b'a' + 1) as char).to_string()),
395 '[' => Some("\x1b".to_string()),
396 '\\' => Some("\x1c".to_string()),
397 ']' => Some("\x1d".to_string()),
398 '@' | ' ' => Some("\0".to_string()),
399 _ => None,
400 };
401 }
402 }
403 if lower.starts_with("alt+") {
404 let rest = &trimmed[4..];
405 if rest.chars().count() == 1 {
406 return Some(format!("\x1b{rest}"));
407 }
408 if let Some(k) = key_bytes(rest) {
409 return Some(format!("\x1b{k}"));
410 }
411 }
412 None
413}
414
415pub(super) fn to_cr(text: &str) -> String {
418 text.replace("\r\n", "\r").replace('\n', "\r")
419}
420
421pub(super) fn chunks(s: &str, max: usize) -> Vec<String> {
423 let chars: Vec<char> = s.chars().collect();
424 chars.chunks(max.max(1)).map(|c| c.iter().collect()).collect()
425}
426
427async fn write(cx: &ToolCtx<'_>, id: &str, bytes: &str) -> Result<()> {
428 for (i, piece) in chunks(bytes, CHUNK_CHARS).iter().enumerate() {
429 if i > 0 {
430 tokio::time::sleep(CHUNK_GAP).await;
431 }
432 let res = pty_shell::call("PtyShellInput", &json!({ "shell_id": id, "text": piece }), cx).await?;
433 if !res.starts_with("wrote to shell") {
434 anyhow::bail!("{res}");
435 }
436 }
437 Ok(())
438}
439
440struct Log {
443 content: String,
444 end: u64,
445 truncated: bool,
446}
447
448async fn read_log(cx: &ToolCtx<'_>, id: &str, since: Option<u64>, tail_lines: u32) -> Result<Log> {
449 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
450 let url = format!("{}/api/v1/ptyshell/read", cx.local_url.trim_end_matches('/'));
451 let req = PtyShellReadRequest {
452 shell_id: id.to_string(),
453 agent_block_id: cx.block_id.to_string(),
454 tail_lines: Some(tail_lines.max(1)),
455 since,
456 };
457 let body = srv_post_json(cx.client, &url, cx.auth_key, &serde_json::to_value(&req)?, "Terminal read").await?;
458 let r: PtyShellReadResponse = serde_json::from_value(body)?;
459 let held = incomplete_escape(&r.content);
463 let mut content = r.content;
464 content.truncate(content.len() - held);
465 Ok(Log { content, end: r.end.saturating_sub(held as u64), truncated: r.truncated })
466}
467
468pub(super) fn incomplete_escape(s: &str) -> usize {
473 const MOST: usize = 256;
474 let Some(p) = s.rfind('\x1b') else { return 0 };
475 let rest = &s[p..];
476 if rest.len() > MOST {
477 return 0;
478 }
479 let mut chars = rest.chars().skip(1);
480 let open = match chars.next() {
481 None => true,
482 Some('[') => !chars.any(|d| ('@'..='~').contains(&d)),
483 Some(']' | 'P' | '_' | '^') => !chars.any(|d| d == '\x07'),
484 Some(_) => false,
485 };
486 if open { rest.len() } else { 0 }
487}
488
489async fn read_action(arguments: &Value, cx: &ToolCtx<'_>) -> Result<Value> {
490 let id = resolve(arguments, cx).await?;
491 let (running, exit_code) = status(cx, &id).await?;
492 if known(&id).kind == Kind::Background {
493 let mut out = json!({
494 "terminal": id, "kind": "background", "running": running, "exit_code": exit_code,
495 "note": "A background job's output streams into its shell row in this conversation; this reads its state only.",
496 });
497 if !running {
498 add_capture_outcome(cx, &id, &mut out).await;
499 }
500 return Ok(out);
501 }
502 let since = arguments.get("since").and_then(|v| v.as_u64());
503 let tail_lines = arguments.get("tail_lines").and_then(|v| v.as_u64()).unwrap_or(80) as u32;
504 let log = read_log(cx, &id, since, tail_lines).await?;
505 let raw = arguments.get("raw").and_then(|v| v.as_bool()).unwrap_or(false);
506 Ok(json!({
507 "terminal": id,
508 "output": if raw { log.content } else { strip_ansi(&log.content) },
509 "truncated": log.truncated,
510 "since": log.end,
511 "running": running,
512 "exit_code": exit_code,
513 }))
514}
515
516async fn status(cx: &ToolCtx<'_>, id: &str) -> Result<(bool, Option<i32>)> {
517 require_agent_env(cx.local_url, cx.auth_key, cx.block_id)?;
518 let base = cx.local_url.trim_end_matches('/');
519 match known(id).kind {
520 Kind::Background => {
521 let body = serde_json::to_value(ShellStatusRequest { shell_id: id.to_string() })?;
522 let v = srv_post_json(cx.client, &format!("{base}/api/v1/shell/status"), cx.auth_key, &body, "Terminal status").await?;
523 let r: ShellStatusResponse = serde_json::from_value(v)?;
524 Ok((r.running, r.exit_code))
525 }
526 Kind::Pty => {
527 let body = serde_json::to_value(PtyShellStatusRequest {
528 shell_id: id.to_string(),
529 agent_block_id: cx.block_id.to_string(),
530 })?;
531 let v = srv_post_json(cx.client, &format!("{base}/api/v1/ptyshell/status"), cx.auth_key, &body, "Terminal status").await?;
532 let r: PtyShellStatusResponse = serde_json::from_value(v)?;
533 Ok((r.running, r.exit_code))
534 }
535 }
536}
537
538pub(super) fn strip_ansi(s: &str) -> String {
543 let mut out = String::with_capacity(s.len());
544 let mut line = String::new();
545 let mut chars = s.chars().peekable();
546 while let Some(c) = chars.next() {
547 match c {
548 '\x1b' => match chars.peek().copied() {
549 Some('[') => {
550 chars.next();
551 for d in chars.by_ref() {
552 if ('@'..='~').contains(&d) {
553 if matches!(d, 'H' | 'f' | 'E' | 'd' | 'B') && !line.trim().is_empty() {
556 out.push_str(line.trim_end());
557 out.push('\n');
558 line.clear();
559 }
560 break;
561 }
562 }
563 }
564 Some(']') | Some('P') | Some('_') | Some('^') => {
565 chars.next();
566 while let Some(d) = chars.next() {
567 if d == '\x07' {
568 break;
569 }
570 if d == '\x1b' {
571 if chars.peek() == Some(&'\\') {
572 chars.next();
573 }
574 break;
575 }
576 }
577 }
578 Some(_) => {
579 chars.next();
580 }
581 None => {}
582 },
583 '\r' => {
584 if chars.peek() != Some(&'\n') {
585 line.clear();
586 }
587 }
588 '\n' => {
589 out.push_str(line.trim_end());
590 out.push('\n');
591 line.clear();
592 }
593 '\x08' => {
594 line.pop();
595 }
596 '\t' => line.push('\t'),
597 c if c.is_control() => {}
598 c => line.push(c),
599 }
600 }
601 out.push_str(&line);
602 out
603}
604
605async fn wait_action(arguments: &Value, cx: &ToolCtx<'_>) -> Result<Value> {
608 let id = resolve(arguments, cx).await?;
609 let since = match arguments.get("since").and_then(|v| v.as_u64()) {
610 Some(s) => s,
611 None if known(&id).kind == Kind::Pty => read_log(cx, &id, None, 1).await?.end,
612 None => 0,
613 };
614 let mut out = wait_on(arguments, cx, &id, since, 0).await?;
615 out["terminal"] = json!(id);
616 Ok(out)
617}
618
619#[derive(Debug)]
620enum Until {
621 Pattern(regex::Regex),
622 Quiet,
623 Prompt,
624 Exit,
625}
626
627fn parse_until(arguments: &Value) -> Result<Until> {
628 let until = arguments.get("until").and_then(|v| v.as_str()).unwrap_or("");
629 let pattern = arguments.get("pattern").and_then(|v| v.as_str());
630 match until {
631 "pattern" => {
632 let p = pattern.ok_or_else(|| anyhow::anyhow!("until \"pattern\" needs pattern"))?;
633 let fixed = arguments.get("fixed").and_then(|v| v.as_bool()).unwrap_or(false);
634 let src = if fixed { regex::escape(p) } else { p.to_string() };
635 Ok(Until::Pattern(regex::Regex::new(&src).map_err(|e| anyhow::anyhow!("pattern: {e}"))?))
636 }
637 "quiet" => Ok(Until::Quiet),
638 "prompt" => Ok(Until::Prompt),
639 "exit" => Ok(Until::Exit),
640 "" => anyhow::bail!("wait needs until: \"pattern\", \"quiet\", \"prompt\" or \"exit\""),
641 other => anyhow::bail!("unknown until {other:?}: use \"pattern\", \"quiet\", \"prompt\" or \"exit\""),
642 }
643}
644
645async fn wait_on(arguments: &Value, cx: &ToolCtx<'_>, id: &str, since: u64, echo_lines: usize) -> Result<Value> {
649 let until = parse_until(arguments)?;
650 let timeout_ms = arguments
651 .get("timeout_ms")
652 .and_then(|v| v.as_u64())
653 .unwrap_or(DEFAULT_TIMEOUT_MS)
654 .min(MAX_TIMEOUT_MS);
655 let quiet_ms = arguments.get("quiet_ms").and_then(|v| v.as_u64()).unwrap_or(1500);
656 let background = known(id).kind == Kind::Background;
657 let exit = matches!(until, Until::Exit);
658 if background && !exit {
659 anyhow::bail!("a background job can only be waited on with until \"exit\"");
660 }
661 let family = known(id).family;
664 let started = Instant::now();
665 let deadline = started + Duration::from_millis(timeout_ms);
666 let mut last_end = u64::MAX;
669 let mut last_change = Instant::now();
670 loop {
671 let elapsed = started.elapsed().as_millis() as u64;
672 if exit {
673 let (running, exit_code) = status(cx, id).await?;
674 if !running {
675 let mut out = json!({ "how": "exited", "exit_code": exit_code, "elapsed_ms": elapsed });
676 add_capture_outcome(cx, id, &mut out).await;
677 return Ok(out);
678 }
679 } else {
680 let log = read_log(cx, id, Some(since), READ_ALL_LINES).await?;
681 let text = strip_ansi(&log.content);
682 if log.end != last_end {
683 last_end = log.end;
684 last_change = Instant::now();
685 }
686 let quiet_for = last_change.elapsed().as_millis() as u64;
687 let searched = after_lines(&text, echo_lines);
688 let found = match &until {
689 Until::Pattern(re) => re.captures(searched).map(|c| {
690 c.iter().map(|m| m.map(|m| m.as_str().to_string())).collect::<Vec<_>>()
691 }),
692 Until::Quiet => (quiet_for >= quiet_ms).then(Vec::new),
693 Until::Prompt if quiet_for >= 300 => {
697 let now = strip_ansi(&read_log(cx, id, None, 5).await?.content);
698 at_any_prompt(&now, family).then(Vec::new)
699 }
700 Until::Prompt => None,
701 Until::Exit => None,
702 };
703 if let Some(groups) = found {
704 let how = match until {
705 Until::Pattern(_) => "matched",
706 Until::Quiet => "quiet",
707 _ => "prompt",
708 };
709 let mut out = json!({ "how": how, "elapsed_ms": elapsed, "since": log.end, "tail": tail(&text, 20) });
710 if !groups.is_empty() {
711 out["match"] = json!(groups);
712 }
713 return Ok(out);
714 }
715 if Instant::now() >= deadline {
716 return Ok(json!({ "how": "timeout", "elapsed_ms": elapsed, "since": log.end, "tail": tail(&text, 20) }));
717 }
718 }
719 if Instant::now() >= deadline {
720 return Ok(json!({ "how": "timeout", "elapsed_ms": started.elapsed().as_millis() as u64 }));
721 }
722 tokio::time::sleep(POLL).await;
723 }
724}
725
726pub(super) fn after_first_line(text: &str) -> &str {
727 after_lines(text, 1)
728}
729
730pub(super) fn after_lines(text: &str, n: usize) -> &str {
732 let mut rest = text;
733 for _ in 0..n {
734 rest = rest.split_once('\n').map(|(_, r)| r).unwrap_or("");
735 }
736 rest
737}
738
739pub(super) fn tail(text: &str, lines: usize) -> String {
740 let all: Vec<&str> = text.lines().collect();
741 all[all.len().saturating_sub(lines)..].join("\n")
742}
743
744pub(super) fn at_prompt(text: &str, family: ShellFamily) -> bool {
747 let Some(last) = text.lines().rev().find(|l| !l.trim().is_empty()) else { return false };
748 let last = last.trim_end();
749 match family {
750 ShellFamily::Cmd | ShellFamily::Pwsh => {
751 let b = last.as_bytes();
752 (b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && b[2] == b'\\' && last.ends_with('>'))
753 || (last.starts_with("PS ") && last.ends_with('>'))
754 }
755 ShellFamily::Posix | ShellFamily::Fish => ["$", "#", "%", ">", "❯"].iter().any(|p| last.ends_with(p)),
756 }
757}
758
759pub(super) fn at_any_prompt(text: &str, family: Option<ShellFamily>) -> bool {
761 match family {
762 Some(f) => at_prompt(text, f),
763 None => at_prompt(text, ShellFamily::Cmd) || at_prompt(text, ShellFamily::Posix),
764 }
765}
766
767pub(super) fn without_trailing_comment(command: &str, family: ShellFamily) -> &str {
774 if family == ShellFamily::Cmd {
775 return command;
776 }
777 let (mut single, mut double, mut escaped) = (false, false, false);
778 let mut prev_space = true;
779 for (i, c) in command.char_indices() {
780 if escaped {
781 escaped = false;
782 } else if c == '\\' && !single && family != ShellFamily::Pwsh {
783 escaped = true;
784 } else if c == '`' && family == ShellFamily::Pwsh && !single {
785 escaped = true;
786 } else if c == '\'' && !double {
787 single = !single;
788 } else if c == '"' && !single {
789 double = !double;
790 } else if c == '#' && !single && !double && prev_space {
791 return command[..i].trim_end();
792 }
793 prev_space = c.is_whitespace();
794 }
795 command
796}
797
798pub(super) fn without_trailing_semicolon(command: &str, family: ShellFamily) -> &str {
802 let c = command.trim_end();
803 let esc = if family == ShellFamily::Pwsh { '`' } else { '\\' };
804 match c.strip_suffix(';') {
805 Some(before) if family != ShellFamily::Cmd => {
806 let escaped = before.chars().rev().take_while(|&ch| ch == esc).count() % 2 == 1;
807 if escaped { c } else { before.trim_end() }
808 }
809 _ => c,
810 }
811}
812
813pub(super) fn open_ending(command: &str, family: ShellFamily) -> Option<&'static str> {
818 let (esc, name) = match family {
819 ShellFamily::Cmd => ('^', "^"),
820 ShellFamily::Pwsh => ('`', "`"),
821 ShellFamily::Posix | ShellFamily::Fish => ('\\', "\\"),
822 };
823 let escapes = |s: &str| s.chars().rev().take_while(|&ch| ch == esc).count() % 2 == 1;
826 let c = command.trim_end();
827 for end in ["&&", "||", "|", "&"] {
828 if let Some(before) = c.strip_suffix(end) {
829 return (!escapes(before)).then_some(end);
831 }
832 }
833 escapes(c).then_some(name)
834}
835
836pub(super) fn with_exit_marker(command: &str, family: ShellFamily, nonce: &str) -> String {
845 match family {
846 ShellFamily::Cmd => format!("{command} & call echo __AMX_RC_{nonce}_%^ERRORLEVEL%__"),
847 ShellFamily::Posix => format!("{command}; echo \"__AMX_RC_{nonce}_$?__\""),
848 ShellFamily::Fish => format!("{command}; echo \"__AMX_RC_{nonce}_\"$status\"__\""),
851 ShellFamily::Pwsh => format!(
852 "{command}; echo \"__AMX_RC_{nonce}_$(if ($?) {{ 0 }} elseif ($LASTEXITCODE) {{ $LASTEXITCODE }} else {{ 1 }})__\""
853 ),
854 }
855}
856
857pub(super) fn in_dir(command: &str, cwd: &str, family: ShellFamily) -> Result<String> {
862 let home_rest = match cwd {
863 "~" => Some(""),
864 _ => cwd.strip_prefix("~/").or_else(|| cwd.strip_prefix("~\\")),
865 };
866 Ok(match family {
867 ShellFamily::Cmd => {
868 if cwd.contains('%') {
870 anyhow::bail!("cmd can't take a cwd with % literally: cd there with type first, then run");
871 }
872 format!("cd /d \"{cwd}\" && {command}")
873 }
874 ShellFamily::Posix | ShellFamily::Fish => {
875 let quote = |s: &str| match family {
876 ShellFamily::Fish => format!("'{}'", s.replace('\\', "\\\\").replace('\'', "\\'")),
877 _ => format!("'{}'", s.replace('\'', "'\\''")),
878 };
879 let dir = match home_rest {
880 Some("") => "~".to_string(),
881 Some(rest) => format!("~/{}", quote(rest)),
882 None => quote(cwd),
883 };
884 format!("cd {dir} && {command}")
885 }
886 ShellFamily::Pwsh => {
887 let quote = |s: &str| format!("'{}'", s.replace('\'', "''"));
888 let dir = match home_rest {
889 Some("") => "$HOME".to_string(),
890 Some(rest) => format!("(Join-Path $HOME {})", quote(rest)),
891 None => quote(cwd),
892 };
893 format!("Set-Location -LiteralPath {dir}; {command}")
894 }
895 })
896}
897
898pub(super) fn clear_line(family: ShellFamily) -> &'static str {
901 match family {
902 ShellFamily::Cmd | ShellFamily::Pwsh => "\x1b",
903 ShellFamily::Posix | ShellFamily::Fish => "\x15",
904 }
905}
906
907pub(super) fn exit_marker(text: &str, nonce: &str) -> Option<(String, i64)> {
910 let re = regex::Regex::new(&format!(r"__AMX_RC_{}_(-?\d+)__", regex::escape(nonce))).ok()?;
911 let caps = re.captures(text)?;
912 let m = caps.get(0)?;
913 let code = caps[1].parse().ok()?;
914 let tag = format!("__AMX_RC_{nonce}_");
918 let before = &text[..m.start()];
919 let kept: Vec<(usize, char)> = before.char_indices().filter(|(_, c)| *c != '\n').collect();
922 let joined: String = kept.iter().map(|(_, c)| *c).collect();
923 let start = match joined.rfind(&tag) {
924 Some(j) => {
925 let at = kept[joined[..j + tag.len()].chars().count() - 1].0;
926 before[at..].find('\n').map(|n| at + n + 1).unwrap_or(m.start())
927 }
928 None => 0,
929 };
930 Some((text[start..m.start()].trim_end().to_string(), code))
933}
934
935async fn await_prompt(cx: &ToolCtx<'_>, id: &str) -> Result<()> {
938 let family = known(id).family;
939 let deadline = Instant::now() + Duration::from_millis(2000);
940 loop {
941 let tail = strip_ansi(&read_log(cx, id, None, 5).await?.content);
942 if at_any_prompt(&tail, family) {
943 return Ok(());
944 }
945 if Instant::now() >= deadline {
946 anyhow::bail!(
947 "the terminal isn't at a shell prompt, so something is running in it: read it, drive it with type, \
948 or wait with until \"prompt\"; run types a command only at a prompt"
949 );
950 }
951 tokio::time::sleep(POLL).await;
952 }
953}
954
955fn gives_secrets(arguments: &Value) -> bool {
958 let named = |k: &str| arguments.get(k).is_some_and(|s| s.as_object().is_some_and(|o| !o.is_empty()));
959 named("secrets")
960 || named("secret_files")
961 || arguments.get("stdin_secret").and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty())
962 || captures(arguments)
963}
964
965const NEVER_STARTED: Duration = Duration::from_secs(15);
967
968async fn run_with_secrets(arguments: &Value, command: &str, cx: &ToolCtx<'_>) -> Result<Value> {
973 if command.contains('\n') {
974 anyhow::bail!("run takes one command line; join steps with && (or put them in a script file)");
975 }
976 let mut args = arguments.clone();
977 args["cmd"] = json!(command);
978 let created = shell::create(&args, cx).await?;
979 let mut out = wait_for_job(arguments, created.shell_id, cx).await?;
980 if let Some(a) = created.approval {
981 out["approval"] = json!(a);
982 }
983 Ok(out)
984}
985
986async fn wait_for_job(arguments: &Value, id: String, cx: &ToolCtx<'_>) -> Result<Value> {
988 remember(&id, Kind::Background, arg_str(arguments, "connection").map(str::to_string));
989 if captures(arguments) {
990 CAPTURES.lock().unwrap_or_else(|p| p.into_inner()).insert(id.clone());
991 }
992 let timeout_ms = arguments.get("timeout_ms").and_then(|v| v.as_u64()).unwrap_or(120_000).min(MAX_TIMEOUT_MS);
993 let started = Instant::now();
994 let deadline = started + Duration::from_millis(timeout_ms);
995 let base = cx.local_url.trim_end_matches('/').to_string();
996 sign_ui_automation_auth().map_err(|e| anyhow::anyhow!("the job started, but reading its output needs this agent's signed identity: {e}"))?;
999 let mut seen = false;
1002 let mut last_error = String::new();
1003 let mut last: Option<agentmux_common::api_types::ShellOutputResponse> = None;
1004 loop {
1005 let body = serde_json::to_value(agentmux_common::api_types::ShellOutputRequest { shell_id: id.clone(), auth: sign_ui_automation_auth()? })?;
1006 let polled = srv_post_json(cx.client, &format!("{base}/api/v1/shell/output"), cx.auth_key, &body, "Terminal output").await;
1007 match polled.and_then(|v| Ok(serde_json::from_value::<agentmux_common::api_types::ShellOutputResponse>(v)?)) {
1008 Ok(r) => {
1009 seen = true;
1010 last = Some(r);
1011 }
1012 Err(e) => last_error = e.to_string(),
1013 }
1014 if !seen && (started.elapsed() > NEVER_STARTED || Instant::now() >= deadline) {
1016 return Ok(json!({
1017 "terminal": id,
1018 "how": "no-output",
1019 "note": format!("The job was created but srv has no output for it, so it may not have started ({last_error}). Check it with wait until \"exit\"; close stops it."),
1020 }));
1021 }
1022 let Some(r) = last.clone() else {
1023 tokio::time::sleep(POLL).await;
1024 continue;
1025 };
1026 let lines: Vec<&str> = r.output.lines().collect();
1027 let cut = lines.len() > MAX_RUN_LINES;
1028 let output = lines[lines.len().saturating_sub(MAX_RUN_LINES)..].join("\n");
1029 if !r.running {
1031 let mut done = json!({
1032 "terminal": id,
1033 "exit_code": r.exit_code,
1034 "output": output,
1035 "truncated": r.truncated || cut,
1036 "duration_ms": started.elapsed().as_millis() as u64,
1037 "note": "The output is cleaned of the Vault values the command was given or printed: they show as [vault:<id>].",
1038 });
1039 if !r.captured.is_empty() {
1040 done["captured"] = json!(r.captured);
1041 }
1042 if let Some(why) = r.withheld {
1043 done["withheld"] = json!(why);
1044 done["note"] = json!(if r.captured.is_empty() {
1045 "The capture failed, so the output is withheld: nothing it printed went into the Vault. The person can open the output in the Vault."
1046 } else {
1047 "The values went into the Vault (captured), but the output is withheld: it couldn't be cleaned of them."
1048 });
1049 }
1050 return Ok(done);
1051 }
1052 if Instant::now() >= deadline {
1053 return Ok(json!({
1054 "terminal": id,
1055 "how": "timeout",
1056 "running": true,
1057 "output": output,
1058 "truncated": r.truncated || cut,
1059 "note": if arguments.get("capture").is_some_and(|c| !c.is_null()) {
1060 "Still running as a background job; its output is held until it ends, for capture: wait with until \"exit\" waits for it; close stops it."
1061 } else {
1062 "Still running as a background job: wait with until \"exit\" waits for it; close stops it."
1063 },
1064 }));
1065 }
1066 tokio::time::sleep(POLL).await;
1067 }
1068}
1069
1070fn check_run_arguments(arguments: &Value) -> Result<()> {
1072 for key in ["secrets", "secret_files"] {
1073 if let Some(s) = arguments.get(key).filter(|v| !v.is_null()) {
1074 if !s.as_object().is_some_and(|o| o.values().all(|v| v.is_string())) {
1075 anyhow::bail!("{key} must be an object of environment variable names to Vault entry ids, e.g. {{\"STRIPE_API_KEY\": \"api-key-stripe\"}}");
1076 }
1077 }
1078 }
1079 if arguments.get("stdin_secret").is_some_and(|v| !v.is_null() && !v.is_string()) {
1080 anyhow::bail!("stdin_secret is one Vault entry id, e.g. \"api-key-registry\"");
1081 }
1082 if let Some(c) = arguments.get("capture").filter(|v| !v.is_null()) {
1085 if !c.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(Value::is_object)) {
1086 anyhow::bail!("capture is a list of rules, e.g. [{{\"as\": {{\"kind\": \"api-key\", \"label\": \"GitHub token\"}}, \"from\": {{\"stdout\": \"all\"}}}}]; the command did not run");
1087 }
1088 }
1089 Ok(())
1090}
1091
1092async fn run_background(arguments: &Value, command: &str, cx: &ToolCtx<'_>) -> Result<Value> {
1094 let mut args = arguments.clone();
1095 args["cmd"] = json!(command);
1096 let created = shell::create(&args, cx).await?;
1097 let id = created.shell_id;
1098 remember(&id, Kind::Background, arg_str(arguments, "connection").map(str::to_string));
1099 if captures(arguments) {
1100 CAPTURES.lock().unwrap_or_else(|p| p.into_inner()).insert(id.clone());
1101 }
1102 let mut out = json!({
1103 "terminal": id,
1104 "kind": "background",
1105 "note": "Runs as a background job; its output streams into a shell row in this conversation. \
1106 wait with until \"exit\" waits for it; close stops it.",
1107 });
1108 if let Some(a) = created.approval {
1109 out["approval"] = json!(a);
1110 }
1111 Ok(out)
1112}
1113
1114async fn run_action(arguments: &Value, cx: &ToolCtx<'_>) -> Result<Value> {
1115 let command = arg_str(arguments, "command").ok_or_else(|| anyhow::anyhow!("run needs command"))?;
1116 let background = arguments.get("background").and_then(|v| v.as_bool()).unwrap_or(false);
1117 check_run_arguments(arguments)?;
1118 if !background && gives_secrets(arguments) {
1122 return run_with_secrets(arguments, command, cx).await;
1123 }
1124 if background {
1125 return run_background(arguments, command, cx).await;
1126 }
1127 if command.contains('\n') {
1128 anyhow::bail!("run takes one command line; join steps with && (or use type for a script)");
1129 }
1130 let mut id = resolve(arguments, cx).await?;
1131 if let Some(wanted) = arg_str(arguments, "connection") {
1135 let current = known(&id).connection.unwrap_or_else(|| "local".to_string());
1136 if wanted != current && arg_str(arguments, "terminal").is_none() {
1137 id = open(arguments, cx).await?["terminal"].as_str().unwrap_or_default().to_string();
1138 }
1139 }
1140 await_prompt(cx, &id).await?;
1143 let family = family_of(cx, &id).await?;
1144 let command = without_trailing_semicolon(without_trailing_comment(command, family), family);
1145 if let Some(end) = open_ending(command, family) {
1146 anyhow::bail!(
1147 "run waits for a command to finish, and this one ends with {end:?}: \
1148 complete it, or for one that keeps running pass background: true"
1149 );
1150 }
1151 let line = match arg_str(arguments, "cwd") {
1152 Some(cwd) => in_dir(command, cwd, family)?,
1153 None => command.to_string(),
1154 };
1155 let nonce = uuid::Uuid::new_v4().simple().to_string()[..8].to_string();
1156 write(cx, &id, clear_line(family)).await?;
1157 tokio::time::sleep(Duration::from_millis(50)).await;
1158 let start = read_log(cx, &id, None, 1).await?.end;
1159 write(cx, &id, &format!("{}\r", with_exit_marker(&line, family, &nonce))).await?;
1160 let timeout_ms = arguments
1161 .get("timeout_ms")
1162 .and_then(|v| v.as_u64())
1163 .unwrap_or(120_000)
1164 .min(MAX_TIMEOUT_MS);
1165 let started = Instant::now();
1166 let deadline = started + Duration::from_millis(timeout_ms);
1167 loop {
1168 let log = read_log(cx, &id, Some(start), READ_ALL_LINES).await?;
1169 let text = strip_ansi(&log.content);
1170 if let Some((output, exit_code)) = exit_marker(&text, &nonce) {
1171 let lines: Vec<&str> = output.lines().collect();
1172 let truncated = lines.len() > MAX_RUN_LINES;
1173 let output = lines[lines.len().saturating_sub(MAX_RUN_LINES)..].join("\n");
1174 return Ok(json!({
1175 "terminal": id,
1176 "exit_code": exit_code,
1177 "output": output,
1178 "truncated": truncated,
1179 "duration_ms": started.elapsed().as_millis() as u64,
1180 "since": log.end,
1181 }));
1182 }
1183 if Instant::now() >= deadline {
1184 return Ok(json!({
1185 "terminal": id,
1186 "how": "timeout",
1187 "note": "Still running (or waiting for input). Read it, type into it, or send keys [\"Ctrl+C\"].",
1188 "tail": tail(&text, 20),
1189 "since": log.end,
1190 }));
1191 }
1192 tokio::time::sleep(POLL).await;
1193 }
1194}
1195
1196#[cfg(test)]
1197#[path = "../tests/terminal_tests.rs"]
1198mod tests;