1use std::borrow::Cow;
35use std::future::Future;
36use std::pin::Pin;
37use std::sync::Arc;
38
39use aither_core::LanguageModel;
40use aither_core::llm::Tool;
41use aither_core::llm::tool::ToolDefinition;
42#[cfg(feature = "mcp")]
43use aither_mcp::McpConnection;
44#[cfg(feature = "skills")]
45use aither_skills::SkillRegistry;
46use askama::Template;
47use async_fs as fs;
48use executor_core::Executor;
49use schemars::JsonSchema;
50use serde::de::DeserializeOwned;
51
52use crate::hook::Hook;
53use crate::{Agent, AgentBuilder, config::AgentKind, context::serialize_xml};
54use aither_sandbox::builtin::{InputTerminalTool, KillTerminalTool, ReadTerminalDeltaTool};
55use aither_sandbox::{
56 CommandPayload, ContainerShellRuntime, PermissionHandler, ShellRuntimeAvailability,
57 ShellSessionRegistry, SshServer, SshSessionAuthorizer, TerminalTool, TerminalToolFactory,
58 TerminalToolFactoryReceiver, ToolRegistryBuilder, Unconfigured, terminal_tool_factory_channel,
59};
60
61#[derive(Template)]
63#[template(path = "system.txt", escape = "none")]
64struct SystemPrompt {
65 os: String,
66 os_version: String,
67 arch: &'static str,
68 user_cwd: String,
69 sandbox_dir: String,
70 tools: String,
71 host_profile: &'static str,
72 host_runtime_context: String,
73 skills: String,
74 has_skills: bool,
75 subagents: String,
76 has_subagents: bool,
77 is_macos: bool,
78}
79
80#[derive(serde::Serialize)]
81struct ShellRuntimeContextXml {
82 available_backends: ShellRuntimeAvailableBackendsXml,
83 runtime: &'static str,
84}
85
86#[derive(serde::Serialize)]
87struct ShellRuntimeAvailableBackendsXml {
88 #[serde(rename = "@local")]
89 local: bool,
90 #[serde(rename = "@ssh")]
91 ssh: bool,
92}
93
94fn join_text(parts: &[&str]) -> String {
95 let capacity = parts.iter().map(|part| part.len()).sum();
96 let mut output = String::with_capacity(capacity);
97 for part in parts {
98 output.push_str(part);
99 }
100 output
101}
102
103fn path_error_text(prefix: &str, path: &std::path::Path, error: &impl std::fmt::Display) -> String {
104 let path_text = path.display().to_string();
105 let error_text = error.to_string();
106 join_text(&[prefix, path_text.as_str(), "': ", error_text.as_str()])
107}
108
109fn quoted_path_error_text(
110 prefix: &str,
111 first_path: &std::path::Path,
112 infix: &str,
113 second_path: &std::path::Path,
114 error: &impl std::fmt::Display,
115) -> String {
116 let first_path_text = first_path.display().to_string();
117 let second_path_text = second_path.display().to_string();
118 let error_text = error.to_string();
119 join_text(&[
120 prefix,
121 first_path_text.as_str(),
122 infix,
123 second_path_text.as_str(),
124 "': ",
125 error_text.as_str(),
126 ])
127}
128
129#[derive(Debug, Clone)]
131pub struct SkillInfo {
132 pub name: String,
134 pub description: String,
136}
137
138#[derive(Debug, Clone)]
140pub struct SubagentInfo {
141 pub name: String,
143 pub description: String,
145 pub path: String,
147}
148
149pub struct TerminalAgentBuilder<LLM, P, E, H = ()>
154where
155 LLM: LanguageModel + Clone,
156 P: PermissionHandler + 'static,
157 E: Executor + Clone + 'static,
158{
159 inner: AgentBuilder<LLM, LLM, LLM, H>,
160 terminal_tool: TerminalTool<P, E, Unconfigured>,
161 registry_builder: ToolRegistryBuilder,
162 terminal_tool_factory: TerminalToolFactory,
163 terminal_tool_factory_receiver: Option<TerminalToolFactoryReceiver>,
164 tool_descriptions: Vec<(String, String)>,
165 skills: Vec<SkillInfo>,
166 subagents: Vec<SubagentInfo>,
167 shell_sessions: ShellSessionRegistry,
168 #[cfg(feature = "skills")]
169 skill_registry: Option<SkillRegistry>,
170}
171
172impl<LLM, P, E, H> std::fmt::Debug for TerminalAgentBuilder<LLM, P, E, H>
173where
174 LLM: LanguageModel + Clone,
175 P: PermissionHandler + 'static,
176 E: Executor + Clone + 'static,
177{
178 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179 f.debug_struct("TerminalAgentBuilder")
180 .field("tool_count", &self.tool_descriptions.len())
181 .field("skill_count", &self.skills.len())
182 .field("subagent_count", &self.subagents.len())
183 .finish_non_exhaustive()
184 }
185}
186
187impl<LLM, P, E> TerminalAgentBuilder<LLM, P, E, ()>
188where
189 LLM: LanguageModel + Clone,
190 P: PermissionHandler + 'static,
191 E: Executor + Clone + 'static,
192{
193 pub fn new(llm: LLM, mut terminal_tool: TerminalTool<P, E, Unconfigured>) -> Self {
199 let (terminal_tool_factory, terminal_tool_factory_receiver) =
200 terminal_tool_factory_channel();
201 let registry_builder = ToolRegistryBuilder::new();
202 let mut tool_descriptions = Vec::new();
203
204 let shell_sessions = ShellSessionRegistry::new(ShellRuntimeAvailability {
205 local: true,
206 container: false,
207 ssh: false,
208 });
209
210 let job_registry = terminal_tool.job_registry();
211 let kill_terminal_tool = KillTerminalTool::new(job_registry.clone());
212 let input_terminal_tool = InputTerminalTool::new(job_registry.clone());
213 let read_terminal_delta_tool = ReadTerminalDeltaTool::new(job_registry);
214 terminal_tool = terminal_tool.with_shell_sessions(shell_sessions.clone());
215
216 let kill_def = ToolDefinition::new(&kill_terminal_tool);
217 tool_descriptions.push((
218 kill_def.name().to_string(),
219 short_description(kill_def.description()),
220 ));
221 let input_def = ToolDefinition::new(&input_terminal_tool);
222 tool_descriptions.push((
223 input_def.name().to_string(),
224 short_description(input_def.description()),
225 ));
226 let read_delta_def = ToolDefinition::new(&read_terminal_delta_tool);
227 tool_descriptions.push((
228 read_delta_def.name().to_string(),
229 short_description(read_delta_def.description()),
230 ));
231
232 let inner = AgentBuilder::new(llm)
233 .tool(kill_terminal_tool)
234 .tool(input_terminal_tool)
235 .tool(read_terminal_delta_tool);
236
237 Self {
238 inner,
239 terminal_tool,
240 registry_builder,
241 terminal_tool_factory,
242 terminal_tool_factory_receiver: Some(terminal_tool_factory_receiver),
243 tool_descriptions,
244 skills: Vec::new(),
245 subagents: Vec::new(),
246 shell_sessions,
247 #[cfg(feature = "skills")]
248 skill_registry: None,
249 }
250 }
251}
252
253impl<LLM, P, E, H> TerminalAgentBuilder<LLM, P, E, H>
254where
255 LLM: LanguageModel + Clone,
256 P: PermissionHandler + 'static,
257 E: Executor + Clone + 'static,
258 H: Hook,
259{
260 async fn resolve_absolute_dir(
261 path: &std::path::Path,
262 kind: &str,
263 ) -> Result<std::path::PathBuf, crate::AgentError> {
264 fs::create_dir_all(path).await.map_err(|error| {
265 let prefix = join_text(&["failed to create ", kind, " directory '"]);
266 crate::AgentError::Config(path_error_text(prefix.as_str(), path, &error))
267 })?;
268
269 fs::canonicalize(path).await.map_err(|error| {
270 let prefix = join_text(&["failed to canonicalize ", kind, " directory '"]);
271 crate::AgentError::Config(path_error_text(prefix.as_str(), path, &error))
272 })
273 }
274
275 async fn register_readable_dir(
276 mut self,
277 source_path: &std::path::Path,
278 kind: &str,
279 ) -> Result<Self, crate::AgentError> {
280 let abs_path = Self::resolve_absolute_dir(source_path, kind).await?;
281 self.terminal_tool = self.terminal_tool.with_readable_paths([abs_path]);
282 Ok(self)
283 }
284
285 async fn attach_readable_symlink(
286 mut self,
287 source_path: &std::path::Path,
288 kind: &str,
289 link_name: &str,
290 ) -> Result<Self, crate::AgentError> {
291 let abs_path = Self::resolve_absolute_dir(source_path, kind).await?;
292 let symlink_path = self.terminal_tool.working_dir().join(link_name);
293
294 match fs::symlink_metadata(&symlink_path).await {
295 Ok(metadata) => {
296 if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() {
297 fs::remove_dir(&symlink_path).await.map_err(|error| {
298 crate::AgentError::Config(path_error_text(
299 "failed to remove existing directory '",
300 &symlink_path,
301 &error,
302 ))
303 })?;
304 } else {
305 fs::remove_file(&symlink_path).await.map_err(|error| {
306 crate::AgentError::Config(path_error_text(
307 "failed to remove existing file '",
308 &symlink_path,
309 &error,
310 ))
311 })?;
312 }
313 }
314 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
315 Err(error) => {
316 return Err(crate::AgentError::Config(path_error_text(
317 "failed to inspect '",
318 &symlink_path,
319 &error,
320 )));
321 }
322 }
323
324 #[cfg(unix)]
325 {
326 fs::unix::symlink(&abs_path, &symlink_path)
327 .await
328 .map_err(|error| {
329 crate::AgentError::Config(quoted_path_error_text(
330 "failed to create symlink '",
331 &symlink_path,
332 "' -> '",
333 &abs_path,
334 &error,
335 ))
336 })?;
337 }
338 #[cfg(windows)]
339 {
340 fs::windows::symlink_dir(&abs_path, &symlink_path)
341 .await
342 .map_err(|error| {
343 crate::AgentError::Config(quoted_path_error_text(
344 "failed to create symlink '",
345 &symlink_path,
346 "' -> '",
347 &abs_path,
348 &error,
349 ))
350 })?;
351 }
352
353 self.terminal_tool = self.terminal_tool.with_readable_paths([abs_path]);
354 Ok(self)
355 }
356
357 #[must_use]
359 pub fn shell_runtime_availability(mut self, availability: ShellRuntimeAvailability) -> Self {
360 self.shell_sessions = self.shell_sessions.with_availability(availability.clone());
361 self.terminal_tool = self
362 .terminal_tool
363 .with_shell_sessions(self.shell_sessions.clone())
364 .with_shell_runtime_availability(availability);
365 self
366 }
367
368 #[must_use]
374 pub fn ssh_servers(mut self, servers: Vec<SshServer>) -> Self {
375 self.shell_sessions = self
376 .shell_sessions
377 .with_ssh_servers(servers)
378 .expect("invalid ssh server configuration");
379 self.terminal_tool = self
380 .terminal_tool
381 .with_shell_sessions(self.shell_sessions.clone());
382 self
383 }
384
385 #[must_use]
387 pub fn ssh_authorizer(mut self, authorizer: Arc<dyn SshSessionAuthorizer>) -> Self {
388 self.shell_sessions = self.shell_sessions.with_ssh_authorizer(authorizer);
389 self.terminal_tool = self
390 .terminal_tool
391 .with_shell_sessions(self.shell_sessions.clone());
392 self
393 }
394
395 #[must_use]
397 pub fn container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
398 self.shell_sessions = self.shell_sessions.with_container_runtime(runtime.clone());
399 self.terminal_tool = self.terminal_tool.with_container_runtime(runtime);
400 self
401 }
402
403 #[must_use]
415 pub fn tool<T>(mut self, tool: T) -> Self
416 where
417 T: Tool + Send + Sync + 'static,
418 T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
419 {
420 let name = tool.name().to_string();
421 let def = ToolDefinition::new(&tool);
423 let description = def.description();
424 self.tool_descriptions
425 .push((name, short_description(description)));
426 self.registry_builder.configure_tool(tool);
427 self
428 }
429
430 #[must_use]
436 pub fn definition_handler<F>(mut self, definition: &ToolDefinition, handler: F) -> Self
437 where
438 F: Fn(
439 serde_json::Value,
440 )
441 -> Pin<Box<dyn Future<Output = Result<Option<CommandPayload>, String>> + Send>>
442 + Send
443 + Sync
444 + 'static,
445 {
446 let name = definition.name().to_string();
447 let description = definition.description().to_string();
448 self.tool_descriptions
449 .push((name, short_description(description.as_str())));
450 self.registry_builder
451 .configure_definition_handler(definition, handler);
452 self
453 }
454
455 #[cfg(feature = "mcp")]
457 #[must_use]
458 pub fn mcp_connection(mut self, conn: McpConnection) -> Self {
459 let definitions = aither_mcp::register_terminal_commands(&mut self.registry_builder, conn);
460 self.tool_descriptions
461 .extend(definitions.into_iter().map(|definition| {
462 (
463 definition.name().to_string(),
464 short_description(definition.description()),
465 )
466 }));
467 self
468 }
469
470 #[must_use]
472 pub fn tool_with_desc<T>(mut self, tool: T, description: impl Into<String>) -> Self
473 where
474 T: Tool + Send + Sync + 'static,
475 T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
476 {
477 let name = tool.name().to_string();
478 self.tool_descriptions.push((name, description.into()));
479 self.registry_builder.configure_tool(tool);
480 self
481 }
482
483 #[must_use]
487 pub fn tool_description(
488 mut self,
489 name: impl Into<String>,
490 description: impl Into<String>,
491 ) -> Self {
492 self.tool_descriptions
493 .push((name.into(), description.into()));
494 self
495 }
496
497 #[must_use]
499 pub fn system_prompt_raw(mut self, prompt: impl Into<String>) -> Self {
500 self.inner = self.inner.system_prompt(prompt.into());
501 self
502 }
503
504 #[must_use]
506 pub fn persona_prompt(mut self, prompt: impl Into<String>) -> Self {
507 self.inner = self.inner.persona_prompt(prompt.into());
508 self
509 }
510
511 #[must_use]
513 pub fn agent_kind(mut self, kind: AgentKind) -> Self {
514 self.inner = self.inner.agent_kind(kind);
515 self
516 }
517
518 #[must_use]
520 pub fn transcript_path(mut self, path: impl Into<String>) -> Self {
521 self.inner = self.inner.transcript_path(path.into());
522 self
523 }
524
525 #[must_use]
527 pub fn transcript(mut self, path: impl Into<std::path::PathBuf>) -> Self {
528 self.inner = self.inner.transcript(path);
529 self
530 }
531
532 #[must_use]
534 pub fn system<T: serde::Serialize>(mut self, value: T) -> Self {
535 self.inner = self.inner.system(value);
536 self
537 }
538
539 #[must_use]
541 pub fn system_named(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
542 self.inner = self.inner.system_named(tag, content);
543 self
544 }
545
546 #[must_use]
554 pub fn system_text(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
555 self.inner = self.inner.system_text(tag, content);
556 self
557 }
558
559 #[must_use]
567 pub fn with_default_prompt(mut self) -> Self {
568 let availability = self.shell_sessions.availability();
569 let host_profile = if availability.container {
570 "container"
571 } else if availability.local {
572 "heel"
573 } else if availability.ssh {
574 "remote"
575 } else {
576 panic!("terminal agent requires at least one shell backend")
577 };
578 let runtime_kind = match host_profile {
579 "container" => "linux_container",
580 "remote" => "remote_ssh",
581 "heel" => "user_local_machine",
582 _ => unreachable!("validated host profile"),
583 };
584 let shell_context = serialize_xml(
585 "shell_runtime",
586 &ShellRuntimeContextXml {
587 available_backends: ShellRuntimeAvailableBackendsXml {
588 local: availability.local || availability.container,
589 ssh: availability.ssh,
590 },
591 runtime: runtime_kind,
592 },
593 );
594 self.inner = self.inner.system_named("shell_runtime", shell_context);
595
596 let ssh_context = describe_ssh_servers(&self.shell_sessions.list_ssh_servers());
597 let host_runtime_context =
598 describe_host_runtime_context(host_profile, &availability, ssh_context.as_str());
599
600 let tools = render_tool_descriptions(&self.tool_descriptions);
602
603 let has_skills = !self.skills.is_empty();
605 let skills = render_skill_descriptions(&self.skills);
606
607 let has_subagents = !self.subagents.is_empty();
609 let subagents = render_subagent_descriptions(&self.subagents);
610
611 let sandbox_dir = self.terminal_tool.working_dir().display().to_string();
613 let user_cwd =
614 std::env::current_dir().map_or_else(|_| ".".to_string(), |p| p.display().to_string());
615
616 let (os, os_version) = get_os_info();
618 let arch = std::env::consts::ARCH;
619 let is_macos = cfg!(target_os = "macos");
620
621 let template = SystemPrompt {
622 os,
623 os_version,
624 arch,
625 user_cwd,
626 sandbox_dir,
627 tools,
628 host_profile,
629 host_runtime_context,
630 skills,
631 has_skills,
632 subagents,
633 has_subagents,
634 is_macos,
635 };
636
637 let prompt = template
638 .render()
639 .expect("failed to render system prompt template");
640 self.inner = self.inner.system_prompt(prompt);
641 self
642 }
643
644 pub fn hook<NH: Hook>(self, hook: NH) -> TerminalAgentBuilder<LLM, P, E, crate::HCons<NH, H>> {
646 TerminalAgentBuilder {
647 inner: self.inner.hook(hook),
648 terminal_tool: self.terminal_tool,
649 registry_builder: self.registry_builder,
650 terminal_tool_factory: self.terminal_tool_factory,
651 terminal_tool_factory_receiver: self.terminal_tool_factory_receiver,
652 tool_descriptions: self.tool_descriptions,
653 skills: self.skills,
654 subagents: self.subagents,
655 shell_sessions: self.shell_sessions,
656 #[cfg(feature = "skills")]
657 skill_registry: self.skill_registry,
658 }
659 }
660
661 #[cfg(feature = "skills")]
668 async fn load_skills(
669 mut self,
670 path: impl AsRef<std::path::Path>,
671 ) -> Result<Self, crate::AgentError> {
672 use aither_skills::SkillLoader;
673
674 let path = path.as_ref().to_path_buf();
675 let abs_path = Self::resolve_absolute_dir(&path, "skills").await?;
676 let loader = SkillLoader::new().add_path(&abs_path);
677 let mut registry = self.skill_registry.take().unwrap_or_default();
678 registry.load_from(&loader).await.map_err(|error| {
679 crate::AgentError::Config(path_error_text(
680 "failed to load skills from '",
681 &abs_path,
682 &error,
683 ))
684 })?;
685
686 let skills = registry.all().into_iter().cloned().collect::<Vec<_>>();
687 self.skills.clear();
688 tracing::info!(count = skills.len(), path = %abs_path.display(), "Loaded skills");
689 for skill in skills {
690 tracing::debug!(name = %skill.name, "Loaded skill");
691 self.skills.push(SkillInfo {
692 name: skill.name,
693 description: skill.description,
694 });
695 }
696 self.skill_registry = Some(registry);
697
698 Ok(self)
699 }
700
701 #[cfg(feature = "skills")]
702 pub async fn with_skills(
708 self,
709 path: impl AsRef<std::path::Path>,
710 ) -> Result<Self, crate::AgentError> {
711 let path = path.as_ref().to_path_buf();
712 self.load_skills(&path)
713 .await?
714 .attach_readable_symlink(&path, "skills", "skills")
715 .await
716 }
717
718 #[cfg(feature = "skills")]
727 pub async fn with_skills_readable_only(
728 self,
729 path: impl AsRef<std::path::Path>,
730 ) -> Result<Self, crate::AgentError> {
731 let path = path.as_ref().to_path_buf();
732 self.load_skills(&path)
733 .await?
734 .register_readable_dir(&path, "skills")
735 .await
736 }
737
738 #[must_use]
740 pub fn skill(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
741 self.skills.push(SkillInfo {
742 name: name.into(),
743 description: description.into(),
744 });
745 self
746 }
747
748 async fn load_subagents(
761 mut self,
762 path: impl AsRef<std::path::Path>,
763 ) -> Result<Self, crate::AgentError> {
764 use crate::subagent_file::SubagentDefinition;
765
766 let path = path.as_ref().to_path_buf();
767 let abs_path = Self::resolve_absolute_dir(&path, "subagents").await?;
768
769 let defs = SubagentDefinition::load_from_dir_async(&abs_path)
770 .await
771 .map_err(|error| {
772 crate::AgentError::Config(path_error_text(
773 "failed to load subagents from '",
774 &abs_path,
775 &error,
776 ))
777 })?;
778
779 for def in defs {
780 let mut filename = def.id.clone();
781 filename.push_str(".md");
782 self.subagents.push(SubagentInfo {
783 name: def.id,
784 description: def.description,
785 path: filename,
786 });
787 }
788
789 Ok(self)
790 }
791
792 pub async fn with_subagents(
798 self,
799 path: impl AsRef<std::path::Path>,
800 ) -> Result<Self, crate::AgentError> {
801 let path = path.as_ref().to_path_buf();
802 self.load_subagents(&path)
803 .await?
804 .attach_readable_symlink(&path, "subagents", "subagents")
805 .await
806 }
807
808 pub async fn with_subagents_readable_only(
817 self,
818 path: impl AsRef<std::path::Path>,
819 ) -> Result<Self, crate::AgentError> {
820 let path = path.as_ref().to_path_buf();
821 self.load_subagents(&path)
822 .await?
823 .register_readable_dir(&path, "subagents")
824 .await
825 }
826
827 #[must_use]
829 pub fn max_iterations(mut self, limit: usize) -> Self {
830 self.inner = self.inner.max_iterations(limit);
831 self
832 }
833
834 pub fn tool_descriptions(&self) -> &[(String, String)] {
838 &self.tool_descriptions
839 }
840
841 #[must_use]
843 pub fn terminal_tool_factory(&self) -> TerminalToolFactory {
844 self.terminal_tool_factory.clone()
845 }
846
847 pub const fn tool_registry_mut(&mut self) -> &mut ToolRegistryBuilder {
849 &mut self.registry_builder
850 }
851
852 pub fn sandbox_dir(&self) -> Cow<'_, str> {
854 self.terminal_tool.working_dir().to_string_lossy()
855 }
856
857 pub fn build(self) -> Agent<LLM, LLM, LLM, H> {
862 let registry = std::sync::Arc::new(
864 self.registry_builder
865 .build(self.terminal_tool.outputs_dir()),
866 );
867
868 let terminal_tool = self.terminal_tool.with_registry(registry);
870
871 if let Some(receiver) = self.terminal_tool_factory_receiver {
873 terminal_tool.start_factory_service(receiver);
874 }
875
876 let inner = self.inner.terminal(terminal_tool);
877 #[cfg(feature = "skills")]
878 let inner = if let Some(registry) = self.skill_registry {
879 inner.skill_registry(Arc::new(registry))
880 } else {
881 inner
882 };
883
884 inner.build()
885 }
886}
887
888fn short_description(description: &str) -> String {
889 description
890 .split('.')
891 .next()
892 .unwrap_or(description)
893 .trim()
894 .to_string()
895}
896
897fn push_bullet_line(output: &mut String, body: &str) {
898 if !output.is_empty() {
899 output.push('\n');
900 }
901 output.push_str("- ");
902 output.push_str(body);
903}
904
905fn render_tool_descriptions(entries: &[(String, String)]) -> String {
906 let mut output = String::new();
907 for (name, description) in entries {
908 let mut line = String::with_capacity(name.len() + description.len() + 2);
909 line.push_str(name.as_str());
910 line.push_str(": ");
911 line.push_str(description.as_str());
912 push_bullet_line(&mut output, line.as_str());
913 }
914 output
915}
916
917fn render_skill_descriptions(entries: &[SkillInfo]) -> String {
918 let mut output = String::new();
919 for skill in entries {
920 let mut line = String::with_capacity(skill.name.len() + skill.description.len() + 2);
921 line.push_str(skill.name.as_str());
922 line.push_str(": ");
923 line.push_str(skill.description.as_str());
924 push_bullet_line(&mut output, line.as_str());
925 }
926 output
927}
928
929fn render_subagent_descriptions(entries: &[SubagentInfo]) -> String {
930 let mut output = String::new();
931 for subagent in entries {
932 let mut line = String::with_capacity(
933 subagent.name.len() + subagent.path.len() + subagent.description.len() + 5,
934 );
935 line.push_str(subagent.name.as_str());
936 line.push_str(" (");
937 line.push_str(subagent.path.as_str());
938 line.push_str("): ");
939 line.push_str(subagent.description.as_str());
940 push_bullet_line(&mut output, line.as_str());
941 }
942 output
943}
944
945fn describe_host_runtime_context(
946 host_profile: &str,
947 availability: &ShellRuntimeAvailability,
948 ssh_context: &str,
949) -> String {
950 let mut output = String::new();
951 match host_profile {
952 "container" => {
953 output.push_str(
954 "Linux container runtime. Default mode has network enabled. You may install dependencies freely. SSH available: ",
955 );
956 output.push_str(if availability.ssh { "true" } else { "false" });
957 output.push_str(". ");
958 }
959 "remote" => {
960 output.push_str(
961 "Remote SSH runtime. Default mode runs on the configured SSH target with network enabled. Local CLI commands exposed through terminal are unavailable unless a local backend also exists. ",
962 );
963 }
964 "heel" => {
965 output.push_str(
966 "User machine runtime in sandbox. Default mode has network enabled. Use unsafe for host-level side effects. SSH available: ",
967 );
968 output.push_str(if availability.ssh { "true" } else { "false" });
969 output.push_str(". ");
970 }
971 _ => unreachable!("validated host profile"),
972 }
973 output.push_str(ssh_context);
974 output
975}
976
977fn describe_ssh_servers(servers: &[SshServer]) -> String {
978 if servers.is_empty() {
979 "No SSH servers are configured.".to_string()
980 } else if servers.len() == 1 {
981 let server = &servers[0];
982 let mut output = String::with_capacity(server.id().len() + server.target.len() + 89);
983 output.push_str("Configured SSH server: ");
984 output.push_str(server.id());
985 output.push_str(" (");
986 output.push_str(server.target.as_str());
987 output.push_str("). When using SSH backend, ssh_server_id may be omitted because only one server is configured.");
988 output
989 } else {
990 let mut listings = String::new();
991 for server in servers {
992 if !listings.is_empty() {
993 listings.push_str(", ");
994 }
995 listings.push_str(server.id());
996 listings.push_str(" (");
997 listings.push_str(server.target.as_str());
998 listings.push(')');
999 }
1000 let mut output = String::with_capacity(listings.len() + 24);
1001 output.push_str("Configured SSH servers: ");
1002 output.push_str(listings.as_str());
1003 output.push('.');
1004 output
1005 }
1006}
1007
1008fn get_os_info() -> (String, String) {
1010 #[cfg(target_os = "macos")]
1011 {
1012 let version = std::process::Command::new("sw_vers")
1013 .arg("-productVersion")
1014 .output()
1015 .ok()
1016 .and_then(|o| String::from_utf8(o.stdout).ok())
1017 .map_or_else(|| "unknown".to_string(), |s| s.trim().to_string());
1018 ("macOS".to_string(), version)
1019 }
1020
1021 #[cfg(target_os = "linux")]
1022 {
1023 let version = std::fs::read_to_string("/etc/os-release")
1025 .ok()
1026 .and_then(|content| {
1027 content
1028 .lines()
1029 .find(|line| line.starts_with("PRETTY_NAME="))
1030 .map(|line| {
1031 line.trim_start_matches("PRETTY_NAME=")
1032 .trim_matches('"')
1033 .to_string()
1034 })
1035 })
1036 .unwrap_or_else(|| {
1037 std::process::Command::new("uname")
1039 .arg("-r")
1040 .output()
1041 .ok()
1042 .and_then(|o| String::from_utf8(o.stdout).ok())
1043 .map_or_else(|| "unknown".to_string(), |s| s.trim().to_string())
1044 });
1045 ("Linux".to_string(), version)
1046 }
1047
1048 #[cfg(target_os = "windows")]
1049 {
1050 let version = std::process::Command::new("cmd")
1051 .args(["/C", "ver"])
1052 .output()
1053 .ok()
1054 .and_then(|o| String::from_utf8(o.stdout).ok())
1055 .map_or_else(|| "unknown".to_string(), |s| s.trim().to_string());
1056 ("Windows".to_string(), version)
1057 }
1058
1059 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
1060 {
1061 (std::env::consts::OS.to_string(), "unknown".to_string())
1062 }
1063}
1064
1065#[cfg(test)]
1066mod tests {
1067 use super::*;
1068 use std::borrow::Cow;
1069
1070 use aither_core::LanguageModel;
1071 use aither_core::llm::{Event, LLMRequest, Tool, model::Profile as ModelProfile};
1072 use aither_sandbox::permission::NoopPermissionHandler;
1073 use executor_core::tokio::TokioGlobal;
1074 use futures_core::Stream;
1075 use schemars::JsonSchema;
1076 use serde::Deserialize;
1077 use tempfile::tempdir;
1078
1079 #[derive(Debug)]
1080 struct MockError;
1081
1082 impl std::fmt::Display for MockError {
1083 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1084 f.write_str("mock error")
1085 }
1086 }
1087
1088 impl std::error::Error for MockError {}
1089
1090 #[derive(Clone)]
1091 struct MockLlm;
1092
1093 impl LanguageModel for MockLlm {
1094 type Error = MockError;
1095
1096 fn respond(
1097 &self,
1098 _request: LLMRequest,
1099 ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
1100 futures_lite::stream::empty()
1101 }
1102
1103 fn profile(&self) -> impl std::future::Future<Output = ModelProfile> + Send {
1104 std::future::ready(ModelProfile::new(
1105 "mock",
1106 "test",
1107 "mock-model",
1108 "mock model",
1109 100_000,
1110 ))
1111 }
1112 }
1113
1114 struct MockTool;
1115
1116 #[derive(Debug, JsonSchema, Deserialize)]
1117 struct MockArgs;
1118
1119 impl Tool for MockTool {
1120 fn name(&self) -> Cow<'static, str> {
1121 "mock_tool".into()
1122 }
1123
1124 type Arguments = MockArgs;
1125 type Res = aither_core::llm::ToolResult;
1126
1127 fn call(
1128 &self,
1129 _args: Self::Arguments,
1130 ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
1131 std::future::ready(Ok(aither_core::llm::ToolResult::text("ok")))
1132 }
1133 }
1134
1135 #[test]
1137 fn test_types_compile() {
1138 fn _assert_send_sync<T: Send + Sync>() {}
1140 }
1142
1143 #[test]
1144 fn test_get_os_info() {
1145 let (os_name, os_version) = get_os_info();
1146 assert!(!os_name.is_empty());
1147 assert!(!os_version.is_empty());
1148 #[cfg(target_os = "macos")]
1150 assert_eq!(os_name, "macOS");
1151 }
1152
1153 #[test]
1154 fn test_system_prompt_container_profile_excludes_heel_modes() {
1155 let prompt = SystemPrompt {
1156 os: "macOS".to_string(),
1157 os_version: "15.0".to_string(),
1158 arch: "arm64",
1159 user_cwd: "/tmp/project".to_string(),
1160 sandbox_dir: "/tmp/sandbox".to_string(),
1161 tools: "- terminal: Execute terminal commands".to_string(),
1162 host_profile: "container",
1163 host_runtime_context: "runtime=linux_container".to_string(),
1164 skills: String::new(),
1165 has_skills: false,
1166 subagents: String::new(),
1167 has_subagents: false,
1168 is_macos: true,
1169 }
1170 .render()
1171 .expect("failed to render container prompt");
1172
1173 assert!(prompt.contains("<runtime>Linux container runtime</runtime>"));
1174 assert!(prompt.contains("<shell-runtime>"));
1175 assert!(!prompt.contains("<shell-modes>"));
1176 assert!(prompt.contains("install dependencies freely"));
1177 }
1178
1179 #[test]
1180 fn test_system_prompt_heel_profile_includes_shell_modes() {
1181 let prompt = SystemPrompt {
1182 os: "macOS".to_string(),
1183 os_version: "15.0".to_string(),
1184 arch: "arm64",
1185 user_cwd: "/tmp/project".to_string(),
1186 sandbox_dir: "/tmp/sandbox".to_string(),
1187 tools: "- terminal: Execute terminal commands".to_string(),
1188 host_profile: "heel",
1189 host_runtime_context: "runtime=user_local_machine".to_string(),
1190 skills: String::new(),
1191 has_skills: false,
1192 subagents: String::new(),
1193 has_subagents: false,
1194 is_macos: true,
1195 }
1196 .render()
1197 .expect("failed to render heel prompt");
1198
1199 assert!(prompt.contains("<shell-modes>"));
1200 assert!(!prompt.contains("<shell-runtime>"));
1201 assert!(prompt.contains("<unsafe>"));
1202 }
1203
1204 #[tokio::test(flavor = "multi_thread")]
1205 async fn terminal_agent_builder_keeps_ipc_tools_out_of_llm_tool_surface() {
1206 let dir = tempdir().expect("tempdir should exist");
1207 let terminal_tool =
1208 aither_sandbox::TerminalTool::<NoopPermissionHandler, TokioGlobal>::new_exact(
1209 dir.path(),
1210 NoopPermissionHandler,
1211 TokioGlobal,
1212 )
1213 .await
1214 .expect("terminal tool should initialize");
1215
1216 let agent = TerminalAgentBuilder::new(MockLlm, terminal_tool)
1217 .tool(MockTool)
1218 .with_default_prompt()
1219 .build();
1220
1221 let mut tool_names = agent
1222 .tools
1223 .definitions()
1224 .into_iter()
1225 .map(|definition| definition.name().to_string())
1226 .collect::<Vec<_>>();
1227 tool_names.sort();
1228
1229 assert_eq!(
1230 tool_names,
1231 vec![
1232 "terminal".to_string(),
1233 "terminal_input".to_string(),
1234 "terminal_kill".to_string(),
1235 "terminal_read".to_string(),
1236 ]
1237 );
1238 }
1239}