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