1#![doc = include_str!("../README.md")]
10
11ai6::guatiao::providers!(ContainerTheaters);
12
13mod settings;
14
15use std::process::Command;
16use std::sync::Arc;
17use std::time::{SystemTime, UNIX_EPOCH};
18
19use agentic_host_child::{Child, Pump, capture, start_failure};
20use ai6::guatiao::Bytes;
21use ai6::guatiao::library::ProviderError;
22use ai6::guatiao::{FromValue, Status, ToValue, Value};
23use ai6::{
24 Capabilities, ChosenSettings, MadeTheater, MadeTheaters, Output, TheaterProvider,
25 TheaterRequest,
26};
27
28pub use settings::Settings;
29
30pub const TEMPLATE_LABEL: &str = "ai6.theater";
32pub const MISSION_LABEL: &str = "ai6.mission";
34pub const CREATED_LABEL: &str = "ai6.created";
36
37pub trait Engine: Send + Sync {
40 fn run(&self, args: &[String]) -> Result<Output, ProviderError>;
42}
43
44struct Process {
45 executable: String,
46 timeout_ms: u64,
48 max_output: u64,
49}
50
51impl Engine for Process {
52 fn run(&self, args: &[String]) -> Result<Output, ProviderError> {
53 let mut command = Command::new(&self.executable);
54 command.args(args);
55 let process = Child::spawn(command, false, true, Pump::default())
56 .map_err(|error| start_failure(&self.executable, &error))?
57 .into_process();
58 let timeout =
59 (self.timeout_ms > 0).then(|| std::time::Duration::from_millis(self.timeout_ms));
60 let captured = capture(
61 &*process,
62 timeout,
63 usize::try_from(self.max_output).unwrap_or(usize::MAX),
64 )?;
65 Ok(Output {
66 code: captured.exit.as_ref().and_then(|exit| exit.code),
67 signal: captured.exit.as_ref().and_then(|exit| exit.signal),
68 stdout: Bytes(captured.stdout),
69 stderr: Bytes(captured.stderr),
70 timed_out: captured.exit.is_none(),
71 truncated: captured.truncated,
72 })
73 }
74}
75
76#[derive(ai6::guatiao::Provider)]
78#[provider(
79 TheaterProvider,
80 id = "ephemeral-container",
81 name = "ephemeral container",
82 config = Settings,
83 crate = ::ai6::guatiao
84)]
85pub struct ContainerTheaters {
86 engine: Arc<dyn Engine>,
87 settings: Settings,
88}
89
90impl TryFrom<Settings> for ContainerTheaters {
91 type Error = ProviderError;
92
93 fn try_from(settings: Settings) -> Result<Self, Self::Error> {
94 let settings = settings
95 .checked()
96 .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?;
97 Ok(Self {
98 engine: Arc::new(Process {
99 executable: settings.engine(),
100 timeout_ms: settings.engine_timeout_ms(),
101 max_output: settings.engine_output_bytes(),
102 }),
103 settings,
104 })
105 }
106}
107
108impl ContainerTheaters {
109 pub fn with_engine(engine: Arc<dyn Engine>, settings: Settings) -> Result<Self, ProviderError> {
111 let settings = settings
112 .checked()
113 .map_err(|why| refuse(Status::GUATIAO_ERR_BAD_VALUE, why))?;
114 Ok(Self { engine, settings })
115 }
116
117 fn engine(&self, args: Vec<String>) -> Result<Output, ProviderError> {
118 self.engine.run(&args)
119 }
120
121 fn labels(&self, container: &str) -> Result<Option<(String, String, u64)>, ProviderError> {
124 let format = format!(
125 "{{{{index .Config.Labels \"{TEMPLATE_LABEL}\"}}}}\t{{{{index .Config.Labels \"{MISSION_LABEL}\"}}}}\t{{{{index .Config.Labels \"{CREATED_LABEL}\"}}}}"
126 );
127 let output = self.engine(vec![
128 "inspect".to_owned(),
129 "--format".to_owned(),
130 format,
131 container.to_owned(),
132 ])?;
133 if output.code != Some(0) {
134 return Ok(None);
135 }
136 let text = String::from_utf8_lossy(&output.stdout.0);
137 let mut fields = text.trim().splitn(3, '\t');
138 Ok(Some((
139 fields.next().unwrap_or_default().to_owned(),
140 fields.next().unwrap_or_default().to_owned(),
141 fields
142 .next()
143 .and_then(|created| created.trim().parse().ok())
144 .unwrap_or_default(),
145 )))
146 }
147
148 fn made(
149 &self,
150 name: &str,
151 template: String,
152 mission: String,
153 created_at: u64,
154 ) -> Result<MadeTheater, ProviderError> {
155 let mut transport = std::collections::BTreeMap::new();
156 transport.insert("container".to_owned(), container_name(name));
157 transport.insert("engine".to_owned(), self.settings.engine());
158 if let Some(user) = &self.settings.user {
159 transport.insert("user".to_owned(), user.clone());
160 }
161 Ok(MadeTheater {
162 name: name.to_owned(),
163 template,
164 mission,
165 created_at,
166 transport: "container".to_owned(),
167 settings: transport
168 .into_iter()
169 .fold(ChosenSettings::new(), |settings, (key, value)| {
170 settings.with(&key, value)
171 }),
172 })
173 }
174}
175
176pub fn container_name(name: &str) -> String {
178 format!("ai6-{name}")
179}
180
181fn valid_name(name: &str) -> bool {
182 !name.is_empty()
183 && name.len() <= 128
184 && name.starts_with(|c: char| c.is_ascii_alphanumeric())
185 && name
186 .bytes()
187 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
188}
189
190impl TheaterProvider for ContainerTheaters {
191 fn capabilities(&self) -> Result<Value, ProviderError> {
192 Capabilities {
193 run: true,
194 files: true,
195 os: Some("linux".to_owned()),
196 ..Capabilities::default()
197 }
198 .to_value()
199 .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error.to_string()))
200 }
201
202 fn create(&self, request: &Value) -> Result<Value, ProviderError> {
203 let request = TheaterRequest::from_value(request)
204 .map_err(|error| refuse(Status::GUATIAO_ERR_BAD_VALUE, error.to_string()))?;
205 if !valid_name(&request.name) {
206 return Err(refuse(
207 Status::GUATIAO_ERR_BAD_VALUE,
208 format!("{:?} cannot name a container", request.name),
209 ));
210 }
211 let container = container_name(&request.name);
212 if let Some((template, mission, created_at)) = self.labels(&container)? {
213 let started = self.engine(vec!["start".to_owned(), container.clone()])?;
215 if started.code != Some(0) {
216 return Err(refuse(
217 Status::GUATIAO_ERR_INTERNAL,
218 format!(
219 "container {container:?} did not start: {}",
220 failure(&started)
221 ),
222 ));
223 }
224 return self
225 .made(&request.name, template, mission, created_at)?
226 .to_value()
227 .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error.to_string()));
228 }
229 let created_at = SystemTime::now()
230 .duration_since(UNIX_EPOCH)
231 .map_or(0, |elapsed| elapsed.as_secs());
232 let mut args = vec![
233 "run".to_owned(),
234 "--detach".to_owned(),
235 "--name".to_owned(),
236 container.clone(),
237 "--label".to_owned(),
238 format!("{TEMPLATE_LABEL}={}", request.template),
239 "--label".to_owned(),
240 format!("{MISSION_LABEL}={}", request.mission),
241 "--label".to_owned(),
242 format!("{CREATED_LABEL}={created_at}"),
243 ];
244 args.extend(self.settings.run_args.iter().cloned());
245 if let Some(workspace) = &request.trial_workspace {
246 if !std::path::Path::new(workspace).is_absolute()
247 || workspace.contains([',', '\n', '\r'])
248 {
249 return Err(refuse(
250 Status::GUATIAO_ERR_BAD_VALUE,
251 "invalid trial workspace",
252 ));
253 }
254 args.extend([
255 "--mount".to_owned(),
256 format!("type=bind,source={workspace},target=/ai6-trial"),
257 ]);
258 }
259 args.push(self.settings.image.clone());
260 args.extend(self.settings.command());
261 let output = self.engine(args)?;
262 if output.code != Some(0) {
263 return Err(refuse(
264 Status::GUATIAO_ERR_INTERNAL,
265 format!("container {container:?} was not made: {}", failure(&output)),
266 ));
267 }
268 self.made(&request.name, request.template, request.mission, created_at)?
269 .to_value()
270 .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error.to_string()))
271 }
272
273 fn destroy(&self, name: &str) -> Result<(), ProviderError> {
274 let container = container_name(name);
275 if self.labels(&container)?.is_none() {
276 return Ok(());
277 }
278 let output = self.engine(vec![
279 "rm".to_owned(),
280 "--force".to_owned(),
281 container.clone(),
282 ])?;
283 if output.code == Some(0) || self.labels(&container)?.is_none() {
284 Ok(())
285 } else {
286 Err(refuse(
287 Status::GUATIAO_ERR_INTERNAL,
288 format!(
289 "container {container:?} was not removed: {}",
290 failure(&output)
291 ),
292 ))
293 }
294 }
295
296 fn list(&self, template: &str) -> Result<Value, ProviderError> {
297 let output = self.engine(vec![
298 "ps".to_owned(),
299 "--all".to_owned(),
300 "--filter".to_owned(),
301 format!("label={TEMPLATE_LABEL}={template}"),
302 "--format".to_owned(),
303 "{{.Names}}".to_owned(),
304 ])?;
305 if output.code != Some(0) {
306 return Err(refuse(
307 Status::GUATIAO_ERR_INTERNAL,
308 format!("the containers could not be listed: {}", failure(&output)),
309 ));
310 }
311 let mut theaters = Vec::new();
312 for container in String::from_utf8_lossy(&output.stdout.0).lines() {
313 let container = container.trim();
314 let Some(name) = container.strip_prefix("ai6-") else {
315 continue;
316 };
317 if let Some((made_from, mission, created_at)) = self.labels(container)?
318 && made_from == template
319 {
320 theaters.push(self.made(name, made_from, mission, created_at)?);
321 }
322 }
323 theaters.sort_by_key(|made| made.created_at);
324 MadeTheaters { theaters }
325 .to_value()
326 .map_err(|error| refuse(Status::GUATIAO_ERR_INTERNAL, error.to_string()))
327 }
328}
329
330fn failure(output: &Output) -> String {
331 let stderr = String::from_utf8_lossy(&output.stderr.0);
332 let status = output.code.map_or_else(
333 || "no exit status".to_owned(),
334 |code| format!("exit {code}"),
335 );
336 match stderr.trim().lines().last() {
337 Some(line) => format!("{status}: {line}"),
338 None => status,
339 }
340}
341
342fn refuse(status: Status, message: impl std::fmt::Display) -> ProviderError {
343 ProviderError::new(status, &message.to_string())
344}
345
346#[cfg(test)]
347mod tests {
348 use std::collections::BTreeMap;
349 use std::sync::Mutex;
350
351 use ai6::guatiao::Bytes;
352
353 use super::*;
354
355 #[derive(Default)]
357 struct Fake {
358 containers: Mutex<BTreeMap<String, (String, String, String)>>,
359 commands: Mutex<Vec<Vec<String>>>,
360 }
361
362 fn answer(code: i64, stdout: &str) -> Output {
363 Output {
364 code: Some(code),
365 stdout: Bytes(stdout.as_bytes().to_vec()),
366 ..Output::default()
367 }
368 }
369
370 impl Engine for Fake {
371 fn run(&self, args: &[String]) -> Result<Output, ProviderError> {
372 self.commands.lock().unwrap().push(args.to_vec());
373 let mut containers = self.containers.lock().unwrap();
374 let label = |args: &[String], key: &str| {
375 args.iter()
376 .find_map(|arg| arg.strip_prefix(&format!("{key}=")))
377 .unwrap_or_default()
378 .to_owned()
379 };
380 Ok(match args[0].as_str() {
381 "inspect" => match containers.get(&args[3]) {
382 Some((template, mission, created)) => {
383 answer(0, &format!("{template}\t{mission}\t{created}\n"))
384 }
385 None => answer(1, ""),
386 },
387 "run" => {
388 containers.insert(
389 args[3].clone(),
390 (
391 label(args, TEMPLATE_LABEL),
392 label(args, MISSION_LABEL),
393 label(args, CREATED_LABEL),
394 ),
395 );
396 answer(0, "id\n")
397 }
398 "rm" => {
399 containers.remove(&args[2]);
400 answer(0, "")
401 }
402 "ps" => answer(
403 0,
404 &containers
405 .keys()
406 .map(|name| format!("{name}\n"))
407 .collect::<String>(),
408 ),
409 _ => answer(0, ""),
410 })
411 }
412 }
413
414 fn provider(engine: &Arc<Fake>) -> ContainerTheaters {
415 ContainerTheaters::with_engine(
416 engine.clone(),
417 ai6::provider_settings::settings_from_text(
418 ai6::bootstrap::format::Format::Toml,
419 r#"image = "fedora:44"
420engine = "podman"
421run_args = ["--network", "none"]
422"#,
423 )
424 .unwrap(),
425 )
426 .unwrap()
427 }
428
429 fn create(provider: &ContainerTheaters, name: &str, mission: &str) -> MadeTheater {
430 let request = TheaterRequest {
431 trial_workspace: None,
432 name: name.to_owned(),
433 template: "scratch".to_owned(),
434 mission: mission.to_owned(),
435 };
436 MadeTheater::from_value(&provider.create(&request.to_value().unwrap()).unwrap()).unwrap()
437 }
438
439 #[test]
440 fn a_theater_is_a_labelled_container_reached_by_the_container_transport() {
441 let engine = Arc::new(Fake::default());
442 let provider = provider(&engine);
443 let made = create(&provider, "scratch-m1", "m1");
444 assert_eq!(made.transport, "container");
445 assert_eq!(
446 serde_json::to_value(&made.settings).unwrap(),
447 serde_json::json!({"container": "ai6-scratch-m1", "engine": "podman"})
448 );
449 let run = engine.commands.lock().unwrap()[1].clone();
450 assert_eq!(
451 run[..4],
452 ["run", "--detach", "--name", "ai6-scratch-m1"].map(str::to_owned)
453 );
454 assert!(run.contains(&"ai6.mission=m1".to_owned()));
455 assert_eq!(
456 run[run.len() - 5..],
457 ["--network", "none", "fedora:44", "sleep", "infinity"].map(str::to_owned)
458 );
459
460 let again = create(&provider, "scratch-m1", "m1");
462 assert_eq!(again.created_at, made.created_at);
463 assert_eq!(engine.containers.lock().unwrap().len(), 1);
464
465 let listed = MadeTheaters::from_value(&provider.list("scratch").unwrap())
466 .unwrap()
467 .theaters;
468 assert_eq!(listed, [made]);
469 assert!(
470 MadeTheaters::from_value(&provider.list("other").unwrap())
471 .unwrap()
472 .theaters
473 .is_empty()
474 );
475
476 provider.destroy("scratch-m1").unwrap();
477 provider.destroy("scratch-m1").unwrap();
478 assert!(engine.containers.lock().unwrap().is_empty());
479 let bad = TheaterRequest {
480 trial_workspace: None,
481 name: "-rm".to_owned(),
482 template: "scratch".to_owned(),
483 mission: "m".to_owned(),
484 };
485 assert!(provider.create(&bad.to_value().unwrap()).is_err());
486 }
487}