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    /// Execute a command directly in the VM (not in a container).
326    ///
327    /// This runs the command in the agent's Alpine rootfs without any
328    /// container isolation. Useful for VM-level operations and debugging.
329    VmExec {
330        /// Command and arguments.
331        command: Vec<String>,
332        /// Environment variables.
333        #[serde(default)]
334        env: Vec<(String, String)>,
335        /// Working directory in the VM.
336        workdir: Option<String>,
337        /// Timeout in milliseconds.
338        #[serde(default)]
339        timeout_ms: Option<u64>,
340        /// Interactive mode - stream I/O instead of buffering.
341        #[serde(default)]
342        interactive: bool,
343        /// Allocate a pseudo-TTY for the command.
344        #[serde(default)]
345        tty: bool,
346        /// Background mode - spawn and return PID immediately without waiting.
347        #[serde(default)]
348        background: bool,
349        /// Data to pipe to the command's stdin.
350        #[serde(default)]
351        stdin_data: Option<String>,
352    },
353
354    /// Run a command in an image's rootfs.
355    ///
356    /// This prepares an overlay, chroots into it, and executes the command.
357    /// Returns stdout, stderr, and exit code when the command completes.
358    Run {
359        /// Image reference (must be pulled first).
360        image: String,
361        /// Command and arguments.
362        command: Vec<String>,
363        /// Environment variables.
364        #[serde(default)]
365        env: Vec<(String, String)>,
366        /// Working directory inside the rootfs.
367        workdir: Option<String>,
368        /// User inside the rootfs. If omitted, the OCI image default applies.
369        #[serde(default, skip_serializing_if = "Option::is_none")]
370        user: Option<String>,
371        /// Volume mounts to bind into the container.
372        /// Each tuple is (virtiofs_tag, container_path, read_only).
373        #[serde(default)]
374        mounts: Vec<(String, String, bool)>,
375        /// Timeout in milliseconds. If the command exceeds this duration,
376        /// it will be killed and return exit code 124.
377        #[serde(default)]
378        timeout_ms: Option<u64>,
379        /// Interactive mode - stream I/O instead of buffering.
380        /// When true, output is streamed via Stdout/Stderr responses,
381        /// and stdin can be sent via the Stdin request.
382        #[serde(default)]
383        interactive: bool,
384        /// Allocate a pseudo-TTY for the command.
385        /// Enables terminal features like colors, line editing, and signal handling.
386        #[serde(default)]
387        tty: bool,
388        /// Detached mode — start the container and return immediately with the
389        /// container ID. Only meaningful when `persistent_overlay_id` is set.
390        /// Returns a `Completed` response with `stdout` containing the container ID.
391        #[serde(default)]
392        detached: bool,
393        /// Run the workload as an unprivileged container: restricted capabilities,
394        /// read-only cgroup, and no extra tmpfs. The default (false) is "VM-grade"
395        /// — since the microVM is the isolation boundary, the workload gets a full
396        /// capability set and the mounts an init system needs (so any image, incl.
397        /// systemd, boots). Opt in for defense-in-depth when running untrusted code.
398        #[serde(default)]
399        unprivileged: bool,
400        /// If set, use a persistent overlay that survives across exec sessions.
401        /// The overlay is identified by this ID (typically the machine name)
402        /// and reused on subsequent runs. If not set, an ephemeral overlay is
403        /// created and destroyed after the run.
404        #[serde(default, skip_serializing_if = "Option::is_none")]
405        persistent_overlay_id: Option<String>,
406        /// Data to pipe to the command's stdin (non-interactive runs only).
407        /// The pipe is closed after writing, so the command sees EOF.
408        #[serde(default, skip_serializing_if = "Option::is_none")]
409        stdin_data: Option<String>,
410        /// Spawn the container and return immediately with the crun PID.
411        /// The container runs detached; stdout/stderr go to /dev/null.
412        /// Incompatible with `interactive` and `tty`.
413        #[serde(default)]
414        background: bool,
415    },
416
417    /// Send stdin data to a running interactive command.
418    Stdin {
419        /// Input data to send to the command's stdin.
420        #[serde(with = "base64_bytes")]
421        data: Vec<u8>,
422    },
423
424    /// Resize the PTY window (for TTY mode).
425    Resize {
426        /// New width in columns.
427        cols: u16,
428        /// New height in rows.
429        rows: u16,
430    },
431
432    // ========================================================================
433    // File I/O
434    // ========================================================================
435    /// Write a file inside the VM in a single message.
436    ///
437    /// Use only for files up to [`FILE_WRITE_SINGLE_SHOT_MAX`]. Larger
438    /// files must stream via [`Self::FileWriteBegin`] +
439    /// [`Self::FileWriteChunk`] to avoid exceeding [`MAX_FRAME_SIZE`]
440    /// after base64 + JSON inflation.
441    FileWrite {
442        /// Absolute path in the VM filesystem.
443        path: String,
444        /// File contents.
445        #[serde(with = "base64_bytes")]
446        data: Vec<u8>,
447        /// File mode (e.g., 0o644). None = default (0644).
448        #[serde(default)]
449        mode: Option<u32>,
450    },
451
452    /// Open a streaming file upload session on this connection.
453    ///
454    /// Must be followed by one or more [`Self::FileWriteChunk`]
455    /// requests. The final chunk sets `done: true` to finalize.
456    /// Dropping the connection (or sending any non-chunk request)
457    /// before `done` aborts the session and leaves no partial file
458    /// at `path`.
459    ///
460    /// Sessions are per-connection — one session at a time.
461    FileWriteBegin {
462        /// Absolute path in the VM filesystem.
463        path: String,
464        /// File mode (e.g., 0o644). None = default (0644).
465        #[serde(default)]
466        mode: Option<u32>,
467        /// Expected total size in bytes. Rejected if it exceeds
468        /// [`FILE_TRANSFER_MAX_TOTAL`]. The agent uses this for an
469        /// early-fail check only; the actual size written is the sum
470        /// of chunk byte lengths.
471        total_size: u64,
472    },
473
474    /// Append a chunk to the currently open streaming upload.
475    /// If `done` is true, the agent fsyncs and atomically renames the
476    /// staging file onto the target path.
477    FileWriteChunk {
478        /// Chunk bytes. Typically [`FILE_WRITE_CHUNK_SIZE`] except
479        /// for the last chunk.
480        #[serde(with = "base64_bytes")]
481        data: Vec<u8>,
482        /// True on the final chunk; closes and renames the staging
483        /// file. False on intermediate chunks.
484        done: bool,
485    },
486
487    /// Read a file from the VM.
488    FileRead {
489        /// Absolute path in the VM filesystem.
490        path: String,
491    },
492
493    /// Create (without starting) a Kubernetes pod container whose rootfs is a
494    /// virtiofs-shared host directory (containerd snapshotter output) and whose
495    /// process definition comes from the host's OCI config. The agent builds
496    /// its crun bundle around the shared rootfs; nothing runs until
497    /// `PodStart`. Part of the containerd shim v2 datapath
498    /// (docs/kubernetes-runtime.md).
499    PodCreate {
500        /// Container ID (containerd task id).
501        id: String,
502        /// Rootfs path relative to the sandbox's shared virtiofs mount. The
503        /// shim boots the sandbox VM with ONE shared dir and bind-mounts each
504        /// container's rootfs under it (virtiofs shares are fixed at boot, but
505        /// pod containers are created afterwards), so the guest resolves this
506        /// as `<sandbox-share-mount>/<rootfs_rel>`.
507        rootfs_rel: String,
508        /// The host OCI runtime spec (config.json bytes). The agent extracts
509        /// process/env/cwd/user/mounts/resources and grafts them onto its own
510        /// guest bundle template; host-specific namespaces/paths are ignored.
511        spec_json: String,
512        /// Allocate a PTY for the init process.
513        #[serde(default)]
514        tty: bool,
515    },
516
517    /// Start a pod container created by `PodCreate` (or an exec process
518    /// registered by `PodExec`), streaming its I/O on THIS connection:
519    /// `Started` → `Stdout`/`Stderr`... → `Exited`. Stdin arrives via `Stdin`
520    /// requests; PTY resize via `Resize`.
521    PodStart {
522        /// Container ID.
523        id: String,
524        /// Exec process to start instead of the init process.
525        #[serde(default, skip_serializing_if = "Option::is_none")]
526        exec_id: Option<String>,
527    },
528
529    /// Register an exec process for a running pod container. Started later by
530    /// `PodStart { exec_id }`.
531    PodExec {
532        /// Container ID.
533        id: String,
534        /// Exec process ID (unique within the container).
535        exec_id: String,
536        /// OCI Process JSON (containerd's ExecProcessRequest spec).
537        process_json: String,
538        /// Allocate a PTY for the exec process.
539        #[serde(default)]
540        tty: bool,
541    },
542
543    /// Signal a pod container's init process (or one exec process).
544    PodSignal {
545        /// Container ID.
546        id: String,
547        /// Exec process to signal instead of init.
548        #[serde(default, skip_serializing_if = "Option::is_none")]
549        exec_id: Option<String>,
550        /// Signal number (SIGKILL = 9, SIGTERM = 15, ...).
551        signal: u32,
552        /// Signal the whole container process group.
553        #[serde(default)]
554        all: bool,
555    },
556
557    /// List PIDs inside a pod container (guest view).
558    PodPids {
559        /// Container ID.
560        id: String,
561    },
562
563    /// Sample a pod container's resource usage (guest view). The agent reads the
564    /// container's process tree from /proc (there is no per-container cgroup); the
565    /// shim maps the reply into containerd's cgroups metrics for CRI stats.
566    PodStats {
567        /// Container ID.
568        id: String,
569    },
570
571    /// Remove a pod container's (or exec process's) guest resources after
572    /// exit: bundle, cgroup, PTY. Exit status was already streamed by
573    /// `PodStart`'s `Exited`.
574    PodDelete {
575        /// Container ID.
576        id: String,
577        /// Exec process to remove instead of the whole container.
578        #[serde(default, skip_serializing_if = "Option::is_none")]
579        exec_id: Option<String>,
580    },
581}
582
583impl AgentRequest {
584    /// A log-safe one-line summary of the request.
585    ///
586    /// This string is written to the machine's console log, which is exposed
587    /// over the logs API — so it must NEVER include credential- or data-bearing
588    /// fields: registry `auth`, `env` (which can carry host-resolved secrets),
589    /// `proxy` (may embed credentials), or `data` (file/stdin bytes). Only the
590    /// variant name plus a non-secret identifier (image) is emitted.
591    ///
592    /// The match is exhaustive with no catch-all on purpose: adding a new
593    /// variant forces a compile error here, so redaction is a deliberate
594    /// decision rather than an accidental leak in some future request type.
595    pub fn log_summary(&self) -> String {
596        match self {
597            AgentRequest::Ping => "Ping".into(),
598            AgentRequest::FsNotify { events } => format!("FsNotify {{ count: {} }}", events.len()),
599            AgentRequest::Pull { image, .. } => format!("Pull {{ image: {image} }}"),
600            AgentRequest::Query { image, .. } => format!("Query {{ image: {image} }}"),
601            AgentRequest::ListImages => "ListImages".into(),
602            AgentRequest::GarbageCollect { .. } => "GarbageCollect".into(),
603            AgentRequest::PrepareOverlay { .. } => "PrepareOverlay".into(),
604            AgentRequest::CleanupOverlay { .. } => "CleanupOverlay".into(),
605            AgentRequest::FormatStorage => "FormatStorage".into(),
606            AgentRequest::StorageStatus => "StorageStatus".into(),
607            AgentRequest::NetworkTest { .. } => "NetworkTest".into(),
608            AgentRequest::Shutdown => "Shutdown".into(),
609            AgentRequest::ExportLayer { .. } => "ExportLayer".into(),
610            AgentRequest::VmExec { .. } => "VmExec".into(),
611            AgentRequest::Run { image, .. } => format!("Run {{ image: {image} }}"),
612            AgentRequest::Stdin { .. } => "Stdin".into(),
613            AgentRequest::Resize { .. } => "Resize".into(),
614            AgentRequest::FileWrite { .. } => "FileWrite".into(),
615            AgentRequest::FileWriteBegin { .. } => "FileWriteBegin".into(),
616            AgentRequest::FileWriteChunk { .. } => "FileWriteChunk".into(),
617            AgentRequest::FileRead { .. } => "FileRead".into(),
618            // Pod requests: spec/process JSON may carry env secrets — emit ids only.
619            AgentRequest::PodCreate { id, .. } => format!("PodCreate {{ id: {id} }}"),
620            AgentRequest::PodStart { id, exec_id } => match exec_id {
621                Some(e) => format!("PodStart {{ id: {id}, exec: {e} }}"),
622                None => format!("PodStart {{ id: {id} }}"),
623            },
624            AgentRequest::PodExec { id, exec_id, .. } => {
625                format!("PodExec {{ id: {id}, exec: {exec_id} }}")
626            }
627            AgentRequest::PodSignal {
628                id, signal, all, ..
629            } => format!("PodSignal {{ id: {id}, signal: {signal}, all: {all} }}"),
630            AgentRequest::PodPids { id } => format!("PodPids {{ id: {id} }}"),
631            AgentRequest::PodStats { id } => format!("PodStats {{ id: {id} }}"),
632            AgentRequest::PodDelete { id, exec_id } => match exec_id {
633                Some(e) => format!("PodDelete {{ id: {id}, exec: {e} }}"),
634                None => format!("PodDelete {{ id: {id} }}"),
635            },
636        }
637    }
638}
639
640/// Agent response types.
641#[derive(Debug, Clone, Serialize, Deserialize)]
642#[serde(tag = "status", rename_all = "snake_case")]
643pub enum AgentResponse {
644    /// Operation completed successfully.
645    Ok {
646        /// Response data (varies by request type).
647        #[serde(default, skip_serializing_if = "Option::is_none")]
648        data: Option<serde_json::Value>,
649    },
650
651    /// Pong response to ping.
652    Pong {
653        /// Protocol version.
654        version: u32,
655        /// Optional agent features that can evolve independently of the base protocol.
656        #[serde(default, skip_serializing_if = "Vec::is_empty")]
657        capabilities: Vec<String>,
658    },
659
660    /// Progress update (for long operations like pull).
661    Progress {
662        /// Human-readable message.
663        message: String,
664        /// Completion percentage (0-100).
665        #[serde(default, skip_serializing_if = "Option::is_none")]
666        percent: Option<u8>,
667        /// Current layer being processed.
668        #[serde(default, skip_serializing_if = "Option::is_none")]
669        layer: Option<String>,
670    },
671
672    /// Operation failed.
673    Error {
674        /// Error message.
675        message: String,
676        /// Error code (for programmatic handling).
677        #[serde(default, skip_serializing_if = "Option::is_none")]
678        code: Option<String>,
679    },
680
681    /// Command execution completed (non-interactive mode).
682    Completed {
683        /// Exit code from the command.
684        exit_code: i32,
685        /// Standard output (may be truncated). `Vec<u8>` preserves binary
686        /// output (image bytes, tarballs, etc.) that would be truncated by
687        /// `String` at the first non-UTF-8 byte. Serialized as base64 JSON
688        /// string — the same format as the streaming `Stdout` variant.
689        #[serde(with = "base64_bytes")]
690        stdout: Vec<u8>,
691        /// Standard error (may be truncated).
692        #[serde(with = "base64_bytes")]
693        stderr: Vec<u8>,
694    },
695
696    /// Command started (interactive mode).
697    /// Indicates the command is running and ready to receive stdin.
698    Started,
699
700    /// Stdout data from a running command (interactive mode).
701    Stdout {
702        /// Output data.
703        #[serde(with = "base64_bytes")]
704        data: Vec<u8>,
705    },
706
707    /// Stderr data from a running command (interactive mode).
708    Stderr {
709        /// Error output data.
710        #[serde(with = "base64_bytes")]
711        data: Vec<u8>,
712    },
713
714    /// Command exited (interactive mode).
715    Exited {
716        /// Exit code from the command.
717        exit_code: i32,
718        /// The container was terminated by the cgroup OOM killer. The shim
719        /// turns this into a TaskOOM event so the CRI reports
720        /// `reason=OOMKilled`. Only ever set on a pod container's init exit.
721        #[serde(default)]
722        oom: bool,
723    },
724
725    /// PIDs inside a pod container (`PodPids` reply).
726    Pids {
727        /// Guest PIDs, container-init first when known.
728        pids: Vec<u32>,
729    },
730
731    /// Resource usage sample for a pod container (`PodStats` reply). Summed over
732    /// the container's process tree read from /proc (no per-container cgroup).
733    Stats {
734        /// Cumulative CPU time of the process tree, in nanoseconds.
735        cpu_usage_ns: u64,
736        /// Resident memory of the process tree, in bytes.
737        memory_bytes: u64,
738    },
739
740    /// Streaming binary-data chunk.
741    ///
742    /// Used by every streaming download direction: the agent sends
743    /// one or more `DataChunk` responses in sequence, with `done: true`
744    /// on the final chunk. Current producers: `ExportLayer` and
745    /// `FileRead`.
746    ///
747    /// Payload size per chunk should stay under
748    /// [`LAYER_CHUNK_SIZE`] so the encoded frame (~1.33× after
749    /// base64) fits inside [`MAX_FRAME_SIZE`] with JSON overhead to
750    /// spare.
751    DataChunk {
752        /// Chunk bytes. Empty allowed on the final frame (common for
753        /// EOF-on-clean-boundary cases).
754        #[serde(with = "base64_bytes")]
755        data: Vec<u8>,
756        /// True on the final chunk of the stream.
757        done: bool,
758    },
759}
760
761// ============================================================================
762// Error Code Constants
763// ============================================================================
764//
765// Standard error codes for AgentResponse::Error. Using constants ensures
766// consistency across the codebase and makes error handling more reliable.
767
768/// Error codes for agent responses.
769pub mod error_codes {
770    /// Request payload was invalid or malformed.
771    pub const INVALID_REQUEST: &str = "INVALID_REQUEST";
772    /// Requested resource was not found.
773    pub const NOT_FOUND: &str = "NOT_FOUND";
774    /// Internal error during operation.
775    pub const INTERNAL_ERROR: &str = "INTERNAL_ERROR";
776    /// Image pull operation failed.
777    pub const PULL_FAILED: &str = "PULL_FAILED";
778    /// Image query operation failed.
779    pub const QUERY_FAILED: &str = "QUERY_FAILED";
780    /// Command execution failed.
781    pub const RUN_FAILED: &str = "RUN_FAILED";
782    /// Command execution failed in container.
783    pub const EXEC_FAILED: &str = "EXEC_FAILED";
784    /// Process spawn failed.
785    pub const SPAWN_FAILED: &str = "SPAWN_FAILED";
786    /// Mount operation failed.
787    pub const MOUNT_FAILED: &str = "MOUNT_FAILED";
788    /// File I/O operation failed.
789    pub const FILE_IO_FAILED: &str = "FILE_IO_FAILED";
790    /// Overlay filesystem operation failed.
791    pub const OVERLAY_FAILED: &str = "OVERLAY_FAILED";
792    /// Cleanup operation failed.
793    pub const CLEANUP_FAILED: &str = "CLEANUP_FAILED";
794    /// Storage format operation failed.
795    pub const FORMAT_FAILED: &str = "FORMAT_FAILED";
796    /// Storage status query failed.
797    pub const STATUS_FAILED: &str = "STATUS_FAILED";
798    /// List operation failed.
799    pub const LIST_FAILED: &str = "LIST_FAILED";
800    /// Garbage collection failed.
801    pub const GC_FAILED: &str = "GC_FAILED";
802    /// Container creation failed.
803    pub const CREATE_FAILED: &str = "CREATE_FAILED";
804    /// Container start failed.
805    pub const START_FAILED: &str = "START_FAILED";
806    /// Container stop failed.
807    pub const STOP_FAILED: &str = "STOP_FAILED";
808    /// Container delete failed.
809    pub const DELETE_FAILED: &str = "DELETE_FAILED";
810    /// Export operation failed.
811    pub const EXPORT_FAILED: &str = "EXPORT_FAILED";
812    /// Serialization error.
813    pub const SERIALIZATION_ERROR: &str = "SERIALIZATION_ERROR";
814    /// Message size exceeds maximum.
815    pub const MESSAGE_TOO_LARGE: &str = "MESSAGE_TOO_LARGE";
816    /// Process wait operation failed.
817    pub const WAIT_FAILED: &str = "WAIT_FAILED";
818}
819
820impl AgentResponse {
821    /// Create an error response with the given message and code.
822    ///
823    /// # Example
824    ///
825    /// ```
826    /// use smolvm_protocol::{AgentResponse, error_codes};
827    ///
828    /// let response = AgentResponse::error("image not found", error_codes::NOT_FOUND);
829    /// ```
830    pub fn error(message: impl Into<String>, code: &str) -> Self {
831        AgentResponse::Error {
832            message: message.into(),
833            code: Some(code.to_string()),
834        }
835    }
836
837    /// Create an error response from a Result's error, with the given code.
838    ///
839    /// # Example
840    ///
841    /// ```ignore
842    /// let response = some_operation()
843    ///     .map(|data| AgentResponse::ok_with_data(data))
844    ///     .unwrap_or_else(|e| AgentResponse::from_err(e, error_codes::PULL_FAILED));
845    /// ```
846    pub fn from_err<E: std::fmt::Display>(err: E, code: &str) -> Self {
847        AgentResponse::Error {
848            message: err.to_string(),
849            code: Some(code.to_string()),
850        }
851    }
852
853    /// Create an Ok response with optional JSON data.
854    pub fn ok(data: Option<serde_json::Value>) -> Self {
855        AgentResponse::Ok { data }
856    }
857
858    /// Create an Ok response with JSON-serializable data.
859    ///
860    /// Returns an error response if serialization fails.
861    pub fn ok_with_data<T: serde::Serialize>(data: T) -> Self {
862        match serde_json::to_value(data) {
863            Ok(value) => AgentResponse::Ok { data: Some(value) },
864            Err(e) => AgentResponse::error(
865                format!("failed to serialize response: {}", e),
866                error_codes::SERIALIZATION_ERROR,
867            ),
868        }
869    }
870
871    /// Convert a Result into an AgentResponse.
872    ///
873    /// On success, serializes the value to JSON. On error, creates an error response.
874    ///
875    /// # Example
876    ///
877    /// ```ignore
878    /// let response = AgentResponse::from_result(
879    ///     storage::pull_image(image),
880    ///     error_codes::PULL_FAILED,
881    /// );
882    /// ```
883    pub fn from_result<T, E>(result: Result<T, E>, error_code: &str) -> Self
884    where
885        T: serde::Serialize,
886        E: std::fmt::Display,
887    {
888        match result {
889            Ok(data) => Self::ok_with_data(data),
890            Err(e) => Self::from_err(e, error_code),
891        }
892    }
893}
894
895/// Image information returned by Query/ListImages.
896#[derive(Debug, Clone, Serialize, Deserialize)]
897pub struct ImageInfo {
898    /// Image reference.
899    pub reference: String,
900    /// Image digest (sha256:...).
901    pub digest: String,
902    /// Image size in bytes.
903    pub size: u64,
904    /// Creation timestamp (ISO 8601).
905    pub created: Option<String>,
906    /// Platform architecture.
907    pub architecture: String,
908    /// Platform OS.
909    pub os: String,
910    /// Number of layers.
911    pub layer_count: usize,
912    /// Layer digests in order.
913    pub layers: Vec<String>,
914    /// Image entrypoint (from OCI config).
915    #[serde(default)]
916    pub entrypoint: Vec<String>,
917    /// Image default command (from OCI config).
918    #[serde(default)]
919    pub cmd: Vec<String>,
920    /// Image environment variables (from OCI config).
921    #[serde(default)]
922    pub env: Vec<String>,
923    /// Image working directory (from OCI config).
924    #[serde(default)]
925    pub workdir: Option<String>,
926    /// Image default user (from OCI config).
927    #[serde(default)]
928    pub user: Option<String>,
929}
930
931/// Overlay preparation result.
932#[derive(Debug, Clone, Serialize, Deserialize)]
933pub struct OverlayInfo {
934    /// Path to the merged overlay rootfs.
935    pub rootfs_path: String,
936    /// Path to the upper (writable) directory.
937    pub upper_path: String,
938    /// Path to the work directory.
939    pub work_path: String,
940}
941
942/// Storage status information.
943#[derive(Debug, Clone, Serialize, Deserialize)]
944pub struct StorageStatus {
945    /// Whether the storage is formatted and ready.
946    pub ready: bool,
947    /// Total size in bytes.
948    pub total_bytes: u64,
949    /// Used size in bytes.
950    pub used_bytes: u64,
951    /// Number of cached layers.
952    pub layer_count: usize,
953    /// Number of cached images.
954    pub image_count: usize,
955}
956
957/// Registry authentication credentials for pulling images.
958///
959/// `Debug` is hand-written to redact the password: this value is carried inside
960/// `AgentRequest::Pull`, and any `{:?}` of that request (e.g. a tracing span)
961/// would otherwise serialize the token verbatim into the machine's console log,
962/// which is exposed over the logs API.
963#[derive(Clone, Serialize, Deserialize)]
964pub struct RegistryAuth {
965    /// Username for authentication.
966    pub username: String,
967    /// Password or token for authentication.
968    pub password: String,
969}
970
971impl std::fmt::Debug for RegistryAuth {
972    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
973        f.debug_struct("RegistryAuth")
974            .field("username", &self.username)
975            .field("password", &"***")
976            .finish()
977    }
978}
979
980// ============================================================================
981// Workload VM Protocol (Command Execution)
982// ============================================================================
983
984/// Messages from host to workload VM.
985#[derive(Debug, Clone, Serialize, Deserialize)]
986#[serde(tag = "type", rename_all = "snake_case")]
987pub enum HostMessage {
988    /// Authentication request.
989    Auth {
990        /// Authentication token (base64).
991        token: String,
992        /// Protocol version.
993        protocol_version: u32,
994    },
995
996    /// Run a command.
997    Run {
998        /// Request ID for correlating responses.
999        request_id: u64,
1000        /// Command and arguments.
1001        command: Vec<String>,
1002        /// Environment variables.
1003        env: Vec<(String, String)>,
1004        /// Working directory.
1005        workdir: Option<String>,
1006    },
1007
1008    /// Execute a command in running VM.
1009    Exec {
1010        /// Request ID.
1011        request_id: u64,
1012        /// Command and arguments.
1013        command: Vec<String>,
1014        /// Allocate a TTY.
1015        tty: bool,
1016    },
1017
1018    /// Send a signal to a running command.
1019    Signal {
1020        /// Request ID of the command.
1021        request_id: u64,
1022        /// Signal number.
1023        signal: i32,
1024    },
1025
1026    /// Request graceful shutdown.
1027    Stop {
1028        /// Timeout in milliseconds.
1029        timeout_ms: u64,
1030    },
1031}
1032
1033/// Messages from workload VM to host.
1034#[derive(Debug, Clone, Serialize, Deserialize)]
1035#[serde(tag = "type", rename_all = "snake_case")]
1036pub enum GuestMessage {
1037    /// Authentication successful.
1038    AuthOk,
1039
1040    /// Authentication failed.
1041    AuthFailed,
1042
1043    /// VM is ready to receive commands.
1044    Ready,
1045
1046    /// Command started.
1047    Started {
1048        /// Request ID.
1049        request_id: u64,
1050    },
1051
1052    /// Stdout data from command.
1053    Stdout {
1054        /// Request ID.
1055        request_id: u64,
1056        /// Output data.
1057        #[serde(with = "base64_bytes")]
1058        data: Vec<u8>,
1059        /// Whether output was truncated.
1060        truncated: bool,
1061    },
1062
1063    /// Stderr data from command.
1064    Stderr {
1065        /// Request ID.
1066        request_id: u64,
1067        /// Output data.
1068        #[serde(with = "base64_bytes")]
1069        data: Vec<u8>,
1070        /// Whether output was truncated.
1071        truncated: bool,
1072    },
1073
1074    /// Command exited.
1075    Exit {
1076        /// Request ID.
1077        request_id: u64,
1078        /// Exit code.
1079        code: i32,
1080        /// Exit reason.
1081        reason: String,
1082    },
1083
1084    /// Error occurred.
1085    Error {
1086        /// Request ID (if applicable).
1087        request_id: Option<u64>,
1088        /// Error message.
1089        message: String,
1090    },
1091}
1092
1093// ============================================================================
1094// Wire Format Helpers
1095// ============================================================================
1096
1097/// Envelope that wraps any message with an optional trace ID for correlation.
1098///
1099/// On the wire, the trace_id is flattened into the JSON alongside the message
1100/// fields: `{"trace_id":"abc123","method":"ping"}`.
1101#[derive(Debug, Clone, Serialize, Deserialize)]
1102pub struct Envelope<T> {
1103    /// Trace ID for correlating host API requests to agent operations.
1104    #[serde(skip_serializing_if = "Option::is_none", default)]
1105    pub trace_id: Option<String>,
1106    /// The wrapped message.
1107    #[serde(flatten)]
1108    pub body: T,
1109}
1110
1111impl<T> Envelope<T> {
1112    /// Create an envelope with no trace ID.
1113    pub fn new(body: T) -> Self {
1114        Self {
1115            trace_id: None,
1116            body,
1117        }
1118    }
1119
1120    /// Create an envelope with an optional trace ID.
1121    pub fn with_trace_id(body: T, trace_id: Option<String>) -> Self {
1122        Self { trace_id, body }
1123    }
1124}
1125
1126/// Encode a message to wire format (length-prefixed JSON).
1127pub fn encode_message<T: Serialize>(msg: &T) -> Result<Vec<u8>, serde_json::Error> {
1128    let json = serde_json::to_vec(msg)?;
1129    let len = json.len() as u32;
1130
1131    let mut buf = Vec::with_capacity(4 + json.len());
1132    buf.extend_from_slice(&len.to_be_bytes());
1133    buf.extend_from_slice(&json);
1134
1135    Ok(buf)
1136}
1137
1138/// Decode a message from wire format.
1139pub fn decode_message<T: for<'de> Deserialize<'de>>(data: &[u8]) -> Result<T, DecodeError> {
1140    if data.len() < 4 {
1141        return Err(DecodeError::TooShort);
1142    }
1143
1144    let len = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
1145
1146    if len > MAX_FRAME_SIZE as usize {
1147        return Err(DecodeError::TooLarge(len));
1148    }
1149
1150    if data.len() < 4 + len {
1151        return Err(DecodeError::Incomplete {
1152            expected: len,
1153            got: data.len() - 4,
1154        });
1155    }
1156
1157    serde_json::from_slice(&data[4..4 + len]).map_err(DecodeError::Json)
1158}
1159
1160/// Error decoding a wire message.
1161#[derive(Debug)]
1162pub enum DecodeError {
1163    /// Data too short to contain length header.
1164    TooShort,
1165    /// Frame size exceeds maximum.
1166    TooLarge(usize),
1167    /// Incomplete frame.
1168    Incomplete {
1169        /// Expected length.
1170        expected: usize,
1171        /// Actual length.
1172        got: usize,
1173    },
1174    /// JSON parse error.
1175    Json(serde_json::Error),
1176}
1177
1178impl std::fmt::Display for DecodeError {
1179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1180        match self {
1181            DecodeError::TooShort => write!(f, "data too short for length header"),
1182            DecodeError::TooLarge(size) => write!(f, "frame too large: {} bytes", size),
1183            DecodeError::Incomplete { expected, got } => {
1184                write!(
1185                    f,
1186                    "incomplete frame: expected {} bytes, got {}",
1187                    expected, got
1188                )
1189            }
1190            DecodeError::Json(e) => write!(f, "JSON decode error: {}", e),
1191        }
1192    }
1193}
1194
1195impl std::error::Error for DecodeError {}
1196
1197#[cfg(test)]
1198mod tests {
1199    use super::*;
1200
1201    #[test]
1202    fn test_encode_decode_roundtrip() {
1203        let req = AgentRequest::Pull {
1204            image: "alpine:latest".to_string(),
1205            oci_platform: Some("linux/arm64".to_string()),
1206            auth: None,
1207            proxy: None,
1208            no_proxy: None,
1209        };
1210
1211        let encoded = encode_message(&req).unwrap();
1212        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1213
1214        let AgentRequest::Pull {
1215            image,
1216            oci_platform,
1217            auth,
1218            proxy,
1219            no_proxy,
1220        } = decoded
1221        else {
1222            panic!("expected Pull variant, got {:?}", decoded);
1223        };
1224        assert_eq!(image, "alpine:latest");
1225        assert_eq!(oci_platform, Some("linux/arm64".to_string()));
1226        assert!(auth.is_none());
1227        assert!(proxy.is_none());
1228        assert!(no_proxy.is_none());
1229    }
1230
1231    #[test]
1232    fn test_encode_decode_with_auth() {
1233        let req = AgentRequest::Pull {
1234            image: "ghcr.io/owner/repo:latest".to_string(),
1235            oci_platform: None,
1236            auth: Some(RegistryAuth {
1237                username: "testuser".to_string(),
1238                password: "testpass".to_string(),
1239            }),
1240            proxy: None,
1241            no_proxy: None,
1242        };
1243
1244        let encoded = encode_message(&req).unwrap();
1245        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1246
1247        let AgentRequest::Pull {
1248            image,
1249            oci_platform,
1250            auth,
1251            proxy: _,
1252            no_proxy: _,
1253        } = decoded
1254        else {
1255            panic!("expected Pull variant, got {:?}", decoded);
1256        };
1257        assert_eq!(image, "ghcr.io/owner/repo:latest");
1258        assert!(oci_platform.is_none());
1259        let auth = auth.expect("auth should be Some");
1260        assert_eq!(auth.username, "testuser");
1261        assert_eq!(auth.password, "testpass");
1262    }
1263
1264    #[test]
1265    fn test_encode_decode_with_proxy() {
1266        let req = AgentRequest::Pull {
1267            image: "alpine:latest".to_string(),
1268            oci_platform: None,
1269            auth: None,
1270            proxy: Some("http://192.168.127.254:3128".to_string()),
1271            no_proxy: Some("127.0.0.1,localhost,.internal".to_string()),
1272        };
1273
1274        let encoded = encode_message(&req).unwrap();
1275        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1276
1277        let AgentRequest::Pull {
1278            proxy, no_proxy, ..
1279        } = decoded
1280        else {
1281            panic!("expected Pull variant, got {:?}", decoded);
1282        };
1283        assert_eq!(proxy.as_deref(), Some("http://192.168.127.254:3128"));
1284        assert_eq!(no_proxy.as_deref(), Some("127.0.0.1,localhost,.internal"));
1285    }
1286
1287    #[test]
1288    fn test_decode_too_short() {
1289        let data = [0u8; 2];
1290        let result: Result<AgentRequest, _> = decode_message(&data);
1291        assert!(matches!(result, Err(DecodeError::TooShort)));
1292    }
1293
1294    #[test]
1295    fn test_decode_incomplete() {
1296        let mut data = vec![0, 0, 0, 100]; // claims 100 bytes
1297        data.extend_from_slice(b"{}"); // only 2 bytes of payload
1298        let result: Result<AgentRequest, _> = decode_message(&data);
1299        assert!(matches!(result, Err(DecodeError::Incomplete { .. })));
1300    }
1301
1302    #[test]
1303    fn test_agent_request_serialization() {
1304        let req = AgentRequest::Ping;
1305        let json = serde_json::to_string(&req).unwrap();
1306        assert!(json.contains("ping"));
1307
1308        let req = AgentRequest::PrepareOverlay {
1309            image: "ubuntu:22.04".to_string(),
1310            workload_id: "wl-123".to_string(),
1311        };
1312        let json = serde_json::to_string(&req).unwrap();
1313        assert!(json.contains("prepare_overlay"));
1314    }
1315
1316    #[test]
1317    fn test_agent_response_serialization() {
1318        let resp = AgentResponse::Pong {
1319            version: PROTOCOL_VERSION,
1320            capabilities: vec![forkpoint::WORKER_READY_CAPABILITY.to_string()],
1321        };
1322        let json = serde_json::to_string(&resp).unwrap();
1323        assert!(json.contains("pong"));
1324        assert!(json.contains(forkpoint::WORKER_READY_CAPABILITY));
1325
1326        let legacy: AgentResponse =
1327            serde_json::from_str(r#"{"status":"pong","version":1}"#).unwrap();
1328        assert!(matches!(
1329            legacy,
1330            AgentResponse::Pong {
1331                version: PROTOCOL_VERSION,
1332                capabilities
1333            } if capabilities.is_empty()
1334        ));
1335
1336        let resp = AgentResponse::Progress {
1337            message: "Pulling layer 1/3".to_string(),
1338            percent: Some(33),
1339            layer: Some("sha256:abc123".to_string()),
1340        };
1341        let json = serde_json::to_string(&resp).unwrap();
1342        assert!(json.contains("progress"));
1343    }
1344
1345    #[test]
1346    fn file_write_begin_roundtrips() {
1347        let req = AgentRequest::FileWriteBegin {
1348            path: "/tmp/target".into(),
1349            mode: Some(0o600),
1350            total_size: 123_456_789,
1351        };
1352        let bytes = encode_message(&req).unwrap();
1353        let back: AgentRequest = decode_message(&bytes).unwrap();
1354        match back {
1355            AgentRequest::FileWriteBegin {
1356                path,
1357                mode,
1358                total_size,
1359            } => {
1360                assert_eq!(path, "/tmp/target");
1361                assert_eq!(mode, Some(0o600));
1362                assert_eq!(total_size, 123_456_789);
1363            }
1364            _ => panic!("wrong variant"),
1365        }
1366    }
1367
1368    #[test]
1369    fn file_write_chunk_roundtrips_binary_data() {
1370        // Binary data (bytes outside UTF-8) must survive the base64
1371        // trip intact. If the encoding ever silently lossifies, this
1372        // fires.
1373        let payload: Vec<u8> = (0u8..=255).collect();
1374        let req = AgentRequest::FileWriteChunk {
1375            data: payload.clone(),
1376            done: true,
1377        };
1378        let bytes = encode_message(&req).unwrap();
1379        let back: AgentRequest = decode_message(&bytes).unwrap();
1380        match back {
1381            AgentRequest::FileWriteChunk { data, done } => {
1382                assert_eq!(data, payload);
1383                assert!(done);
1384            }
1385            _ => panic!("wrong variant"),
1386        }
1387    }
1388
1389    #[test]
1390    fn file_write_size_constants_are_frame_safe() {
1391        // Sanity: a single streaming chunk at FILE_WRITE_CHUNK_SIZE
1392        // must fit inside MAX_FRAME_SIZE after base64 (+ ~33%) and
1393        // JSON overhead. If anyone bumps CHUNK_SIZE past the limit,
1394        // this test fires before production does.
1395        let chunk_bytes = FILE_WRITE_CHUNK_SIZE as u64;
1396        let base64_bytes = chunk_bytes.div_ceil(3) * 4; // ceil(n/3)*4
1397        let json_overhead = 256u64; // method tag, done bool, quotes
1398        let total = base64_bytes + json_overhead;
1399        assert!(
1400            total < MAX_FRAME_SIZE as u64,
1401            "FILE_WRITE_CHUNK_SIZE of {} bytes would produce a frame \
1402             of ~{} bytes which exceeds MAX_FRAME_SIZE of {}",
1403            chunk_bytes,
1404            total,
1405            MAX_FRAME_SIZE
1406        );
1407    }
1408
1409    #[test]
1410    fn test_ports_constants() {
1411        assert_eq!(ports::WORKLOAD_CONTROL, 5000);
1412        assert_eq!(ports::WORKLOAD_LOGS, 5001);
1413        assert_eq!(ports::AGENT_CONTROL, 6000);
1414        assert_eq!(ports::SSH_AGENT, 6001);
1415    }
1416
1417    #[test]
1418    fn test_cid_constants() {
1419        assert_eq!(cid::HOST, 2);
1420        assert_eq!(cid::GUEST, 3);
1421    }
1422
1423    #[test]
1424    fn test_envelope_serialization_with_trace_id() {
1425        let req = AgentRequest::Ping;
1426        let envelope = Envelope::with_trace_id(&req, Some("abc123".to_string()));
1427        let json = serde_json::to_string(&envelope).unwrap();
1428
1429        // trace_id should be flattened alongside the method tag
1430        assert!(json.contains("\"trace_id\":\"abc123\""));
1431        assert!(json.contains("\"method\":\"ping\""));
1432
1433        // Deserialize back — Envelope<AgentRequest> with flatten
1434        let parsed: Envelope<AgentRequest> = serde_json::from_str(&json).unwrap();
1435        assert_eq!(parsed.trace_id.as_deref(), Some("abc123"));
1436        assert!(matches!(parsed.body, AgentRequest::Ping));
1437    }
1438
1439    #[test]
1440    fn test_envelope_without_trace_id() {
1441        let req = AgentRequest::Ping;
1442        let envelope = Envelope::new(&req);
1443        let json = serde_json::to_string(&envelope).unwrap();
1444
1445        // No trace_id field (skip_serializing_if = None)
1446        assert!(!json.contains("trace_id"));
1447        assert!(json.contains("\"method\":\"ping\""));
1448    }
1449
1450    #[test]
1451    fn test_envelope_backward_compat_bare_request() {
1452        // A bare AgentRequest (no Envelope) should fail to parse as Envelope
1453        // but succeed as bare AgentRequest — this is the agent's fallback path
1454        let bare_json = r#"{"method":"ping"}"#;
1455
1456        // Envelope parse should fail (no body field to flatten into)
1457        // Actually with flatten, this may work — let's verify
1458        let envelope_result = serde_json::from_str::<Envelope<AgentRequest>>(bare_json);
1459        let bare_result = serde_json::from_str::<AgentRequest>(bare_json);
1460
1461        // At least one must succeed for backward compat
1462        assert!(
1463            envelope_result.is_ok() || bare_result.is_ok(),
1464            "Neither Envelope nor bare parse succeeded"
1465        );
1466
1467        // Bare parse must always work
1468        assert!(bare_result.is_ok());
1469        assert!(matches!(bare_result.unwrap(), AgentRequest::Ping));
1470
1471        // If Envelope works, trace_id should be None
1472        if let Ok(env) = envelope_result {
1473            assert!(env.trace_id.is_none());
1474        }
1475    }
1476}