Skip to main content

microvms_core/agents/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Agent VMs: the L3 helpers over the lifecycle (`docs/AGENT-VMS.md`).
3//!
4//! # What this module is
5//!
6//! One VM with a coding agent installed, model access wired, running as a non-root user,
7//! and one call that hands the agent a task. Every step is a composition of
8//! [`crate::sandbox`] and [`crate::session`] calls that
9//! `examples/coding-agents-on-bedrock/run.sh` performed by hand; this module is where
10//! that composition, and the four measured traps it closes, live once:
11//!
12//! 1. **Root silently breaks the agent.** Claude Code's `--dangerously-skip-permissions`
13//!    refuses to run as uid 0 and then denies its own tool calls while still reporting
14//!    (measured: zero shell calls as root, 147 as uid 1000). Every prompt runs as
15//!    [`AGENT_UID`]/[`AGENT_GID`], and the image creates that user.
16//! 2. **The daemon's execs start from an empty environment**, so the agent's subshells
17//!    find no `PATH` and every command exits 127. The environment file sets it.
18//! 3. **The daemon writes uploaded files as root, mode 0600**, which a demoted agent
19//!    cannot read. One root `chown` follows the uploads.
20//! 4. **Codex reaches Bedrock through `bedrock-runtime`'s `/openai/v1`** on the Responses
21//!    wire API, with an inference-profile model id and hosted web search disabled. Its
22//!    config file names that host for the launch region, and its credential comes from
23//!    `AWS_BEARER_TOKEN_BEDROCK` rather than the provider's `env_key`.
24//!
25//! # What it is not
26//!
27//! Not an orchestrator (`docs/STRATEGY.md`): no scheduling, no retries across VMs, no
28//! turn loop. Not a harness provider class: a Harbor environment or an eve backend
29//! imports its harness and lives there, calling this. And not a place agent detail
30//! sprawls: every vendor-shaped fact is a row in [`profile`], dated.
31//!
32//! # Two shapes over one recipe
33//!
34//! [`AgentVm`] owns a [`Sandbox`] and is the shape for a caller who builds, launches,
35//! provisions, prompts, and tears down in one process. The free functions
36//! ([`install_access`], [`prompt`], [`installed_agents`]) take a [`Session`], because the
37//! CLI's refresh and prompt paths hold an attached session for a VM some earlier process
38//! launched and no sandbox at all; `AgentVm`'s methods delegate to them so the two
39//! paths cannot drift.
40
41pub 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
57/// The uid every agent runs as, and the owner of `/workspace`. Created by the image.
58pub const AGENT_UID: u32 = 1000;
59/// The gid to match.
60pub const AGENT_GID: u32 = 1000;
61/// The image `WORKDIR`, the agent's `HOME`, and where a synced project lands. The same
62/// path `microvms-cli/src/sync.rs` names as `REMOTE_WORKDIR`, on purpose: `run <DIR>`
63/// and `agent-up --project` put the tree in the same place.
64pub const WORKDIR: &str = "/workspace";
65/// The size class agent sessions default to: a 4 GiB always-present ceiling at half the
66/// floor cost of the 2048 default, because agent sessions are peaky (the example's
67/// measured choice, `examples/coding-agents-on-bedrock/microvm.toml`).
68pub const DEFAULT_SIZE: SizeClass = SizeClass::Mib1024;
69/// The default wait for one prompt. Agent tasks run minutes, not seconds.
70pub const DEFAULT_PROMPT_TIMEOUT: Duration = Duration::from_secs(900);
71/// How long the root `chown` after the uploads may take.
72const CHOWN_TIMEOUT: Duration = Duration::from_secs(60);
73
74/// One agent to install, with its two overridable defaults.
75#[derive(Clone, Debug, Eq, PartialEq)]
76pub struct AgentSpec {
77    pub agent: Agent,
78    /// The model id, or `None` for the profile's default.
79    pub model: Option<String>,
80    /// An npm version to pin the CLI to (`@<version>` on the install line), or `None`
81    /// for the registry's latest at build time. A pin changes the Dockerfile text and
82    /// therefore the reuse hash (AGENT-3).
83    pub cli_version: Option<String>,
84}
85
86impl AgentSpec {
87    /// The profile's defaults.
88    pub fn new(agent: Agent) -> Self {
89        Self {
90            agent,
91            model: None,
92            cli_version: None,
93        }
94    }
95
96    /// Override the model.
97    pub fn with_model(mut self, model: impl Into<String>) -> Self {
98        self.model = Some(model.into());
99        self
100    }
101
102    /// Pin the CLI version.
103    pub fn with_cli_version(mut self, version: impl Into<String>) -> Self {
104        self.cli_version = Some(version.into());
105        self
106    }
107
108    /// The model this spec resolves to.
109    pub fn model(&self) -> &str {
110        self.model
111            .as_deref()
112            .unwrap_or(self.agent.profile().default_model)
113    }
114
115    /// The `npm install -g` argument for this spec.
116    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
124/// Refuses an empty spec list and a repeated agent.
125///
126/// Both are caller mistakes with no sensible reading: an image with no agent is
127/// `microvm build`, and two rows for one agent would have two models for one CLI.
128///
129/// Public because the bindings hold a spec list beside a shared sandbox rather than an
130/// [`AgentVm`], and the refusal has to be this one rather than a copy of it.
131pub 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
152/// The specs in the fixed order the image layers, the marker, and the name use.
153fn 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
159/// The spec in `specs` for `agent`, or the refusal [`AgentVm::prompt`] gives.
160pub 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
172/// [`AgentVm::image_name`] for a caller holding the sandbox and the specs separately:
173/// the bindings, whose sandbox sits behind a lock shared with every session they hand out.
174pub 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
183/// [`AgentVm::image_request`] for a caller holding the sandbox and the specs separately.
184pub 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
205/// [`AgentVm::launch_request`] for a caller holding the specs separately.
206pub 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
218/// The stem of the image name: `agent-vm-<agents>` in profile order (AGENT-3). The
219/// caller appends the artifact content hash, exactly as `build --reuse` does.
220pub 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
228/// The Dockerfile for an image carrying `specs` (AGENT-2).
229///
230/// Built by splicing into [`default_dockerfile`]'s output rather than by re-listing its
231/// lines, so the stanza this produces *is* the default build's stanza plus layers: a
232/// change to the daemon lines there reaches here with no second copy to update. The
233/// splice points are the two lines the stanza is guaranteed to carry (`RUN chmod 0755
234/// /agentd` and `RUN mkdir -p /workspace`), and the test asserts both were found.
235pub 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    // Owned by the agent uid, because WORKDIR is where every exec lands and a root-owned
284    // one fails a demoted workload at its first write (docs/EMBEDDING.md).
285    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/// Model access for the agents: a Bedrock bearer token minted for a region.
303///
304/// A struct rather than an enum until a second access path exists to name
305/// (`docs/AGENT-VMS.md`, phase 2).
306#[derive(Clone, Debug)]
307pub struct BedrockAccess {
308    pub region: Region,
309    pub token: BearerToken,
310}
311
312/// One file to place in the guest.
313#[derive(Clone, Debug, Eq, PartialEq)]
314pub struct GuestFile {
315    pub path: String,
316    pub contents: Vec<u8>,
317    /// Octal, as the file route takes it.
318    pub mode: &'static str,
319}
320
321/// Wraps `value` in double quotes for `sh`, escaping the four characters that are
322/// special inside them. Used for the environment file, whose values are model ids, a
323/// region, and a token (base64 plus the prefix), none of which contain them today; the
324/// escaping is what keeps that "today" from mattering.
325pub 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
338/// Wraps `value` in single quotes for `sh`. A single quote inside becomes `'\''`, the
339/// one sequence that is literal under every POSIX shell. Used for the task text, which
340/// is the caller's prose and may contain anything.
341pub 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
355/// The files `install_access` places (AGENT-5, AGENT-6): the environment file, Codex's
356/// config when Codex is present, and the marker. Pure, so a test reads the exact bytes.
357pub 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    // PATH first and explicit: the daemon spawns execs from an empty environment, and
365    // Claude Code's Bash tool snapshots the shell it starts from, so without this line
366    // the agent's subshells find no `ls`, `wc`, or `python3`.
367    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        // World-readable is fine and useful: it names models, never a credential, and the
414        // agent itself may want to read it.
415        mode: "0644",
416    });
417    Ok(files)
418}
419
420/// Places the provisioning files and hands `/workspace` to the agent uid (AGENT-5).
421///
422/// The daemon writes every upload as root, so the `chown` is not optional and it runs
423/// as the daemon's own user, after the uploads, in one exec. Re-runnable: a second call
424/// with a fresh token overwrites the same files, which is how a 12-hour token is
425/// refreshed on a long-lived VM (AGENT-8).
426pub 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
461/// The agents a running VM was provisioned with, read from the guest marker (AGENT-10).
462///
463/// Answers from the VM rather than from a local record so a process that holds only
464/// the identifier triple can prompt correctly. A VM with no marker is one `agent-up`
465/// never provisioned, and the error says which command fixes that.
466pub 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/// The knobs on one prompt.
516#[derive(Clone, Debug, Default)]
517pub struct PromptOptions {
518    /// A stable exec id, for a retry that must not spawn twice. `None` mints one.
519    pub exec_id: Option<String>,
520    /// A daemon-side wall-clock budget for the agent process. `None` leaves the exec
521    /// unbounded on the daemon's side; the caller's wait still has its own deadline.
522    pub timeout: Option<Duration>,
523}
524
525/// The start request for one task (AGENT-7). Pure; the test reads every field.
526pub 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        // Empty on the wire: the environment file is the environment, sourced by the
547        // command, so the token never rides in a request body.
548        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
556/// The headless command with `<TASK>` where the quoted task goes, for a caller who wants
557/// to run it through `exec --stream` or read what `prompt` would do.
558pub fn headless_command_template(agent: Agent) -> String {
559    format!(
560        ". {ENV_FILE} && {}",
561        profile::headless_command(agent, "'<TASK>'")
562    )
563}
564
565/// Starts one task and returns its handle. Wait, stream, poll, or ack through the
566/// handle, exactly as for any other exec.
567pub 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
576/// One VM with coding agents in it: the [`Sandbox`] plus the specs it was built for.
577///
578/// Runtime-checked, like the sandbox it wraps, and for the same reason: one object is
579/// what the bindings can hold.
580pub 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    /// Wraps a sandbox for `specs`. Refuses an empty or repeated set.
596    pub fn new(sandbox: Sandbox, specs: Vec<AgentSpec>) -> Result<Self, Error> {
597        require_specs(&specs)?;
598        Ok(Self { sandbox, specs })
599    }
600
601    /// A VM for Claude Code with the profile's defaults.
602    pub fn claude_code(sandbox: Sandbox) -> Self {
603        Self {
604            sandbox,
605            specs: vec![AgentSpec::new(Agent::ClaudeCode)],
606        }
607    }
608
609    /// A VM for Codex with the profile's defaults.
610    pub fn codex(sandbox: Sandbox) -> Self {
611        Self {
612            sandbox,
613            specs: vec![AgentSpec::new(Agent::Codex)],
614        }
615    }
616
617    /// The specs this VM carries, in profile order.
618    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    /// The session, once [`AgentVm::launch`] has run.
631    pub fn session(&self) -> Option<&Session> {
632        self.sandbox.session()
633    }
634
635    /// The image name for these specs and this binary: the stem plus the first twelve
636    /// hex characters of the artifact content hash, so an unchanged binary and an
637    /// unchanged spec set name the image `build --reuse` would find (AGENT-3).
638    pub fn image_name(&self, request: &CreateImageRequest) -> String {
639        image_name_for(&self.sandbox, &self.specs, request)
640    }
641
642    /// The create request for this VM's image, named per [`AgentVm::image_name`].
643    ///
644    /// `code_artifact_uri` is left **empty** for the caller to fill: the upload is theirs
645    /// (S3 is not in this crate's dependency set), and the key they choose is usually
646    /// derived from the name this method just computed. `Sandbox::preflight` refuses a
647    /// request whose URI is still blank.
648    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    /// Builds the image. The caller has uploaded the artifact to the request's URI.
658    pub async fn build(&mut self, request: CreateImageRequest) -> Result<&Image, Error> {
659        self.sandbox.build_image(request).await
660    }
661
662    /// The launch request: egress on (AGENT-9), because neither agent reaches Bedrock
663    /// without it, and the token label set to the image name.
664    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    /// Launches and waits for the daemon to answer.
673    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    /// [`install_access`] on this VM's session.
691    pub async fn install_access(&self, access: &BedrockAccess) -> Result<(), Error> {
692        install_access(self.require_session()?, &self.specs, access).await
693    }
694
695    /// [`prompt`] on this VM's session, for one of the agents it carries.
696    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    /// Tears the VM down; see [`Sandbox::terminate`].
707    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    // ── the Dockerfile (AGENT-2) ─────────────────────────────────────────────
744
745    /// **The derived Dockerfile passes every guard preflight runs**, and carries the four
746    /// things the recipe needs: the layers, the user, the owned WORKDIR, the daemon lines.
747    ///
748    /// **Falsification** — drop the `chown` from the mkdir line and the ownership assert
749    /// goes red; emit the `dnf` line per profile and the count assert goes red; move
750    /// `WORKDIR` above the layers and the order assert goes red.
751    #[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    /// A version pin appears on the install line and nowhere else, so it changes the
789    /// Dockerfile text (and therefore the reuse hash) and nothing about the recipe.
790    #[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    /// The name stem is order-independent and spells the agents in profile order.
816    #[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    // ── the provisioning files (AGENT-5, AGENT-6) ────────────────────────────
826
827    /// **Claude alone gets two files; Codex adds its config.** The environment file sets
828    /// PATH and HOME, carries the token under each agent's variable, and every value is
829    /// double-quoted. The marker names the agents and their resolved models.
830    #[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    // ── install and read-back through the recorder ───────────────────────────
910
911    /// **The uploads go out in file order, then exactly one root chown.** The exec that
912    /// hands the workspace over runs as the daemon's own user (no `user` on the wire),
913    /// after every PUT.
914    #[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    /// A failed chown is a failure, not a warning: a workspace the agent cannot write is
959    /// a VM every prompt fails in.
960    #[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    /// **The marker round-trips**: what `provisioning_files` wrote is what
985    /// `installed_agents` reads back, models included.
986    #[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    /// A VM with no marker is a precondition failure naming the command that writes one,
1007    /// and any other refusal propagates as itself.
1008    #[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    // ── the prompt (AGENT-7) ─────────────────────────────────────────────────
1023
1024    /// **Every field of the start request is the recipe's.** uid and gid 1000, the
1025    /// workspace as cwd, an empty wire env, the env file sourced first, the task
1026    /// single-quoted, the daemon-side timeout only when asked for.
1027    #[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    // ── AgentVm ──────────────────────────────────────────────────────────────
1084
1085    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    /// **The image request is named by content and the URI is left to the caller.**
1094    /// Same binary and specs give the same name; a different binary gives a different one.
1095    #[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    /// The named constructors carry the request's own names, and a prompt for an agent
1149    /// the VM does not carry is refused before any wire call.
1150    #[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}