1use std::borrow::Cow;
35use std::future::Future;
36use std::marker::PhantomData;
37use std::pin::Pin;
38use std::sync::Arc;
39
40use aither_core::LanguageModel;
41use aither_core::llm::Tool;
42use aither_core::llm::tool::ToolDefinition;
43#[cfg(feature = "mcp")]
44use aither_mcp::McpConnection;
45#[cfg(feature = "skills")]
46use aither_skills::SkillRegistry;
47use askama::Template;
48use async_fs as fs;
49use executor_core::Executor;
50use schemars::JsonSchema;
51use serde::de::DeserializeOwned;
52
53use crate::hook::Hook;
54use crate::{Agent, AgentBuilder, config::AgentKind, context::serialize_xml};
55use aither_sandbox::builtin::{InputTerminalTool, KillTerminalTool, ReadTerminalDeltaTool};
56use aither_sandbox::{
57 CommandPayload, ContainerShellRuntime, PermissionHandler, ShellRuntimeAvailability,
58 ShellSessionRegistry, SshServer, SshSessionAuthorizer, TerminalTool, TerminalToolFactory,
59 TerminalToolFactoryReceiver, ToolDistribution, ToolRegistryBuilder, ToolRuntimeError,
60 Unconfigured, terminal_tool_factory_channel,
61};
62
63#[derive(Template)]
65#[template(path = "system.txt", escape = "none")]
66#[allow(clippy::struct_excessive_bools)]
67struct SystemPrompt {
68 os: String,
69 os_version: String,
70 arch: &'static str,
71 user_cwd: String,
72 sandbox_dir: String,
73 tools: String,
74 host_profile: &'static str,
75 host_runtime_context: String,
76 skills: String,
77 has_skills: bool,
78 subagents: String,
79 has_subagents: bool,
80 is_macos: bool,
81 has_websearch_command: bool,
82}
83
84#[derive(serde::Serialize)]
85struct ShellRuntimeContextXml {
86 available_backends: ShellRuntimeAvailableBackendsXml,
87 runtime: &'static str,
88}
89
90#[derive(serde::Serialize)]
91struct ShellRuntimeAvailableBackendsXml {
92 #[serde(rename = "@local")]
93 local: bool,
94 #[serde(rename = "@ssh")]
95 ssh: bool,
96}
97
98fn join_text(parts: &[&str]) -> String {
99 let capacity = parts.iter().map(|part| part.len()).sum();
100 let mut output = String::with_capacity(capacity);
101 for part in parts {
102 output.push_str(part);
103 }
104 output
105}
106
107fn path_error_text(prefix: &str, path: &std::path::Path, error: &impl std::fmt::Display) -> String {
108 let path_text = path.display().to_string();
109 let error_text = error.to_string();
110 join_text(&[prefix, path_text.as_str(), "': ", error_text.as_str()])
111}
112
113fn quoted_path_error_text(
114 prefix: &str,
115 first_path: &std::path::Path,
116 infix: &str,
117 second_path: &std::path::Path,
118 error: &impl std::fmt::Display,
119) -> String {
120 let first_path_text = first_path.display().to_string();
121 let second_path_text = second_path.display().to_string();
122 let error_text = error.to_string();
123 join_text(&[
124 prefix,
125 first_path_text.as_str(),
126 infix,
127 second_path_text.as_str(),
128 "': ",
129 error_text.as_str(),
130 ])
131}
132
133#[derive(Debug, Clone)]
135pub struct SkillInfo {
136 pub name: String,
138 pub description: String,
140}
141
142#[derive(Debug, Clone)]
144pub struct SubagentInfo {
145 pub name: String,
147 pub description: String,
149 pub path: String,
151}
152
153#[derive(Debug, Clone, Copy)]
156pub struct Unprepared;
157
158#[derive(Debug, Clone, Copy)]
165pub struct Prepared;
166
167pub struct TerminalAgentBuilder<LLM, P, E, H = (), S = Unprepared>
176where
177 LLM: LanguageModel + Clone,
178 P: PermissionHandler + 'static,
179 E: Executor + Clone + 'static,
180{
181 inner: AgentBuilder<LLM, LLM, LLM, H>,
182 terminal_tool: TerminalTool<P, E, Unconfigured>,
183 registry_builder: ToolRegistryBuilder,
184 terminal_tool_factory: TerminalToolFactory,
185 terminal_tool_factory_receiver: Option<TerminalToolFactoryReceiver>,
186 tool_descriptions: Vec<(String, String)>,
187 skills: Vec<SkillInfo>,
188 subagents: Vec<SubagentInfo>,
189 #[cfg(feature = "skills")]
190 skill_registry: Option<SkillRegistry>,
191 state: PhantomData<S>,
192}
193
194impl<LLM, P, E, H, S> std::fmt::Debug for TerminalAgentBuilder<LLM, P, E, H, S>
195where
196 LLM: LanguageModel + Clone,
197 P: PermissionHandler + 'static,
198 E: Executor + Clone + 'static,
199{
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 f.debug_struct("TerminalAgentBuilder")
202 .field("tool_count", &self.tool_descriptions.len())
203 .field("skill_count", &self.skills.len())
204 .field("subagent_count", &self.subagents.len())
205 .finish_non_exhaustive()
206 }
207}
208
209impl<LLM, P, E> TerminalAgentBuilder<LLM, P, E, ()>
210where
211 LLM: LanguageModel + Clone,
212 P: PermissionHandler + 'static,
213 E: Executor + Clone + 'static,
214{
215 pub fn new(llm: LLM, mut terminal_tool: TerminalTool<P, E, Unconfigured>) -> Self {
221 let (terminal_tool_factory, terminal_tool_factory_receiver) =
222 terminal_tool_factory_channel();
223 let mut registry_builder = ToolRegistryBuilder::new();
224 let mut tool_descriptions = Vec::new();
225
226 let shell_sessions = ShellSessionRegistry::new(ShellRuntimeAvailability {
227 local: true,
228 container: false,
229 ssh: false,
230 });
231
232 let job_registry = terminal_tool.job_registry();
233 let kill_terminal_tool = KillTerminalTool::new(job_registry.clone());
234 let input_terminal_tool = InputTerminalTool::new(job_registry.clone());
235 let read_terminal_delta_tool = ReadTerminalDeltaTool::new(job_registry);
236 terminal_tool = terminal_tool.with_shell_sessions(shell_sessions);
237
238 let kill_def = ToolDefinition::new(&kill_terminal_tool);
239 tool_descriptions.push((
240 kill_def.name().to_string(),
241 short_description(kill_def.description()),
242 ));
243 let input_def = ToolDefinition::new(&input_terminal_tool);
244 tool_descriptions.push((
245 input_def.name().to_string(),
246 short_description(input_def.description()),
247 ));
248 let read_delta_def = ToolDefinition::new(&read_terminal_delta_tool);
249 tool_descriptions.push((
250 read_delta_def.name().to_string(),
251 short_description(read_delta_def.description()),
252 ));
253
254 registry_builder.configure_tool(kill_terminal_tool);
255 registry_builder.configure_tool(input_terminal_tool);
256 registry_builder.configure_tool(read_terminal_delta_tool);
257 let inner = AgentBuilder::new(llm);
258
259 Self {
260 inner,
261 terminal_tool,
262 registry_builder,
263 terminal_tool_factory,
264 terminal_tool_factory_receiver: Some(terminal_tool_factory_receiver),
265 tool_descriptions,
266 skills: Vec::new(),
267 subagents: Vec::new(),
268 #[cfg(feature = "skills")]
269 skill_registry: None,
270 state: PhantomData,
271 }
272 }
273}
274
275impl<LLM, P, E, H, S> TerminalAgentBuilder<LLM, P, E, H, S>
276where
277 LLM: LanguageModel + Clone,
278 P: PermissionHandler + 'static,
279 E: Executor + Clone + 'static,
280 H: Hook,
281{
282 fn rebuild<NH, NS>(
284 self,
285 inner: impl FnOnce(AgentBuilder<LLM, LLM, LLM, H>) -> AgentBuilder<LLM, LLM, LLM, NH>,
286 ) -> TerminalAgentBuilder<LLM, P, E, NH, NS> {
287 TerminalAgentBuilder {
288 inner: inner(self.inner),
289 terminal_tool: self.terminal_tool,
290 registry_builder: self.registry_builder,
291 terminal_tool_factory: self.terminal_tool_factory,
292 terminal_tool_factory_receiver: self.terminal_tool_factory_receiver,
293 tool_descriptions: self.tool_descriptions,
294 skills: self.skills,
295 subagents: self.subagents,
296 #[cfg(feature = "skills")]
297 skill_registry: self.skill_registry,
298 state: PhantomData,
299 }
300 }
301
302 async fn resolve_absolute_dir(
303 path: &std::path::Path,
304 kind: &str,
305 ) -> Result<std::path::PathBuf, crate::AgentError> {
306 fs::create_dir_all(path).await.map_err(|error| {
307 let prefix = join_text(&["failed to create ", kind, " directory '"]);
308 crate::AgentError::Config(path_error_text(prefix.as_str(), path, &error))
309 })?;
310
311 fs::canonicalize(path).await.map_err(|error| {
312 let prefix = join_text(&["failed to canonicalize ", kind, " directory '"]);
313 crate::AgentError::Config(path_error_text(prefix.as_str(), path, &error))
314 })
315 }
316
317 async fn register_readable_dir(
318 mut self,
319 source_path: &std::path::Path,
320 kind: &str,
321 ) -> Result<Self, crate::AgentError> {
322 let abs_path = Self::resolve_absolute_dir(source_path, kind).await?;
323 self.terminal_tool = self.terminal_tool.with_readable_paths([abs_path]);
324 Ok(self)
325 }
326
327 async fn attach_readable_symlink(
328 mut self,
329 source_path: &std::path::Path,
330 kind: &str,
331 link_name: &str,
332 ) -> Result<Self, crate::AgentError> {
333 let abs_path = Self::resolve_absolute_dir(source_path, kind).await?;
334 let symlink_path = self.terminal_tool.working_dir().join(link_name);
335
336 match fs::symlink_metadata(&symlink_path).await {
337 Ok(metadata) => {
338 if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() {
339 fs::remove_dir(&symlink_path).await.map_err(|error| {
340 crate::AgentError::Config(path_error_text(
341 "failed to remove existing directory '",
342 &symlink_path,
343 &error,
344 ))
345 })?;
346 } else {
347 fs::remove_file(&symlink_path).await.map_err(|error| {
348 crate::AgentError::Config(path_error_text(
349 "failed to remove existing file '",
350 &symlink_path,
351 &error,
352 ))
353 })?;
354 }
355 }
356 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
357 Err(error) => {
358 return Err(crate::AgentError::Config(path_error_text(
359 "failed to inspect '",
360 &symlink_path,
361 &error,
362 )));
363 }
364 }
365
366 #[cfg(unix)]
367 {
368 fs::unix::symlink(&abs_path, &symlink_path)
369 .await
370 .map_err(|error| {
371 crate::AgentError::Config(quoted_path_error_text(
372 "failed to create symlink '",
373 &symlink_path,
374 "' -> '",
375 &abs_path,
376 &error,
377 ))
378 })?;
379 }
380 #[cfg(windows)]
381 {
382 fs::windows::symlink_dir(&abs_path, &symlink_path)
383 .await
384 .map_err(|error| {
385 crate::AgentError::Config(quoted_path_error_text(
386 "failed to create symlink '",
387 &symlink_path,
388 "' -> '",
389 &abs_path,
390 &error,
391 ))
392 })?;
393 }
394
395 self.terminal_tool = self.terminal_tool.with_readable_paths([abs_path]);
396 Ok(self)
397 }
398
399 #[must_use]
411 pub fn tool<T>(mut self, tool: T) -> Self
412 where
413 T: Tool + Send + Sync + 'static,
414 T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
415 {
416 let name = tool.name().to_string();
417 let def = ToolDefinition::new(&tool);
419 let description = def.description();
420 self.tool_descriptions
421 .push((name, short_description(description)));
422 self.registry_builder.configure_tool(tool);
423 self
424 }
425
426 #[must_use]
432 pub fn definition_handler<F>(mut self, definition: &ToolDefinition, handler: F) -> Self
433 where
434 F: Fn(
435 serde_json::Value,
436 )
437 -> Pin<Box<dyn Future<Output = Result<Option<CommandPayload>, String>> + Send>>
438 + Send
439 + Sync
440 + 'static,
441 {
442 let name = definition.name().to_string();
443 let description = definition.description().to_string();
444 self.tool_descriptions
445 .push((name, short_description(description.as_str())));
446 self.registry_builder
447 .configure_definition_handler(definition, handler);
448 self
449 }
450
451 #[cfg(feature = "mcp")]
453 #[must_use]
454 pub fn mcp_connection(mut self, conn: McpConnection) -> Self {
455 let definitions = aither_mcp::register_terminal_commands(&mut self.registry_builder, conn);
456 self.tool_descriptions
457 .extend(definitions.into_iter().map(|definition| {
458 (
459 definition.name().to_string(),
460 short_description(definition.description()),
461 )
462 }));
463 self
464 }
465
466 #[must_use]
468 pub fn tool_with_desc<T>(mut self, tool: T, description: impl Into<String>) -> Self
469 where
470 T: Tool + Send + Sync + 'static,
471 T::Arguments: DeserializeOwned + JsonSchema + Send + 'static,
472 {
473 let name = tool.name().to_string();
474 self.tool_descriptions.push((name, description.into()));
475 self.registry_builder.configure_tool(tool);
476 self
477 }
478
479 #[must_use]
483 pub fn tool_description(
484 mut self,
485 name: impl Into<String>,
486 description: impl Into<String>,
487 ) -> Self {
488 self.tool_descriptions
489 .push((name.into(), description.into()));
490 self
491 }
492
493 #[must_use]
495 pub fn system_prompt_raw(mut self, prompt: impl Into<String>) -> Self {
496 self.inner = self.inner.system_prompt(prompt.into());
497 self
498 }
499
500 #[must_use]
502 pub fn persona_prompt(mut self, prompt: impl Into<String>) -> Self {
503 self.inner = self.inner.persona_prompt(prompt.into());
504 self
505 }
506
507 #[must_use]
509 pub fn agent_kind(mut self, kind: AgentKind) -> Self {
510 self.inner = self.inner.agent_kind(kind);
511 self
512 }
513
514 #[must_use]
516 pub fn transcript_path(mut self, path: impl Into<String>) -> Self {
517 self.inner = self.inner.transcript_path(path.into());
518 self
519 }
520
521 #[must_use]
523 pub fn transcript(mut self, path: impl Into<std::path::PathBuf>) -> Self {
524 self.inner = self.inner.transcript(path);
525 self
526 }
527
528 #[must_use]
530 pub fn system<T: serde::Serialize>(mut self, value: T) -> Self {
531 self.inner = self.inner.system(value);
532 self
533 }
534
535 #[must_use]
537 pub fn system_named(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
538 self.inner = self.inner.system_named(tag, content);
539 self
540 }
541
542 #[must_use]
550 pub fn system_text(mut self, tag: impl Into<String>, content: impl Into<String>) -> Self {
551 self.inner = self.inner.system_text(tag, content);
552 self
553 }
554
555 #[must_use]
563 pub fn with_default_prompt(mut self) -> Self {
564 let availability = self.terminal_tool.shell_sessions().availability();
565 let host_profile = if availability.container {
566 "container"
567 } else if availability.local {
568 "heel"
569 } else if availability.ssh {
570 "remote"
571 } else {
572 panic!("terminal agent requires at least one shell backend")
573 };
574 let runtime_kind = match host_profile {
575 "container" => "linux_container",
576 "remote" => "remote_ssh",
577 "heel" => "user_local_machine",
578 _ => unreachable!("validated host profile"),
579 };
580 let shell_context = serialize_xml(
581 "shell_runtime",
582 &ShellRuntimeContextXml {
583 available_backends: ShellRuntimeAvailableBackendsXml {
584 local: availability.local || availability.container,
585 ssh: availability.ssh,
586 },
587 runtime: runtime_kind,
588 },
589 );
590 self.inner = self.inner.system_named("shell_runtime", shell_context);
591
592 let ssh_context =
593 describe_ssh_servers(&self.terminal_tool.shell_sessions().list_ssh_servers());
594 let host_runtime_context =
595 describe_host_runtime_context(host_profile, &availability, ssh_context.as_str());
596
597 let tools = render_tool_descriptions(&self.tool_descriptions);
599
600 let has_skills = !self.skills.is_empty();
602 let skills = render_skill_descriptions(&self.skills);
603
604 let has_subagents = !self.subagents.is_empty();
606 let subagents = render_subagent_descriptions(&self.subagents);
607
608 let sandbox_dir = self.terminal_tool.working_dir().display().to_string();
610 let user_cwd =
611 std::env::current_dir().map_or_else(|_| ".".to_string(), |p| p.display().to_string());
612
613 let (os, os_version) = get_os_info();
615 let arch = std::env::consts::ARCH;
616 let is_macos = cfg!(target_os = "macos");
617
618 let template = SystemPrompt {
619 os,
620 os_version,
621 arch,
622 user_cwd,
623 sandbox_dir,
624 tools,
625 host_profile,
626 host_runtime_context,
627 skills,
628 has_skills,
629 subagents,
630 has_subagents,
631 is_macos,
632 has_websearch_command: self.has_command("websearch"),
633 };
634
635 let prompt = template
636 .render()
637 .expect("failed to render system prompt template");
638 self.inner = self.inner.system_prompt(prompt);
639 self
640 }
641
642 pub fn hook<NH: Hook>(
644 self,
645 hook: NH,
646 ) -> TerminalAgentBuilder<LLM, P, E, crate::HCons<NH, H>, S> {
647 self.rebuild(|inner| inner.hook(hook))
648 }
649
650 #[cfg(feature = "skills")]
657 async fn load_skills(
658 mut self,
659 path: impl AsRef<std::path::Path>,
660 ) -> Result<Self, crate::AgentError> {
661 use aither_skills::SkillLoader;
662
663 let path = path.as_ref().to_path_buf();
664 let abs_path = Self::resolve_absolute_dir(&path, "skills").await?;
665 let loader = SkillLoader::new().add_path(&abs_path);
666 let mut registry = self.skill_registry.take().unwrap_or_default();
667 registry.load_from(&loader).await.map_err(|error| {
668 crate::AgentError::Config(path_error_text(
669 "failed to load skills from '",
670 &abs_path,
671 &error,
672 ))
673 })?;
674
675 let skills = registry.all().into_iter().cloned().collect::<Vec<_>>();
676 self.skills.clear();
677 tracing::info!(count = skills.len(), path = %abs_path.display(), "Loaded skills");
678 for skill in skills {
679 tracing::debug!(name = %skill.name, "Loaded skill");
680 self.skills.push(SkillInfo {
681 name: skill.name,
682 description: skill.description,
683 });
684 }
685 self.skill_registry = Some(registry);
686
687 Ok(self)
688 }
689
690 #[cfg(feature = "skills")]
691 pub async fn with_skills(
697 self,
698 path: impl AsRef<std::path::Path>,
699 ) -> Result<Self, crate::AgentError> {
700 let path = path.as_ref().to_path_buf();
701 self.load_skills(&path)
702 .await?
703 .attach_readable_symlink(&path, "skills", "skills")
704 .await
705 }
706
707 #[cfg(feature = "skills")]
716 pub async fn with_skills_readable_only(
717 self,
718 path: impl AsRef<std::path::Path>,
719 ) -> Result<Self, crate::AgentError> {
720 let path = path.as_ref().to_path_buf();
721 self.load_skills(&path)
722 .await?
723 .register_readable_dir(&path, "skills")
724 .await
725 }
726
727 #[must_use]
729 pub fn skill(mut self, name: impl Into<String>, description: impl Into<String>) -> Self {
730 self.skills.push(SkillInfo {
731 name: name.into(),
732 description: description.into(),
733 });
734 self
735 }
736
737 async fn load_subagents(
750 mut self,
751 path: impl AsRef<std::path::Path>,
752 ) -> Result<Self, crate::AgentError> {
753 use crate::subagent_file::SubagentDefinition;
754
755 let path = path.as_ref().to_path_buf();
756 let abs_path = Self::resolve_absolute_dir(&path, "subagents").await?;
757
758 let defs = SubagentDefinition::load_from_dir_async(&abs_path)
759 .await
760 .map_err(|error| {
761 crate::AgentError::Config(path_error_text(
762 "failed to load subagents from '",
763 &abs_path,
764 &error,
765 ))
766 })?;
767
768 for def in defs {
769 let mut filename = def.id.clone();
770 filename.push_str(".md");
771 self.subagents.push(SubagentInfo {
772 name: def.id,
773 description: def.description,
774 path: filename,
775 });
776 }
777
778 Ok(self)
779 }
780
781 pub async fn with_subagents(
787 self,
788 path: impl AsRef<std::path::Path>,
789 ) -> Result<Self, crate::AgentError> {
790 let path = path.as_ref().to_path_buf();
791 self.load_subagents(&path)
792 .await?
793 .attach_readable_symlink(&path, "subagents", "subagents")
794 .await
795 }
796
797 pub async fn with_subagents_readable_only(
806 self,
807 path: impl AsRef<std::path::Path>,
808 ) -> Result<Self, crate::AgentError> {
809 let path = path.as_ref().to_path_buf();
810 self.load_subagents(&path)
811 .await?
812 .register_readable_dir(&path, "subagents")
813 .await
814 }
815
816 #[must_use]
818 pub fn max_iterations(mut self, limit: usize) -> Self {
819 self.inner = self.inner.max_iterations(limit);
820 self
821 }
822
823 pub fn tool_descriptions(&self) -> &[(String, String)] {
827 &self.tool_descriptions
828 }
829
830 fn has_command(&self, name: &str) -> bool {
832 self.tool_descriptions.iter().any(|(n, _)| n == name)
833 }
834
835 #[must_use]
837 pub fn terminal_tool_factory(&self) -> TerminalToolFactory {
838 self.terminal_tool_factory.clone()
839 }
840
841 pub const fn tool_registry_mut(&mut self) -> &mut ToolRegistryBuilder {
843 &mut self.registry_builder
844 }
845
846 pub fn sandbox_dir(&self) -> Cow<'_, str> {
848 self.terminal_tool.working_dir().to_string_lossy()
849 }
850
851 pub fn build(self) -> Agent<LLM, LLM, LLM, H> {
860 let websearch_command = self.has_command("websearch");
863
864 let registry = std::sync::Arc::new(
866 self.registry_builder
867 .build(self.terminal_tool.outputs_dir()),
868 );
869
870 let terminal_tool = self.terminal_tool.with_registry(registry);
872
873 if let Some(receiver) = self.terminal_tool_factory_receiver {
875 terminal_tool.start_factory_service(receiver);
876 }
877
878 let inner = if self.inner.has_system_named("knowledge_and_time") {
879 self.inner
880 } else {
881 self.inner.system_named(
882 "knowledge_and_time",
883 crate::agent::KnowledgeAndTimeTemplate { websearch_command }
884 .render()
885 .expect("failed to render knowledge_and_time template"),
886 )
887 };
888 let inner = inner.terminal(terminal_tool);
889 #[cfg(feature = "skills")]
890 let inner = if let Some(registry) = self.skill_registry {
891 inner.skill_registry(Arc::new(registry))
892 } else {
893 inner
894 };
895
896 inner.build()
897 }
898}
899
900impl<LLM, P, E, H> TerminalAgentBuilder<LLM, P, E, H, Unprepared>
901where
902 LLM: LanguageModel + Clone,
903 P: PermissionHandler + 'static,
904 E: Executor + Clone + 'static,
905 H: Hook,
906{
907 #[must_use]
909 pub fn shell_runtime_availability(mut self, availability: ShellRuntimeAvailability) -> Self {
910 self.terminal_tool = self
911 .terminal_tool
912 .with_shell_runtime_availability(availability);
913 self
914 }
915
916 #[must_use]
922 pub fn ssh_servers(mut self, servers: Vec<SshServer>) -> Self {
923 let sessions = self
924 .terminal_tool
925 .shell_sessions()
926 .clone()
927 .with_ssh_servers(servers)
928 .expect("invalid ssh server configuration");
929 self.terminal_tool = self.terminal_tool.with_shell_sessions(sessions);
930 self
931 }
932
933 #[must_use]
935 pub fn ssh_authorizer<T: SshSessionAuthorizer + 'static>(mut self, authorizer: Arc<T>) -> Self {
936 let sessions = self
937 .terminal_tool
938 .shell_sessions()
939 .clone()
940 .with_ssh_authorizer(authorizer);
941 self.terminal_tool = self.terminal_tool.with_shell_sessions(sessions);
942 self
943 }
944
945 #[must_use]
947 pub fn container_runtime(mut self, runtime: ContainerShellRuntime) -> Self {
948 self.terminal_tool = self.terminal_tool.with_container_runtime(runtime);
949 self
950 }
951
952 pub async fn initialize_tools(
962 mut self,
963 distribution: &ToolDistribution,
964 cache_root: &std::path::Path,
965 ) -> Result<TerminalAgentBuilder<LLM, P, E, H, Prepared>, ToolRuntimeError> {
966 self.terminal_tool = self
967 .terminal_tool
968 .initialize_tools(distribution, cache_root)
969 .await?;
970 Ok(self.rebuild(std::convert::identity))
971 }
972
973 pub async fn prepared_shell_sessions(
986 mut self,
987 sessions: ShellSessionRegistry,
988 ) -> Result<TerminalAgentBuilder<LLM, P, E, H, Prepared>, ToolRuntimeError> {
989 self.terminal_tool = self.terminal_tool.adopt_prepared_tools(sessions).await?;
990 Ok(self.rebuild(std::convert::identity))
991 }
992}
993
994impl<LLM, P, E, H> TerminalAgentBuilder<LLM, P, E, H, Prepared>
995where
996 LLM: LanguageModel + Clone,
997 P: PermissionHandler + 'static,
998 E: Executor + Clone + 'static,
999 H: Hook,
1000{
1001 #[must_use]
1004 pub const fn shell_sessions(&self) -> &ShellSessionRegistry {
1005 self.terminal_tool.shell_sessions()
1006 }
1007}
1008
1009fn short_description(description: &str) -> String {
1010 description
1011 .split('.')
1012 .next()
1013 .unwrap_or(description)
1014 .trim()
1015 .to_string()
1016}
1017
1018fn push_bullet_line(output: &mut String, body: &str) {
1019 if !output.is_empty() {
1020 output.push('\n');
1021 }
1022 output.push_str("- ");
1023 output.push_str(body);
1024}
1025
1026fn render_tool_descriptions(entries: &[(String, String)]) -> String {
1027 let mut output = String::new();
1028 for (name, description) in entries {
1029 let mut line = String::with_capacity(name.len() + description.len() + 2);
1030 line.push_str(name.as_str());
1031 line.push_str(": ");
1032 line.push_str(description.as_str());
1033 push_bullet_line(&mut output, line.as_str());
1034 }
1035 output
1036}
1037
1038fn render_skill_descriptions(entries: &[SkillInfo]) -> String {
1039 let mut output = String::new();
1040 for skill in entries {
1041 let mut line = String::with_capacity(skill.name.len() + skill.description.len() + 2);
1042 line.push_str(skill.name.as_str());
1043 line.push_str(": ");
1044 line.push_str(skill.description.as_str());
1045 push_bullet_line(&mut output, line.as_str());
1046 }
1047 output
1048}
1049
1050fn render_subagent_descriptions(entries: &[SubagentInfo]) -> String {
1051 let mut output = String::new();
1052 for subagent in entries {
1053 let mut line = String::with_capacity(
1054 subagent.name.len() + subagent.path.len() + subagent.description.len() + 5,
1055 );
1056 line.push_str(subagent.name.as_str());
1057 line.push_str(" (");
1058 line.push_str(subagent.path.as_str());
1059 line.push_str("): ");
1060 line.push_str(subagent.description.as_str());
1061 push_bullet_line(&mut output, line.as_str());
1062 }
1063 output
1064}
1065
1066fn describe_host_runtime_context(
1067 host_profile: &str,
1068 availability: &ShellRuntimeAvailability,
1069 ssh_context: &str,
1070) -> String {
1071 let mut output = String::new();
1072 match host_profile {
1073 "container" => {
1074 output.push_str(
1075 "Linux container runtime. Default mode has network enabled. You may install dependencies freely. SSH available: ",
1076 );
1077 output.push_str(if availability.ssh { "true" } else { "false" });
1078 output.push_str(". ");
1079 }
1080 "remote" => {
1081 output.push_str(
1082 "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. ",
1083 );
1084 }
1085 "heel" => {
1086 output.push_str(
1087 "User machine runtime in sandbox. Default mode has network enabled. Use unsafe for host-level side effects. SSH available: ",
1088 );
1089 output.push_str(if availability.ssh { "true" } else { "false" });
1090 output.push_str(". ");
1091 }
1092 _ => unreachable!("validated host profile"),
1093 }
1094 output.push_str(ssh_context);
1095 output
1096}
1097
1098fn describe_ssh_servers(servers: &[SshServer]) -> String {
1099 if servers.is_empty() {
1100 "No SSH servers are configured.".to_string()
1101 } else if servers.len() == 1 {
1102 let server = &servers[0];
1103 let mut output = String::with_capacity(server.id().len() + server.target.len() + 89);
1104 output.push_str("Configured SSH server: ");
1105 output.push_str(server.id());
1106 output.push_str(" (");
1107 output.push_str(server.target.as_str());
1108 output.push_str("). When using SSH backend, ssh_server_id may be omitted because only one server is configured.");
1109 output
1110 } else {
1111 let mut listings = String::new();
1112 for server in servers {
1113 if !listings.is_empty() {
1114 listings.push_str(", ");
1115 }
1116 listings.push_str(server.id());
1117 listings.push_str(" (");
1118 listings.push_str(server.target.as_str());
1119 listings.push(')');
1120 }
1121 let mut output = String::with_capacity(listings.len() + 24);
1122 output.push_str("Configured SSH servers: ");
1123 output.push_str(listings.as_str());
1124 output.push('.');
1125 output
1126 }
1127}
1128
1129fn get_os_info() -> (String, String) {
1131 #[cfg(target_os = "macos")]
1132 {
1133 let version = std::process::Command::new("sw_vers")
1134 .arg("-productVersion")
1135 .output()
1136 .ok()
1137 .and_then(|o| String::from_utf8(o.stdout).ok())
1138 .map_or_else(|| "unknown".to_string(), |s| s.trim().to_string());
1139 ("macOS".to_string(), version)
1140 }
1141
1142 #[cfg(target_os = "linux")]
1143 {
1144 let version = std::fs::read_to_string("/etc/os-release")
1146 .ok()
1147 .and_then(|content| {
1148 content
1149 .lines()
1150 .find(|line| line.starts_with("PRETTY_NAME="))
1151 .map(|line| {
1152 line.trim_start_matches("PRETTY_NAME=")
1153 .trim_matches('"')
1154 .to_string()
1155 })
1156 })
1157 .unwrap_or_else(|| {
1158 std::process::Command::new("uname")
1160 .arg("-r")
1161 .output()
1162 .ok()
1163 .and_then(|o| String::from_utf8(o.stdout).ok())
1164 .map_or_else(|| "unknown".to_string(), |s| s.trim().to_string())
1165 });
1166 ("Linux".to_string(), version)
1167 }
1168
1169 #[cfg(target_os = "windows")]
1170 {
1171 let version = std::process::Command::new("cmd")
1172 .args(["/C", "ver"])
1173 .output()
1174 .ok()
1175 .and_then(|o| String::from_utf8(o.stdout).ok())
1176 .map_or_else(|| "unknown".to_string(), |s| s.trim().to_string());
1177 ("Windows".to_string(), version)
1178 }
1179
1180 #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
1181 {
1182 (std::env::consts::OS.to_string(), "unknown".to_string())
1183 }
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188 use super::*;
1189 use std::borrow::Cow;
1190
1191 use aither_core::LanguageModel;
1192 use aither_core::llm::{Event, LLMRequest, Tool, model::Profile as ModelProfile};
1193 use aither_sandbox::permission::NoopPermissionHandler;
1194 use executor_core::tokio::TokioGlobal;
1195 use futures_core::Stream;
1196 use schemars::JsonSchema;
1197 use serde::Deserialize;
1198 use tempfile::tempdir;
1199
1200 #[derive(Debug)]
1201 struct MockError;
1202
1203 impl std::fmt::Display for MockError {
1204 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1205 f.write_str("mock error")
1206 }
1207 }
1208
1209 impl std::error::Error for MockError {}
1210
1211 #[derive(Clone)]
1212 struct MockLlm {
1213 requests: async_channel::Sender<LLMRequest>,
1214 }
1215
1216 impl LanguageModel for MockLlm {
1217 type Error = MockError;
1218
1219 fn respond(
1220 &self,
1221 request: LLMRequest,
1222 ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
1223 self.requests
1224 .try_send(request)
1225 .expect("record model request");
1226 futures_lite::stream::empty()
1227 }
1228
1229 fn profile(&self) -> impl std::future::Future<Output = ModelProfile> + Send {
1230 std::future::ready(ModelProfile::new(
1231 "mock",
1232 "test",
1233 "mock-model",
1234 "mock model",
1235 100_000,
1236 ))
1237 }
1238 }
1239
1240 struct MockTool;
1241
1242 #[derive(Debug, JsonSchema, Deserialize)]
1243 struct MockArgs;
1244
1245 impl Tool for MockTool {
1246 fn name(&self) -> Cow<'static, str> {
1247 "mock_tool".into()
1248 }
1249
1250 type Arguments = MockArgs;
1251 type Res = aither_core::llm::ToolResult;
1252
1253 fn call(
1254 &self,
1255 _args: Self::Arguments,
1256 _cx: aither_core::llm::ToolContext,
1257 ) -> impl std::future::Future<Output = aither_core::Result<Self::Res>> + Send {
1258 std::future::ready(Ok(aither_core::llm::ToolResult::text("ok")))
1259 }
1260 }
1261
1262 #[test]
1264 fn test_types_compile() {
1265 fn _assert_send_sync<T: Send + Sync>() {}
1267 }
1269
1270 #[test]
1271 fn test_get_os_info() {
1272 let (os_name, os_version) = get_os_info();
1273 assert_ne!(os_name, "");
1274 assert_ne!(os_version, "");
1275 #[cfg(target_os = "macos")]
1277 assert_eq!(os_name, "macOS");
1278 }
1279
1280 #[test]
1281 fn test_system_prompt_container_profile_excludes_heel_modes() {
1282 let prompt = SystemPrompt {
1283 os: "macOS".to_string(),
1284 os_version: "15.0".to_string(),
1285 arch: "arm64",
1286 user_cwd: "/tmp/project".to_string(),
1287 sandbox_dir: "/tmp/sandbox".to_string(),
1288 tools: "- terminal: Execute terminal commands".to_string(),
1289 host_profile: "container",
1290 host_runtime_context: "runtime=linux_container".to_string(),
1291 skills: String::new(),
1292 has_skills: false,
1293 subagents: String::new(),
1294 has_subagents: false,
1295 is_macos: true,
1296 has_websearch_command: true,
1297 }
1298 .render()
1299 .expect("failed to render container prompt");
1300
1301 assert!(prompt.contains("<runtime>Linux container runtime</runtime>"));
1302 assert!(prompt.contains("<shell-runtime>"));
1303 assert!(!prompt.contains("<shell-modes>"));
1304 assert!(prompt.contains("install dependencies freely"));
1305 }
1306
1307 #[test]
1308 fn test_system_prompt_heel_profile_includes_shell_modes() {
1309 let prompt = SystemPrompt {
1310 os: "macOS".to_string(),
1311 os_version: "15.0".to_string(),
1312 arch: "arm64",
1313 user_cwd: "/tmp/project".to_string(),
1314 sandbox_dir: "/tmp/sandbox".to_string(),
1315 tools: "- terminal: Execute terminal commands".to_string(),
1316 host_profile: "heel",
1317 host_runtime_context: "runtime=user_local_machine".to_string(),
1318 skills: String::new(),
1319 has_skills: false,
1320 subagents: String::new(),
1321 has_subagents: false,
1322 is_macos: true,
1323 has_websearch_command: true,
1324 }
1325 .render()
1326 .expect("failed to render heel prompt");
1327
1328 assert!(prompt.contains("<shell-modes>"));
1329 assert!(!prompt.contains("<shell-runtime>"));
1330 assert!(prompt.contains("<unsafe>"));
1331 }
1332
1333 async fn compile_baseline_fixture(source: &std::path::Path) -> std::path::PathBuf {
1336 let fixture = source.join("baseline_tool.rs");
1337 async_fs::write(
1338 &fixture,
1339 include_bytes!("../templates/test_baseline_tool.rs"),
1340 )
1341 .await
1342 .unwrap();
1343 let path = source
1344 .join("baseline-tool")
1345 .with_extension(std::env::consts::EXE_EXTENSION);
1346 let compiled = async_process::Command::new("rustc")
1347 .arg("--crate-name")
1348 .arg("baseline_tool")
1349 .arg(&fixture)
1350 .arg("-o")
1351 .arg(&path)
1352 .kill_on_drop(true)
1353 .output()
1354 .await
1355 .unwrap();
1356 assert!(compiled.status.success(), "{compiled:?}");
1357 path
1358 }
1359
1360 async fn fixture_distribution(
1362 binary: &std::path::Path,
1363 version: &str,
1364 ) -> aither_sandbox::ToolDistribution {
1365 use aither_sandbox::{
1366 ManagedTool, ToolArtifact, ToolArtifactFormat, ToolDistribution, ToolTarget,
1367 };
1368 use sha2::Digest as _;
1369 #[derive(serde::Serialize)]
1370 struct Manifest {
1371 artifacts: Vec<ToolArtifact>,
1372 }
1373 let bytes = async_fs::read(binary).await.unwrap();
1374 let artifacts = ManagedTool::ALL
1375 .into_iter()
1376 .map(|tool| ToolArtifact {
1377 tool,
1378 version: version.into(),
1379 target: ToolTarget::native().unwrap(),
1380 url: aither_sandbox::ToolArtifactLocation::Download(
1381 url::Url::from_file_path(binary).unwrap(),
1382 ),
1383 sha256: format!("{:x}", sha2::Sha256::digest(&bytes)),
1384 encoding: ToolArtifactFormat::Executable,
1385 })
1386 .collect();
1387 ToolDistribution::from_json(&serde_json::to_vec(&Manifest { artifacts }).unwrap()).unwrap()
1388 }
1389
1390 async fn noop_terminal(
1391 dir: &std::path::Path,
1392 ) -> aither_sandbox::TerminalTool<NoopPermissionHandler, TokioGlobal> {
1393 aither_sandbox::TerminalTool::new_exact(dir, NoopPermissionHandler, TokioGlobal)
1394 .await
1395 .expect("terminal tool should initialize")
1396 }
1397
1398 #[derive(Clone)]
1400 struct BaselineCommandLlm {
1401 requests: async_channel::Sender<LLMRequest>,
1402 turns: Arc<std::sync::atomic::AtomicUsize>,
1403 }
1404
1405 impl LanguageModel for BaselineCommandLlm {
1406 type Error = MockError;
1407
1408 fn respond(
1409 &self,
1410 request: LLMRequest,
1411 ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
1412 self.requests
1413 .try_send(request)
1414 .expect("record model request");
1415 let turn = self.turns.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1416 let event = if turn == 0 {
1417 Event::ToolCall(aither_core::llm::ToolCall::new(
1418 "baseline",
1419 "terminal",
1420 serde_json::json!({
1421 "description": "Run every baseline command",
1422 "script": "apply_patch --version && rg --version && ast-grep --version && jq --version",
1423 "mode": "sandboxed",
1424 "timeout": 30,
1425 "raw": true
1426 }),
1427 ))
1428 } else {
1429 Event::Text("done".into())
1430 };
1431 futures_lite::stream::once(Ok(event))
1432 }
1433
1434 fn profile(&self) -> impl std::future::Future<Output = ModelProfile> + Send {
1435 std::future::ready(ModelProfile::new(
1436 "mock",
1437 "test",
1438 "mock-model",
1439 "mock model",
1440 100_000,
1441 ))
1442 }
1443 }
1444
1445 #[tokio::test(flavor = "multi_thread")]
1446 async fn rebuilt_agent_adopts_prepared_tools_and_runs_baseline_commands() {
1447 let source = tempdir().unwrap();
1448 let binary = compile_baseline_fixture(source.path()).await;
1449 let distribution = fixture_distribution(&binary, "1.0.0").await;
1450 let cache = tempdir().unwrap();
1451 let (requests, _captured) = async_channel::bounded(4);
1452 let first_dir = tempdir().unwrap();
1453 let first =
1454 TerminalAgentBuilder::new(MockLlm { requests }, noop_terminal(first_dir.path()).await)
1455 .initialize_tools(&distribution, cache.path())
1456 .await
1457 .expect("first agent prepares its tools");
1458 let prepared = first.shell_sessions().clone();
1459 let _first_agent = first.build();
1460
1461 let (requests, captured) = async_channel::bounded(4);
1462 let second_dir = tempdir().unwrap();
1463 let mut second = TerminalAgentBuilder::new(
1464 BaselineCommandLlm {
1465 requests,
1466 turns: Arc::default(),
1467 },
1468 noop_terminal(second_dir.path()).await,
1469 )
1470 .max_iterations(2)
1471 .with_default_prompt()
1472 .prepared_shell_sessions(prepared)
1473 .await
1474 .expect("second agent adopts the prepared registry")
1475 .build();
1476 let events = second.run("Check the baseline commands", []);
1477 futures_lite::pin!(events);
1478 while futures_lite::StreamExt::next(&mut events).await.is_some() {}
1479
1480 let first_request = captured
1481 .try_recv()
1482 .expect("first model request was recorded");
1483 assert!(
1484 first_request
1485 .messages()
1486 .iter()
1487 .any(|message| message.content().contains("<prepared_tools>")),
1488 "the adopted catalog reaches the model"
1489 );
1490 let second_request = captured
1491 .try_recv()
1492 .expect("the terminal result was sent back to the model");
1493 let transcript = second_request
1494 .messages()
1495 .iter()
1496 .map(aither_core::llm::Message::content)
1497 .collect::<Vec<_>>()
1498 .join("\n");
1499 assert!(
1500 transcript.contains("baseline-tool 1.0.0"),
1501 "baseline commands ran from the adopted tools: {transcript}"
1502 );
1503 }
1504
1505 #[tokio::test(flavor = "multi_thread")]
1506 async fn adoption_skips_the_version_probe_that_preparation_runs() {
1507 let source = tempdir().unwrap();
1508 let binary = compile_baseline_fixture(source.path()).await;
1509 let distribution = fixture_distribution(&binary, "2.0.0").await;
1512 let cache = tempdir().unwrap();
1513 let (requests, _captured) = async_channel::bounded(4);
1514
1515 let probed_dir = tempdir().unwrap();
1516 let probed = TerminalAgentBuilder::new(
1517 MockLlm {
1518 requests: requests.clone(),
1519 },
1520 noop_terminal(probed_dir.path()).await,
1521 )
1522 .initialize_tools(&distribution, cache.path())
1523 .await;
1524 assert!(matches!(
1525 probed,
1526 Err(aither_sandbox::ToolRuntimeError::VersionMismatch(_))
1527 ));
1528
1529 let prepared = ShellSessionRegistry::new(ShellRuntimeAvailability::default())
1530 .initialize_tools(&distribution, cache.path())
1531 .await
1532 .expect("registry preparation runs no terminal probe");
1533 let adopted_dir = tempdir().unwrap();
1534 TerminalAgentBuilder::new(
1535 MockLlm { requests },
1536 noop_terminal(adopted_dir.path()).await,
1537 )
1538 .prepared_shell_sessions(prepared)
1539 .await
1540 .expect("adoption does not probe versions again")
1541 .build();
1542 }
1543
1544 #[tokio::test(flavor = "multi_thread")]
1545 async fn terminal_agent_builder_keeps_ipc_tools_out_of_llm_tool_surface() {
1546 let dir = tempdir().expect("tempdir should exist");
1547 let terminal_tool = noop_terminal(dir.path()).await;
1548 let source = tempdir().unwrap();
1549 let cache = tempdir().unwrap();
1550 let binary = compile_baseline_fixture(source.path()).await;
1551 let distribution = fixture_distribution(&binary, "1.0.0").await;
1552 let (requests, captured) = async_channel::bounded(4);
1553 let mut agent = TerminalAgentBuilder::new(MockLlm { requests }, terminal_tool)
1554 .max_iterations(1)
1555 .tool(MockTool)
1556 .with_default_prompt()
1557 .initialize_tools(&distribution, cache.path())
1558 .await
1559 .unwrap()
1560 .build();
1561
1562 let mut tool_names = agent
1563 .tools
1564 .definitions()
1565 .into_iter()
1566 .map(|definition| definition.name().to_string())
1567 .collect::<Vec<_>>();
1568 tool_names.sort();
1569
1570 assert_eq!(tool_names, vec!["terminal".to_string()]);
1571 let events = agent.run("Inspect the repository", []);
1572 futures_lite::pin!(events);
1573 while futures_lite::StreamExt::next(&mut events).await.is_some() {}
1574 let request = captured
1575 .try_recv()
1576 .expect("first model request was recorded");
1577 assert_eq!(
1578 request
1579 .tool_definitions()
1580 .iter()
1581 .map(ToolDefinition::name)
1582 .collect::<Vec<_>>(),
1583 vec!["terminal"]
1584 );
1585 let catalog = request
1586 .messages()
1587 .iter()
1588 .find(|message| message.content().contains("<prepared_tools>"))
1589 .expect("first request contains prepared catalog")
1590 .content();
1591 for command in ["apply_patch", "rg -n", "ast-grep run", "jq"] {
1592 assert!(catalog.contains(command));
1593 }
1594 }
1595}