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, AgentPermissionMode, 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 egress posture every agent VM launches with (AGENT-9).
219///
220/// Derived from the launch request rather than asserted, so the CLI's `agent-up` envelope
221/// reports what [`launch_request_for`] actually asks for. `open`, and deliberately so:
222/// neither coding agent reaches Bedrock without the connector. An operator who wants an
223/// agent VM that cannot reach anything else needs a network control this platform does not
224/// offer — see `docs/TRUST.md`, **Egress**.
225pub fn agent_vm_egress_posture() -> crate::control::EgressPosture {
226    launch_request_for(&[], "arn:image", None).egress_posture()
227}
228
229/// The stem of the image name: `agent-vm-<agents>` in profile order (AGENT-3). The
230/// caller appends the artifact content hash, exactly as `build --reuse` does.
231pub 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
239/// The Dockerfile for an image carrying `specs` (AGENT-2).
240///
241/// Built by splicing into [`default_dockerfile`]'s output rather than by re-listing its
242/// lines, so the stanza this produces *is* the default build's stanza plus layers: a
243/// change to the daemon lines there reaches here with no second copy to update. The
244/// splice points are the two lines the stanza is guaranteed to carry (`RUN chmod 0755
245/// /agentd` and `RUN mkdir -p /workspace`), and the test asserts both were found.
246pub 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    // Owned by the agent uid, because WORKDIR is where every exec lands and a root-owned
295    // one fails a demoted workload at its first write (docs/EMBEDDING.md).
296    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/// Model access for the agents: a Bedrock bearer token minted for a region.
314///
315/// A struct rather than an enum until a second access path exists to name
316/// (`docs/AGENT-VMS.md`, phase 2).
317#[derive(Clone, Debug)]
318pub struct BedrockAccess {
319    pub region: Region,
320    pub token: BearerToken,
321}
322
323/// One file to place in the guest.
324#[derive(Clone, Debug, Eq, PartialEq)]
325pub struct GuestFile {
326    pub path: String,
327    pub contents: Vec<u8>,
328    /// Octal, as the file route takes it.
329    pub mode: &'static str,
330}
331
332/// Wraps `value` in double quotes for `sh`, escaping the four characters that are
333/// special inside them. Used for the environment file, whose values are model ids, a
334/// region, and a token (base64 plus the prefix), none of which contain them today; the
335/// escaping is what keeps that "today" from mattering.
336pub 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
349/// Wraps `value` in single quotes for `sh`. A single quote inside becomes `'\''`, the
350/// one sequence that is literal under every POSIX shell. Used for the task text, which
351/// is the caller's prose and may contain anything.
352pub 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
366/// The files `install_access` places (AGENT-5, AGENT-6): the environment file, Codex's
367/// config when Codex is present, and the marker. Pure, so a test reads the exact bytes.
368pub 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    // PATH first and explicit: the daemon spawns execs from an empty environment, and
376    // Claude Code's Bash tool snapshots the shell it starts from, so without this line
377    // the agent's subshells find no `ls`, `wc`, or `python3`.
378    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        // World-readable is fine and useful: it names models, never a credential, and the
425        // agent itself may want to read it.
426        mode: "0644",
427    });
428    Ok(files)
429}
430
431/// Places the provisioning files and hands `/workspace` to the agent uid (AGENT-5).
432///
433/// The daemon writes every upload as root, so the `chown` is not optional and it runs
434/// as the daemon's own user, after the uploads, in one exec. Re-runnable: a second call
435/// with a fresh token overwrites the same files, which is how a 12-hour token is
436/// refreshed on a long-lived VM (AGENT-8).
437pub 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
473/// The agents a running VM was provisioned with, read from the guest marker (AGENT-10).
474///
475/// Answers from the VM rather than from a local record so a process that holds only
476/// the identifier triple can prompt correctly. A VM with no marker is one `agent-up`
477/// never provisioned, and the error says which command fixes that.
478pub 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
527/// Probe the installed executable as the guest agent UID, without sourcing credentials.
528/// Only a numeric version is returned; arbitrary guest stdout/stderr never enters reports.
529pub 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/// The knobs on one prompt.
570#[derive(Clone, Debug, Default)]
571pub struct PromptOptions {
572    /// A stable exec id, for a retry that must not spawn twice. `None` mints one.
573    pub exec_id: Option<String>,
574    /// A daemon-side wall-clock budget for the agent process. `None` leaves the exec
575    /// unbounded on the daemon's side; the caller's wait still has its own deadline.
576    pub timeout: Option<Duration>,
577    /// Guest agent permissions, independent of VM privileges. Defaults to agent-default.
578    pub permission_mode: AgentPermissionMode,
579    /// Terminate residual test servers/fuzzers when the main agent exits. Opt-in.
580    pub reap_group_on_exit: bool,
581}
582
583/// The start request for one task (AGENT-7). Pure; the test reads every field.
584pub 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        // Empty on the wire: the environment file is the environment, sourced by the
608        // command, so the token never rides in a request body.
609        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
618/// The headless command with `<TASK>` where the quoted task goes, for a caller who wants
619/// to run it through `exec --stream` or read what `prompt` would do.
620pub fn headless_command_template(agent: Agent) -> String {
621    format!(
622        ". {ENV_FILE} && {}",
623        profile::headless_command(agent, "'<TASK>'", AgentPermissionMode::AgentDefault)
624    )
625}
626
627/// Starts one task and returns its handle. Wait, stream, poll, or ack through the
628/// handle, exactly as for any other exec.
629pub 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
638/// One VM with coding agents in it: the [`Sandbox`] plus the specs it was built for.
639///
640/// Runtime-checked, like the sandbox it wraps, and for the same reason: one object is
641/// what the bindings can hold.
642pub 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    /// Wraps a sandbox for `specs`. Refuses an empty or repeated set.
658    pub fn new(sandbox: Sandbox, specs: Vec<AgentSpec>) -> Result<Self, Error> {
659        require_specs(&specs)?;
660        Ok(Self { sandbox, specs })
661    }
662
663    /// An agent VM for a VM another process launched; see [`Sandbox::adopt`].
664    ///
665    /// The specs are the caller's statement of what the VM carries, checked like
666    /// [`AgentVm::new`] checks them. Read [`installed_agents`] first when the adopting
667    /// process does not know.
668    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    /// Adopts the VM registered as `name` in `store`; see [`Sandbox::from_name`].
681    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    /// [`AgentVm::adopt`] over a plane resolved for `region`; the bindings' entry point.
694    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    /// The sandbox and specs, for a binding that holds them separately.
708    pub fn into_parts(self) -> (Sandbox, Vec<AgentSpec>) {
709        (self.sandbox, self.specs)
710    }
711
712    /// A VM for Claude Code with the profile's defaults.
713    pub fn claude_code(sandbox: Sandbox) -> Self {
714        Self {
715            sandbox,
716            specs: vec![AgentSpec::new(Agent::ClaudeCode)],
717        }
718    }
719
720    /// A VM for Codex with the profile's defaults.
721    pub fn codex(sandbox: Sandbox) -> Self {
722        Self {
723            sandbox,
724            specs: vec![AgentSpec::new(Agent::Codex)],
725        }
726    }
727
728    /// The specs this VM carries, in profile order.
729    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    /// The session, once [`AgentVm::launch`] has run.
742    pub fn session(&self) -> Option<&Session> {
743        self.sandbox.session()
744    }
745
746    /// The image name for these specs and this binary: the stem plus the first twelve
747    /// hex characters of the artifact content hash, so an unchanged binary and an
748    /// unchanged spec set name the image `build --reuse` would find (AGENT-3).
749    pub fn image_name(&self, request: &CreateImageRequest) -> String {
750        image_name_for(&self.sandbox, &self.specs, request)
751    }
752
753    /// The create request for this VM's image, named per [`AgentVm::image_name`].
754    ///
755    /// `code_artifact_uri` is left **empty** for the caller to fill: the upload is theirs
756    /// (S3 is not in this crate's dependency set), and the key they choose is usually
757    /// derived from the name this method just computed. `Sandbox::preflight` refuses a
758    /// request whose URI is still blank.
759    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    /// Builds the image. The caller has uploaded the artifact to the request's URI.
769    pub async fn build(&mut self, request: CreateImageRequest) -> Result<&Image, Error> {
770        self.sandbox.build_image(request).await
771    }
772
773    /// The launch request: egress on (AGENT-9), because neither agent reaches Bedrock
774    /// without it, and the token label set to the image name.
775    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    /// Launches and waits for the daemon to answer.
784    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    /// [`install_access`] on this VM's session.
802    pub async fn install_access(&self, access: &BedrockAccess) -> Result<(), Error> {
803        install_access(self.require_session()?, &self.specs, access).await
804    }
805
806    /// [`prompt`] on this VM's session, for one of the agents it carries.
807    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    /// Tears the VM down; see [`Sandbox::terminate`].
818    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    // ── the Dockerfile (AGENT-2) ─────────────────────────────────────────────
855
856    /// **The derived Dockerfile passes every guard preflight runs**, and carries the four
857    /// things the recipe needs: the layers, the user, the owned WORKDIR, the daemon lines.
858    ///
859    /// **Falsification** — drop the `chown` from the mkdir line and the ownership assert
860    /// goes red; emit the `dnf` line per profile and the count assert goes red; move
861    /// `WORKDIR` above the layers and the order assert goes red.
862    #[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    /// A version pin appears on the install line and nowhere else, so it changes the
900    /// Dockerfile text (and therefore the reuse hash) and nothing about the recipe.
901    #[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    /// The name stem is order-independent and spells the agents in profile order.
927    #[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    // ── the provisioning files (AGENT-5, AGENT-6) ────────────────────────────
937
938    /// **Claude alone gets two files; Codex adds its config.** The environment file sets
939    /// PATH and HOME, carries the token under each agent's variable, and every value is
940    /// double-quoted. The marker names the agents and their resolved models.
941    #[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    // ── install and read-back through the recorder ───────────────────────────
1021
1022    /// **The uploads go out in file order, then exactly one root chown.** The exec that
1023    /// hands the workspace over runs as the daemon's own user (no `user` on the wire),
1024    /// after every PUT.
1025    #[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    /// A failed chown is a failure, not a warning: a workspace the agent cannot write is
1070    /// a VM every prompt fails in.
1071    #[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    /// **The marker round-trips**: what `provisioning_files` wrote is what
1096    /// `installed_agents` reads back, models included.
1097    #[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    /// A VM with no marker is a precondition failure naming the command that writes one,
1118    /// and any other refusal propagates as itself.
1119    #[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    // ── the prompt (AGENT-7) ─────────────────────────────────────────────────
1134
1135    /// **Every field of the start request is the recipe's.** uid and gid 1000, the
1136    /// workspace as cwd, an empty wire env, the env file sourced first, the task
1137    /// single-quoted, the daemon-side timeout only when asked for.
1138    #[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    // ── AgentVm ──────────────────────────────────────────────────────────────
1196
1197    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    /// `AgentVm::adopt` checks the specs before any call, and adopts with the lifecycle the
1206    /// service reports.
1207    #[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    /// **The image request is named by content and the URI is left to the caller.**
1243    /// Same binary and specs give the same name; a different binary gives a different one.
1244    #[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    /// The named constructors carry the request's own names, and a prompt for an agent
1298    /// the VM does not carry is refused before any wire call.
1299    #[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    // Runs the rendered command through a real POSIX shell.
1382    #[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}