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, 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 image_stem(specs: &[AgentSpec]) -> String {
221 let agents: Vec<&str> = ordered(specs)
222 .into_iter()
223 .map(|spec| spec.agent.as_str())
224 .collect();
225 format!("agent-vm-{}", agents.join("-"))
226}
227
228pub fn dockerfile(specs: &[AgentSpec], base: &BaseImage, port: u16) -> Result<String, Error> {
236 require_specs(specs)?;
237 let stanza = default_dockerfile(port, Some(WORKDIR), base, None);
238 let mut lines: Vec<String> = stanza.lines().map(str::to_string).collect();
239
240 let chmod = lines
241 .iter()
242 .position(|line| line == "RUN chmod 0755 /agentd")
243 .ok_or_else(|| stanza_drift("RUN chmod 0755 /agentd"))?;
244 let mut layers = vec![
245 String::new(),
246 "# The coding agents. Node 22 runs both CLIs; the rest is what a coding agent".to_string(),
247 "# expects of a working shell. Unpinned unless a cli_version was given, so the".to_string(),
248 "# image carries the registry's latest at build time and a pin changes the reuse hash."
249 .to_string(),
250 format!(
251 "RUN dnf install -y --setopt=install_weak_deps=0 {} && dnf clean all",
252 profile::SYSTEM_PACKAGES
253 ),
254 ];
255 let packages: Vec<String> = ordered(specs)
256 .into_iter()
257 .map(AgentSpec::npm_spec)
258 .collect();
259 layers.push(format!(
260 "RUN npm install -g {} && npm cache clean --force",
261 packages.join(" ")
262 ));
263 layers.extend([
264 String::new(),
265 "# The non-root user the agents run as. Appended directly because `useradd` is not"
266 .to_string(),
267 "# in the minimal base. Not decoration: Claude Code refuses --dangerously-skip-permissions"
268 .to_string(),
269 "# as root and then denies its own tool calls while still reporting (measured: zero"
270 .to_string(),
271 "# shell calls as uid 0, 147 as uid 1000 on the same task).".to_string(),
272 format!(
273 "RUN echo \"agent:x:{AGENT_UID}:{AGENT_GID}::{WORKDIR}:/bin/bash\" >> /etc/passwd \\"
274 ),
275 format!(" && echo \"agent:x:{AGENT_GID}:\" >> /etc/group"),
276 ]);
277 lines.splice(chmod + 1..chmod + 1, layers);
278
279 let mkdir = lines
280 .iter()
281 .position(|line| line == &format!("RUN mkdir -p {WORKDIR}"))
282 .ok_or_else(|| stanza_drift("RUN mkdir -p /workspace"))?;
283 lines[mkdir] = format!("RUN mkdir -p {WORKDIR} && chown {AGENT_UID}:{AGENT_GID} {WORKDIR}");
286
287 let mut text = lines.join("\n");
288 text.push('\n');
289 Ok(text)
290}
291
292fn stanza_drift(line: &str) -> Error {
293 Error::new(
294 ErrorKind::Unexpected,
295 format!(
296 "default_dockerfile no longer emits `{line}`, so the agent layers have no splice \
297 point. Update agents::dockerfile beside the stanza change."
298 ),
299 )
300}
301
302#[derive(Clone, Debug)]
307pub struct BedrockAccess {
308 pub region: Region,
309 pub token: BearerToken,
310}
311
312#[derive(Clone, Debug, Eq, PartialEq)]
314pub struct GuestFile {
315 pub path: String,
316 pub contents: Vec<u8>,
317 pub mode: &'static str,
319}
320
321pub fn sh_double_quote(value: &str) -> String {
326 let mut quoted = String::with_capacity(value.len() + 2);
327 quoted.push('"');
328 for ch in value.chars() {
329 if matches!(ch, '"' | '\\' | '$' | '`') {
330 quoted.push('\\');
331 }
332 quoted.push(ch);
333 }
334 quoted.push('"');
335 quoted
336}
337
338pub fn sh_single_quote(value: &str) -> String {
342 let mut quoted = String::with_capacity(value.len() + 2);
343 quoted.push('\'');
344 for ch in value.chars() {
345 if ch == '\'' {
346 quoted.push_str("'\\''");
347 } else {
348 quoted.push(ch);
349 }
350 }
351 quoted.push('\'');
352 quoted
353}
354
355pub fn provisioning_files(
358 specs: &[AgentSpec],
359 access: &BedrockAccess,
360) -> Result<Vec<GuestFile>, Error> {
361 require_specs(specs)?;
362 let specs = ordered(specs);
363
364 let mut env = vec![
368 ("HOME", WORKDIR.to_string()),
369 ("PATH", "/usr/local/bin:/usr/bin:/bin".to_string()),
370 ("AWS_REGION", access.region.as_str().to_string()),
371 ];
372 for spec in &specs {
373 env.extend(profile::env_pairs(
374 spec.agent,
375 spec.model(),
376 access.token.expose(),
377 ));
378 }
379 let mut env_file = String::new();
380 for (key, value) in env {
381 env_file.push_str(&format!("export {key}={}\n", sh_double_quote(&value)));
382 }
383
384 let mut files = vec![GuestFile {
385 path: ENV_FILE.to_string(),
386 contents: env_file.into_bytes(),
387 mode: "0600",
388 }];
389 if let Some(codex) = specs.iter().find(|spec| spec.agent == Agent::Codex) {
390 files.push(GuestFile {
391 path: CODEX_CONFIG_FILE.to_string(),
392 contents: profile::codex_config(codex.model(), &access.region).into_bytes(),
393 mode: "0600",
394 });
395 }
396 let marker = serde_json::json!({
397 "version": 1,
398 "region": access.region.as_str(),
399 "agents": specs.iter().map(|spec| serde_json::json!({
400 "agent": spec.agent.as_str(),
401 "model": spec.model(),
402 "cliVersion": spec.cli_version,
403 })).collect::<Vec<_>>(),
404 });
405 files.push(GuestFile {
406 path: MARKER_FILE.to_string(),
407 contents: serde_json::to_vec_pretty(&marker).map_err(|error| {
408 Error::new(
409 ErrorKind::Unexpected,
410 format!("the marker will not serialize: {error}"),
411 )
412 })?,
413 mode: "0644",
416 });
417 Ok(files)
418}
419
420pub async fn install_access(
427 session: &Session,
428 specs: &[AgentSpec],
429 access: &BedrockAccess,
430) -> Result<(), Error> {
431 for file in provisioning_files(specs, access)? {
432 session
433 .upload_file(&file.path, &file.contents, Some(file.mode))
434 .await?;
435 }
436 let request = crate::protocol::exec::StartRequest {
437 exec_id: mint_exec_id(),
438 command: vec![format!("chown -R {AGENT_UID}:{AGENT_GID} {WORKDIR}")],
439 shell: true,
440 cwd: None,
441 env: std::collections::HashMap::new(),
442 user: None,
443 group: None,
444 timeout_sec: Some(CHOWN_TIMEOUT.as_secs_f64()),
445 stdin: false,
446 };
447 let result = session.run_sync(request, CHOWN_TIMEOUT).await?;
448 if !result.succeeded() {
449 return Err(Error::new(
450 ErrorKind::ExecFailed,
451 format!(
452 "handing {WORKDIR} to uid {AGENT_UID} failed (exit {:?}): {}",
453 result.exit_code(),
454 result.stderr().trim()
455 ),
456 ));
457 }
458 Ok(())
459}
460
461pub async fn installed_agents(session: &Session) -> Result<Vec<AgentSpec>, Error> {
467 let bytes = match session.download_file(MARKER_FILE).await {
468 Ok(bytes) => bytes,
469 Err(error) if error.wire_kind() == Some(crate::error::WireKind::NotFound) => {
470 return Err(Error::new(
471 ErrorKind::Precondition,
472 format!(
473 "{MARKER_FILE} is not in this VM, so it was not provisioned as an agent \
474 VM. `microvm agent-up --vm-name <NAME>` installs an agent and writes \
475 the marker; `--agent` names one explicitly when the marker is absent."
476 ),
477 ));
478 }
479 Err(error) => return Err(error),
480 };
481 let marker: serde_json::Value = serde_json::from_slice(&bytes).map_err(|error| {
482 Error::new(
483 ErrorKind::Protocol,
484 format!("{MARKER_FILE} is not the JSON agent-up wrote: {error}"),
485 )
486 })?;
487 let rows = marker["agents"].as_array().ok_or_else(|| {
488 Error::new(
489 ErrorKind::Protocol,
490 format!("{MARKER_FILE} carries no `agents` array"),
491 )
492 })?;
493 let mut specs = Vec::with_capacity(rows.len());
494 for row in rows {
495 let name = row["agent"].as_str().unwrap_or_default();
496 let agent = Agent::parse(name).ok_or_else(|| {
497 Error::new(
498 ErrorKind::Protocol,
499 format!("{MARKER_FILE} names an agent this client has no profile for: {name:?}"),
500 )
501 })?;
502 let mut spec = AgentSpec::new(agent);
503 if let Some(model) = row["model"].as_str() {
504 spec.model = Some(model.to_string());
505 }
506 if let Some(version) = row["cliVersion"].as_str() {
507 spec.cli_version = Some(version.to_string());
508 }
509 specs.push(spec);
510 }
511 require_specs(&specs)?;
512 Ok(specs)
513}
514
515#[derive(Clone, Debug, Default)]
517pub struct PromptOptions {
518 pub exec_id: Option<String>,
520 pub timeout: Option<Duration>,
523}
524
525pub fn prompt_request(
527 spec: &AgentSpec,
528 task: &str,
529 options: &PromptOptions,
530) -> Result<crate::protocol::exec::StartRequest, Error> {
531 if task.trim().is_empty() {
532 return Err(Error::invalid_arg(
533 "the task is empty. An agent prompted with nothing answers with nothing, at the \
534 price of a model call.",
535 ));
536 }
537 let command = format!(
538 ". {ENV_FILE} && {}",
539 profile::headless_command(spec.agent, &sh_single_quote(task))
540 );
541 Ok(crate::protocol::exec::StartRequest {
542 exec_id: options.exec_id.clone().unwrap_or_else(mint_exec_id),
543 command: vec![command],
544 shell: true,
545 cwd: Some(WORKDIR.to_string()),
546 env: std::collections::HashMap::new(),
549 user: Some(AGENT_UID),
550 group: Some(AGENT_GID),
551 timeout_sec: options.timeout.map(|timeout| timeout.as_secs_f64()),
552 stdin: false,
553 })
554}
555
556pub fn headless_command_template(agent: Agent) -> String {
559 format!(
560 ". {ENV_FILE} && {}",
561 profile::headless_command(agent, "'<TASK>'")
562 )
563}
564
565pub async fn prompt(
568 session: &Session,
569 spec: &AgentSpec,
570 task: &str,
571 options: &PromptOptions,
572) -> Result<ExecHandle, Error> {
573 session.run(prompt_request(spec, task, options)?).await
574}
575
576pub struct AgentVm {
581 sandbox: Sandbox,
582 specs: Vec<AgentSpec>,
583}
584
585impl std::fmt::Debug for AgentVm {
586 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
587 f.debug_struct("AgentVm")
588 .field("agents", &self.specs)
589 .field("sandbox", &self.sandbox)
590 .finish()
591 }
592}
593
594impl AgentVm {
595 pub fn new(sandbox: Sandbox, specs: Vec<AgentSpec>) -> Result<Self, Error> {
597 require_specs(&specs)?;
598 Ok(Self { sandbox, specs })
599 }
600
601 pub fn claude_code(sandbox: Sandbox) -> Self {
603 Self {
604 sandbox,
605 specs: vec![AgentSpec::new(Agent::ClaudeCode)],
606 }
607 }
608
609 pub fn codex(sandbox: Sandbox) -> Self {
611 Self {
612 sandbox,
613 specs: vec![AgentSpec::new(Agent::Codex)],
614 }
615 }
616
617 pub fn specs(&self) -> Vec<AgentSpec> {
619 ordered(&self.specs).into_iter().cloned().collect()
620 }
621
622 pub fn sandbox(&self) -> &Sandbox {
623 &self.sandbox
624 }
625
626 pub fn sandbox_mut(&mut self) -> &mut Sandbox {
627 &mut self.sandbox
628 }
629
630 pub fn session(&self) -> Option<&Session> {
632 self.sandbox.session()
633 }
634
635 pub fn image_name(&self, request: &CreateImageRequest) -> String {
639 image_name_for(&self.sandbox, &self.specs, request)
640 }
641
642 pub fn image_request(
649 &self,
650 binary: Vec<u8>,
651 build_role_arn: impl Into<String>,
652 size: SizeClass,
653 ) -> Result<CreateImageRequest, Error> {
654 image_request_for(&self.sandbox, &self.specs, binary, build_role_arn, size)
655 }
656
657 pub async fn build(&mut self, request: CreateImageRequest) -> Result<&Image, Error> {
659 self.sandbox.build_image(request).await
660 }
661
662 pub fn launch_request(
665 &self,
666 image_identifier: impl Into<String>,
667 execution_role_arn: Option<String>,
668 ) -> RunRequest {
669 launch_request_for(&self.specs, image_identifier, execution_role_arn)
670 }
671
672 pub async fn launch(&mut self, request: RunRequest) -> Result<&Session, Error> {
674 let session = self.sandbox.run(request).await?;
675 session
676 .wait_until_ready(crate::session::DEFAULT_READY_TIMEOUT)
677 .await?;
678 Ok(session)
679 }
680
681 fn require_session(&self) -> Result<&Session, Error> {
682 self.sandbox.session().ok_or_else(|| {
683 Error::new(
684 ErrorKind::Precondition,
685 "this agent VM has not been launched; call `launch` first.",
686 )
687 })
688 }
689
690 pub async fn install_access(&self, access: &BedrockAccess) -> Result<(), Error> {
692 install_access(self.require_session()?, &self.specs, access).await
693 }
694
695 pub async fn prompt(
697 &self,
698 agent: Agent,
699 task: &str,
700 options: &PromptOptions,
701 ) -> Result<ExecHandle, Error> {
702 let spec = spec_for(&self.specs, agent)?;
703 prompt(self.require_session()?, spec, task, options).await
704 }
705
706 pub async fn terminate(&mut self, opts: TeardownOpts) -> TeardownReport {
708 self.sandbox.terminate(opts).await
709 }
710}
711
712#[cfg(test)]
713mod tests {
714 use std::sync::Arc;
715
716 use super::*;
717 use crate::control::artifact::{
718 require_daemon_cmd, require_matching_agentd_port, require_matching_from, require_workdir,
719 };
720 use crate::session::testing::{Recorder, Reply, session_with};
721
722 fn both() -> Vec<AgentSpec> {
723 vec![
724 AgentSpec::new(Agent::Codex),
725 AgentSpec::new(Agent::ClaudeCode),
726 ]
727 }
728
729 fn access() -> BedrockAccess {
730 BedrockAccess {
731 region: Region::UsEast1,
732 token: bedrock::mint_with(
733 &aws_credential_types::Credentials::new("AKID", "secret", None, None, "t"),
734 &Region::UsEast1,
735 Duration::from_secs(60),
736 std::time::SystemTime::UNIX_EPOCH,
737 )
738 .expect("mints")
739 .token,
740 }
741 }
742
743 #[test]
752 fn the_dockerfile_passes_the_guards_and_carries_the_recipe() {
753 let base = BaseImage::al2023();
754 let text = dockerfile(&both(), &base, 9000).expect("derives");
755
756 require_matching_from(&base, &text).expect("FROM pairs with the base");
757 require_workdir(&base, Some(&text)).expect("a WORKDIR is declared");
758 require_daemon_cmd(&text).expect("ENTRYPOINT [] + CMD agentd survive");
759 require_matching_agentd_port(9000, &text).expect("the port agrees");
760
761 assert_eq!(
762 text.matches("RUN dnf install").count(),
763 1,
764 "the system layer is emitted once for two profiles:\n{text}"
765 );
766 assert!(
767 text.contains("RUN dnf install -y --setopt=install_weak_deps=0 nodejs22 nodejs22-npm "),
768 "with weak deps off, bare `npm` is Node 18's and the npm layer exits 127:\n{text}"
769 );
770 assert!(
771 text.contains("RUN npm install -g @anthropic-ai/claude-code @openai/codex && npm"),
772 "both CLIs in profile order, in one layer:\n{text}"
773 );
774 assert!(
775 text.contains("agent:x:1000:1000::/workspace:/bin/bash"),
776 "{text}"
777 );
778 assert!(
779 text.contains("RUN mkdir -p /workspace && chown 1000:1000 /workspace"),
780 "{text}"
781 );
782 let layers_at = text.find("RUN npm install").expect("layers");
783 let workdir_at = text.find("WORKDIR /workspace").expect("workdir");
784 let cmd_at = text.find("CMD [\"/agentd\"]").expect("cmd");
785 assert!(layers_at < workdir_at && workdir_at < cmd_at, "{text}");
786 }
787
788 #[test]
791 fn a_cli_version_pin_reaches_the_install_line() {
792 let base = BaseImage::al2023();
793 let pinned = vec![AgentSpec::new(Agent::ClaudeCode).with_cli_version("2.1.0")];
794 let text = dockerfile(&pinned, &base, 9000).expect("derives");
795 assert!(text.contains("@anthropic-ai/claude-code@2.1.0"), "{text}");
796 let plain = dockerfile(&[AgentSpec::new(Agent::ClaudeCode)], &base, 9000).expect("d");
797 assert_ne!(text, plain);
798 }
799
800 #[test]
801 fn an_empty_or_repeated_spec_set_is_refused_before_any_text_is_built() {
802 let base = BaseImage::al2023();
803 assert_eq!(
804 dockerfile(&[], &base, 9000).expect_err("empty").kind(),
805 ErrorKind::InvalidArg
806 );
807 let twice = vec![AgentSpec::new(Agent::Codex), AgentSpec::new(Agent::Codex)];
808 let error = dockerfile(&twice, &base, 9000).expect_err("repeated");
809 assert!(
810 error.to_string().contains("codex is named twice"),
811 "{error}"
812 );
813 }
814
815 #[test]
817 fn the_image_stem_is_stable_under_spec_order() {
818 assert_eq!(image_stem(&both()), "agent-vm-claude-code-codex");
819 assert_eq!(
820 image_stem(&[AgentSpec::new(Agent::Codex)]),
821 "agent-vm-codex"
822 );
823 }
824
825 #[test]
831 fn a_codex_only_vm_still_gets_the_variable_codex_reads() {
832 let files = provisioning_files(&[AgentSpec::new(Agent::Codex)], &access()).expect("files");
833 let env = String::from_utf8(files[0].contents.clone()).expect("utf-8");
834 assert!(
835 env.contains("export AWS_BEARER_TOKEN_BEDROCK="),
836 "no Claude Code profile is present to export it, and Codex 401s without it:\n{env}"
837 );
838 }
839
840 #[test]
841 fn the_file_set_follows_the_profiles_and_the_env_file_is_quoted() {
842 let access = access();
843 let claude_only =
844 provisioning_files(&[AgentSpec::new(Agent::ClaudeCode)], &access).expect("files");
845 assert_eq!(
846 claude_only
847 .iter()
848 .map(|f| f.path.as_str())
849 .collect::<Vec<_>>(),
850 vec![ENV_FILE, MARKER_FILE]
851 );
852
853 let files = provisioning_files(&both(), &access).expect("files");
854 assert_eq!(
855 files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(),
856 vec![ENV_FILE, CODEX_CONFIG_FILE, MARKER_FILE]
857 );
858 let env = String::from_utf8(files[0].contents.clone()).expect("utf-8");
859 assert_eq!(files[0].mode, "0600");
860 assert!(
861 env.contains("export PATH=\"/usr/local/bin:/usr/bin:/bin\"\n"),
862 "{env}"
863 );
864 assert!(env.contains("export HOME=\"/workspace\"\n"), "{env}");
865 assert!(env.contains("export AWS_REGION=\"us-east-1\"\n"), "{env}");
866 assert!(
867 env.contains("export CLAUDE_CODE_USE_BEDROCK=\"1\"\n"),
868 "{env}"
869 );
870 assert!(
871 env.contains("export ANTHROPIC_MODEL=\"global.anthropic.claude-opus-5\"\n"),
872 "{env}"
873 );
874 let token = access.token.expose();
875 assert!(env.contains(&format!("export AWS_BEARER_TOKEN_BEDROCK=\"{token}\"\n")));
876 assert!(env.contains(&format!("export OPENAI_API_KEY=\"{token}\"\n")));
877
878 let config = String::from_utf8(files[1].contents.clone()).expect("utf-8");
879 assert!(
880 config.contains("bedrock-runtime.us-east-1.amazonaws.com/openai/v1"),
881 "{config}"
882 );
883 assert!(
884 config.contains("model = \"global.openai.gpt-5.6-sol\""),
885 "{config}"
886 );
887
888 let marker: serde_json::Value = serde_json::from_slice(&files[2].contents).expect("json");
889 assert_eq!(files[2].mode, "0644");
890 assert_eq!(marker["agents"][0]["agent"], "claude-code");
891 assert_eq!(marker["agents"][1]["agent"], "codex");
892 assert_eq!(marker["agents"][1]["model"], "global.openai.gpt-5.6-sol");
893 assert!(
894 !files[2]
895 .contents
896 .windows(token.len())
897 .any(|w| w == token.as_bytes()),
898 "the marker is world-readable and must never carry the token"
899 );
900 }
901
902 #[test]
903 fn shell_quoting_escapes_what_each_quote_style_cannot_hold() {
904 assert_eq!(sh_double_quote("a$b\"c`d\\e"), "\"a\\$b\\\"c\\`d\\\\e\"");
905 assert_eq!(sh_single_quote("it's"), "'it'\\''s'");
906 assert_eq!(sh_single_quote("plain"), "'plain'");
907 }
908
909 #[tokio::test(start_paused = true)]
915 async fn install_access_uploads_then_chowns_as_root() {
916 let recorder = Recorder::with([
917 Reply::Body(200, Vec::new()),
918 Reply::Body(200, Vec::new()),
919 Reply::Body(200, Vec::new()),
920 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"running"})),
921 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"exited"})),
922 Reply::ok(serde_json::json!({
923 "exec_id":"c1","phase":"exited","exit_code":0,"signal":null,
924 "stdout":"","stderr":"","truncated":false,"writers_may_be_alive":false
925 })),
926 ]);
927 let (session, _, _) = session_with(Arc::clone(&recorder));
928
929 install_access(&session, &both(), &access())
930 .await
931 .expect("installs");
932
933 let seen = recorder.requests();
934 assert_eq!(seen.len(), 6, "{seen:#?}");
935 for (request, (encoded, mode)) in seen.iter().zip([
936 ("%2Fworkspace%2F.agent-env", "0600"),
937 ("%2Fworkspace%2F.codex%2Fconfig.toml", "0600"),
938 ("%2Fworkspace%2F.agent-vm.json", "0644"),
939 ]) {
940 assert_eq!(request.method, "PUT");
941 assert_eq!(
942 request.path,
943 format!("/v1/fs/file?path={encoded}&mode={mode}"),
944 "each file goes to the file route with its own mode"
945 );
946 }
947 assert_eq!(seen[3].path, "/v1/exec/start");
948 let start: serde_json::Value = serde_json::from_slice(&seen[3].body).expect("json");
949 assert_eq!(start["command"][0], "chown -R 1000:1000 /workspace");
950 assert_eq!(start["shell"], true);
951 assert!(
952 start["user"].is_null(),
953 "the chown runs as the daemon's own user"
954 );
955 assert_eq!(seen[5].path, "/v1/exec/c1/ack");
956 }
957
958 #[tokio::test(start_paused = true)]
961 async fn a_failed_chown_fails_the_install() {
962 let recorder = Recorder::with([
963 Reply::Body(200, Vec::new()),
964 Reply::Body(200, Vec::new()),
965 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"running"})),
966 Reply::ok(serde_json::json!({"exec_id":"c1","phase":"exited"})),
967 Reply::ok(serde_json::json!({
968 "exec_id":"c1","phase":"exited","exit_code":1,"signal":null,
969 "stdout":"","stderr":"chown: cannot access","truncated":false,
970 "writers_may_be_alive":false
971 })),
972 ]);
973 let (session, _, _) = session_with(recorder);
974 let error = install_access(&session, &[AgentSpec::new(Agent::ClaudeCode)], &access())
975 .await
976 .expect_err("fails");
977 assert_eq!(error.kind(), ErrorKind::ExecFailed);
978 assert!(
979 error.to_string().contains("chown: cannot access"),
980 "{error}"
981 );
982 }
983
984 #[tokio::test]
987 async fn installed_agents_reads_the_marker_back() {
988 let specs = vec![
989 AgentSpec::new(Agent::ClaudeCode).with_model("global.anthropic.claude-sonnet-5"),
990 AgentSpec::new(Agent::Codex).with_cli_version("0.50.0"),
991 ];
992 let files = provisioning_files(&specs, &access()).expect("files");
993 let marker = files.last().expect("marker").contents.clone();
994 let recorder = Recorder::with([Reply::Body(200, marker)]);
995 let (session, _, _) = session_with(recorder);
996
997 let read = installed_agents(&session).await.expect("reads");
998 assert_eq!(read.len(), 2);
999 assert_eq!(read[0].agent, Agent::ClaudeCode);
1000 assert_eq!(read[0].model(), "global.anthropic.claude-sonnet-5");
1001 assert_eq!(read[1].agent, Agent::Codex);
1002 assert_eq!(read[1].cli_version.as_deref(), Some("0.50.0"));
1003 assert_eq!(read[1].model(), "global.openai.gpt-5.6-sol");
1004 }
1005
1006 #[tokio::test]
1009 async fn a_missing_marker_names_agent_up_and_other_failures_propagate() {
1010 let recorder = Recorder::with([
1011 Reply::Body(404, b"not found".to_vec()),
1012 Reply::Body(503, b"not bootstrapped".to_vec()),
1013 ]);
1014 let (session, _, _) = session_with(recorder);
1015 let error = installed_agents(&session).await.expect_err("absent");
1016 assert_eq!(error.kind(), ErrorKind::Precondition);
1017 assert!(error.to_string().contains("agent-up"), "{error}");
1018 let other = installed_agents(&session).await.expect_err("503");
1019 assert_ne!(other.kind(), ErrorKind::Precondition);
1020 }
1021
1022 #[test]
1028 fn the_prompt_request_runs_the_agent_demoted_in_the_workspace() {
1029 let spec = AgentSpec::new(Agent::ClaudeCode);
1030 let request = prompt_request(
1031 &spec,
1032 "count the files; it's quick",
1033 &PromptOptions {
1034 exec_id: Some("p1".into()),
1035 timeout: Some(Duration::from_secs(120)),
1036 },
1037 )
1038 .expect("builds");
1039 assert_eq!(request.exec_id, "p1");
1040 assert_eq!(request.user, Some(1000));
1041 assert_eq!(request.group, Some(1000));
1042 assert_eq!(request.cwd.as_deref(), Some("/workspace"));
1043 assert!(request.shell);
1044 assert!(
1045 request.env.is_empty(),
1046 "the token never rides in the request"
1047 );
1048 assert_eq!(request.timeout_sec, Some(120.0));
1049 assert!(!request.stdin);
1050 assert_eq!(
1051 request.command,
1052 vec![
1053 ". /workspace/.agent-env && claude -p 'count the files; it'\\''s quick' \
1054 --allowedTools Bash,Read,Edit,Write,Grep,Glob"
1055 .to_string()
1056 ]
1057 );
1058
1059 let codex = prompt_request(
1060 &AgentSpec::new(Agent::Codex),
1061 "hi",
1062 &PromptOptions::default(),
1063 )
1064 .expect("builds");
1065 assert!(
1066 codex.command[0].contains("codex exec --skip-git-repo-check -s workspace-write 'hi'")
1067 );
1068 assert!(codex.timeout_sec.is_none());
1069 assert!(!codex.exec_id.is_empty(), "an id was minted");
1070 }
1071
1072 #[test]
1073 fn an_empty_task_is_refused_locally() {
1074 let error = prompt_request(
1075 &AgentSpec::new(Agent::Codex),
1076 " \n",
1077 &PromptOptions::default(),
1078 )
1079 .expect_err("empty");
1080 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1081 }
1082
1083 fn sandbox() -> Sandbox {
1086 Sandbox::with_control_plane(crate::control::ControlPlane::with_transport(
1087 Arc::new(crate::control::fake::FakeControlPlane::new()),
1088 Region::UsEast1,
1089 Arc::new(crate::control::fake::TestClock::new()),
1090 ))
1091 }
1092
1093 #[test]
1096 fn the_image_request_is_content_named_and_egress_is_on_at_launch() {
1097 let vm = AgentVm::new(sandbox(), both()).expect("specs");
1098 let a = vm
1099 .image_request(
1100 b"daemon".to_vec(),
1101 "arn:aws:iam::123456789012:role/b",
1102 DEFAULT_SIZE,
1103 )
1104 .expect("request");
1105 let b = vm
1106 .image_request(
1107 b"daemon".to_vec(),
1108 "arn:aws:iam::123456789012:role/b",
1109 DEFAULT_SIZE,
1110 )
1111 .expect("request");
1112 let c = vm
1113 .image_request(
1114 b"other".to_vec(),
1115 "arn:aws:iam::123456789012:role/b",
1116 DEFAULT_SIZE,
1117 )
1118 .expect("request");
1119 assert_eq!(a.name, b.name);
1120 assert_ne!(a.name, c.name);
1121 assert!(
1122 a.name.starts_with("agent-vm-claude-code-codex-"),
1123 "{}",
1124 a.name
1125 );
1126 assert_eq!(a.name.len(), "agent-vm-claude-code-codex-".len() + 12);
1127 assert_eq!(a.token_scope.as_deref(), Some(a.name.as_str()));
1128 assert!(a.code_artifact_uri.is_empty(), "the upload is the caller's");
1129 assert!(
1130 a.dockerfile
1131 .as_deref()
1132 .is_some_and(|d| d.contains("@openai/codex"))
1133 );
1134 assert_eq!(a.size, SizeClass::Mib1024);
1135
1136 let launch = vm.launch_request("arn:image", Some("arn:role".into()));
1137 assert!(
1138 launch.egress,
1139 "neither agent reaches Bedrock without egress"
1140 );
1141 assert_eq!(launch.image_identifier.as_deref(), Some("arn:image"));
1142 assert_eq!(
1143 launch.token_scope.as_deref(),
1144 Some("agent-vm-claude-code-codex")
1145 );
1146 }
1147
1148 #[tokio::test]
1151 async fn the_named_constructors_carry_one_agent_each() {
1152 let claude = AgentVm::claude_code(sandbox());
1153 assert_eq!(claude.specs(), vec![AgentSpec::new(Agent::ClaudeCode)]);
1154 let codex = AgentVm::codex(sandbox());
1155 assert_eq!(codex.specs(), vec![AgentSpec::new(Agent::Codex)]);
1156
1157 let error = codex
1158 .prompt(Agent::ClaudeCode, "hi", &PromptOptions::default())
1159 .await
1160 .expect_err("wrong agent");
1161 assert_eq!(error.kind(), ErrorKind::InvalidArg);
1162 assert!(error.to_string().contains("carries codex"), "{error}");
1163 let unlaunched = codex
1164 .prompt(Agent::Codex, "hi", &PromptOptions::default())
1165 .await
1166 .expect_err("no session");
1167 assert_eq!(unlaunched.kind(), ErrorKind::Precondition);
1168 }
1169}