1use super::*;
8use super::app_api::connections::{self, AgentTarget};
9
10type Prepared = (Option<super::shell_secrets::Injected>, (Option<crate::backend::vault::capture::Job>, Vec<String>));
13
14async fn prepare_secrets(
18 state: &AppState,
19 caller: Option<&super::caller::Caller>,
20 req: &ShellCreateRequest,
21 remote: bool,
22 preapproved: Option<&super::shell_secrets::Preapproved>,
23) -> Result<Prepared, Response> {
24 let gives = req.secrets.as_ref().is_some_and(|m| !m.is_empty())
25 || req.stdin_secret.as_deref().is_some_and(|s| !s.trim().is_empty())
26 || req.secret_files.as_ref().is_some_and(|m| !m.is_empty())
27 || req.capture.as_ref().is_some_and(|c| !c.is_empty());
28 let reason = if gives && preapproved.is_none() {
29 crate::backend::vault::history::require_reason(req.reason.as_deref()).map_err(|e| (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response())?
30 } else {
31 req.reason.clone().unwrap_or_default()
32 };
33 let wanted = super::shell_secrets::Wanted { env: req.secrets.as_ref(), stdin: req.stdin_secret.as_deref(), files: req.secret_files.as_ref(), reason: &reason, caller };
34 let cwd = req.cwd.as_deref().unwrap_or("");
35 let injecting = super::shell_secrets::inject(state, &req.agent_block_id, req.auth.as_ref(), wanted, remote, &req.cmd, cwd, preapproved);
36 let capturing = super::shell_secrets::plan_capture(state, caller, &req.agent_block_id, req.auth.as_ref(), req.capture.as_deref(), &req.cmd, cwd, &reason);
37 tokio::try_join!(injecting, capturing).map_err(|(code, why)| (code, Json(json!({ "error": why }))).into_response())
38}
39
40pub(super) fn calling_pane(
43 state: &AppState,
44 caller: Option<&super::caller::Caller>,
45 auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
46) -> Result<String, String> {
47 if let Some(uid) = caller.and_then(super::caller::Caller::uid) {
48 return crate::backend::reactive::handler::get_global_handler()
49 .block_for_uid(uid)
50 .ok_or_else(|| "this agent has no pane registered".to_string());
51 }
52 match auth {
53 Some(auth) => crate::server::ui_handlers::verified_block_id(state, caller, auth)
54 .map_err(|e| format!("could not verify which agent is asking: {e}")),
55 None => Err("a shell call needs the calling agent's token or signed identity, which this call did not carry".to_string()),
56 }
57}
58
59pub(super) fn own_pane(
62 state: &AppState,
63 caller: Option<&super::caller::Caller>,
64 named: &str,
65 auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
66) -> Result<String, Response> {
67 let refuse = |why: &str| (StatusCode::FORBIDDEN, Json(json!({ "error": why }))).into_response();
68 let pane = calling_pane(state, caller, auth).map_err(|e| refuse(&e))?;
69 if !named.is_empty() && named != pane {
70 return Err(refuse("this request names another agent's pane: a shell call acts on your own pane, so use your own pane's shell, or message that agent"));
71 }
72 Ok(pane)
73}
74
75fn refuse_foreign_shell(state: &AppState, caller: Option<&super::caller::Caller>, shell_id: &str) -> Option<Response> {
78 let pane = match own_pane(state, caller, "", None) {
79 Ok(pane) => pane,
80 Err(refusal) => return Some(refusal),
81 };
82 let owner = state.shell_sessions.get_status(shell_id).block_id;
83 (!owner.is_empty() && owner != pane)
84 .then(|| (StatusCode::FORBIDDEN, Json(json!({ "error": "this shell belongs to another agent's pane: use your own pane's shell, or message that agent" }))).into_response())
85}
86
87pub(super) async fn handle_shell_create(
93 State(state): State<AppState>,
94 caller: Option<axum::Extension<super::caller::Caller>>,
95 Json(mut req): Json<ShellCreateRequest>,
96) -> Response {
97 match own_pane(&state, caller.as_deref(), &req.agent_block_id, req.auth.as_ref()) {
98 Ok(pane) => req.agent_block_id = pane,
99 Err(refusal) => return refusal,
100 }
101 create_shell(state, caller.as_deref(), req, None).await
102}
103
104fn refuse(status: StatusCode, error: impl serde::Serialize) -> Response {
106 (status, Json(json!({ "error": error }))).into_response()
107}
108
109async fn resolve_target(state: &AppState, req: &ShellCreateRequest) -> Result<(AgentTarget, String), Response> {
113 let target = connections::for_agent(&state.broker, req.connection.as_deref()).await.map_err(|e| refuse(StatusCode::BAD_REQUEST, e))?;
114 let mut ssh_agent = String::new();
118 if let AgentTarget::Ssh(dest) = &target {
119 if crate::backend::remote::askpass::program().is_none() {
122 let e = "this AgentMux has no askpass helper (agentmux-bashwrap) to run an agent's SSH command with";
123 return Err(refuse(StatusCode::BAD_REQUEST, e));
124 }
125 ssh_agent = connections::verified_agent(state, &req.agent_block_id, req.auth.as_ref()).map_err(|e| refuse(StatusCode::FORBIDDEN, e))?;
126 let connection = dest.name();
127 connections::consent_for_ssh(state, &req.agent_block_id, &ssh_agent, &connection, &req.cmd).await.map_err(|e| refuse(StatusCode::FORBIDDEN, e))?;
128 }
129 Ok((target, ssh_agent))
130}
131
132fn effective_cwd(req: &ShellCreateRequest, agent_block: Option<&crate::backend::obj::Block>, remote: bool) -> Option<String> {
142 if remote {
143 return req.cwd.clone();
144 }
145 let block_cwd = || {
146 agent_block.and_then(|block| {
147 let cwd = crate::backend::obj::meta_get_string(&block.meta, "cmd:cwd", "");
148 if cwd.is_empty() { None } else { Some(cwd.to_string()) }
149 })
150 };
151 req.cwd.clone().or_else(block_cwd).and_then(|c| crate::backend::base::normalize_working_dir(&c))
152}
153
154fn base_env(req: &ShellCreateRequest, agent_block: Option<&crate::backend::obj::Block>) -> std::collections::HashMap<String, String> {
165 let mut env = agent_block.map(|block| crate::backend::blockcontroller::cmd_env_of(&block.meta)).unwrap_or_default();
166 env.extend(req.env.iter().flatten().map(|(k, v)| (k.clone(), v.clone())));
167 env
168}
169
170struct SecretRuntime {
172 scrubber: Option<Arc<crate::backend::vault::scrub::Scrubber>>,
173 stdin_once: Option<zeroize::Zeroizing<String>>,
174 secret_dir: Option<crate::backend::vault::files::SecretDir>,
175}
176
177fn apply_injected(
181 injected: Option<super::shell_secrets::Injected>,
182 env: &mut std::collections::HashMap<String, String>,
183 went_ahead: &mut Vec<String>,
184) -> Result<SecretRuntime, Response> {
185 let Some(i) = injected else {
186 return Ok(SecretRuntime { scrubber: None, stdin_once: None, secret_dir: None });
187 };
188 went_ahead.extend(i.went_ahead);
189 env.extend(i.env);
190 let mut secret_dir = None;
191 if !i.files.is_empty() {
192 let dir = crate::backend::vault::files::SecretDir::create().map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
193 for (name, value) in &i.files {
194 let path = dir.write(name, value).map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, e))?;
195 env.insert(name.clone(), path.to_string_lossy().into_owned());
196 }
197 secret_dir = Some(dir);
198 }
199 Ok(SecretRuntime { scrubber: Some(Arc::new(i.scrubber)), stdin_once: i.stdin, secret_dir })
200}
201
202fn launch_for(
205 state: &AppState,
206 req: &ShellCreateRequest,
207 target: &AgentTarget,
208 ssh_agent: &str,
209 env: &mut std::collections::HashMap<String, String>,
210 cwd_there: &str,
211) -> Result<(Option<(String, Vec<String>)>, Option<String>), Response> {
212 match target {
213 AgentTarget::Local => Ok((None, None)),
214 AgentTarget::Wsl(distro) => {
217 crate::backend::gh_guard::apply_gh_guard_in(env, &crate::backend::gh_guard::guard_config_home());
221 let caller_keys: Vec<String> = req.env.iter().flat_map(|e| e.keys().cloned()).collect();
222 let wslenv = shell_wslenv(&std::env::var("WSLENV").unwrap_or_default(), &caller_keys, env);
223 env.insert("WSLENV".to_string(), wslenv);
224 let args = crate::backend::remote::wsl::launch(distro, &req.cmd, &[], cwd_there).args;
225 Ok((Some(("wsl.exe".to_string(), args)), None))
226 }
227 AgentTarget::Ssh(dest) => {
228 use crate::backend::remote::{askpass, ssh};
229 let (Some(ssh_path), Some(askpass_program)) = (ssh::binary(), askpass::program()) else {
230 let e = "this AgentMux has no ssh or no askpass helper (agentmux-bashwrap) to run an agent's SSH command with";
231 return Err(refuse(StatusCode::BAD_REQUEST, e));
232 };
233 let secret = askpass::grant(askpass::AskpassGrant {
236 agent_block_id: req.agent_block_id.clone(),
237 agent: ssh_agent.to_string(),
238 connection: dest.name(),
239 user_pane: false,
240 });
241 let local_url = std::env::var("AGENTMUX_LOCAL_URL").unwrap_or_default();
242 env.extend(askpass::ssh_env(&secret, &askpass_program, &local_url, &state.auth_key));
243 let args = ssh::launch_exec(dest, &req.cmd, cwd_there, ssh::shared_control_dir().as_deref());
244 Ok((Some((ssh_path.to_string_lossy().into_owned(), args)), Some(secret)))
245 }
246 }
247}
248
249pub(super) async fn create_shell(
252 state: AppState, caller: Option<&super::caller::Caller>,
253 req: ShellCreateRequest,
254 preapproved: Option<&super::shell_secrets::Preapproved>,
255) -> Response {
256 let (target, ssh_agent) = match resolve_target(&state, &req).await {
257 Ok(resolved) => resolved,
258 Err(refused) => return refused,
259 };
260 let remote = !matches!(target, AgentTarget::Local);
261
262 if req.capture_stdin == Some(true) && req.stdin_secret.as_deref().is_some_and(|s| !s.trim().is_empty()) {
264 let e = "stdin_secret and capture_stdin can't be used together: stdin is closed once the value is written";
265 return refuse(StatusCode::BAD_REQUEST, e);
266 }
267 let (injected, (capture, mut went_ahead)) = match prepare_secrets(&state, caller, &req, remote, preapproved).await {
270 Ok(both) => both,
271 Err(refused) => return refused,
272 };
273 let shell_id = uuid::Uuid::new_v4().to_string();
274 let title = req.title.as_deref().unwrap_or(&req.cmd).to_string();
275
276 let agent_block = state.mstore.get::<crate::backend::obj::Block>(&req.agent_block_id).ok().flatten();
278 let effective_cwd = effective_cwd(&req, agent_block.as_ref(), remote);
279 let mut effective_env = base_env(&req, agent_block.as_ref());
280 let secrets = match apply_injected(injected, &mut effective_env, &mut went_ahead) {
281 Ok(secrets) => secrets,
282 Err(refused) => return refused,
283 };
284 reserve_agent_env(&state.mstore, &req.agent_block_id, &mut effective_env);
285 let (launch, askpass_secret) = match launch_for(&state, &req, &target, &ssh_agent, &mut effective_env, effective_cwd.as_deref().unwrap_or_default()) {
286 Ok(launched) => launched,
287 Err(refused) => return refused,
288 };
289
290 tracing::info!(
291 block_id = %req.agent_block_id,
292 shell_id = %shell_id,
293 cmd = %req.cmd,
294 cwd = ?effective_cwd,
295 wsl = ?(if let AgentTarget::Wsl(distro) = &target { Some(distro) } else { None }),
296 ssh = matches!(target, AgentTarget::Ssh(_)),
297 "shell.create"
298 );
299
300 let created = crate::backend::shell_node::ShellNodeCreateEvent {
309 shell_id: shell_id.clone(),
310 cmd: req.cmd.clone(),
311 cwd: effective_cwd.clone(),
312 title: title.clone(),
313 timestamp: agentmux_common::time::now_ms_u64(),
314 };
315 state.broker.publish_event::<crate::backend::mps_events::ShellNodeCreate>(&created, vec![format!("block:{}", req.agent_block_id)], 64);
316
317 let runner = crate::backend::shell_node::ShellNodeRunner {
319 shell_id: shell_id.clone(),
320 block_id: req.agent_block_id,
321 cmd: req.cmd,
322 title,
323 cwd: if launch.is_some() { None } else { effective_cwd },
324 launch,
325 askpass_secret,
326 extra_env: effective_env,
327 broker: Arc::clone(&state.broker),
328 registry: Arc::clone(&state.shell_sessions),
329 capture_stdin: req.capture_stdin.unwrap_or(false),
330 scrubber: secrets.scrubber,
331 stdin_once: secrets.stdin_once,
332 secret_dir: secrets.secret_dir,
333 capture,
334 };
335 tokio::spawn(runner.run());
336
337 (StatusCode::OK, Json(ShellCreateResponse { shell_id, approval: super::vault_ask::approval(&went_ahead) })).into_response()
338}
339
340pub(super) async fn handle_shell_stop(
347 State(state): State<AppState>,
348 caller: Option<axum::Extension<super::caller::Caller>>,
349 Json(req): Json<ShellStopRequest>,
350) -> Response {
351 if let Some(refusal) = refuse_foreign_shell(&state, caller.as_deref(), &req.shell_id) {
352 return refusal;
353 }
354 let stopped = state.shell_sessions.stop(&req.shell_id);
355 tracing::info!(shell_id = %req.shell_id, stopped, "shell.stop");
356 (StatusCode::OK, Json(json!({ "stopped": stopped }))).into_response()
357}
358
359pub(super) async fn handle_shell_input(
365 State(state): State<AppState>,
366 caller: Option<axum::Extension<super::caller::Caller>>,
367 Json(req): Json<ShellInputRequest>,
368) -> Response {
369 if let Some(refusal) = refuse_foreign_shell(&state, caller.as_deref(), &req.shell_id) {
370 return refusal;
371 }
372 let (written, reason) = match state.shell_sessions.resolve_stdin(&req.shell_id) {
377 Ok(tx) => {
378 let mut text = req.text.clone();
379 if !text.ends_with('\n') {
380 text.push('\n');
381 }
382 if tx.send(text).is_ok() {
383 tracing::debug!(shell_id = %req.shell_id, "shell.input: written");
384 (true, None)
385 } else {
386 tracing::debug!(shell_id = %req.shell_id, "shell.input: write failed");
388 (false, Some(ShellInputFailure::WriteFailed))
389 }
390 }
391 Err(failure) => {
392 tracing::debug!(shell_id = %req.shell_id, ?failure, "shell.input: no target");
393 (false, Some(failure))
394 }
395 };
396 (StatusCode::OK, Json(ShellInputResponse { written, reason })).into_response()
397}
398
399pub(super) async fn handle_shell_status(
405 State(state): State<AppState>,
406 caller: Option<axum::Extension<super::caller::Caller>>,
407 Json(req): Json<ShellStatusRequest>,
408) -> Response {
409 if let Some(refusal) = refuse_foreign_shell(&state, caller.as_deref(), &req.shell_id) {
410 return refusal;
411 }
412 let s = state.shell_sessions.get_status(&req.shell_id);
413 (StatusCode::OK, Json(ShellStatusResponse {
414 running: s.running,
415 exit_code: s.exit_code,
416 line_count: s.line_count,
417 }))
418 .into_response()
419}
420
421pub(super) async fn handle_shell_output(
425 State(state): State<AppState>,
426 caller: Option<axum::Extension<super::caller::Caller>>,
427 Json(req): Json<agentmux_common::api_types::ShellOutputRequest>,
428) -> impl IntoResponse {
429 let pane = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
432 Ok(p) => p,
433 Err(e) => return (StatusCode::FORBIDDEN, Json(json!({ "error": format!("could not verify which agent is asking: {e}") }))).into_response(),
434 };
435 let s = state.shell_sessions.get_status(&req.shell_id);
436 let (Some(tail), true) = (s.tail.as_ref(), s.block_id == pane) else {
437 let why = "no cleaned output is kept for this job: only a job given Vault secrets keeps it, and only for the pane that started it";
438 return (StatusCode::NOT_FOUND, Json(json!({ "error": why }))).into_response();
439 };
440 let lines: Vec<String> = tail.lock().iter().cloned().collect();
441 let truncated = s.line_count as usize > lines.len() || s.tail_clipped;
442 (
443 StatusCode::OK,
444 Json(agentmux_common::api_types::ShellOutputResponse {
445 running: s.running,
446 exit_code: s.exit_code,
447 output: lines.join("\n"),
448 truncated,
449 captured: s.captured.clone(),
450 withheld: s.withheld.clone(),
451 }),
452 )
453 .into_response()
454}
455
456pub(super) use crate::backend::blockcontroller::META_KEY_SHELL_SUBBLOCK_ID;
465
466pub(super) const AGENT_LOCK_WINDOW_MS: i64 = 4000;
475
476pub(crate) use crate::backend::blockcontroller::agent_lock::META_KEY_AGENT_LOCK_UNTIL;
483
484pub(super) fn is_owned_by_agent(
496 mstore: &crate::backend::storage::store::Store,
497 shell_id: &str,
498 agent_block_id: &str,
499) -> bool {
500 mstore
501 .get::<crate::backend::obj::Block>(shell_id)
502 .ok()
503 .flatten()
504 .map(|b| {
505 b.parentoref == format!("block:{agent_block_id}")
506 && b.meta.get("view").and_then(|v| v.as_str()) == Some("term")
507 })
508 .unwrap_or(false)
509}
510
511pub(super) fn broadcast_meta_update(
518 state: &AppState,
519 block_id: &str,
520 meta_update: &crate::backend::obj::MetaMapType,
521) -> Result<(), String> {
522 let oref_str = format!("block:{block_id}");
523 crate::server::service::object_helpers::update_object_meta(&state.mstore, &oref_str, meta_update)?;
524 let block = state
525 .mstore
526 .must_get::<crate::backend::obj::Block>(block_id)
527 .map_err(|e| e.to_string())?;
528 let update = crate::backend::obj::MuxObjUpdate {
529 updatetype: "update".into(),
530 otype: "block".into(),
531 oid: block_id.to_string(),
532 obj: Some(crate::backend::obj::mux_obj_to_value(&block)),
533 };
534 state.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&update, oref_str));
535 Ok(())
536}
537
538pub(super) async fn try_attach_to_existing_shell(
567 state: &AppState,
568 agent_block_id: &str,
569 id: &str,
570 connection: &str,
571) -> Option<axum::response::Response> {
572 let block = state.mstore.get::<crate::backend::obj::Block>(id).ok().flatten()?;
573
574 if let Some(conflict) = connection_conflict(&block, connection) {
575 if let std::ops::ControlFlow::Break(answer) = settle_connection_conflict(state, agent_block_id, id, &block, conflict) {
576 return answer;
577 }
578 }
579
580 let baseline_len = state
586 .filestore
587 .stat(id, "term")
588 .ok()
589 .flatten()
590 .map(|info| info.size as usize)
591 .unwrap_or(0);
592
593 if let Err(e) = resync_existing_shell(state, &block) {
594 if e == blockcontroller::RESYNC_ERR_ALREADY_EXITED {
595 drop_exited_shell(state, agent_block_id, id);
596 return None;
597 }
598 return Some(
599 (
600 StatusCode::INTERNAL_SERVER_ERROR,
601 Json(json!({ "error": format!("ptyshell.create: resync existing shell: {e}") })),
602 )
603 .into_response(),
604 );
605 }
606 if let Some(conflict) = connection_conflict(&block, connection) {
609 return Some(conflict);
610 }
611 answer_conpty_handshake_if_seen(state, id, baseline_len).await;
612 tracing::info!(block_id = %id, parent_id = %agent_block_id, "ptyshell.create: reused");
613 Some((StatusCode::OK, Json(PtyShellCreateResponse { shell_id: id.to_string() })).into_response())
614}
615
616fn settle_connection_conflict(
626 state: &AppState,
627 agent_block_id: &str,
628 id: &str,
629 block: &crate::backend::obj::Block,
630 conflict: axum::response::Response,
631) -> std::ops::ControlFlow<Option<axum::response::Response>> {
632 use std::ops::ControlFlow;
633 let created_this_run = crate::backend::obj::meta_get_string(&block.meta, META_KEY_PTYSHELL_BOOT_ID, "") == *state.boot_id;
634 match blockcontroller::get_block_controller_status(id) {
635 Some(s) if s.shellprocstatus == blockcontroller::STATUS_RUNNING => ControlFlow::Break(Some(conflict)),
636 None if created_this_run => ControlFlow::Break(Some(conflict)),
637 None => {
638 clear_shell_pointer_if(state, agent_block_id, id);
639 tracing::info!(
640 block_id = %id,
641 parent_id = %agent_block_id,
642 "ptyshell.create: pane's shell is not running and was on another connection — falling through to a fresh shell"
643 );
644 ControlFlow::Break(None)
645 }
646 Some(_) => ControlFlow::Continue(()),
647 }
648}
649
650fn resync_existing_shell(state: &AppState, block: &crate::backend::obj::Block) -> Result<(), String> {
651 let registry = state.mstore.shared_agent_registry();
652 blockcontroller::resync_controller(
653 block,
654 "ptyshell",
655 None,
656 false,
657 false,
672 Some(Arc::clone(&state.broker)),
673 Some(Arc::clone(&state.event_bus)),
674 Some(Arc::clone(&state.mstore)),
675 Some(Arc::clone(&state.filestore)),
676 Some(Arc::clone(&state.id_store)),
677 Some(Arc::clone(&state.identity_store)),
678 registry,
679 state.boot_id.clone(),
680 &state.auth_key,
681 Some(Arc::clone(&state.config_watcher)),
682 )
683 .map(|_| ())
684 .map_err(|e| e.to_string())
685}
686
687fn drop_exited_shell(state: &AppState, agent_block_id: &str, id: &str) {
727 clear_shell_pointer_if(state, agent_block_id, id);
728 tracing::info!(
729 block_id = %id,
730 parent_id = %agent_block_id,
731 "ptyshell.create: pane's shell already exited, not respawning — falling through to a fresh shell"
732 );
733}
734
735pub(super) const META_KEY_PTYSHELL_BOOT_ID: &str = "ptyshell:bootid";
737
738fn clear_shell_pointer_if(state: &AppState, agent_block_id: &str, id: &str) {
742 if let Ok(mut parent) = state.mstore.must_get::<crate::backend::obj::Block>(agent_block_id) {
743 if parent.meta.get(META_KEY_SHELL_SUBBLOCK_ID).and_then(|v| v.as_str()) == Some(id) {
744 parent.meta.insert(META_KEY_SHELL_SUBBLOCK_ID.to_string(), serde_json::Value::Null);
745 if state.mstore.update(&mut parent).is_ok() {
746 let update = crate::backend::obj::MuxObjUpdate {
747 updatetype: "update".into(),
748 otype: "block".into(),
749 oid: agent_block_id.to_string(),
750 obj: Some(crate::backend::obj::mux_obj_to_value(&parent)),
751 };
752 state.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxObjUpdated>(&update, format!("block:{agent_block_id}")));
753 }
754 }
755 }
756}
757
758pub(super) fn connection_conflict(
762 shell_block: &crate::backend::obj::Block,
763 wanted: &str,
764) -> Option<axum::response::Response> {
765 let running_on = crate::backend::obj::meta_get_string(
766 &shell_block.meta,
767 blockcontroller::META_KEY_CONNECTION,
768 "local",
769 );
770 if crate::backend::remote::conn::same_connection(&running_on, wanted) {
771 let ssh = matches!(
775 crate::backend::remote::ConnTarget::parse(&running_on),
776 Ok(crate::backend::remote::ConnTarget::Ssh(_))
777 );
778 let for_an_agent = !crate::backend::obj::meta_get_string(
779 &shell_block.meta,
780 crate::backend::remote::askpass::META_KEY_AGENT_BLOCK,
781 "",
782 )
783 .is_empty();
784 if ssh && !for_an_agent {
785 let error = format!(
786 "this pane's shell on '{running_on}' was opened by the user, and its ssh may ask for a \
787 password in it, so an agent cannot share it. Use Terminal with action \"run\" and background: true instead, or ask the user to close it."
788 );
789 return Some((StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response());
790 }
791 return None;
792 }
793 let error = format!(
794 "this pane's shell is running on '{running_on}', not '{wanted}'. \
795 End it with Terminal action \"type\" (text \"exit\", submit: true) and open it again, \
796 or open it with connection '{running_on}' to use it"
797 );
798 Some((StatusCode::CONFLICT, Json(json!({ "error": error }))).into_response())
799}
800
801fn reserve_agent_env(
807 mstore: &crate::backend::storage::store::Store,
808 agent_block_id: &str,
809 env: &mut std::collections::HashMap<String, String>,
810) {
811 crate::server::agent_handlers::identity_env::carry_block_slug_identity_env(mstore, agent_block_id, env);
812 crate::backend::gh_guard::apply_gh_guard(env);
813 if let Some(block) = mstore.get::<crate::backend::obj::Block>(agent_block_id).ok().flatten() {
814 crate::backend::git_program_settings::apply_for_spawn(env, &block.meta);
815 }
816 crate::backend::account_login_guard::strip_account_login(env);
817}
818
819fn shell_wslenv(existing: &str, caller_keys: &[String], env: &std::collections::HashMap<String, String>) -> String {
823 let identity = crate::backend::remote::wsl::AGENT_IDENTITY_ENV.into_iter().filter(|k| env.contains_key(*k));
824 crate::backend::remote::wsl::wslenv_with(existing, caller_keys.iter().map(String::as_str).chain(identity))
825}
826
827#[cfg(test)]
828mod reserved_env_tests {
829 #[test]
833 fn the_reserved_identity_crosses_into_wsl() {
834 let env: std::collections::HashMap<String, String> =
835 ["AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID", "GIT_AUTHOR_EMAIL"]
836 .into_iter()
837 .map(|k| (k.to_string(), "loap-3".to_string()))
838 .collect();
839 let wslenv = super::shell_wslenv("", &["MY_VAR".to_string()], &env);
840 let names: Vec<&str> = wslenv.split(':').collect();
841 for key in ["MY_VAR", "AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID", "GIT_AUTHOR_EMAIL", "GH_CONFIG_DIR/p"] {
842 assert!(names.contains(&key), "{key} in {wslenv}");
843 }
844 assert!(!names.contains(&"GIT_COMMITTER_NAME"), "{wslenv}");
845 assert!(!wslenv.contains("AGENTMUX_AUTH_KEY"), "{wslenv}");
846 }
847
848 #[test]
852 fn a_request_env_cannot_put_back_an_old_identity() {
853 use crate::backend::storage::store::Store;
854 let store = Store::open_in_memory().unwrap();
855 let mut def = crate::backend::storage::agents::test_agent_def("uid-shell", "Loap #3", "claude", "host", 1, "");
856 def.slug = "loap-3".to_string();
857 store.agent_def_insert(&mut def).unwrap();
858 let mut meta = crate::backend::obj::MetaMapType::new();
859 meta.insert("view".to_string(), serde_json::json!("agent"));
860 meta.insert("agentId".to_string(), serde_json::json!("uid-shell"));
861 let mut block = crate::backend::obj::Block { oid: "block-shell".to_string(), meta, ..Default::default() };
862 store.insert(&mut block).unwrap();
863
864 let old = "loap-loap-2-loap-3";
865 let mut env: std::collections::HashMap<String, String> = [
866 ("AGENTMUX_AGENT_ID", old),
867 ("AGENTMUX_AGENT_SLUG", old),
868 ("MUXBUS_AGENT_ID", old),
869 ("GIT_AUTHOR_EMAIL", "loap-loap-2-loap-3@agents.local"),
870 ]
871 .into_iter()
872 .map(|(k, v)| (k.to_string(), v.to_string()))
873 .collect();
874 super::reserve_agent_env(&store, "block-shell", &mut env);
875 for key in ["AGENTMUX_AGENT_ID", "AGENTMUX_AGENT_SLUG", "MUXBUS_AGENT_ID"] {
876 assert_eq!(env[key], "loap-3", "{key}");
877 }
878 assert_eq!(env["GIT_AUTHOR_EMAIL"], "loap-3@agents.local");
879 assert!(env["GH_CONFIG_DIR"].ends_with("gh-loap-3"));
880 }
881
882 #[test]
885 fn a_shell_command_in_a_shared_folder_has_git_that_runs_nothing_the_folder_names() {
886 use crate::backend::storage::store::Store;
887 let (data, shared, plain) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
888 crate::backend::mcp_config_file::with_data_home(data.path(), || {
889 crate::backend::mcp_folder_rule::mark(&shared.path().to_string_lossy());
890 let store = Store::open_in_memory().unwrap();
891 for (id, folder) in [("block-shared", shared.path()), ("block-plain", plain.path())] {
892 let mut meta = crate::backend::obj::MetaMapType::new();
893 meta.insert("view".to_string(), serde_json::json!("agent"));
894 meta.insert("agentMode".to_string(), serde_json::json!("host"));
895 meta.insert("cmd:cwd".to_string(), serde_json::json!(folder.to_string_lossy()));
896 let mut block = crate::backend::obj::Block { oid: id.to_string(), meta, ..Default::default() };
897 store.insert(&mut block).unwrap();
898 }
899 let given = |block: &str| {
900 let mut env = std::collections::HashMap::new();
901 super::reserve_agent_env(&store, block, &mut env);
902 env
903 };
904 let shared_env = given("block-shared");
905 assert!(shared_env.values().any(|v| v == "core.fsmonitor"), "{shared_env:?}");
906 assert_eq!(shared_env.get("GIT_PROXY_COMMAND").map(String::as_str), Some(""));
907 let plain_env = given("block-plain");
908 assert!(!plain_env.values().any(|v| v == "core.fsmonitor") && !plain_env.contains_key("GIT_PROXY_COMMAND"), "{plain_env:?}");
909 });
910 }
911}
912
913#[cfg(test)]
914mod shared_shell_tests {
915 use super::connection_conflict;
916
917 fn shell(conn: &str, for_agent: bool) -> crate::backend::obj::Block {
918 let mut b = crate::backend::obj::Block::default();
919 b.meta.insert("connection".into(), serde_json::json!(conn));
920 if for_agent {
921 b.meta.insert(
922 crate::backend::remote::askpass::META_KEY_AGENT_BLOCK.into(),
923 serde_json::json!("agent-pane"),
924 );
925 }
926 b
927 }
928
929 #[test]
932 fn an_agent_never_shares_the_users_own_ssh_shell() {
933 assert!(connection_conflict(&shell("area54", false), "area54").is_some());
934 assert!(connection_conflict(&shell("area54", true), "area54").is_none());
935 assert!(connection_conflict(&shell("local", false), "local").is_none());
936 assert!(connection_conflict(&shell("wsl://Ubuntu", false), "wsl://Ubuntu").is_none());
937 assert!(connection_conflict(&shell("area54", true), "local").is_some(), "another connection");
938 }
939}
940
941#[cfg(test)]
942#[path = "http_shell_create_tests.rs"]
943mod create_tests;