1pub mod bedrock;
42pub mod profile;
43
44use std::time::Duration;
45
46use crate::control::artifact::{BaseImage, default_dockerfile};
47use crate::control::{CreateImageRequest, Image};
48use crate::error::{Error, ErrorKind};
49use crate::region::Region;
50use crate::sandbox::{RunRequest, Sandbox, TeardownOpts, TeardownReport};
51use crate::session::{ExecHandle, Session, mint_exec_id};
52use crate::sizing::SizeClass;
53
54pub use bedrock::{BearerToken, Minted};
55pub use profile::{Agent, AgentPermissionMode, CODEX_CONFIG_FILE, ENV_FILE, MARKER_FILE, Profile};
56
57pub const AGENT_UID: u32 = 1000;
59pub const AGENT_GID: u32 = 1000;
61pub const WORKDIR: &str = "/workspace";
65pub const DEFAULT_SIZE: SizeClass = SizeClass::Mib1024;
69pub const DEFAULT_PROMPT_TIMEOUT: Duration = Duration::from_secs(900);
71const CHOWN_TIMEOUT: Duration = Duration::from_secs(60);
73
74#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct AgentSpec {
77 pub agent: Agent,
78 pub model: Option<String>,
80 pub cli_version: Option<String>,
84}
85
86impl AgentSpec {
87 pub fn new(agent: Agent) -> Self {
89 Self {
90 agent,
91 model: None,
92 cli_version: None,
93 }
94 }
95
96 pub fn with_model(mut self, model: impl Into<String>) -> Self {
98 self.model = Some(model.into());
99 self
100 }
101
102 pub fn with_cli_version(mut self, version: impl Into<String>) -> Self {
104 self.cli_version = Some(version.into());
105 self
106 }
107
108 pub fn model(&self) -> &str {
110 self.model
111 .as_deref()
112 .unwrap_or(self.agent.profile().default_model)
113 }
114
115 fn npm_spec(&self) -> String {
117 match &self.cli_version {
118 Some(version) => format!("{}@{version}", self.agent.profile().npm_package),
119 None => self.agent.profile().npm_package.to_string(),
120 }
121 }
122}
123
124pub fn require_specs(specs: &[AgentSpec]) -> Result<(), Error> {
132 if specs.is_empty() {
133 return Err(Error::invalid_arg(
134 "no agent named. An agent VM installs at least one of: claude-code, codex.",
135 ));
136 }
137 for (index, spec) in specs.iter().enumerate() {
138 if specs[..index]
139 .iter()
140 .any(|earlier| earlier.agent == spec.agent)
141 {
142 return Err(Error::invalid_arg(format!(
143 "the agent {} is named twice; one row per agent, because a second row \
144 would be a second model for the same CLI.",
145 spec.agent
146 )));
147 }
148 }
149 Ok(())
150}
151
152fn ordered(specs: &[AgentSpec]) -> Vec<&AgentSpec> {
154 let mut sorted: Vec<&AgentSpec> = specs.iter().collect();
155 sorted.sort_by_key(|spec| spec.agent);
156 sorted
157}
158
159pub fn spec_for(specs: &[AgentSpec], agent: Agent) -> Result<&AgentSpec, Error> {
161 specs
162 .iter()
163 .find(|spec| spec.agent == agent)
164 .ok_or_else(|| {
165 Error::invalid_arg(format!(
166 "this VM carries {}, not {agent}.",
167 image_stem(specs).trim_start_matches("agent-vm-")
168 ))
169 })
170}
171
172pub fn image_name_for(
175 sandbox: &Sandbox,
176 specs: &[AgentSpec],
177 request: &CreateImageRequest,
178) -> String {
179 let hash = sandbox.artifact_content_hash_for(request);
180 format!("{}-{}", image_stem(specs), &hash[..12])
181}
182
183pub fn image_request_for(
185 sandbox: &Sandbox,
186 specs: &[AgentSpec],
187 binary: Vec<u8>,
188 build_role_arn: impl Into<String>,
189 size: SizeClass,
190) -> Result<CreateImageRequest, Error> {
191 require_specs(specs)?;
192 let base = BaseImage::al2023();
193 let dockerfile = dockerfile(specs, &base, sandbox.port())?;
194 let mut request =
195 CreateImageRequest::new(image_stem(specs), binary, String::new(), build_role_arn);
196 request.base_image = base;
197 request.dockerfile = Some(dockerfile);
198 request.size = size;
199 let name = image_name_for(sandbox, specs, &request);
200 request.name = name.clone();
201 request.token_scope = Some(name);
202 Ok(request)
203}
204
205pub fn launch_request_for(
207 specs: &[AgentSpec],
208 image_identifier: impl Into<String>,
209 execution_role_arn: Option<String>,
210) -> RunRequest {
211 let identifier = image_identifier.into();
212 let mut request = RunRequest::new().with_image(&identifier).with_egress();
213 request.execution_role_arn = execution_role_arn;
214 request.token_scope = Some(image_stem(specs));
215 request
216}
217
218pub fn agent_vm_egress_posture() -> crate::control::EgressPosture {
226 launch_request_for(&[], "arn:image", None).egress_posture()
227}
228
229pub fn image_stem(specs: &[AgentSpec]) -> String {
232 let agents: Vec<&str> = ordered(specs)
233 .into_iter()
234 .map(|spec| spec.agent.as_str())
235 .collect();
236 format!("agent-vm-{}", agents.join("-"))
237}
238
239pub fn dockerfile(specs: &[AgentSpec], base: &BaseImage, port: u16) -> Result<String, Error> {
247 require_specs(specs)?;
248 let stanza = default_dockerfile(port, Some(WORKDIR), base, None);
249 let mut lines: Vec<String> = stanza.lines().map(str::to_string).collect();
250
251 let chmod = lines
252 .iter()
253 .position(|line| line == "RUN chmod 0755 /agentd")
254 .ok_or_else(|| stanza_drift("RUN chmod 0755 /agentd"))?;
255 let mut layers = vec![
256 String::new(),
257 "# The coding agents. Node 22 runs both CLIs; the rest is what a coding agent".to_string(),
258 "# expects of a working shell. Unpinned unless a cli_version was given, so the".to_string(),
259 "# image carries the registry's latest at build time and a pin changes the reuse hash."
260 .to_string(),
261 format!(
262 "RUN dnf install -y --setopt=install_weak_deps=0 {} && dnf clean all",
263 profile::SYSTEM_PACKAGES
264 ),
265 ];
266 let packages: Vec<String> = ordered(specs)
267 .into_iter()
268 .map(AgentSpec::npm_spec)
269 .collect();
270 layers.push(format!(
271 "RUN npm install -g {} && npm cache clean --force",
272 packages.join(" ")
273 ));
274 layers.extend([
275 String::new(),
276 "# The non-root user the agents run as. Appended directly because `useradd` is not"
277 .to_string(),
278 "# in the minimal base. Not decoration: Claude Code refuses --dangerously-skip-permissions"
279 .to_string(),
280 "# as root and then denies its own tool calls while still reporting (measured: zero"
281 .to_string(),
282 "# shell calls as uid 0, 147 as uid 1000 on the same task).".to_string(),
283 format!(
284 "RUN echo \"agent:x:{AGENT_UID}:{AGENT_GID}::{WORKDIR}:/bin/bash\" >> /etc/passwd \\"
285 ),
286 format!(" && echo \"agent:x:{AGENT_GID}:\" >> /etc/group"),
287 ]);
288 lines.splice(chmod + 1..chmod + 1, layers);
289
290 let mkdir = lines
291 .iter()
292 .position(|line| line == &format!("RUN mkdir -p {WORKDIR}"))
293 .ok_or_else(|| stanza_drift("RUN mkdir -p /workspace"))?;
294 lines[mkdir] = format!("RUN mkdir -p {WORKDIR} && chown {AGENT_UID}:{AGENT_GID} {WORKDIR}");
297
298 let mut text = lines.join("\n");
299 text.push('\n');
300 Ok(text)
301}
302
303fn stanza_drift(line: &str) -> Error {
304 Error::new(
305 ErrorKind::Unexpected,
306 format!(
307 "default_dockerfile no longer emits `{line}`, so the agent layers have no splice \
308 point. Update agents::dockerfile beside the stanza change."
309 ),
310 )
311}
312
313#[derive(Clone, Debug)]
318pub struct BedrockAccess {
319 pub region: Region,
320 pub token: BearerToken,
321}
322
323#[derive(Clone, Debug, Eq, PartialEq)]
325pub struct GuestFile {
326 pub path: String,
327 pub contents: Vec<u8>,
328 pub mode: &'static str,
330}
331
332pub fn sh_double_quote(value: &str) -> String {
337 let mut quoted = String::with_capacity(value.len() + 2);
338 quoted.push('"');
339 for ch in value.chars() {
340 if matches!(ch, '"' | '\\' | '$' | '`') {
341 quoted.push('\\');
342 }
343 quoted.push(ch);
344 }
345 quoted.push('"');
346 quoted
347}
348
349pub fn sh_single_quote(value: &str) -> String {
353 let mut quoted = String::with_capacity(value.len() + 2);
354 quoted.push('\'');
355 for ch in value.chars() {
356 if ch == '\'' {
357 quoted.push_str("'\\''");
358 } else {
359 quoted.push(ch);
360 }
361 }
362 quoted.push('\'');
363 quoted
364}
365
366pub fn provisioning_files(
369 specs: &[AgentSpec],
370 access: &BedrockAccess,
371) -> Result<Vec<GuestFile>, Error> {
372 require_specs(specs)?;
373 let specs = ordered(specs);
374
375 let mut env = vec![
379 ("HOME", WORKDIR.to_string()),
380 ("PATH", "/usr/local/bin:/usr/bin:/bin".to_string()),
381 ("AWS_REGION", access.region.as_str().to_string()),
382 ];
383 for spec in &specs {
384 env.extend(profile::env_pairs(
385 spec.agent,
386 spec.model(),
387 access.token.expose(),
388 ));
389 }
390 let mut env_file = String::new();
391 for (key, value) in env {
392 env_file.push_str(&format!("export {key}={}\n", sh_double_quote(&value)));
393 }
394
395 let mut files = vec![GuestFile {
396 path: ENV_FILE.to_string(),
397 contents: env_file.into_bytes(),
398 mode: "0600",
399 }];
400 if let Some(codex) = specs.iter().find(|spec| spec.agent == Agent::Codex) {
401 files.push(GuestFile {
402 path: CODEX_CONFIG_FILE.to_string(),
403 contents: profile::codex_config(codex.model(), &access.region).into_bytes(),
404 mode: "0600",
405 });
406 }
407 let marker = serde_json::json!({
408 "version": 1,
409 "region": access.region.as_str(),
410 "agents": specs.iter().map(|spec| serde_json::json!({
411 "agent": spec.agent.as_str(),
412 "model": spec.model(),
413 "cliVersion": spec.cli_version,
414 })).collect::<Vec<_>>(),
415 });
416 files.push(GuestFile {
417 path: MARKER_FILE.to_string(),
418 contents: serde_json::to_vec_pretty(&marker).map_err(|error| {
419 Error::new(
420 ErrorKind::Unexpected,
421 format!("the marker will not serialize: {error}"),
422 )
423 })?,
424 mode: "0644",
427 });
428 Ok(files)
429}
430
431pub async fn install_access(
438 session: &Session,
439 specs: &[AgentSpec],
440 access: &BedrockAccess,
441) -> Result<(), Error> {
442 for file in provisioning_files(specs, access)? {
443 session
444 .upload_file(&file.path, &file.contents, Some(file.mode))
445 .await?;
446 }
447 let request = crate::protocol::exec::StartRequest {
448 exec_id: mint_exec_id(),
449 command: vec![format!("chown -R {AGENT_UID}:{AGENT_GID} {WORKDIR}")],
450 shell: true,
451 cwd: None,
452 env: std::collections::HashMap::new(),
453 user: None,
454 group: None,
455 timeout_sec: Some(CHOWN_TIMEOUT.as_secs_f64()),
456 stdin: false,
457 reap_group_on_exit: false,
458 };
459 let result = session.run_sync(request, CHOWN_TIMEOUT).await?;
460 if !result.succeeded() {
461 return Err(Error::new(
462 ErrorKind::ExecFailed,
463 format!(
464 "handing {WORKDIR} to uid {AGENT_UID} failed (exit {:?}): {}",
465 result.exit_code(),
466 result.stderr().trim()
467 ),
468 ));
469 }
470 Ok(())
471}
472
473pub async fn installed_agents(session: &Session) -> Result<Vec<AgentSpec>, Error> {
479 let bytes = match session.download_file(MARKER_FILE).await {
480 Ok(bytes) => bytes,
481 Err(error) if error.wire_kind() == Some(crate::error::WireKind::NotFound) => {
482 return Err(Error::new(
483 ErrorKind::Precondition,
484 format!(
485 "{MARKER_FILE} is not in this VM, so it was not provisioned as an agent \
486 VM. `microvm agent-up --vm-name <NAME>` installs an agent and writes \
487 the marker; `--agent` names one explicitly when the marker is absent."
488 ),
489 ));
490 }
491 Err(error) => return Err(error),
492 };
493 let marker: serde_json::Value = serde_json::from_slice(&bytes).map_err(|error| {
494 Error::new(
495 ErrorKind::Protocol,
496 format!("{MARKER_FILE} is not the JSON agent-up wrote: {error}"),
497 )
498 })?;
499 let rows = marker["agents"].as_array().ok_or_else(|| {
500 Error::new(
501 ErrorKind::Protocol,
502 format!("{MARKER_FILE} carries no `agents` array"),
503 )
504 })?;
505 let mut specs = Vec::with_capacity(rows.len());
506 for row in rows {
507 let name = row["agent"].as_str().unwrap_or_default();
508 let agent = Agent::parse(name).ok_or_else(|| {
509 Error::new(
510 ErrorKind::Protocol,
511 format!("{MARKER_FILE} names an agent this client has no profile for: {name:?}"),
512 )
513 })?;
514 let mut spec = AgentSpec::new(agent);
515 if let Some(model) = row["model"].as_str() {
516 spec.model = Some(model.to_string());
517 }
518 if let Some(version) = row["cliVersion"].as_str() {
519 spec.cli_version = Some(version.to_string());
520 }
521 specs.push(spec);
522 }
523 require_specs(&specs)?;
524 Ok(specs)
525}
526
527pub async fn installed_version(session: &Session, agent: Agent) -> Result<String, Error> {
530 let request = crate::protocol::exec::StartRequest {
531 exec_id: mint_exec_id(),
532 command: profile::version_command(agent),
533 shell: false,
534 cwd: Some(WORKDIR.to_string()),
535 env: std::collections::HashMap::from([(
536 "PATH".into(),
537 "/usr/local/bin:/usr/bin:/bin".into(),
538 )]),
539 user: Some(AGENT_UID),
540 group: Some(AGENT_GID),
541 timeout_sec: Some(10.0),
542 stdin: false,
543 reap_group_on_exit: true,
544 };
545 let result = session.run_sync(request, Duration::from_secs(25)).await?;
546 if result.succeeded()
547 && let Some(version) = reported_version(result.stdout())
548 {
549 return Ok(version.to_string());
550 }
551 Err(Error::new(
552 ErrorKind::Precondition,
553 format!(
554 "could not read {agent}'s installed version; verify the pinned agent executable in the image",
555 ),
556 ))
557}
558
559fn reported_version(output: &str) -> Option<&str> {
560 output.split_ascii_whitespace().find(|word| {
561 word.len() <= 32
562 && word.split('.').count() == 3
563 && word
564 .split('.')
565 .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit()))
566 })
567}
568
569#[derive(Clone, Debug, Default)]
571pub struct PromptOptions {
572 pub exec_id: Option<String>,
574 pub timeout: Option<Duration>,
577 pub permission_mode: AgentPermissionMode,
579 pub reap_group_on_exit: bool,
581}
582
583pub fn prompt_request(
585 spec: &AgentSpec,
586 task: &str,
587 options: &PromptOptions,
588) -> Result<crate::protocol::exec::StartRequest, Error> {
589 if task.trim().is_empty() {
590 return Err(Error::invalid_arg(
591 "the task is empty. An agent prompted with nothing answers with nothing, at the \
592 price of a model call.",
593 ));
594 }
595 if options.timeout.is_some_and(|timeout| timeout.is_zero()) {
596 return Err(Error::invalid_arg("execution timeout must be positive"));
597 }
598 let command = format!(
599 ". {ENV_FILE} && {}",
600 profile::headless_command(spec.agent, &sh_single_quote(task), options.permission_mode)
601 );
602 Ok(crate::protocol::exec::StartRequest {
603 exec_id: options.exec_id.clone().unwrap_or_else(mint_exec_id),
604 command: vec![command],
605 shell: true,
606 cwd: Some(WORKDIR.to_string()),
607 env: std::collections::HashMap::new(),
610 user: Some(AGENT_UID),
611 group: Some(AGENT_GID),
612 timeout_sec: options.timeout.map(|timeout| timeout.as_secs_f64()),
613 stdin: false,
614 reap_group_on_exit: options.reap_group_on_exit,
615 })
616}
617
618pub fn headless_command_template(agent: Agent) -> String {
621 format!(
622 ". {ENV_FILE} && {}",
623 profile::headless_command(agent, "'<TASK>'", AgentPermissionMode::AgentDefault)
624 )
625}
626
627pub async fn prompt(
630 session: &Session,
631 spec: &AgentSpec,
632 task: &str,
633 options: &PromptOptions,
634) -> Result<ExecHandle, Error> {
635 session.run(prompt_request(spec, task, options)?).await
636}
637
638pub struct AgentVm {
643 sandbox: Sandbox,
644 specs: Vec<AgentSpec>,
645}
646
647impl std::fmt::Debug for AgentVm {
648 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
649 f.debug_struct("AgentVm")
650 .field("agents", &self.specs)
651 .field("sandbox", &self.sandbox)
652 .finish()
653 }
654}
655
656impl AgentVm {
657 pub fn new(sandbox: Sandbox, specs: Vec<AgentSpec>) -> Result<Self, Error> {
659 require_specs(&specs)?;
660 Ok(Self { sandbox, specs })
661 }
662
663 pub async fn adopt(
669 control: crate::control::ControlPlane,
670 specs: Vec<AgentSpec>,
671 microvm_id: impl Into<String>,
672 endpoint: impl Into<String>,
673 agent_token: impl Into<String>,
674 ) -> Result<Self, Error> {
675 require_specs(&specs)?;
676 let sandbox = Sandbox::adopt(control, microvm_id, endpoint, agent_token).await?;
677 Ok(Self { sandbox, specs })
678 }
679
680 pub async fn from_name(
682 store: &dyn crate::names::NameStore,
683 specs: Vec<AgentSpec>,
684 name: &str,
685 region: Option<Region>,
686 port: Option<u16>,
687 ) -> Result<Self, Error> {
688 require_specs(&specs)?;
689 let sandbox = Sandbox::from_name(store, name, region, port).await?;
690 Ok(Self { sandbox, specs })
691 }
692
693 pub async fn adopt_in(
695 region: Region,
696 specs: Vec<AgentSpec>,
697 microvm_id: impl Into<String>,
698 endpoint: impl Into<String>,
699 agent_token: impl Into<String>,
700 port: Option<u16>,
701 ) -> Result<Self, Error> {
702 require_specs(&specs)?;
703 let sandbox = Sandbox::adopt_in(region, microvm_id, endpoint, agent_token, port).await?;
704 Ok(Self { sandbox, specs })
705 }
706
707 pub fn into_parts(self) -> (Sandbox, Vec<AgentSpec>) {
709 (self.sandbox, self.specs)
710 }
711
712 pub fn claude_code(sandbox: Sandbox) -> Self {
714 Self {
715 sandbox,
716 specs: vec![AgentSpec::new(Agent::ClaudeCode)],
717 }
718 }
719
720 pub fn codex(sandbox: Sandbox) -> Self {
722 Self {
723 sandbox,
724 specs: vec![AgentSpec::new(Agent::Codex)],
725 }
726 }
727
728 pub fn specs(&self) -> Vec<AgentSpec> {
730 ordered(&self.specs).into_iter().cloned().collect()
731 }
732
733 pub fn sandbox(&self) -> &Sandbox {
734 &self.sandbox
735 }
736
737 pub fn sandbox_mut(&mut self) -> &mut Sandbox {
738 &mut self.sandbox
739 }
740
741 pub fn session(&self) -> Option<&Session> {
743 self.sandbox.session()
744 }
745
746 pub fn image_name(&self, request: &CreateImageRequest) -> String {
750 image_name_for(&self.sandbox, &self.specs, request)
751 }
752
753 pub fn image_request(
760 &self,
761 binary: Vec<u8>,
762 build_role_arn: impl Into<String>,
763 size: SizeClass,
764 ) -> Result<CreateImageRequest, Error> {
765 image_request_for(&self.sandbox, &self.specs, binary, build_role_arn, size)
766 }
767
768 pub async fn build(&mut self, request: CreateImageRequest) -> Result<&Image, Error> {
770 self.sandbox.build_image(request).await
771 }
772
773 pub fn launch_request(
776 &self,
777 image_identifier: impl Into<String>,
778 execution_role_arn: Option<String>,
779 ) -> RunRequest {
780 launch_request_for(&self.specs, image_identifier, execution_role_arn)
781 }
782
783 pub async fn launch(&mut self, request: RunRequest) -> Result<&Session, Error> {
785 let session = self.sandbox.run(request).await?;
786 session
787 .wait_until_ready(crate::session::DEFAULT_READY_TIMEOUT)
788 .await?;
789 Ok(session)
790 }
791
792 fn require_session(&self) -> Result<&Session, Error> {
793 self.sandbox.session().ok_or_else(|| {
794 Error::new(
795 ErrorKind::Precondition,
796 "this agent VM has not been launched; call `launch` first.",
797 )
798 })
799 }
800
801 pub async fn install_access(&self, access: &BedrockAccess) -> Result<(), Error> {
803 install_access(self.require_session()?, &self.specs, access).await
804 }
805
806 pub async fn prompt(
808 &self,
809 agent: Agent,
810 task: &str,
811 options: &PromptOptions,
812 ) -> Result<ExecHandle, Error> {
813 let spec = spec_for(&self.specs, agent)?;
814 prompt(self.require_session()?, spec, task, options).await
815 }
816
817 pub async fn terminate(&mut self, opts: TeardownOpts) -> TeardownReport {
819 self.sandbox.terminate(opts).await
820 }
821}
822
823#[cfg(test)]
824mod tests {
825 use std::sync::Arc;
826
827 use super::*;
828 use crate::control::artifact::{
829 require_daemon_cmd, require_matching_agentd_port, require_matching_from, require_workdir,
830 };
831 use crate::session::testing::{Recorder, Reply, session_with};
832
833 fn both() -> Vec<AgentSpec> {
834 vec![
835 AgentSpec::new(Agent::Codex),
836 AgentSpec::new(Agent::ClaudeCode),
837 ]
838 }
839
840 fn access() -> BedrockAccess {
841 BedrockAccess {
842 region: Region::UsEast1,
843 token: bedrock::mint_with(
844 &aws_credential_types::Credentials::new("AKID", "secret", None, None, "t"),
845 &Region::UsEast1,
846 Duration::from_secs(60),
847 std::time::SystemTime::UNIX_EPOCH,
848 )
849 .expect("mints")
850 .token,
851 }
852 }
853
854 #[test]
863 fn the_dockerfile_passes_the_guards_and_carries_the_recipe() {
864 let base = BaseImage::al2023();
865 let text = dockerfile(&both(), &base, 9000).expect("derives");
866
867 require_matching_from(&base, &text).expect("FROM pairs with the base");
868 require_workdir(&base, Some(&text)).expect("a WORKDIR is declared");
869 require_daemon_cmd(&text).expect("ENTRYPOINT [] + CMD agentd survive");
870 require_matching_agentd_port(9000, &text).expect("the port agrees");
871
872 assert_eq!(
873 text.matches("RUN dnf install").count(),
874 1,
875 "the system layer is emitted once for two profiles:\n{text}"
876 );
877 assert!(
878 text.contains("RUN dnf install -y --setopt=install_weak_deps=0 nodejs22 nodejs22-npm "),
879 "with weak deps off, bare `npm` is Node 18's and the npm layer exits 127:\n{text}"
880 );
881 assert!(
882 text.contains("RUN npm install -g @anthropic-ai/claude-code @openai/codex && npm"),
883 "both CLIs in profile order, in one layer:\n{text}"
884 );
885 assert!(
886 text.contains("agent:x:1000:1000::/workspace:/bin/bash"),
887 "{text}"
888 );
889 assert!(
890 text.contains("RUN mkdir -p /workspace && chown 1000:1000 /workspace"),
891 "{text}"
892 );
893 let layers_at = text.find("RUN npm install").expect("layers");
894 let workdir_at = text.find("WORKDIR /workspace").expect("workdir");
895 let cmd_at = text.find("CMD [\"/agentd\"]").expect("cmd");
896 assert!(layers_at < workdir_at && workdir_at < cmd_at, "{text}");
897 }
898
899 #[test]
902 fn a_cli_version_pin_reaches_the_install_line() {
903 let base = BaseImage::al2023();
904 let pinned = vec![AgentSpec::new(Agent::ClaudeCode).with_cli_version("2.1.0")];
905 let text = dockerfile(&pinned, &base, 9000).expect("derives");
906 assert!(text.contains("@anthropic-ai/claude-code@2.1.0"), "{text}");
907 let plain = dockerfile(&[AgentSpec::new(Agent::ClaudeCode)], &base, 9000).expect("d");
908 assert_ne!(text, plain);
909 }
910
911 #[test]
912 fn an_empty_or_repeated_spec_set_is_refused_before_any_text_is_built() {
913 let base = BaseImage::al2023();
914 assert_eq!(
915 dockerfile(&[], &base, 9000).expect_err("empty").kind(),
916 ErrorKind::InvalidArg
917 );
918 let twice = vec![AgentSpec::new(Agent::Codex), AgentSpec::new(Agent::Codex)];
919 let error = dockerfile(&twice, &base, 9000).expect_err("repeated");
920 assert!(
921 error.to_string().contains("codex is named twice"),
922 "{error}"
923 );
924 }
925
926 #[test]
928 fn the_image_stem_is_stable_under_spec_order() {
929 assert_eq!(image_stem(&both()), "agent-vm-claude-code-codex");
930 assert_eq!(
931 image_stem(&[AgentSpec::new(Agent::Codex)]),
932 "agent-vm-codex"
933 );
934 }
935
936 #[test]
942 fn a_codex_only_vm_still_gets_the_variable_codex_reads() {
943 let files = provisioning_files(&[AgentSpec::new(Agent::Codex)], &access()).expect("files");
944 let env = String::from_utf8(files[0].contents.clone()).expect("utf-8");
945 assert!(
946 env.contains("export AWS_BEARER_TOKEN_BEDROCK="),
947 "no Claude Code profile is present to export it, and Codex 401s without it:\n{env}"
948 );
949 }
950
951 #[test]
952 fn the_file_set_follows_the_profiles_and_the_env_file_is_quoted() {
953 let access = access();
954 let claude_only =
955 provisioning_files(&[AgentSpec::new(Agent::ClaudeCode)], &access).expect("files");
956 assert_eq!(
957 claude_only
958 .iter()
959 .map(|f| f.path.as_str())
960 .collect::<Vec<_>>(),
961 vec![ENV_FILE, MARKER_FILE]
962 );
963
964 let files = provisioning_files(&both(), &access).expect("files");
965 assert_eq!(
966 files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
967 vec![ENV_FILE, CODEX_CONFIG_FILE, MARKER_FILE]
968 );
969 let env = String::from_utf8(files[0].contents.clone()).expect("utf-8");
970 assert_eq!(files[0].mode, "0600");
971 assert!(
972 env.contains("export PATH=\"/usr/local/bin:/usr/bin:/bin\"\n"),
973 "{env}"
974 );
975 assert!(env.contains("export HOME=\"/workspace\"\n"), "{env}");
976 assert!(env.contains("export AWS_REGION=\"us-east-1\"\n"), "{env}");
977 assert!(
978 env.contains("export CLAUDE_CODE_USE_BEDROCK=\"1\"\n"),
979 "{env}"
980 );
981 assert!(
982 env.contains("export ANTHROPIC_MODEL=\"global.anthropic.claude-opus-5\"\n"),
983 "{env}"
984 );
985 let token = access.token.expose();
986 assert!(env.contains(&format!("export AWS_BEARER_TOKEN_BEDROCK=\"{token}\"\n")));
987 assert!(env.contains(&format!("export OPENAI_API_KEY=\"{token}\"\n")));
988
989 let config = String::from_utf8(files[1].contents.clone()).expect("utf-8");
990 assert!(
991 config.contains("bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
992 "{config}"
993 );
994 assert!(
995 config.contains("model = \"global.openai.gpt-5.6-sol\""),
996 "{config}"
997 );
998
999 let marker: serde_json::Value = serde_json::from_slice(&files[2].contents).expect("json");
1000 assert_eq!(files[2].mode, "0644");
1001 assert_eq!(marker["agents"][0]["agent"], "claude-code");
1002 assert_eq!(marker["agents"][1]["agent"], "codex");
1003 assert_eq!(marker["agents"][1]["model"], "global.openai.gpt-5.6-sol");
1004 assert!(
1005 !files[2]
1006 .contents
1007 .windows(token.len())
1008 .any(|w| w == token.as_bytes()),
1009 "the marker is world-readable and must never carry the token"
1010 );
1011 }
1012
1013 #[test]
1014 fn shell_quoting_escapes_what_each_quote_style_cannot_hold() {
1015 assert_eq!(sh_double_quote("a$b\"c`d\\e"), "\"a\\$b\\\"c\\`d\\\\e\"");
1016 assert_eq!(sh_single_quote("it's"), "'it'\\''s'");
1017 assert_eq!(sh_single_quote("plain"), "'plain'");
1018 }
1019
1020 #[tokio::test(start_paused = true)]
1026 async fn install_access_uploads_then_chowns_as_root() {
1027 let recorder = Recorder::with([
1028 Reply::Body(200, Vec::new()),
1029 Reply::Body(200, Vec::new()),
1030 Reply::Body(200, Vec::new()),
1031 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"running"})),
1032 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"exited"})),
1033 Reply::ok(serde_json::json!({
1034 "exec_id":"c1","phase":"exited","exit_code":0,"signal":null,
1035 "stdout":"","stderr":"","truncated":false,"writers_may_be_alive":false
1036 })),
1037 ]);
1038 let (session, _, _) = session_with(Arc::clone(&recorder));
1039
1040 install_access(&session, &both(), &access())
1041 .await
1042 .expect("installs");
1043
1044 let seen = recorder.requests();
1045 assert_eq!(seen.len(), 6, "{seen:#?}");
1046 for (request, (encoded, mode)) in seen.iter().zip([
1047 ("%2Fworkspace%2F.agent-env", "0600"),
1048 ("%2Fworkspace%2F.codex%2Fconfig.toml", "0600"),
1049 ("%2Fworkspace%2F.agent-vm.json", "0644"),
1050 ]) {
1051 assert_eq!(request.method, "PUT");
1052 assert_eq!(
1053 request.path,
1054 format!("/v1/fs/file?path={encoded}&mode={mode}"),
1055 "each file goes to the file route with its own mode"
1056 );
1057 }
1058 assert_eq!(seen[3].path, "/v1/exec/start");
1059 let start: serde_json::Value = serde_json::from_slice(&seen[3].body).expect("json");
1060 assert_eq!(start["command"][0], "chown -R 1000:1000 /workspace");
1061 assert_eq!(start["shell"], true);
1062 assert!(
1063 start["user"].is_null(),
1064 "the chown runs as the daemon's own user"
1065 );
1066 assert_eq!(seen[5].path, "/v1/exec/c1/ack");
1067 }
1068
1069 #[tokio::test(start_paused = true)]
1072 async fn a_failed_chown_fails_the_install() {
1073 let recorder = Recorder::with([
1074 Reply::Body(200, Vec::new()),
1075 Reply::Body(200, Vec::new()),
1076 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"running"})),
1077 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"exited"})),
1078 Reply::ok(serde_json::json!({
1079 "exec_id":"c1","phase":"exited","exit_code":1,"signal":null,
1080 "stdout":"","stderr":"chown: cannot access","truncated":false,
1081 "writers_may_be_alive":false
1082 })),
1083 ]);
1084 let (session, _, _) = session_with(recorder);
1085 let error = install_access(&session, &[AgentSpec::new(Agent::ClaudeCode)], &access())
1086 .await
1087 .expect_err("fails");
1088 assert_eq!(error.kind(), ErrorKind::ExecFailed);
1089 assert!(
1090 error.to_string().contains("chown: cannot access"),
1091 "{error}"
1092 );
1093 }
1094
1095 #[tokio::test]
1098 async fn installed_agents_reads_the_marker_back() {
1099 let specs = vec![
1100 AgentSpec::new(Agent::ClaudeCode).with_model("global.anthropic.claude-sonnet-5"),
1101 AgentSpec::new(Agent::Codex).with_cli_version("0.50.0"),
1102 ];
1103 let files = provisioning_files(&specs, &access()).expect("files");
1104 let marker = files.last().expect("marker").contents.clone();
1105 let recorder = Recorder::with([Reply::Body(200, marker)]);
1106 let (session, _, _) = session_with(recorder);
1107
1108 let read = installed_agents(&session).await.expect("reads");
1109 assert_eq!(read.len(), 2);
1110 assert_eq!(read[0].agent, Agent::ClaudeCode);
1111 assert_eq!(read[0].model(), "global.anthropic.claude-sonnet-5");
1112 assert_eq!(read[1].agent, Agent::Codex);
1113 assert_eq!(read[1].cli_version.as_deref(), Some("0.50.0"));
1114 assert_eq!(read[1].model(), "global.openai.gpt-5.6-sol");
1115 }
1116
1117 #[tokio::test]
1120 async fn a_missing_marker_names_agent_up_and_other_failures_propagate() {
1121 let recorder = Recorder::with([
1122 Reply::Body(404, b"not found".to_vec()),
1123 Reply::Body(503, b"not bootstrapped".to_vec()),
1124 ]);
1125 let (session, _, _) = session_with(recorder);
1126 let error = installed_agents(&session).await.expect_err("absent");
1127 assert_eq!(error.kind(), ErrorKind::Precondition);
1128 assert!(error.to_string().contains("agent-up"), "{error}");
1129 let other = installed_agents(&session).await.expect_err("503");
1130 assert_ne!(other.kind(), ErrorKind::Precondition);
1131 }
1132
1133 #[test]
1139 fn the_prompt_request_runs_the_agent_demoted_in_the_workspace() {
1140 let spec = AgentSpec::new(Agent::ClaudeCode);
1141 let request = prompt_request(
1142 &spec,
1143 "count the files; it's quick",
1144 &PromptOptions {
1145 exec_id: Some("p1".into()),
1146 timeout: Some(Duration::from_secs(120)),
1147 ..PromptOptions::default()
1148 },
1149 )
1150 .expect("builds");
1151 assert_eq!(request.exec_id, "p1");
1152 assert_eq!(request.user, Some(1000));
1153 assert_eq!(request.group, Some(1000));
1154 assert_eq!(request.cwd.as_deref(), Some("/workspace"));
1155 assert!(request.shell);
1156 assert!(
1157 request.env.is_empty(),
1158 "the token never rides in the request"
1159 );
1160 assert_eq!(request.timeout_sec, Some(120.0));
1161 assert!(!request.stdin);
1162 assert_eq!(
1163 request.command,
1164 vec![
1165 ". /workspace/.agent-env && claude -p 'count the files; it'\\''s quick' \
1166 --allowedTools Bash,Read,Edit,Write,Grep,Glob"
1167 .to_string()
1168 ]
1169 );
1170
1171 let codex = prompt_request(
1172 &AgentSpec::new(Agent::Codex),
1173 "hi",
1174 &PromptOptions::default(),
1175 )
1176 .expect("builds");
1177 assert!(
1178 codex.command[0].contains("codex exec --skip-git-repo-check -s workspace-write 'hi'")
1179 );
1180 assert!(codex.timeout_sec.is_none());
1181 assert!(!codex.exec_id.is_empty(), "an id was minted");
1182 }
1183
1184 #[test]
1185 fn an_empty_task_is_refused_locally() {
1186 let error = prompt_request(
1187 &AgentSpec::new(Agent::Codex),
1188 " \n",
1189 &PromptOptions::default(),
1190 )
1191 .expect_err("empty");
1192 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1193 }
1194
1195 fn sandbox() -> Sandbox {
1198 Sandbox::with_control_plane(crate::control::ControlPlane::with_transport(
1199 Arc::new(crate::control::fake::FakeControlPlane::new()),
1200 Region::UsEast1,
1201 Arc::new(crate::control::fake::TestClock::new()),
1202 ))
1203 }
1204
1205 #[tokio::test]
1208 async fn an_agent_vm_adopts_with_checked_specs_and_the_service_lifecycle() {
1209 use crate::control::fake::{Answer, FakeControlPlane, TestClock, microvm_response};
1210 let plane = |recorder: &Arc<FakeControlPlane>| {
1211 crate::control::ControlPlane::with_transport(
1212 Arc::clone(recorder) as Arc<dyn crate::control::transport::Transport>,
1213 Region::UsEast1,
1214 Arc::new(TestClock::new()),
1215 )
1216 };
1217 let endpoint = "https://mvm-abc123.microvm.us-east-1.amazonaws.com";
1218
1219 let recorder = Arc::new(FakeControlPlane::new());
1220 let error = AgentVm::adopt(plane(&recorder), vec![], "mvm-abc123", endpoint, "t")
1221 .await
1222 .expect_err("an empty spec set");
1223 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1224 assert_eq!(recorder.calls().len(), 0);
1225
1226 let recorder = Arc::new(FakeControlPlane::new());
1227 recorder.answer(
1228 "GetMicrovm",
1229 Answer::ok(microvm_response("SUSPENDED", None)),
1230 );
1231 let vm = AgentVm::adopt(plane(&recorder), both(), "mvm-abc123", endpoint, "t")
1232 .await
1233 .expect("adopts");
1234 assert!(vm.sandbox().adopted());
1235 assert_eq!(
1236 vm.sandbox().lifecycle(),
1237 crate::sandbox::Lifecycle::Suspended
1238 );
1239 assert_eq!(vm.specs().len(), 2);
1240 }
1241
1242 #[test]
1245 fn the_image_request_is_content_named_and_egress_is_on_at_launch() {
1246 let vm = AgentVm::new(sandbox(), both()).expect("specs");
1247 let a = vm
1248 .image_request(
1249 b"daemon".to_vec(),
1250 "arn:aws:iam::123456789012:role/b",
1251 DEFAULT_SIZE,
1252 )
1253 .expect("request");
1254 let b = vm
1255 .image_request(
1256 b"daemon".to_vec(),
1257 "arn:aws:iam::123456789012:role/b",
1258 DEFAULT_SIZE,
1259 )
1260 .expect("request");
1261 let c = vm
1262 .image_request(
1263 b"other".to_vec(),
1264 "arn:aws:iam::123456789012:role/b",
1265 DEFAULT_SIZE,
1266 )
1267 .expect("request");
1268 assert_eq!(a.name, b.name);
1269 assert_ne!(a.name, c.name);
1270 assert!(
1271 a.name.starts_with("agent-vm-claude-code-codex-"),
1272 "{}",
1273 a.name
1274 );
1275 assert_eq!(a.name.len(), "agent-vm-claude-code-codex-".len() + 12);
1276 assert_eq!(a.token_scope.as_deref(), Some(a.name.as_str()));
1277 assert!(a.code_artifact_uri.is_empty(), "the upload is the caller's");
1278 assert!(
1279 a.dockerfile
1280 .as_deref()
1281 .is_some_and(|d| d.contains("@openai/codex"))
1282 );
1283 assert_eq!(a.size, SizeClass::Mib1024);
1284
1285 let launch = vm.launch_request("arn:image", Some("arn:role".into()));
1286 assert!(
1287 launch.egress,
1288 "neither agent reaches Bedrock without egress"
1289 );
1290 assert_eq!(launch.image_identifier.as_deref(), Some("arn:image"));
1291 assert_eq!(
1292 launch.token_scope.as_deref(),
1293 Some("agent-vm-claude-code-codex")
1294 );
1295 }
1296
1297 #[tokio::test]
1300 async fn the_named_constructors_carry_one_agent_each() {
1301 let claude = AgentVm::claude_code(sandbox());
1302 assert_eq!(claude.specs(), vec![AgentSpec::new(Agent::ClaudeCode)]);
1303 let codex = AgentVm::codex(sandbox());
1304 assert_eq!(codex.specs(), vec![AgentSpec::new(Agent::Codex)]);
1305
1306 let error = codex
1307 .prompt(Agent::ClaudeCode, "hi", &PromptOptions::default())
1308 .await
1309 .expect_err("wrong agent");
1310 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1311 assert!(error.to_string().contains("carries codex"), "{error}");
1312 let unlaunched = codex
1313 .prompt(Agent::Codex, "hi", &PromptOptions::default())
1314 .await
1315 .expect_err("no session");
1316 assert_eq!(unlaunched.kind(), ErrorKind::Precondition);
1317 }
1318
1319 #[test]
1320 fn unrestricted_permissions_deadline_and_reaping_are_explicit_and_demoted() {
1321 for (agent, expected, forbidden) in [
1322 (
1323 Agent::ClaudeCode,
1324 "--dangerously-skip-permissions",
1325 "--allowedTools",
1326 ),
1327 (
1328 Agent::Codex,
1329 "--dangerously-bypass-approvals-and-sandbox",
1330 "workspace-write",
1331 ),
1332 ] {
1333 let task = "a quote ' and $(touch /tmp/must-not-run); \"hello\"";
1334 let request = prompt_request(
1335 &AgentSpec::new(agent),
1336 task,
1337 &PromptOptions {
1338 exec_id: Some("same-task".into()),
1339 timeout: Some(Duration::from_secs(1200)),
1340 permission_mode: AgentPermissionMode::Unrestricted,
1341 reap_group_on_exit: true,
1342 },
1343 )
1344 .expect("valid");
1345 assert!(request.command[0].contains(expected));
1346 assert!(!request.command[0].contains(forbidden));
1347 assert!(request.command[0].contains(&sh_single_quote(task)));
1348 assert_eq!((request.user, request.group), (Some(1000), Some(1000)));
1349 assert_eq!(request.timeout_sec, Some(1200.0));
1350 assert!(request.reap_group_on_exit);
1351 assert_eq!(request.exec_id, "same-task");
1352 let default =
1353 prompt_request(&AgentSpec::new(agent), task, &PromptOptions::default()).unwrap();
1354 assert!(default.command[0].contains(forbidden));
1355 assert!(!default.command[0].contains(expected));
1356 assert!(!default.reap_group_on_exit);
1357 assert_eq!(default.timeout_sec, None);
1358 }
1359 assert!("auto".parse::<AgentPermissionMode>().is_err());
1360 assert!(
1361 prompt_request(
1362 &AgentSpec::new(Agent::Codex),
1363 "task",
1364 &PromptOptions {
1365 timeout: Some(Duration::ZERO),
1366 ..PromptOptions::default()
1367 }
1368 )
1369 .is_err()
1370 );
1371 }
1372
1373 #[test]
1374 fn version_reporting_only_accepts_numeric_version_words() {
1375 assert_eq!(reported_version("2.1.7 (Claude Code)\n"), Some("2.1.7"));
1376 assert_eq!(reported_version("codex-cli 0.154.0\n"), Some("0.154.0"));
1377 assert_eq!(reported_version("SECRET=credential\n"), None);
1378 assert_eq!(reported_version("1.2.3-secret"), None);
1379 }
1380
1381 #[cfg(unix)]
1383 #[test]
1384 fn unrestricted_task_text_is_one_literal_shell_argument() {
1385 let task = "task ' with $(printf INJECTED) and `printf ALSO` ; $HOME";
1386 for agent in Agent::ALL {
1387 let command = profile::headless_command(
1388 agent,
1389 &sh_single_quote(task),
1390 AgentPermissionMode::Unrestricted,
1391 );
1392 let script = format!(
1393 "claude() {{ printf '%s\\n' \"$@\"; }}; codex() {{ printf '%s\\n' \"$@\"; }}; {command}"
1394 );
1395 let output = std::process::Command::new("/bin/sh")
1396 .args(["-c", &script])
1397 .output()
1398 .unwrap();
1399 assert!(output.status.success());
1400 let stdout = String::from_utf8(output.stdout).unwrap();
1401 assert_eq!(
1402 stdout.lines().filter(|line| *line == task).count(),
1403 1,
1404 "{stdout}"
1405 );
1406 }
1407 }
1408
1409 #[tokio::test]
1410 async fn installed_version_probe_is_demoted_and_never_sources_agent_credentials() {
1411 let recorder = Recorder::with([
1412 Reply::ok(serde_json::json!({"exec_id":"version","phase":"running"})),
1413 Reply::ok(serde_json::json!({"exec_id":"version","phase":"exited"})),
1414 Reply::ok(serde_json::json!({
1415 "exec_id":"version","phase":"exited","exit_code":0,"signal":null,
1416 "stdout":"codex-cli 0.154.0\nSECRET=credential","stderr":"private diagnostic",
1417 "truncated":false,"writers_may_be_alive":false
1418 })),
1419 ]);
1420 let (session, _, _) = session_with(Arc::clone(&recorder));
1421 assert_eq!(
1422 installed_version(&session, Agent::Codex).await.unwrap(),
1423 "0.154.0"
1424 );
1425 let requests = recorder.requests();
1426 let start: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
1427 assert_eq!(start["command"], serde_json::json!(["codex", "--version"]));
1428 assert_eq!(start["shell"], false);
1429 assert_eq!(start["user"], 1000);
1430 assert_eq!(start["group"], 1000);
1431 assert_eq!(
1432 start["env"],
1433 serde_json::json!({"PATH":"/usr/local/bin:/usr/bin:/bin"})
1434 );
1435 assert_eq!(start["timeout_sec"], 10.0);
1436 assert_eq!(start["reap_group_on_exit"], true);
1437 }
1438}