Skip to main content

smolvm_protocol/
lib.rs

1//! Protocol types for smolvm host-guest communication.
2//!
3//! This crate defines the wire protocol for vsock communication between
4//! the smolvm host and the guest agent (smolvm-agent).
5//!
6//! # Protocol Overview
7//!
8//! Communication uses JSON-encoded messages over vsock. Each message is
9//! prefixed with a 4-byte big-endian length header.
10//!
11//! ```text
12//! +----------------+-------------------+
13//! | Length (4 BE)  | JSON payload      |
14//! +----------------+-------------------+
15//! ```
16
17#![deny(missing_docs)]
18
19use serde::{Deserialize, Serialize};
20
21pub mod forkpoint;
22pub mod guest_env;
23pub mod image_ref;
24pub mod publish_socket;
25pub mod retry;
26pub mod secrets;
27
28pub use image_ref::{image_repo, normalize_image_ref};
29pub use secrets::{SecretRef, SecretSourceKind};
30
31/// Serde helper for encoding `Vec<u8>` as a base64 string in JSON.
32///
33/// Without this, serde_json serializes `Vec<u8>` as a JSON array of numbers
34/// (e.g., `[104,101,108,108,111]`), which inflates binary data by ~4x.
35/// Base64 encoding reduces this to ~1.33x.
36pub mod base64_bytes {
37    use base64::{engine::general_purpose::STANDARD, Engine};
38    use serde::{Deserialize, Deserializer, Serializer};
39
40    /// Serialize `Vec<u8>` as a base64 string.
41    pub fn serialize<S: Serializer>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
42        serializer.serialize_str(&STANDARD.encode(data))
43    }
44
45    /// Deserialize a base64 string into `Vec<u8>`.
46    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
47        let s = String::deserialize(deserializer)?;
48        STANDARD.decode(&s).map_err(serde::de::Error::custom)
49    }
50}
51
52/// Protocol version.
53pub const PROTOCOL_VERSION: u32 = 1;
54
55/// virtiofs tag under which the host exposes the Rosetta 2 Linux runtime to the
56/// guest. Shared host↔guest so the launcher's `krun_add_virtiofs` tag and the
57/// guest agent's `mount -t virtiofs` source can't drift apart.
58pub const ROSETTA_TAG: &str = "rosetta";
59
60/// Guest mount point for the Rosetta 2 Linux runtime. The ptrace wrapper execs
61/// `<ROSETTA_GUEST_PATH>/rosetta` (the translator), so this path is baked into
62/// both the wrapper and the `binfmt_misc` registration.
63pub const ROSETTA_GUEST_PATH: &str = "/mnt/rosetta";
64
65/// Maximum frame size (32 MB - layer exports use chunked streaming).
66pub const MAX_FRAME_SIZE: u32 = 32 * 1024 * 1024;
67
68/// Chunk size for streaming layer data (~16 MB raw, ~21 MB as base64 JSON).
69pub const LAYER_CHUNK_SIZE: usize = 16 * 1024 * 1024;
70
71/// Files at or below this size are written with a single `FileWrite`
72/// message. Larger files must stream via
73/// `FileWriteBegin` + `FileWriteChunk` so no single frame approaches
74/// [`MAX_FRAME_SIZE`] (base64 + JSON inflation is ~1.4x).
75///
76/// Chosen to keep the single-shot frame comfortably under the frame
77/// limit while preserving the fast-path latency for small config
78/// files / scripts / keys.
79pub const FILE_WRITE_SINGLE_SHOT_MAX: usize = 1024 * 1024;
80
81/// Payload bytes per streaming upload chunk. Deliberately small —
82/// equal to [`FILE_WRITE_SINGLE_SHOT_MAX`] — so each chunk's encoded
83/// frame (~1.4 MB) fits inside typical kernel Unix-socket send
84/// buffers (`SO_SNDBUF` defaults on the order of 200–256 KiB but
85/// can grow). Larger chunks would force `write_all` to spin waiting
86/// for the agent to drain, and any latency spike trips the 10 s
87/// write timeout with `EAGAIN` — exactly the failure David
88/// reproduced before this fix landed.
89///
90/// Note: [`LAYER_CHUNK_SIZE`] is 16 MiB for agent→host (download)
91/// streaming, which works because the host side of the socket has
92/// more headroom than the guest side. Upload streaming is the
93/// asymmetric case and needs a smaller chunk.
94pub const FILE_WRITE_CHUNK_SIZE: usize = FILE_WRITE_SINGLE_SHOT_MAX;
95
96// The single-shot threshold must be <= the chunk size. They can be equal (a
97// 1 MiB file is a single shot; a 1 MiB + 1 byte file streams as two chunks),
98// but SINGLE_SHOT > CHUNK would be incoherent — a file slightly over the shot
99// threshold would have to stream as a single oversized chunk. Enforced at
100// compile time so a bad edit fails the build rather than a test.
101const _: () = assert!(FILE_WRITE_SINGLE_SHOT_MAX <= FILE_WRITE_CHUNK_SIZE);
102
103/// Hard ceiling on a single file transfer in either direction.
104///
105/// On the write path: enforced at `FileWriteBegin` by the agent —
106/// `total_size > FILE_TRANSFER_MAX_TOTAL` is rejected before any
107/// staging file is created.
108///
109/// On the read path: enforced by the host's `read_file` loop —
110/// after the first chunk that pushes the accumulated total past the
111/// cap, the call bails with an error and the partial buffer is
112/// dropped. This protects the host process from OOM if the guest
113/// (compromised or merely buggy) streams unbounded data.
114///
115/// 4 GiB matches the order-of-magnitude of the default overlay disk and the
116/// `gpu_vram_mib` cap. It is the compiled-in default. The host-side transfer
117/// paths (read/export, including `pack create --from-vm`) raise it at runtime
118/// via `SMOLVM_FILE_TRANSFER_MAX_BYTES` (see
119/// `agent::client::file_transfer_max_total`) so a VM snapshot whose overlay
120/// carries a large dependency tree (e.g. a torch + CUDA-wheels environment is
121/// ~5 GiB) can be packed without lowering the DoS bound for everyone else. The
122/// guest agent's write-path check runs inside the VM and cannot see that host
123/// env var, so it always enforces this const. Callers that need to move larger
124/// blobs routinely should stage via a virtiofs mount instead of `cp`.
125pub const FILE_TRANSFER_MAX_TOTAL: u64 = 4 * 1024 * 1024 * 1024;
126
127/// Filename of the virtiofs-visible marker the agent creates when it is
128/// ready to accept vsock connections.
129///
130/// The host polls for this file through its virtiofs mount of the guest
131/// rootfs. The agent writes it (and optionally a symlink from `/oldroot/`)
132/// during deferred init, just before opening the vsock listener.
133///
134/// Both sides must agree on this name; keeping it here prevents silent drift.
135pub const AGENT_READY_MARKER: &str = ".smolvm-ready";
136
137/// Well-known vsock ports.
138pub mod ports {
139    /// Control channel for workload VMs.
140    pub const WORKLOAD_CONTROL: u32 = 5000;
141    /// Log streaming from workload VMs.
142    pub const WORKLOAD_LOGS: u32 = 5001;
143    /// Agent control port (for OCI operations and management).
144    pub const AGENT_CONTROL: u32 = 6000;
145    /// SSH agent forwarding (host SSH_AUTH_SOCK bridged to guest).
146    pub const SSH_AGENT: u32 = 6001;
147    /// DNS filtering proxy (guest forwards DNS queries to host for filtering).
148    pub const DNS_FILTER: u32 = 6002;
149    /// Docker socket bridge: the guest listens on this vsock port and proxies
150    /// each connection to the in-guest `/var/run/docker.sock`, so the host can
151    /// reach the guest's Docker daemon over a host-side Unix socket
152    /// (`DOCKER_HOST=unix://…`). Inbound (host connects in), like the agent
153    /// control channel — unlike the outbound SSH/DNS/CUDA bridges.
154    pub const DOCKER: u32 = 6003;
155    /// Readiness doorbell: the guest connects OUT to this host port the instant it
156    /// finishes init, and the host's `accept()` fires — an event-driven readiness
157    /// signal that needs no writable filesystem, DAX window, or extra virtio
158    /// device. Outbound (guest connects in), like the SSH/DNS/CUDA bridges. The
159    /// primary readiness signal; the ready-marker file and the control-channel
160    /// ping remain as fallbacks. A fork clone resumes past the ring, so it never
161    /// dials this — clones detect readiness by pinging the restored agent.
162    pub const AGENT_READY: u32 = 6004;
163    /// CUDA-over-vsock (experimental): guest CUDA client forwards Driver-API
164    /// calls to a host CUDA server that runs them on the host NVIDIA GPU.
165    pub const CUDA: u32 = 7000;
166
167    /// Base vsock port for user-published Unix-socket bridges
168    /// (`--expose-socket` / `--mount-socket`). Each published socket is assigned
169    /// `PUBLISH_SOCKET_BASE + index`. Kept clear of the fixed ports above (and of
170    /// CUDA at 7000) so a reasonable number of sockets never collides.
171    pub const PUBLISH_SOCKET_BASE: u32 = 6100;
172
173    /// Maximum number of user-published sockets per VM. Bounds the vsock-port
174    /// window (`6100..6100+MAX`) below CUDA's 7000.
175    pub const PUBLISH_SOCKET_MAX: usize = 64;
176}
177
178/// vsock CID constants.
179pub mod cid {
180    /// Host CID (always 2).
181    pub const HOST: u32 = 2;
182    /// Guest CID (always 3 for the first/only guest).
183    pub const GUEST: u32 = 3;
184    /// Any CID (for listening).
185    pub const ANY: u32 = u32::MAX;
186}
187
188/// fsnotify event masks, mirroring the kernel's `FS_*` bits in
189/// `include/linux/fsnotify_backend.h`. Shared by the host watcher (which maps a
190/// host filesystem event to one of these) and the guest agent (which forwards
191/// the raw bits to `/proc/smolvm-fsnotify`). Only the subset relevant to
192/// file-watching tools is defined.
193pub mod fsnotify_mask {
194    /// File was modified.
195    pub const FS_MODIFY: u32 = 0x0000_0002;
196    /// Metadata changed (chmod/chown/utimes).
197    pub const FS_ATTRIB: u32 = 0x0000_0004;
198    /// Writable file was closed.
199    pub const FS_CLOSE_WRITE: u32 = 0x0000_0008;
200    /// File was moved away from the watched dir.
201    pub const FS_MOVED_FROM: u32 = 0x0000_0040;
202    /// File was moved into the watched dir.
203    pub const FS_MOVED_TO: u32 = 0x0000_0080;
204    /// Subfile was created.
205    pub const FS_CREATE: u32 = 0x0000_0100;
206    /// Subfile was deleted.
207    pub const FS_DELETE: u32 = 0x0000_0200;
208    /// Event occurred against a directory.
209    pub const FS_ISDIR: u32 = 0x4000_0000;
210}
211
212/// A single host-originated filesystem change to replay into the guest.
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct FsNotifyEvent {
215    /// Guest-side absolute path the event occurred on (virtiofs staging path).
216    pub path: String,
217    /// `fsnotify_mask::FS_*` bitmask for the event.
218    pub mask: u32,
219}
220
221// ============================================================================
222// Agent Protocol (OCI Operations)
223// ============================================================================
224
225/// Agent request types (for image management and OCI operations).
226#[derive(Debug, Clone, Serialize, Deserialize)]
227#[serde(tag = "method", rename_all = "snake_case")]
228pub enum AgentRequest {
229    /// Ping to check if agent is alive.
230    Ping,
231
232    /// Inject host-originated fsnotify events into the guest.
233    ///
234    /// virtiofs does not deliver host-side file changes to the guest as
235    /// fsnotify/inotify events, so inotify-based hot-reload (Vite, webpack,
236    /// nodemon) never fires when a mounted file is edited on the host. The host
237    /// watches the mount source and sends the resulting events here; the agent
238    /// writes them to `/proc/smolvm-fsnotify`, which fires the matching event on
239    /// the guest inode so watchers on the (bind-mounted) container path wake up.
240    /// Each `path` is a guest-side absolute path (the virtiofs staging path),
241    /// `mask` an `fsnotify_mask::FS_*` bitmask.
242    FsNotify {
243        /// Host-originated filesystem changes to replay as guest fsnotify events.
244        #[serde(default)]
245        events: Vec<FsNotifyEvent>,
246    },
247
248    /// Pull an OCI image and extract layers.
249    Pull {
250        /// Image reference (e.g., "alpine:latest", "docker.io/library/ubuntu:22.04").
251        image: String,
252        /// OCI platform to pull (e.g., "linux/arm64", "linux/amd64").
253        oci_platform: Option<String>,
254        /// Optional registry authentication credentials.
255        #[serde(default, skip_serializing_if = "Option::is_none")]
256        auth: Option<RegistryAuth>,
257        /// Proxy URL applied to the registry client (sets HTTP_PROXY and HTTPS_PROXY).
258        #[serde(default, skip_serializing_if = "Option::is_none")]
259        proxy: Option<String>,
260        /// Comma-separated NO_PROXY list of hosts/CIDRs that bypass the proxy.
261        #[serde(default, skip_serializing_if = "Option::is_none")]
262        no_proxy: Option<String>,
263    },
264
265    /// Query if an image exists locally.
266    Query {
267        /// Image reference.
268        image: String,
269    },
270
271    /// List all cached images.
272    ListImages,
273
274    /// Run garbage collection on unused layers.
275    GarbageCollect {
276        /// If true, only report what would be deleted.
277        dry_run: bool,
278        /// If true, delete all image manifests and configs first,
279        /// making all layers unreferenced so they get collected.
280        #[serde(default)]
281        purge_all: bool,
282    },
283
284    /// Prepare overlay rootfs for a workload.
285    PrepareOverlay {
286        /// Image reference.
287        image: String,
288        /// Unique workload ID for the overlay.
289        workload_id: String,
290    },
291
292    /// Clean up overlay rootfs for a workload.
293    CleanupOverlay {
294        /// Workload ID to clean up.
295        workload_id: String,
296    },
297
298    /// Format the storage disk (first-time setup).
299    FormatStorage,
300
301    /// Get storage disk status.
302    StorageStatus,
303
304    /// Test network connectivity directly from the agent (not via chroot).
305    /// Used to debug TSI networking.
306    NetworkTest {
307        /// URL to test (e.g., "http://1.1.1.1")
308        url: String,
309    },
310
311    /// Shutdown the agent.
312    Shutdown,
313
314    /// Export a layer as a tar archive.
315    ///
316    /// Used by `smolvm pack` to extract OCI layers for packaging.
317    /// The agent streams the layer tar data back via LayerData responses.
318    ExportLayer {
319        /// Image digest (sha256:...).
320        image_digest: String,
321        /// Layer index (0-based).
322        layer_index: usize,
323    },
324
325    /// Merge a stack of directories into a single tar archive.
326    ///
327    /// `pack create --from-vm` ships the machine's image layers plus whatever the
328    /// container has written since as ONE flattened layer. The merge has to apply
329    /// whiteouts and opaque markers exactly as the runtime would, so it is done
330    /// with a read-only overlay mount rather than a file copy.
331    ///
332    /// The agent owns this rather than the host driving `mount(8)` over `VmExec`,
333    /// because `mount(8)` rejects a `lowerdir=` value beyond ~255 bytes — about
334    /// three OCI layer paths — while the agent can append each layer separately
335    /// through the same `fsconfig` path the runtime container mount uses.
336    FlattenLayers {
337        /// Directories to merge, bottom -> top. Entries that are missing or empty
338        /// are dropped, so a caller may include a container overlay's upper dir
339        /// without first checking whether the machine ever wrote to it.
340        lowerdirs: Vec<String>,
341        /// Guest path to write the tar archive to.
342        output: String,
343    },
344
345    /// Execute a command directly in the VM (not in a container).
346    ///
347    /// This runs the command in the agent's Alpine rootfs without any
348    /// container isolation. Useful for VM-level operations and debugging.
349    VmExec {
350        /// Command and arguments.
351        command: Vec<String>,
352        /// Environment variables.
353        #[serde(default)]
354        env: Vec<(String, String)>,
355        /// Working directory in the VM.
356        workdir: Option<String>,
357        /// Timeout in milliseconds.
358        #[serde(default)]
359        timeout_ms: Option<u64>,
360        /// Interactive mode - stream I/O instead of buffering.
361        #[serde(default)]
362        interactive: bool,
363        /// Allocate a pseudo-TTY for the command.
364        #[serde(default)]
365        tty: bool,
366        /// Background mode - spawn and return PID immediately without waiting.
367        #[serde(default)]
368        background: bool,
369        /// Data to pipe to the command's stdin.
370        #[serde(default)]
371        stdin_data: Option<String>,
372    },
373
374    /// Run a command in an image's rootfs.
375    ///
376    /// This prepares an overlay, chroots into it, and executes the command.
377    /// Returns stdout, stderr, and exit code when the command completes.
378    Run {
379        /// Image reference (must be pulled first).
380        image: String,
381        /// Command and arguments.
382        command: Vec<String>,
383        /// Environment variables.
384        #[serde(default)]
385        env: Vec<(String, String)>,
386        /// Working directory inside the rootfs.
387        workdir: Option<String>,
388        /// User inside the rootfs. If omitted, the OCI image default applies.
389        #[serde(default, skip_serializing_if = "Option::is_none")]
390        user: Option<String>,
391        /// Volume mounts to bind into the container.
392        /// Each tuple is (virtiofs_tag, container_path, read_only).
393        #[serde(default)]
394        mounts: Vec<(String, String, bool)>,
395        /// Timeout in milliseconds. If the command exceeds this duration,
396        /// it will be killed and return exit code 124.
397        #[serde(default)]
398        timeout_ms: Option<u64>,
399        /// Interactive mode - stream I/O instead of buffering.
400        /// When true, output is streamed via Stdout/Stderr responses,
401        /// and stdin can be sent via the Stdin request.
402        #[serde(default)]
403        interactive: bool,
404        /// Allocate a pseudo-TTY for the command.
405        /// Enables terminal features like colors, line editing, and signal handling.
406        #[serde(default)]
407        tty: bool,
408        /// Detached mode — start the container and return immediately with the
409        /// container ID. Only meaningful when `persistent_overlay_id` is set.
410        /// Returns a `Completed` response with `stdout` containing the container ID.
411        #[serde(default)]
412        detached: bool,
413        /// Run the workload as an unprivileged container: restricted capabilities,
414        /// read-only cgroup, and no extra tmpfs. The default (false) is "VM-grade"
415        /// — since the microVM is the isolation boundary, the workload gets a full
416        /// capability set and the mounts an init system needs (so any image, incl.
417        /// systemd, boots). Opt in for defense-in-depth when running untrusted code.
418        #[serde(default)]
419        unprivileged: bool,
420        /// If set, use a persistent overlay that survives across exec sessions.
421        /// The overlay is identified by this ID (typically the machine name)
422        /// and reused on subsequent runs. If not set, an ephemeral overlay is
423        /// created and destroyed after the run.
424        #[serde(default, skip_serializing_if = "Option::is_none")]
425        persistent_overlay_id: Option<String>,
426        /// Data to pipe to the command's stdin (non-interactive runs only).
427        /// The pipe is closed after writing, so the command sees EOF.
428        #[serde(default, skip_serializing_if = "Option::is_none")]
429        stdin_data: Option<String>,
430        /// Spawn the container and return immediately with the crun PID.
431        /// The container runs detached; stdout/stderr go to /dev/null.
432        /// Incompatible with `interactive` and `tty`.
433        #[serde(default)]
434        background: bool,
435    },
436
437    /// Send stdin data to a running interactive command.
438    Stdin {
439        /// Input data to send to the command's stdin.
440        #[serde(with = "base64_bytes")]
441        data: Vec<u8>,
442    },
443
444    /// Resize the PTY window (for TTY mode).
445    Resize {
446        /// New width in columns.
447        cols: u16,
448        /// New height in rows.
449        rows: u16,
450    },
451
452    // ========================================================================
453    // File I/O
454    // ========================================================================
455    /// Write a file inside the VM in a single message.
456    ///
457    /// Use only for files up to [`FILE_WRITE_SINGLE_SHOT_MAX`]. Larger
458    /// files must stream via [`Self::FileWriteBegin`] +
459    /// [`Self::FileWriteChunk`] to avoid exceeding [`MAX_FRAME_SIZE`]
460    /// after base64 + JSON inflation.
461    FileWrite {
462        /// Absolute path in the VM filesystem.
463        path: String,
464        /// File contents.
465        #[serde(with = "base64_bytes")]
466        data: Vec<u8>,
467        /// File mode (e.g., 0o644). None = default (0644).
468        #[serde(default)]
469        mode: Option<u32>,
470    },
471
472    /// Open a streaming file upload session on this connection.
473    ///
474    /// Must be followed by one or more [`Self::FileWriteChunk`]
475    /// requests. The final chunk sets `done: true` to finalize.
476    /// Dropping the connection (or sending any non-chunk request)
477    /// before `done` aborts the session and leaves no partial file
478    /// at `path`.
479    ///
480    /// Sessions are per-connection — one session at a time.
481    FileWriteBegin {
482        /// Absolute path in the VM filesystem.
483        path: String,
484        /// File mode (e.g., 0o644). None = default (0644).
485        #[serde(default)]
486        mode: Option<u32>,
487        /// Expected total size in bytes. Rejected if it exceeds
488        /// [`FILE_TRANSFER_MAX_TOTAL`]. The agent uses this for an
489        /// early-fail check only; the actual size written is the sum
490        /// of chunk byte lengths.
491        total_size: u64,
492    },
493
494    /// Append a chunk to the currently open streaming upload.
495    /// If `done` is true, the agent fsyncs and atomically renames the
496    /// staging file onto the target path.
497    FileWriteChunk {
498        /// Chunk bytes. Typically [`FILE_WRITE_CHUNK_SIZE`] except
499        /// for the last chunk.
500        #[serde(with = "base64_bytes")]
501        data: Vec<u8>,
502        /// True on the final chunk; closes and renames the staging
503        /// file. False on intermediate chunks.
504        done: bool,
505    },
506
507    /// Read a file from the VM.
508    FileRead {
509        /// Absolute path in the VM filesystem.
510        path: String,
511    },
512
513    /// Create (without starting) a Kubernetes pod container whose rootfs is a
514    /// virtiofs-shared host directory (containerd snapshotter output) and whose
515    /// process definition comes from the host's OCI config. The agent builds
516    /// its crun bundle around the shared rootfs; nothing runs until
517    /// `PodStart`. Part of the containerd shim v2 datapath
518    /// (docs/kubernetes-runtime.md).
519    PodCreate {
520        /// Container ID (containerd task id).
521        id: String,
522        /// Rootfs path relative to the sandbox's shared virtiofs mount. The
523        /// shim boots the sandbox VM with ONE shared dir and bind-mounts each
524        /// container's rootfs under it (virtiofs shares are fixed at boot, but
525        /// pod containers are created afterwards), so the guest resolves this
526        /// as `<sandbox-share-mount>/<rootfs_rel>`.
527        rootfs_rel: String,
528        /// The host OCI runtime spec (config.json bytes). The agent extracts
529        /// process/env/cwd/user/mounts/resources and grafts them onto its own
530        /// guest bundle template; host-specific namespaces/paths are ignored.
531        spec_json: String,
532        /// Allocate a PTY for the init process.
533        #[serde(default)]
534        tty: bool,
535    },
536
537    /// Start a pod container created by `PodCreate` (or an exec process
538    /// registered by `PodExec`), streaming its I/O on THIS connection:
539    /// `Started` → `Stdout`/`Stderr`... → `Exited`. Stdin arrives via `Stdin`
540    /// requests; PTY resize via `Resize`.
541    PodStart {
542        /// Container ID.
543        id: String,
544        /// Exec process to start instead of the init process.
545        #[serde(default, skip_serializing_if = "Option::is_none")]
546        exec_id: Option<String>,
547    },
548
549    /// Register an exec process for a running pod container. Started later by
550    /// `PodStart { exec_id }`.
551    PodExec {
552        /// Container ID.
553        id: String,
554        /// Exec process ID (unique within the container).
555        exec_id: String,
556        /// OCI Process JSON (containerd's ExecProcessRequest spec).
557        process_json: String,
558        /// Allocate a PTY for the exec process.
559        #[serde(default)]
560        tty: bool,
561    },
562
563    /// Signal a pod container's init process (or one exec process).
564    PodSignal {
565        /// Container ID.
566        id: String,
567        /// Exec process to signal instead of init.
568        #[serde(default, skip_serializing_if = "Option::is_none")]
569        exec_id: Option<String>,
570        /// Signal number (SIGKILL = 9, SIGTERM = 15, ...).
571        signal: u32,
572        /// Signal the whole container process group.
573        #[serde(default)]
574        all: bool,
575    },
576
577    /// List PIDs inside a pod container (guest view).
578    PodPids {
579        /// Container ID.
580        id: String,
581    },
582
583    /// Sample a pod container's resource usage (guest view). The agent reads the
584    /// container's process tree from /proc (there is no per-container cgroup); the
585    /// shim maps the reply into containerd's cgroups metrics for CRI stats.
586    PodStats {
587        /// Container ID.
588        id: String,
589    },
590
591    /// Remove a pod container's (or exec process's) guest resources after
592    /// exit: bundle, cgroup, PTY. Exit status was already streamed by
593    /// `PodStart`'s `Exited`.
594    PodDelete {
595        /// Container ID.
596        id: String,
597        /// Exec process to remove instead of the whole container.
598        #[serde(default, skip_serializing_if = "Option::is_none")]
599        exec_id: Option<String>,
600    },
601}
602
603impl AgentRequest {
604    /// A log-safe one-line summary of the request.
605    ///
606    /// This string is written to the machine's console log, which is exposed
607    /// over the logs API — so it must NEVER include credential- or data-bearing
608    /// fields: registry `auth`, `env` (which can carry host-resolved secrets),
609    /// `proxy` (may embed credentials), or `data` (file/stdin bytes). Only the
610    /// variant name plus a non-secret identifier (image) is emitted.
611    ///
612    /// The match is exhaustive with no catch-all on purpose: adding a new
613    /// variant forces a compile error here, so redaction is a deliberate
614    /// decision rather than an accidental leak in some future request type.
615    pub fn log_summary(&self) -> String {
616        match self {
617            AgentRequest::Ping => "Ping".into(),
618            AgentRequest::FsNotify { events } => format!("FsNotify {{ count: {} }}", events.len()),
619            AgentRequest::Pull { image, .. } => format!("Pull {{ image: {image} }}"),
620            AgentRequest::Query { image, .. } => format!("Query {{ image: {image} }}"),
621            AgentRequest::ListImages => "ListImages".into(),
622            AgentRequest::GarbageCollect { .. } => "GarbageCollect".into(),
623            AgentRequest::PrepareOverlay { .. } => "PrepareOverlay".into(),
624            AgentRequest::CleanupOverlay { .. } => "CleanupOverlay".into(),
625            AgentRequest::FormatStorage => "FormatStorage".into(),
626            AgentRequest::StorageStatus => "StorageStatus".into(),
627            AgentRequest::NetworkTest { .. } => "NetworkTest".into(),
628            AgentRequest::Shutdown => "Shutdown".into(),
629            AgentRequest::ExportLayer { .. } => "ExportLayer".into(),
630            AgentRequest::FlattenLayers { lowerdirs, .. } => {
631                format!("FlattenLayers {{ count: {} }}", lowerdirs.len())
632            }
633            AgentRequest::VmExec { .. } => "VmExec".into(),
634            AgentRequest::Run { image, .. } => format!("Run {{ image: {image} }}"),
635            AgentRequest::Stdin { .. } => "Stdin".into(),
636            AgentRequest::Resize { .. } => "Resize".into(),
637            AgentRequest::FileWrite { .. } => "FileWrite".into(),
638            AgentRequest::FileWriteBegin { .. } => "FileWriteBegin".into(),
639            AgentRequest::FileWriteChunk { .. } => "FileWriteChunk".into(),
640            AgentRequest::FileRead { .. } => "FileRead".into(),
641            // Pod requests: spec/process JSON may carry env secrets — emit ids only.
642            AgentRequest::PodCreate { id, .. } => format!("PodCreate {{ id: {id} }}"),
643            AgentRequest::PodStart { id, exec_id } => match exec_id {
644                Some(e) => format!("PodStart {{ id: {id}, exec: {e} }}"),
645                None => format!("PodStart {{ id: {id} }}"),
646            },
647            AgentRequest::PodExec { id, exec_id, .. } => {
648                format!("PodExec {{ id: {id}, exec: {exec_id} }}")
649            }
650            AgentRequest::PodSignal {
651                id, signal, all, ..
652            } => format!("PodSignal {{ id: {id}, signal: {signal}, all: {all} }}"),
653            AgentRequest::PodPids { id } => format!("PodPids {{ id: {id} }}"),
654            AgentRequest::PodStats { id } => format!("PodStats {{ id: {id} }}"),
655            AgentRequest::PodDelete { id, exec_id } => match exec_id {
656                Some(e) => format!("PodDelete {{ id: {id}, exec: {e} }}"),
657                None => format!("PodDelete {{ id: {id} }}"),
658            },
659        }
660    }
661}
662
663/// Agent response types.
664#[derive(Debug, Clone, Serialize, Deserialize)]
665#[serde(tag = "status", rename_all = "snake_case")]
666pub enum AgentResponse {
667    /// Operation completed successfully.
668    Ok {
669        /// Response data (varies by request type).
670        #[serde(default, skip_serializing_if = "Option::is_none")]
671        data: Option<serde_json::Value>,
672    },
673
674    /// Pong response to ping.
675    Pong {
676        /// Protocol version.
677        version: u32,
678        /// Optional agent features that can evolve independently of the base protocol.
679        #[serde(default, skip_serializing_if = "Vec::is_empty")]
680        capabilities: Vec<String>,
681    },
682
683    /// Progress update (for long operations like pull).
684    Progress {
685        /// Human-readable message.
686        message: String,
687        /// Completion percentage (0-100).
688        #[serde(default, skip_serializing_if = "Option::is_none")]
689        percent: Option<u8>,
690        /// Current layer being processed.
691        #[serde(default, skip_serializing_if = "Option::is_none")]
692        layer: Option<String>,
693    },
694
695    /// Operation failed.
696    Error {
697        /// Error message.
698        message: String,
699        /// Error code (for programmatic handling).
700        #[serde(default, skip_serializing_if = "Option::is_none")]
701        code: Option<String>,
702    },
703
704    /// Command execution completed (non-interactive mode).
705    Completed {
706        /// Exit code from the command.
707        exit_code: i32,
708        /// Standard output (may be truncated). `Vec<u8>` preserves binary
709        /// output (image bytes, tarballs, etc.) that would be truncated by
710        /// `String` at the first non-UTF-8 byte. Serialized as base64 JSON
711        /// string — the same format as the streaming `Stdout` variant.
712        #[serde(with = "base64_bytes")]
713        stdout: Vec<u8>,
714        /// Standard error (may be truncated).
715        #[serde(with = "base64_bytes")]
716        stderr: Vec<u8>,
717    },
718
719    /// Command started (interactive mode).
720    /// Indicates the command is running and ready to receive stdin.
721    Started,
722
723    /// Stdout data from a running command (interactive mode).
724    Stdout {
725        /// Output data.
726        #[serde(with = "base64_bytes")]
727        data: Vec<u8>,
728    },
729
730    /// Stderr data from a running command (interactive mode).
731    Stderr {
732        /// Error output data.
733        #[serde(with = "base64_bytes")]
734        data: Vec<u8>,
735    },
736
737    /// Command exited (interactive mode).
738    Exited {
739        /// Exit code from the command.
740        exit_code: i32,
741        /// The container was terminated by the cgroup OOM killer. The shim
742        /// turns this into a TaskOOM event so the CRI reports
743        /// `reason=OOMKilled`. Only ever set on a pod container's init exit.
744        #[serde(default)]
745        oom: bool,
746    },
747
748    /// PIDs inside a pod container (`PodPids` reply).
749    Pids {
750        /// Guest PIDs, container-init first when known.
751        pids: Vec<u32>,
752    },
753
754    /// Resource usage sample for a pod container (`PodStats` reply). Summed over
755    /// the container's process tree read from /proc (no per-container cgroup).
756    Stats {
757        /// Cumulative CPU time of the process tree, in nanoseconds.
758        cpu_usage_ns: u64,
759        /// Resident memory of the process tree, in bytes.
760        memory_bytes: u64,
761    },
762
763    /// Streaming binary-data chunk.
764    ///
765    /// Used by every streaming download direction: the agent sends
766    /// one or more `DataChunk` responses in sequence, with `done: true`
767    /// on the final chunk. Current producers: `ExportLayer` and
768    /// `FileRead`.
769    ///
770    /// Payload size per chunk should stay under
771    /// [`LAYER_CHUNK_SIZE`] so the encoded frame (~1.33× after
772    /// base64) fits inside [`MAX_FRAME_SIZE`] with JSON overhead to
773    /// spare.
774    DataChunk {
775        /// Chunk bytes. Empty allowed on the final frame (common for
776        /// EOF-on-clean-boundary cases).
777        #[serde(with = "base64_bytes")]
778        data: Vec<u8>,
779        /// True on the final chunk of the stream.
780        done: bool,
781    },
782}
783
784// ============================================================================
785// Error Code Constants
786// ============================================================================
787//
788// Standard error codes for AgentResponse::Error. Using constants ensures
789// consistency across the codebase and makes error handling more reliable.
790
791/// Error codes for agent responses.
792pub mod error_codes {
793    /// Request payload was invalid or malformed.
794    pub const INVALID_REQUEST: &str = "INVALID_REQUEST";
795    /// Requested resource was not found.
796    pub const NOT_FOUND: &str = "NOT_FOUND";
797    /// Internal error during operation.
798    pub const INTERNAL_ERROR: &str = "INTERNAL_ERROR";
799    /// Image pull operation failed.
800    pub const PULL_FAILED: &str = "PULL_FAILED";
801    /// Image query operation failed.
802    pub const QUERY_FAILED: &str = "QUERY_FAILED";
803    /// Command execution failed.
804    pub const RUN_FAILED: &str = "RUN_FAILED";
805    /// Command execution failed in container.
806    pub const EXEC_FAILED: &str = "EXEC_FAILED";
807    /// Process spawn failed.
808    pub const SPAWN_FAILED: &str = "SPAWN_FAILED";
809    /// Mount operation failed.
810    pub const MOUNT_FAILED: &str = "MOUNT_FAILED";
811    /// File I/O operation failed.
812    pub const FILE_IO_FAILED: &str = "FILE_IO_FAILED";
813    /// Overlay filesystem operation failed.
814    pub const OVERLAY_FAILED: &str = "OVERLAY_FAILED";
815    /// Cleanup operation failed.
816    pub const CLEANUP_FAILED: &str = "CLEANUP_FAILED";
817    /// Storage format operation failed.
818    pub const FORMAT_FAILED: &str = "FORMAT_FAILED";
819    /// Storage status query failed.
820    pub const STATUS_FAILED: &str = "STATUS_FAILED";
821    /// List operation failed.
822    pub const LIST_FAILED: &str = "LIST_FAILED";
823    /// Garbage collection failed.
824    pub const GC_FAILED: &str = "GC_FAILED";
825    /// Container creation failed.
826    pub const CREATE_FAILED: &str = "CREATE_FAILED";
827    /// Container start failed.
828    pub const START_FAILED: &str = "START_FAILED";
829    /// Container stop failed.
830    pub const STOP_FAILED: &str = "STOP_FAILED";
831    /// Container delete failed.
832    pub const DELETE_FAILED: &str = "DELETE_FAILED";
833    /// Export operation failed.
834    pub const EXPORT_FAILED: &str = "EXPORT_FAILED";
835    /// Serialization error.
836    pub const SERIALIZATION_ERROR: &str = "SERIALIZATION_ERROR";
837    /// Message size exceeds maximum.
838    pub const MESSAGE_TOO_LARGE: &str = "MESSAGE_TOO_LARGE";
839    /// Process wait operation failed.
840    pub const WAIT_FAILED: &str = "WAIT_FAILED";
841}
842
843impl AgentResponse {
844    /// Create an error response with the given message and code.
845    ///
846    /// # Example
847    ///
848    /// ```
849    /// use smolvm_protocol::{AgentResponse, error_codes};
850    ///
851    /// let response = AgentResponse::error("image not found", error_codes::NOT_FOUND);
852    /// ```
853    pub fn error(message: impl Into<String>, code: &str) -> Self {
854        AgentResponse::Error {
855            message: message.into(),
856            code: Some(code.to_string()),
857        }
858    }
859
860    /// Create an error response from a Result's error, with the given code.
861    ///
862    /// # Example
863    ///
864    /// ```ignore
865    /// let response = some_operation()
866    ///     .map(|data| AgentResponse::ok_with_data(data))
867    ///     .unwrap_or_else(|e| AgentResponse::from_err(e, error_codes::PULL_FAILED));
868    /// ```
869    pub fn from_err<E: std::fmt::Display>(err: E, code: &str) -> Self {
870        AgentResponse::Error {
871            message: err.to_string(),
872            code: Some(code.to_string()),
873        }
874    }
875
876    /// Create an Ok response with optional JSON data.
877    pub fn ok(data: Option<serde_json::Value>) -> Self {
878        AgentResponse::Ok { data }
879    }
880
881    /// Create an Ok response with JSON-serializable data.
882    ///
883    /// Returns an error response if serialization fails.
884    pub fn ok_with_data<T: serde::Serialize>(data: T) -> Self {
885        match serde_json::to_value(data) {
886            Ok(value) => AgentResponse::Ok { data: Some(value) },
887            Err(e) => AgentResponse::error(
888                format!("failed to serialize response: {}", e),
889                error_codes::SERIALIZATION_ERROR,
890            ),
891        }
892    }
893
894    /// Convert a Result into an AgentResponse.
895    ///
896    /// On success, serializes the value to JSON. On error, creates an error response.
897    ///
898    /// # Example
899    ///
900    /// ```ignore
901    /// let response = AgentResponse::from_result(
902    ///     storage::pull_image(image),
903    ///     error_codes::PULL_FAILED,
904    /// );
905    /// ```
906    pub fn from_result<T, E>(result: Result<T, E>, error_code: &str) -> Self
907    where
908        T: serde::Serialize,
909        E: std::fmt::Display,
910    {
911        match result {
912            Ok(data) => Self::ok_with_data(data),
913            Err(e) => Self::from_err(e, error_code),
914        }
915    }
916}
917
918/// Image information returned by Query/ListImages.
919#[derive(Debug, Clone, Serialize, Deserialize)]
920pub struct ImageInfo {
921    /// Image reference.
922    pub reference: String,
923    /// Image digest (sha256:...).
924    pub digest: String,
925    /// Image size in bytes.
926    pub size: u64,
927    /// Creation timestamp (ISO 8601).
928    pub created: Option<String>,
929    /// Platform architecture.
930    pub architecture: String,
931    /// Platform OS.
932    pub os: String,
933    /// Number of layers.
934    pub layer_count: usize,
935    /// Layer digests in order.
936    pub layers: Vec<String>,
937    /// Image entrypoint (from OCI config).
938    #[serde(default)]
939    pub entrypoint: Vec<String>,
940    /// Image default command (from OCI config).
941    #[serde(default)]
942    pub cmd: Vec<String>,
943    /// Image environment variables (from OCI config).
944    #[serde(default)]
945    pub env: Vec<String>,
946    /// Image working directory (from OCI config).
947    #[serde(default)]
948    pub workdir: Option<String>,
949    /// Image default user (from OCI config).
950    #[serde(default)]
951    pub user: Option<String>,
952}
953
954/// Overlay preparation result.
955#[derive(Debug, Clone, Serialize, Deserialize)]
956pub struct OverlayInfo {
957    /// Path to the merged overlay rootfs.
958    pub rootfs_path: String,
959    /// Path to the upper (writable) directory.
960    pub upper_path: String,
961    /// Path to the work directory.
962    pub work_path: String,
963}
964
965/// Storage status information.
966#[derive(Debug, Clone, Serialize, Deserialize)]
967pub struct StorageStatus {
968    /// Whether the storage is formatted and ready.
969    pub ready: bool,
970    /// Total size in bytes.
971    pub total_bytes: u64,
972    /// Used size in bytes.
973    pub used_bytes: u64,
974    /// Number of cached layers.
975    pub layer_count: usize,
976    /// Number of cached images.
977    pub image_count: usize,
978}
979
980/// Registry authentication credentials for pulling images.
981///
982/// `Debug` is hand-written to redact the password: this value is carried inside
983/// `AgentRequest::Pull`, and any `{:?}` of that request (e.g. a tracing span)
984/// would otherwise serialize the token verbatim into the machine's console log,
985/// which is exposed over the logs API.
986#[derive(Clone, Serialize, Deserialize)]
987pub struct RegistryAuth {
988    /// Username for authentication.
989    pub username: String,
990    /// Password or token for authentication.
991    pub password: String,
992}
993
994impl std::fmt::Debug for RegistryAuth {
995    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
996        f.debug_struct("RegistryAuth")
997            .field("username", &self.username)
998            .field("password", &"***")
999            .finish()
1000    }
1001}
1002
1003// ============================================================================
1004// Workload VM Protocol (Command Execution)
1005// ============================================================================
1006
1007/// Messages from host to workload VM.
1008#[derive(Debug, Clone, Serialize, Deserialize)]
1009#[serde(tag = "type", rename_all = "snake_case")]
1010pub enum HostMessage {
1011    /// Authentication request.
1012    Auth {
1013        /// Authentication token (base64).
1014        token: String,
1015        /// Protocol version.
1016        protocol_version: u32,
1017    },
1018
1019    /// Run a command.
1020    Run {
1021        /// Request ID for correlating responses.
1022        request_id: u64,
1023        /// Command and arguments.
1024        command: Vec<String>,
1025        /// Environment variables.
1026        env: Vec<(String, String)>,
1027        /// Working directory.
1028        workdir: Option<String>,
1029    },
1030
1031    /// Execute a command in running VM.
1032    Exec {
1033        /// Request ID.
1034        request_id: u64,
1035        /// Command and arguments.
1036        command: Vec<String>,
1037        /// Allocate a TTY.
1038        tty: bool,
1039    },
1040
1041    /// Send a signal to a running command.
1042    Signal {
1043        /// Request ID of the command.
1044        request_id: u64,
1045        /// Signal number.
1046        signal: i32,
1047    },
1048
1049    /// Request graceful shutdown.
1050    Stop {
1051        /// Timeout in milliseconds.
1052        timeout_ms: u64,
1053    },
1054}
1055
1056/// Messages from workload VM to host.
1057#[derive(Debug, Clone, Serialize, Deserialize)]
1058#[serde(tag = "type", rename_all = "snake_case")]
1059pub enum GuestMessage {
1060    /// Authentication successful.
1061    AuthOk,
1062
1063    /// Authentication failed.
1064    AuthFailed,
1065
1066    /// VM is ready to receive commands.
1067    Ready,
1068
1069    /// Command started.
1070    Started {
1071        /// Request ID.
1072        request_id: u64,
1073    },
1074
1075    /// Stdout data from command.
1076    Stdout {
1077        /// Request ID.
1078        request_id: u64,
1079        /// Output data.
1080        #[serde(with = "base64_bytes")]
1081        data: Vec<u8>,
1082        /// Whether output was truncated.
1083        truncated: bool,
1084    },
1085
1086    /// Stderr data from command.
1087    Stderr {
1088        /// Request ID.
1089        request_id: u64,
1090        /// Output data.
1091        #[serde(with = "base64_bytes")]
1092        data: Vec<u8>,
1093        /// Whether output was truncated.
1094        truncated: bool,
1095    },
1096
1097    /// Command exited.
1098    Exit {
1099        /// Request ID.
1100        request_id: u64,
1101        /// Exit code.
1102        code: i32,
1103        /// Exit reason.
1104        reason: String,
1105    },
1106
1107    /// Error occurred.
1108    Error {
1109        /// Request ID (if applicable).
1110        request_id: Option<u64>,
1111        /// Error message.
1112        message: String,
1113    },
1114}
1115
1116// ============================================================================
1117// Wire Format Helpers
1118// ============================================================================
1119
1120/// Envelope that wraps any message with an optional trace ID for correlation.
1121///
1122/// On the wire, the trace_id is flattened into the JSON alongside the message
1123/// fields: `{"trace_id":"abc123","method":"ping"}`.
1124#[derive(Debug, Clone, Serialize, Deserialize)]
1125pub struct Envelope<T> {
1126    /// Trace ID for correlating host API requests to agent operations.
1127    #[serde(skip_serializing_if = "Option::is_none", default)]
1128    pub trace_id: Option<String>,
1129    /// The wrapped message.
1130    #[serde(flatten)]
1131    pub body: T,
1132}
1133
1134impl<T> Envelope<T> {
1135    /// Create an envelope with no trace ID.
1136    pub fn new(body: T) -> Self {
1137        Self {
1138            trace_id: None,
1139            body,
1140        }
1141    }
1142
1143    /// Create an envelope with an optional trace ID.
1144    pub fn with_trace_id(body: T, trace_id: Option<String>) -> Self {
1145        Self { trace_id, body }
1146    }
1147}
1148
1149/// Encode a message to wire format (length-prefixed JSON).
1150pub fn encode_message<T: Serialize>(msg: &T) -> Result<Vec<u8>, serde_json::Error> {
1151    let json = serde_json::to_vec(msg)?;
1152    let len = json.len() as u32;
1153
1154    let mut buf = Vec::with_capacity(4 + json.len());
1155    buf.extend_from_slice(&len.to_be_bytes());
1156    buf.extend_from_slice(&json);
1157
1158    Ok(buf)
1159}
1160
1161/// Decode a message from wire format.
1162pub fn decode_message<T: for<'de> Deserialize<'de>>(data: &[u8]) -> Result<T, DecodeError> {
1163    if data.len() < 4 {
1164        return Err(DecodeError::TooShort);
1165    }
1166
1167    let len = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
1168
1169    if len > MAX_FRAME_SIZE as usize {
1170        return Err(DecodeError::TooLarge(len));
1171    }
1172
1173    if data.len() < 4 + len {
1174        return Err(DecodeError::Incomplete {
1175            expected: len,
1176            got: data.len() - 4,
1177        });
1178    }
1179
1180    serde_json::from_slice(&data[4..4 + len]).map_err(DecodeError::Json)
1181}
1182
1183/// Error decoding a wire message.
1184#[derive(Debug)]
1185pub enum DecodeError {
1186    /// Data too short to contain length header.
1187    TooShort,
1188    /// Frame size exceeds maximum.
1189    TooLarge(usize),
1190    /// Incomplete frame.
1191    Incomplete {
1192        /// Expected length.
1193        expected: usize,
1194        /// Actual length.
1195        got: usize,
1196    },
1197    /// JSON parse error.
1198    Json(serde_json::Error),
1199}
1200
1201impl std::fmt::Display for DecodeError {
1202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1203        match self {
1204            DecodeError::TooShort => write!(f, "data too short for length header"),
1205            DecodeError::TooLarge(size) => write!(f, "frame too large: {} bytes", size),
1206            DecodeError::Incomplete { expected, got } => {
1207                write!(
1208                    f,
1209                    "incomplete frame: expected {} bytes, got {}",
1210                    expected, got
1211                )
1212            }
1213            DecodeError::Json(e) => write!(f, "JSON decode error: {}", e),
1214        }
1215    }
1216}
1217
1218impl std::error::Error for DecodeError {}
1219
1220#[cfg(test)]
1221mod tests {
1222    use super::*;
1223
1224    #[test]
1225    fn test_encode_decode_roundtrip() {
1226        let req = AgentRequest::Pull {
1227            image: "alpine:latest".to_string(),
1228            oci_platform: Some("linux/arm64".to_string()),
1229            auth: None,
1230            proxy: None,
1231            no_proxy: None,
1232        };
1233
1234        let encoded = encode_message(&req).unwrap();
1235        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1236
1237        let AgentRequest::Pull {
1238            image,
1239            oci_platform,
1240            auth,
1241            proxy,
1242            no_proxy,
1243        } = decoded
1244        else {
1245            panic!("expected Pull variant, got {:?}", decoded);
1246        };
1247        assert_eq!(image, "alpine:latest");
1248        assert_eq!(oci_platform, Some("linux/arm64".to_string()));
1249        assert!(auth.is_none());
1250        assert!(proxy.is_none());
1251        assert!(no_proxy.is_none());
1252    }
1253
1254    #[test]
1255    fn test_encode_decode_with_auth() {
1256        let req = AgentRequest::Pull {
1257            image: "ghcr.io/owner/repo:latest".to_string(),
1258            oci_platform: None,
1259            auth: Some(RegistryAuth {
1260                username: "testuser".to_string(),
1261                password: "testpass".to_string(),
1262            }),
1263            proxy: None,
1264            no_proxy: None,
1265        };
1266
1267        let encoded = encode_message(&req).unwrap();
1268        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1269
1270        let AgentRequest::Pull {
1271            image,
1272            oci_platform,
1273            auth,
1274            proxy: _,
1275            no_proxy: _,
1276        } = decoded
1277        else {
1278            panic!("expected Pull variant, got {:?}", decoded);
1279        };
1280        assert_eq!(image, "ghcr.io/owner/repo:latest");
1281        assert!(oci_platform.is_none());
1282        let auth = auth.expect("auth should be Some");
1283        assert_eq!(auth.username, "testuser");
1284        assert_eq!(auth.password, "testpass");
1285    }
1286
1287    #[test]
1288    fn test_encode_decode_with_proxy() {
1289        let req = AgentRequest::Pull {
1290            image: "alpine:latest".to_string(),
1291            oci_platform: None,
1292            auth: None,
1293            proxy: Some("http://192.168.127.254:3128".to_string()),
1294            no_proxy: Some("127.0.0.1,localhost,.internal".to_string()),
1295        };
1296
1297        let encoded = encode_message(&req).unwrap();
1298        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1299
1300        let AgentRequest::Pull {
1301            proxy, no_proxy, ..
1302        } = decoded
1303        else {
1304            panic!("expected Pull variant, got {:?}", decoded);
1305        };
1306        assert_eq!(proxy.as_deref(), Some("http://192.168.127.254:3128"));
1307        assert_eq!(no_proxy.as_deref(), Some("127.0.0.1,localhost,.internal"));
1308    }
1309
1310    #[test]
1311    fn test_decode_too_short() {
1312        let data = [0u8; 2];
1313        let result: Result<AgentRequest, _> = decode_message(&data);
1314        assert!(matches!(result, Err(DecodeError::TooShort)));
1315    }
1316
1317    #[test]
1318    fn test_decode_incomplete() {
1319        let mut data = vec![0, 0, 0, 100]; // claims 100 bytes
1320        data.extend_from_slice(b"{}"); // only 2 bytes of payload
1321        let result: Result<AgentRequest, _> = decode_message(&data);
1322        assert!(matches!(result, Err(DecodeError::Incomplete { .. })));
1323    }
1324
1325    #[test]
1326    fn test_agent_request_serialization() {
1327        let req = AgentRequest::Ping;
1328        let json = serde_json::to_string(&req).unwrap();
1329        assert!(json.contains("ping"));
1330
1331        let req = AgentRequest::PrepareOverlay {
1332            image: "ubuntu:22.04".to_string(),
1333            workload_id: "wl-123".to_string(),
1334        };
1335        let json = serde_json::to_string(&req).unwrap();
1336        assert!(json.contains("prepare_overlay"));
1337    }
1338
1339    #[test]
1340    fn test_agent_response_serialization() {
1341        let resp = AgentResponse::Pong {
1342            version: PROTOCOL_VERSION,
1343            capabilities: vec![forkpoint::WORKER_READY_CAPABILITY.to_string()],
1344        };
1345        let json = serde_json::to_string(&resp).unwrap();
1346        assert!(json.contains("pong"));
1347        assert!(json.contains(forkpoint::WORKER_READY_CAPABILITY));
1348
1349        let legacy: AgentResponse =
1350            serde_json::from_str(r#"{"status":"pong","version":1}"#).unwrap();
1351        assert!(matches!(
1352            legacy,
1353            AgentResponse::Pong {
1354                version: PROTOCOL_VERSION,
1355                capabilities
1356            } if capabilities.is_empty()
1357        ));
1358
1359        let resp = AgentResponse::Progress {
1360            message: "Pulling layer 1/3".to_string(),
1361            percent: Some(33),
1362            layer: Some("sha256:abc123".to_string()),
1363        };
1364        let json = serde_json::to_string(&resp).unwrap();
1365        assert!(json.contains("progress"));
1366    }
1367
1368    #[test]
1369    fn file_write_begin_roundtrips() {
1370        let req = AgentRequest::FileWriteBegin {
1371            path: "/tmp/target".into(),
1372            mode: Some(0o600),
1373            total_size: 123_456_789,
1374        };
1375        let bytes = encode_message(&req).unwrap();
1376        let back: AgentRequest = decode_message(&bytes).unwrap();
1377        match back {
1378            AgentRequest::FileWriteBegin {
1379                path,
1380                mode,
1381                total_size,
1382            } => {
1383                assert_eq!(path, "/tmp/target");
1384                assert_eq!(mode, Some(0o600));
1385                assert_eq!(total_size, 123_456_789);
1386            }
1387            _ => panic!("wrong variant"),
1388        }
1389    }
1390
1391    #[test]
1392    fn file_write_chunk_roundtrips_binary_data() {
1393        // Binary data (bytes outside UTF-8) must survive the base64
1394        // trip intact. If the encoding ever silently lossifies, this
1395        // fires.
1396        let payload: Vec<u8> = (0u8..=255).collect();
1397        let req = AgentRequest::FileWriteChunk {
1398            data: payload.clone(),
1399            done: true,
1400        };
1401        let bytes = encode_message(&req).unwrap();
1402        let back: AgentRequest = decode_message(&bytes).unwrap();
1403        match back {
1404            AgentRequest::FileWriteChunk { data, done } => {
1405                assert_eq!(data, payload);
1406                assert!(done);
1407            }
1408            _ => panic!("wrong variant"),
1409        }
1410    }
1411
1412    #[test]
1413    fn file_write_size_constants_are_frame_safe() {
1414        // Sanity: a single streaming chunk at FILE_WRITE_CHUNK_SIZE
1415        // must fit inside MAX_FRAME_SIZE after base64 (+ ~33%) and
1416        // JSON overhead. If anyone bumps CHUNK_SIZE past the limit,
1417        // this test fires before production does.
1418        let chunk_bytes = FILE_WRITE_CHUNK_SIZE as u64;
1419        let base64_bytes = chunk_bytes.div_ceil(3) * 4; // ceil(n/3)*4
1420        let json_overhead = 256u64; // method tag, done bool, quotes
1421        let total = base64_bytes + json_overhead;
1422        assert!(
1423            total < MAX_FRAME_SIZE as u64,
1424            "FILE_WRITE_CHUNK_SIZE of {} bytes would produce a frame \
1425             of ~{} bytes which exceeds MAX_FRAME_SIZE of {}",
1426            chunk_bytes,
1427            total,
1428            MAX_FRAME_SIZE
1429        );
1430    }
1431
1432    #[test]
1433    fn test_ports_constants() {
1434        assert_eq!(ports::WORKLOAD_CONTROL, 5000);
1435        assert_eq!(ports::WORKLOAD_LOGS, 5001);
1436        assert_eq!(ports::AGENT_CONTROL, 6000);
1437        assert_eq!(ports::SSH_AGENT, 6001);
1438    }
1439
1440    #[test]
1441    fn test_cid_constants() {
1442        assert_eq!(cid::HOST, 2);
1443        assert_eq!(cid::GUEST, 3);
1444    }
1445
1446    #[test]
1447    fn test_envelope_serialization_with_trace_id() {
1448        let req = AgentRequest::Ping;
1449        let envelope = Envelope::with_trace_id(&req, Some("abc123".to_string()));
1450        let json = serde_json::to_string(&envelope).unwrap();
1451
1452        // trace_id should be flattened alongside the method tag
1453        assert!(json.contains("\"trace_id\":\"abc123\""));
1454        assert!(json.contains("\"method\":\"ping\""));
1455
1456        // Deserialize back — Envelope<AgentRequest> with flatten
1457        let parsed: Envelope<AgentRequest> = serde_json::from_str(&json).unwrap();
1458        assert_eq!(parsed.trace_id.as_deref(), Some("abc123"));
1459        assert!(matches!(parsed.body, AgentRequest::Ping));
1460    }
1461
1462    #[test]
1463    fn test_envelope_without_trace_id() {
1464        let req = AgentRequest::Ping;
1465        let envelope = Envelope::new(&req);
1466        let json = serde_json::to_string(&envelope).unwrap();
1467
1468        // No trace_id field (skip_serializing_if = None)
1469        assert!(!json.contains("trace_id"));
1470        assert!(json.contains("\"method\":\"ping\""));
1471    }
1472
1473    #[test]
1474    fn test_envelope_backward_compat_bare_request() {
1475        // A bare AgentRequest (no Envelope) should fail to parse as Envelope
1476        // but succeed as bare AgentRequest — this is the agent's fallback path
1477        let bare_json = r#"{"method":"ping"}"#;
1478
1479        // Envelope parse should fail (no body field to flatten into)
1480        // Actually with flatten, this may work — let's verify
1481        let envelope_result = serde_json::from_str::<Envelope<AgentRequest>>(bare_json);
1482        let bare_result = serde_json::from_str::<AgentRequest>(bare_json);
1483
1484        // At least one must succeed for backward compat
1485        assert!(
1486            envelope_result.is_ok() || bare_result.is_ok(),
1487            "Neither Envelope nor bare parse succeeded"
1488        );
1489
1490        // Bare parse must always work
1491        assert!(bare_result.is_ok());
1492        assert!(matches!(bare_result.unwrap(), AgentRequest::Ping));
1493
1494        // If Envelope works, trace_id should be None
1495        if let Ok(env) = envelope_result {
1496            assert!(env.trace_id.is_none());
1497        }
1498    }
1499}