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    },
656
657    /// Progress update (for long operations like pull).
658    Progress {
659        /// Human-readable message.
660        message: String,
661        /// Completion percentage (0-100).
662        #[serde(default, skip_serializing_if = "Option::is_none")]
663        percent: Option<u8>,
664        /// Current layer being processed.
665        #[serde(default, skip_serializing_if = "Option::is_none")]
666        layer: Option<String>,
667    },
668
669    /// Operation failed.
670    Error {
671        /// Error message.
672        message: String,
673        /// Error code (for programmatic handling).
674        #[serde(default, skip_serializing_if = "Option::is_none")]
675        code: Option<String>,
676    },
677
678    /// Command execution completed (non-interactive mode).
679    Completed {
680        /// Exit code from the command.
681        exit_code: i32,
682        /// Standard output (may be truncated). `Vec<u8>` preserves binary
683        /// output (image bytes, tarballs, etc.) that would be truncated by
684        /// `String` at the first non-UTF-8 byte. Serialized as base64 JSON
685        /// string — the same format as the streaming `Stdout` variant.
686        #[serde(with = "base64_bytes")]
687        stdout: Vec<u8>,
688        /// Standard error (may be truncated).
689        #[serde(with = "base64_bytes")]
690        stderr: Vec<u8>,
691    },
692
693    /// Command started (interactive mode).
694    /// Indicates the command is running and ready to receive stdin.
695    Started,
696
697    /// Stdout data from a running command (interactive mode).
698    Stdout {
699        /// Output data.
700        #[serde(with = "base64_bytes")]
701        data: Vec<u8>,
702    },
703
704    /// Stderr data from a running command (interactive mode).
705    Stderr {
706        /// Error output data.
707        #[serde(with = "base64_bytes")]
708        data: Vec<u8>,
709    },
710
711    /// Command exited (interactive mode).
712    Exited {
713        /// Exit code from the command.
714        exit_code: i32,
715        /// The container was terminated by the cgroup OOM killer. The shim
716        /// turns this into a TaskOOM event so the CRI reports
717        /// `reason=OOMKilled`. Only ever set on a pod container's init exit.
718        #[serde(default)]
719        oom: bool,
720    },
721
722    /// PIDs inside a pod container (`PodPids` reply).
723    Pids {
724        /// Guest PIDs, container-init first when known.
725        pids: Vec<u32>,
726    },
727
728    /// Resource usage sample for a pod container (`PodStats` reply). Summed over
729    /// the container's process tree read from /proc (no per-container cgroup).
730    Stats {
731        /// Cumulative CPU time of the process tree, in nanoseconds.
732        cpu_usage_ns: u64,
733        /// Resident memory of the process tree, in bytes.
734        memory_bytes: u64,
735    },
736
737    /// Streaming binary-data chunk.
738    ///
739    /// Used by every streaming download direction: the agent sends
740    /// one or more `DataChunk` responses in sequence, with `done: true`
741    /// on the final chunk. Current producers: `ExportLayer` and
742    /// `FileRead`.
743    ///
744    /// Payload size per chunk should stay under
745    /// [`LAYER_CHUNK_SIZE`] so the encoded frame (~1.33× after
746    /// base64) fits inside [`MAX_FRAME_SIZE`] with JSON overhead to
747    /// spare.
748    DataChunk {
749        /// Chunk bytes. Empty allowed on the final frame (common for
750        /// EOF-on-clean-boundary cases).
751        #[serde(with = "base64_bytes")]
752        data: Vec<u8>,
753        /// True on the final chunk of the stream.
754        done: bool,
755    },
756}
757
758// ============================================================================
759// Error Code Constants
760// ============================================================================
761//
762// Standard error codes for AgentResponse::Error. Using constants ensures
763// consistency across the codebase and makes error handling more reliable.
764
765/// Error codes for agent responses.
766pub mod error_codes {
767    /// Request payload was invalid or malformed.
768    pub const INVALID_REQUEST: &str = "INVALID_REQUEST";
769    /// Requested resource was not found.
770    pub const NOT_FOUND: &str = "NOT_FOUND";
771    /// Internal error during operation.
772    pub const INTERNAL_ERROR: &str = "INTERNAL_ERROR";
773    /// Image pull operation failed.
774    pub const PULL_FAILED: &str = "PULL_FAILED";
775    /// Image query operation failed.
776    pub const QUERY_FAILED: &str = "QUERY_FAILED";
777    /// Command execution failed.
778    pub const RUN_FAILED: &str = "RUN_FAILED";
779    /// Command execution failed in container.
780    pub const EXEC_FAILED: &str = "EXEC_FAILED";
781    /// Process spawn failed.
782    pub const SPAWN_FAILED: &str = "SPAWN_FAILED";
783    /// Mount operation failed.
784    pub const MOUNT_FAILED: &str = "MOUNT_FAILED";
785    /// File I/O operation failed.
786    pub const FILE_IO_FAILED: &str = "FILE_IO_FAILED";
787    /// Overlay filesystem operation failed.
788    pub const OVERLAY_FAILED: &str = "OVERLAY_FAILED";
789    /// Cleanup operation failed.
790    pub const CLEANUP_FAILED: &str = "CLEANUP_FAILED";
791    /// Storage format operation failed.
792    pub const FORMAT_FAILED: &str = "FORMAT_FAILED";
793    /// Storage status query failed.
794    pub const STATUS_FAILED: &str = "STATUS_FAILED";
795    /// List operation failed.
796    pub const LIST_FAILED: &str = "LIST_FAILED";
797    /// Garbage collection failed.
798    pub const GC_FAILED: &str = "GC_FAILED";
799    /// Container creation failed.
800    pub const CREATE_FAILED: &str = "CREATE_FAILED";
801    /// Container start failed.
802    pub const START_FAILED: &str = "START_FAILED";
803    /// Container stop failed.
804    pub const STOP_FAILED: &str = "STOP_FAILED";
805    /// Container delete failed.
806    pub const DELETE_FAILED: &str = "DELETE_FAILED";
807    /// Export operation failed.
808    pub const EXPORT_FAILED: &str = "EXPORT_FAILED";
809    /// Serialization error.
810    pub const SERIALIZATION_ERROR: &str = "SERIALIZATION_ERROR";
811    /// Message size exceeds maximum.
812    pub const MESSAGE_TOO_LARGE: &str = "MESSAGE_TOO_LARGE";
813    /// Process wait operation failed.
814    pub const WAIT_FAILED: &str = "WAIT_FAILED";
815}
816
817impl AgentResponse {
818    /// Create an error response with the given message and code.
819    ///
820    /// # Example
821    ///
822    /// ```
823    /// use smolvm_protocol::{AgentResponse, error_codes};
824    ///
825    /// let response = AgentResponse::error("image not found", error_codes::NOT_FOUND);
826    /// ```
827    pub fn error(message: impl Into<String>, code: &str) -> Self {
828        AgentResponse::Error {
829            message: message.into(),
830            code: Some(code.to_string()),
831        }
832    }
833
834    /// Create an error response from a Result's error, with the given code.
835    ///
836    /// # Example
837    ///
838    /// ```ignore
839    /// let response = some_operation()
840    ///     .map(|data| AgentResponse::ok_with_data(data))
841    ///     .unwrap_or_else(|e| AgentResponse::from_err(e, error_codes::PULL_FAILED));
842    /// ```
843    pub fn from_err<E: std::fmt::Display>(err: E, code: &str) -> Self {
844        AgentResponse::Error {
845            message: err.to_string(),
846            code: Some(code.to_string()),
847        }
848    }
849
850    /// Create an Ok response with optional JSON data.
851    pub fn ok(data: Option<serde_json::Value>) -> Self {
852        AgentResponse::Ok { data }
853    }
854
855    /// Create an Ok response with JSON-serializable data.
856    ///
857    /// Returns an error response if serialization fails.
858    pub fn ok_with_data<T: serde::Serialize>(data: T) -> Self {
859        match serde_json::to_value(data) {
860            Ok(value) => AgentResponse::Ok { data: Some(value) },
861            Err(e) => AgentResponse::error(
862                format!("failed to serialize response: {}", e),
863                error_codes::SERIALIZATION_ERROR,
864            ),
865        }
866    }
867
868    /// Convert a Result into an AgentResponse.
869    ///
870    /// On success, serializes the value to JSON. On error, creates an error response.
871    ///
872    /// # Example
873    ///
874    /// ```ignore
875    /// let response = AgentResponse::from_result(
876    ///     storage::pull_image(image),
877    ///     error_codes::PULL_FAILED,
878    /// );
879    /// ```
880    pub fn from_result<T, E>(result: Result<T, E>, error_code: &str) -> Self
881    where
882        T: serde::Serialize,
883        E: std::fmt::Display,
884    {
885        match result {
886            Ok(data) => Self::ok_with_data(data),
887            Err(e) => Self::from_err(e, error_code),
888        }
889    }
890}
891
892/// Image information returned by Query/ListImages.
893#[derive(Debug, Clone, Serialize, Deserialize)]
894pub struct ImageInfo {
895    /// Image reference.
896    pub reference: String,
897    /// Image digest (sha256:...).
898    pub digest: String,
899    /// Image size in bytes.
900    pub size: u64,
901    /// Creation timestamp (ISO 8601).
902    pub created: Option<String>,
903    /// Platform architecture.
904    pub architecture: String,
905    /// Platform OS.
906    pub os: String,
907    /// Number of layers.
908    pub layer_count: usize,
909    /// Layer digests in order.
910    pub layers: Vec<String>,
911    /// Image entrypoint (from OCI config).
912    #[serde(default)]
913    pub entrypoint: Vec<String>,
914    /// Image default command (from OCI config).
915    #[serde(default)]
916    pub cmd: Vec<String>,
917    /// Image environment variables (from OCI config).
918    #[serde(default)]
919    pub env: Vec<String>,
920    /// Image working directory (from OCI config).
921    #[serde(default)]
922    pub workdir: Option<String>,
923    /// Image default user (from OCI config).
924    #[serde(default)]
925    pub user: Option<String>,
926}
927
928/// Overlay preparation result.
929#[derive(Debug, Clone, Serialize, Deserialize)]
930pub struct OverlayInfo {
931    /// Path to the merged overlay rootfs.
932    pub rootfs_path: String,
933    /// Path to the upper (writable) directory.
934    pub upper_path: String,
935    /// Path to the work directory.
936    pub work_path: String,
937}
938
939/// Storage status information.
940#[derive(Debug, Clone, Serialize, Deserialize)]
941pub struct StorageStatus {
942    /// Whether the storage is formatted and ready.
943    pub ready: bool,
944    /// Total size in bytes.
945    pub total_bytes: u64,
946    /// Used size in bytes.
947    pub used_bytes: u64,
948    /// Number of cached layers.
949    pub layer_count: usize,
950    /// Number of cached images.
951    pub image_count: usize,
952}
953
954/// Registry authentication credentials for pulling images.
955///
956/// `Debug` is hand-written to redact the password: this value is carried inside
957/// `AgentRequest::Pull`, and any `{:?}` of that request (e.g. a tracing span)
958/// would otherwise serialize the token verbatim into the machine's console log,
959/// which is exposed over the logs API.
960#[derive(Clone, Serialize, Deserialize)]
961pub struct RegistryAuth {
962    /// Username for authentication.
963    pub username: String,
964    /// Password or token for authentication.
965    pub password: String,
966}
967
968impl std::fmt::Debug for RegistryAuth {
969    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
970        f.debug_struct("RegistryAuth")
971            .field("username", &self.username)
972            .field("password", &"***")
973            .finish()
974    }
975}
976
977// ============================================================================
978// Workload VM Protocol (Command Execution)
979// ============================================================================
980
981/// Messages from host to workload VM.
982#[derive(Debug, Clone, Serialize, Deserialize)]
983#[serde(tag = "type", rename_all = "snake_case")]
984pub enum HostMessage {
985    /// Authentication request.
986    Auth {
987        /// Authentication token (base64).
988        token: String,
989        /// Protocol version.
990        protocol_version: u32,
991    },
992
993    /// Run a command.
994    Run {
995        /// Request ID for correlating responses.
996        request_id: u64,
997        /// Command and arguments.
998        command: Vec<String>,
999        /// Environment variables.
1000        env: Vec<(String, String)>,
1001        /// Working directory.
1002        workdir: Option<String>,
1003    },
1004
1005    /// Execute a command in running VM.
1006    Exec {
1007        /// Request ID.
1008        request_id: u64,
1009        /// Command and arguments.
1010        command: Vec<String>,
1011        /// Allocate a TTY.
1012        tty: bool,
1013    },
1014
1015    /// Send a signal to a running command.
1016    Signal {
1017        /// Request ID of the command.
1018        request_id: u64,
1019        /// Signal number.
1020        signal: i32,
1021    },
1022
1023    /// Request graceful shutdown.
1024    Stop {
1025        /// Timeout in milliseconds.
1026        timeout_ms: u64,
1027    },
1028}
1029
1030/// Messages from workload VM to host.
1031#[derive(Debug, Clone, Serialize, Deserialize)]
1032#[serde(tag = "type", rename_all = "snake_case")]
1033pub enum GuestMessage {
1034    /// Authentication successful.
1035    AuthOk,
1036
1037    /// Authentication failed.
1038    AuthFailed,
1039
1040    /// VM is ready to receive commands.
1041    Ready,
1042
1043    /// Command started.
1044    Started {
1045        /// Request ID.
1046        request_id: u64,
1047    },
1048
1049    /// Stdout data from command.
1050    Stdout {
1051        /// Request ID.
1052        request_id: u64,
1053        /// Output data.
1054        #[serde(with = "base64_bytes")]
1055        data: Vec<u8>,
1056        /// Whether output was truncated.
1057        truncated: bool,
1058    },
1059
1060    /// Stderr data from command.
1061    Stderr {
1062        /// Request ID.
1063        request_id: u64,
1064        /// Output data.
1065        #[serde(with = "base64_bytes")]
1066        data: Vec<u8>,
1067        /// Whether output was truncated.
1068        truncated: bool,
1069    },
1070
1071    /// Command exited.
1072    Exit {
1073        /// Request ID.
1074        request_id: u64,
1075        /// Exit code.
1076        code: i32,
1077        /// Exit reason.
1078        reason: String,
1079    },
1080
1081    /// Error occurred.
1082    Error {
1083        /// Request ID (if applicable).
1084        request_id: Option<u64>,
1085        /// Error message.
1086        message: String,
1087    },
1088}
1089
1090// ============================================================================
1091// Wire Format Helpers
1092// ============================================================================
1093
1094/// Envelope that wraps any message with an optional trace ID for correlation.
1095///
1096/// On the wire, the trace_id is flattened into the JSON alongside the message
1097/// fields: `{"trace_id":"abc123","method":"ping"}`.
1098#[derive(Debug, Clone, Serialize, Deserialize)]
1099pub struct Envelope<T> {
1100    /// Trace ID for correlating host API requests to agent operations.
1101    #[serde(skip_serializing_if = "Option::is_none", default)]
1102    pub trace_id: Option<String>,
1103    /// The wrapped message.
1104    #[serde(flatten)]
1105    pub body: T,
1106}
1107
1108impl<T> Envelope<T> {
1109    /// Create an envelope with no trace ID.
1110    pub fn new(body: T) -> Self {
1111        Self {
1112            trace_id: None,
1113            body,
1114        }
1115    }
1116
1117    /// Create an envelope with an optional trace ID.
1118    pub fn with_trace_id(body: T, trace_id: Option<String>) -> Self {
1119        Self { trace_id, body }
1120    }
1121}
1122
1123/// Encode a message to wire format (length-prefixed JSON).
1124pub fn encode_message<T: Serialize>(msg: &T) -> Result<Vec<u8>, serde_json::Error> {
1125    let json = serde_json::to_vec(msg)?;
1126    let len = json.len() as u32;
1127
1128    let mut buf = Vec::with_capacity(4 + json.len());
1129    buf.extend_from_slice(&len.to_be_bytes());
1130    buf.extend_from_slice(&json);
1131
1132    Ok(buf)
1133}
1134
1135/// Decode a message from wire format.
1136pub fn decode_message<T: for<'de> Deserialize<'de>>(data: &[u8]) -> Result<T, DecodeError> {
1137    if data.len() < 4 {
1138        return Err(DecodeError::TooShort);
1139    }
1140
1141    let len = u32::from_be_bytes([data[0], data[1], data[2], data[3]]) as usize;
1142
1143    if len > MAX_FRAME_SIZE as usize {
1144        return Err(DecodeError::TooLarge(len));
1145    }
1146
1147    if data.len() < 4 + len {
1148        return Err(DecodeError::Incomplete {
1149            expected: len,
1150            got: data.len() - 4,
1151        });
1152    }
1153
1154    serde_json::from_slice(&data[4..4 + len]).map_err(DecodeError::Json)
1155}
1156
1157/// Error decoding a wire message.
1158#[derive(Debug)]
1159pub enum DecodeError {
1160    /// Data too short to contain length header.
1161    TooShort,
1162    /// Frame size exceeds maximum.
1163    TooLarge(usize),
1164    /// Incomplete frame.
1165    Incomplete {
1166        /// Expected length.
1167        expected: usize,
1168        /// Actual length.
1169        got: usize,
1170    },
1171    /// JSON parse error.
1172    Json(serde_json::Error),
1173}
1174
1175impl std::fmt::Display for DecodeError {
1176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1177        match self {
1178            DecodeError::TooShort => write!(f, "data too short for length header"),
1179            DecodeError::TooLarge(size) => write!(f, "frame too large: {} bytes", size),
1180            DecodeError::Incomplete { expected, got } => {
1181                write!(
1182                    f,
1183                    "incomplete frame: expected {} bytes, got {}",
1184                    expected, got
1185                )
1186            }
1187            DecodeError::Json(e) => write!(f, "JSON decode error: {}", e),
1188        }
1189    }
1190}
1191
1192impl std::error::Error for DecodeError {}
1193
1194#[cfg(test)]
1195mod tests {
1196    use super::*;
1197
1198    #[test]
1199    fn test_encode_decode_roundtrip() {
1200        let req = AgentRequest::Pull {
1201            image: "alpine:latest".to_string(),
1202            oci_platform: Some("linux/arm64".to_string()),
1203            auth: None,
1204            proxy: None,
1205            no_proxy: None,
1206        };
1207
1208        let encoded = encode_message(&req).unwrap();
1209        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1210
1211        let AgentRequest::Pull {
1212            image,
1213            oci_platform,
1214            auth,
1215            proxy,
1216            no_proxy,
1217        } = decoded
1218        else {
1219            panic!("expected Pull variant, got {:?}", decoded);
1220        };
1221        assert_eq!(image, "alpine:latest");
1222        assert_eq!(oci_platform, Some("linux/arm64".to_string()));
1223        assert!(auth.is_none());
1224        assert!(proxy.is_none());
1225        assert!(no_proxy.is_none());
1226    }
1227
1228    #[test]
1229    fn test_encode_decode_with_auth() {
1230        let req = AgentRequest::Pull {
1231            image: "ghcr.io/owner/repo:latest".to_string(),
1232            oci_platform: None,
1233            auth: Some(RegistryAuth {
1234                username: "testuser".to_string(),
1235                password: "testpass".to_string(),
1236            }),
1237            proxy: None,
1238            no_proxy: None,
1239        };
1240
1241        let encoded = encode_message(&req).unwrap();
1242        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1243
1244        let AgentRequest::Pull {
1245            image,
1246            oci_platform,
1247            auth,
1248            proxy: _,
1249            no_proxy: _,
1250        } = decoded
1251        else {
1252            panic!("expected Pull variant, got {:?}", decoded);
1253        };
1254        assert_eq!(image, "ghcr.io/owner/repo:latest");
1255        assert!(oci_platform.is_none());
1256        let auth = auth.expect("auth should be Some");
1257        assert_eq!(auth.username, "testuser");
1258        assert_eq!(auth.password, "testpass");
1259    }
1260
1261    #[test]
1262    fn test_encode_decode_with_proxy() {
1263        let req = AgentRequest::Pull {
1264            image: "alpine:latest".to_string(),
1265            oci_platform: None,
1266            auth: None,
1267            proxy: Some("http://192.168.127.254:3128".to_string()),
1268            no_proxy: Some("127.0.0.1,localhost,.internal".to_string()),
1269        };
1270
1271        let encoded = encode_message(&req).unwrap();
1272        let decoded: AgentRequest = decode_message(&encoded).unwrap();
1273
1274        let AgentRequest::Pull {
1275            proxy, no_proxy, ..
1276        } = decoded
1277        else {
1278            panic!("expected Pull variant, got {:?}", decoded);
1279        };
1280        assert_eq!(proxy.as_deref(), Some("http://192.168.127.254:3128"));
1281        assert_eq!(no_proxy.as_deref(), Some("127.0.0.1,localhost,.internal"));
1282    }
1283
1284    #[test]
1285    fn test_decode_too_short() {
1286        let data = [0u8; 2];
1287        let result: Result<AgentRequest, _> = decode_message(&data);
1288        assert!(matches!(result, Err(DecodeError::TooShort)));
1289    }
1290
1291    #[test]
1292    fn test_decode_incomplete() {
1293        let mut data = vec![0, 0, 0, 100]; // claims 100 bytes
1294        data.extend_from_slice(b"{}"); // only 2 bytes of payload
1295        let result: Result<AgentRequest, _> = decode_message(&data);
1296        assert!(matches!(result, Err(DecodeError::Incomplete { .. })));
1297    }
1298
1299    #[test]
1300    fn test_agent_request_serialization() {
1301        let req = AgentRequest::Ping;
1302        let json = serde_json::to_string(&req).unwrap();
1303        assert!(json.contains("ping"));
1304
1305        let req = AgentRequest::PrepareOverlay {
1306            image: "ubuntu:22.04".to_string(),
1307            workload_id: "wl-123".to_string(),
1308        };
1309        let json = serde_json::to_string(&req).unwrap();
1310        assert!(json.contains("prepare_overlay"));
1311    }
1312
1313    #[test]
1314    fn test_agent_response_serialization() {
1315        let resp = AgentResponse::Pong {
1316            version: PROTOCOL_VERSION,
1317        };
1318        let json = serde_json::to_string(&resp).unwrap();
1319        assert!(json.contains("pong"));
1320
1321        let resp = AgentResponse::Progress {
1322            message: "Pulling layer 1/3".to_string(),
1323            percent: Some(33),
1324            layer: Some("sha256:abc123".to_string()),
1325        };
1326        let json = serde_json::to_string(&resp).unwrap();
1327        assert!(json.contains("progress"));
1328    }
1329
1330    #[test]
1331    fn file_write_begin_roundtrips() {
1332        let req = AgentRequest::FileWriteBegin {
1333            path: "/tmp/target".into(),
1334            mode: Some(0o600),
1335            total_size: 123_456_789,
1336        };
1337        let bytes = encode_message(&req).unwrap();
1338        let back: AgentRequest = decode_message(&bytes).unwrap();
1339        match back {
1340            AgentRequest::FileWriteBegin {
1341                path,
1342                mode,
1343                total_size,
1344            } => {
1345                assert_eq!(path, "/tmp/target");
1346                assert_eq!(mode, Some(0o600));
1347                assert_eq!(total_size, 123_456_789);
1348            }
1349            _ => panic!("wrong variant"),
1350        }
1351    }
1352
1353    #[test]
1354    fn file_write_chunk_roundtrips_binary_data() {
1355        // Binary data (bytes outside UTF-8) must survive the base64
1356        // trip intact. If the encoding ever silently lossifies, this
1357        // fires.
1358        let payload: Vec<u8> = (0u8..=255).collect();
1359        let req = AgentRequest::FileWriteChunk {
1360            data: payload.clone(),
1361            done: true,
1362        };
1363        let bytes = encode_message(&req).unwrap();
1364        let back: AgentRequest = decode_message(&bytes).unwrap();
1365        match back {
1366            AgentRequest::FileWriteChunk { data, done } => {
1367                assert_eq!(data, payload);
1368                assert!(done);
1369            }
1370            _ => panic!("wrong variant"),
1371        }
1372    }
1373
1374    #[test]
1375    fn file_write_size_constants_are_frame_safe() {
1376        // Sanity: a single streaming chunk at FILE_WRITE_CHUNK_SIZE
1377        // must fit inside MAX_FRAME_SIZE after base64 (+ ~33%) and
1378        // JSON overhead. If anyone bumps CHUNK_SIZE past the limit,
1379        // this test fires before production does.
1380        let chunk_bytes = FILE_WRITE_CHUNK_SIZE as u64;
1381        let base64_bytes = chunk_bytes.div_ceil(3) * 4; // ceil(n/3)*4
1382        let json_overhead = 256u64; // method tag, done bool, quotes
1383        let total = base64_bytes + json_overhead;
1384        assert!(
1385            total < MAX_FRAME_SIZE as u64,
1386            "FILE_WRITE_CHUNK_SIZE of {} bytes would produce a frame \
1387             of ~{} bytes which exceeds MAX_FRAME_SIZE of {}",
1388            chunk_bytes,
1389            total,
1390            MAX_FRAME_SIZE
1391        );
1392    }
1393
1394    #[test]
1395    fn test_ports_constants() {
1396        assert_eq!(ports::WORKLOAD_CONTROL, 5000);
1397        assert_eq!(ports::WORKLOAD_LOGS, 5001);
1398        assert_eq!(ports::AGENT_CONTROL, 6000);
1399        assert_eq!(ports::SSH_AGENT, 6001);
1400    }
1401
1402    #[test]
1403    fn test_cid_constants() {
1404        assert_eq!(cid::HOST, 2);
1405        assert_eq!(cid::GUEST, 3);
1406    }
1407
1408    #[test]
1409    fn test_envelope_serialization_with_trace_id() {
1410        let req = AgentRequest::Ping;
1411        let envelope = Envelope::with_trace_id(&req, Some("abc123".to_string()));
1412        let json = serde_json::to_string(&envelope).unwrap();
1413
1414        // trace_id should be flattened alongside the method tag
1415        assert!(json.contains("\"trace_id\":\"abc123\""));
1416        assert!(json.contains("\"method\":\"ping\""));
1417
1418        // Deserialize back — Envelope<AgentRequest> with flatten
1419        let parsed: Envelope<AgentRequest> = serde_json::from_str(&json).unwrap();
1420        assert_eq!(parsed.trace_id.as_deref(), Some("abc123"));
1421        assert!(matches!(parsed.body, AgentRequest::Ping));
1422    }
1423
1424    #[test]
1425    fn test_envelope_without_trace_id() {
1426        let req = AgentRequest::Ping;
1427        let envelope = Envelope::new(&req);
1428        let json = serde_json::to_string(&envelope).unwrap();
1429
1430        // No trace_id field (skip_serializing_if = None)
1431        assert!(!json.contains("trace_id"));
1432        assert!(json.contains("\"method\":\"ping\""));
1433    }
1434
1435    #[test]
1436    fn test_envelope_backward_compat_bare_request() {
1437        // A bare AgentRequest (no Envelope) should fail to parse as Envelope
1438        // but succeed as bare AgentRequest — this is the agent's fallback path
1439        let bare_json = r#"{"method":"ping"}"#;
1440
1441        // Envelope parse should fail (no body field to flatten into)
1442        // Actually with flatten, this may work — let's verify
1443        let envelope_result = serde_json::from_str::<Envelope<AgentRequest>>(bare_json);
1444        let bare_result = serde_json::from_str::<AgentRequest>(bare_json);
1445
1446        // At least one must succeed for backward compat
1447        assert!(
1448            envelope_result.is_ok() || bare_result.is_ok(),
1449            "Neither Envelope nor bare parse succeeded"
1450        );
1451
1452        // Bare parse must always work
1453        assert!(bare_result.is_ok());
1454        assert!(matches!(bare_result.unwrap(), AgentRequest::Ping));
1455
1456        // If Envelope works, trace_id should be None
1457        if let Ok(env) = envelope_result {
1458            assert!(env.trace_id.is_none());
1459        }
1460    }
1461}