System Overview

ClaudioOS is a single-address-space, bare-metal Rust application that boots via UEFI and runs entirely in Ring 0. There is no kernel/user boundary, no syscalls, and no process isolation. Every agent session is a cooperatively-scheduled async task driven by hardware interrupts.

Source entry point: kernel/src/main.rs

+-----------------------------------------------------+
|          Agent Dashboard (6 pane types)              |
|  +--------+ +--------+ +--------+ +------+ +------+ |
|  | Agent  | | Shell  | |Browser | |SysMon| |Scrn- | |
|  | (Claude| | (45+   | |(wraith | |(CPU/ | |saver | |
|  |  +IPC) | |  cmds) | | + TLS) | | mem) | |(5x)  | |
|  +--------+ +--------+ +--------+ +------+ +------+ |
+-----------------------------------------------------+
|  Agent Manager | Session Refresh | SSH Daemon (PQ)   |
|  Git | Email | VectorDB | Streaming | Model Select   |
|  NTP | Search | Notifications | Image Viewer         |
+--------------+--------------+-----------------------+
|  API Client  |     Auth     |   Terminal Renderer   |
|  (Messages   |  (OAuth      |   (framebuffer +      |
|   API + SSE) |   device     |    ANSI + split       |
|              |   flow)      |    panes)             |
+--------------+--------------+-----------------------+
|  Linux Compat (ELF loader + syscall translation)    |
+--------------+--------------+-----------------------+
|              Async Executor (interrupt-driven, SMP)  |
+-----------------------------------------------------+
|  Net (smoltcp + TLS 1.3)  | VFS (ext4/btrfs/NTFS)  |
+----------------------------+------------------------+
|  Intel NIC | VirtIO-net | WiFi | AHCI | NVMe | xHCI|
|  Bluetooth | USB Storage | HDA Audio | GPU | ACPI  |
+------------------------------------+----------------+
|              x86_64 Kernel Core (SMP)                |
|   paging, 48MB heap, GDT/IDT, APIC, PCI, interrupts|
+-----------------------------------------------------+
|              UEFI Boot (bootloader crate v0.11)      |
+-----------------------------------------------------+

Virtual Address Space Map

The bootloader (v0.11) sets up the initial page tables before handing control to kernel_main.

Virtual Address Space (x86_64, 48-bit canonical addresses)
==========================================================

0x0000_0000_0000_0000 +----------------------------------+
                       |  (unmapped / guard)              |
                       +----------------------------------+
                       |  Kernel code + data + rodata     |
                       |  (identity-mapped by bootloader) |
                       +----------------------------------+
                       |  Physical memory offset mapping  |
                       |  (ALL physical RAM accessible    |
                       |   at phys + phys_mem_offset)     |
                       +----------------------------------+
0x0000_4444_4444_0000  |  Kernel Heap (1 MiB)             |
                       |  HEAP_START = 0x4444_4444_0000   |
                       |  HEAP_SIZE  = 1 MiB (1048576)    |
                       |  Managed by linked_list_allocator|
0x0000_4444_4454_0000  +----------------------------------+
                       |  (available for heap growth)     |
                       +----------------------------------+
                       |  Bootloader kernel stack (128K)  |
                       +----------------------------------+
                       |  Heap-allocated stack (256 KiB)  |
                       |  (runtime stack after switch)    |
                       +----------------------------------+
                       |  GOP Framebuffer                 |
                       |  (accessed via phys_mem_offset)  |
                       +----------------------------------+
                       |  IST stacks (static .bss)        |
                       |  IST[0]: 20 KiB double-fault     |
                       |  IST[1]: 16 KiB timer interrupt  |
                       +----------------------------------+

Heap at 0x4444_4444_0000: Chosen to be far from the kernel's identity-mapped region and the bootloader's physical memory mapping. The heap virtual pages are backed by physical frames allocated from the UEFI memory map.

Two kernel stacks: The bootloader provides a 128 KiB stack, but this is nearly exhausted after init. Phase 6 allocates a fresh 256 KiB stack on the heap and switches to it.

Boot Sequence

All phases execute in kernel_main() at kernel/src/main.rs.

UEFI Firmware
    |
    v
bootloader crate (v0.11)
    - Sets up page tables, GOP framebuffer, UEFI memory map
    - Jumps to kernel entry point
    |
    v
kernel_main(boot_info)
    |-- Phase -1: Proof of life (raw serial write)
    |-- Phase 0:  serial::init() + logger::init()
    |-- Phase 1:  gdt::init() (GDT + TSS + data segment)
    |-- Phase 2:  memory::init() (page tables, heap)
    |-- Phase 3:  interrupts::init() (APIC disable, PIC, IDT)
    |-- Phase 3b: keyboard::init()
    |-- Phase 4:  framebuffer::init()
    |-- Phase 5:  pci::enumerate()
    |-- Phase 6:  Heap stack switch + executor start
    v
  executor::run() never returns

Critical ordering: Heap before interrupts (IDT may allocate). Interrupts not enabled until executor is ready. APIC disabled before PIC init.

The Heap Stack Switch

The bootloader's 128 KiB stack is nearly exhausted after init (log formatting is extremely stack-heavy). Phase 6 allocates a fresh 256 KiB stack on the heap and switches to it:

const NEW_STACK_SIZE: usize = 256 * 1024;
let new_stack = alloc::vec![0u8; NEW_STACK_SIZE];
let new_stack_top = new_stack.as_ptr() as u64 + NEW_STACK_SIZE as u64;
core::mem::forget(new_stack);  // Leak -- kernel stack must never be freed

unsafe {
    core::arch::asm!(
        "mov rsp, {stack}",
        "call {entry}",
        stack = in(reg) new_stack_top,
        entry = in(reg) post_stack_switch as *const (),
        options(noreturn)
    );
}

The Vec is leaked with mem::forget because the stack memory must never be freed. post_stack_switch() enables interrupts and starts the executor.

Async Executor Architecture

The executor is a cooperative, single-threaded scheduler where hardware interrupts serve as the sole source of wake-ups.

+------------------+     +-----------------+     +------------------+
|   ISR Handlers   |     |   READY_QUEUE   |     |    Executor      |
|                  |     |   (Mutex<Vec>)  |     |    run() loop    |
|  keyboard_handler| --> | [TaskId(0),     | --> |                  |
|  timer_handler   |     |  TaskId(2), ...]|     | 1. drain queue   |
|  nic_handler     |     +-----------------+     | 2. poll tasks    |
+------------------+           ^                 | 3. hlt if empty  |
                               |                 +------------------+
                      +--------+--------+
                      |   TaskWaker     |
                      |   wake() pushes |
                      |   to READY_QUEUE|
                      +-----------------+

Two separate locks prevent deadlocks: READY_QUEUE (task IDs only, locked briefly by ISRs) and EXECUTOR (full task map, never locked by ISRs).

HLT race fix: Interrupts are disabled before checking if the queue is empty. enable_and_hlt atomically enables interrupts and halts so no work is missed.

Crate Dependency Graph

                    kernel (binary, #![no_std] #![no_main])
                   /   |    |    \    \     \
                  v    v    v     v    v     v
            terminal  net  auth  agent  fs   image-builder
            (active) (Ph2) (Ph3) (Ph4) (Ph3) (host-side)
               |       |    |     |     |
               v       v    v     v     v
          alloc + core (all #![no_std])

GDT and TSS

Source: kernel/src/gdt.rs

Even in 64-bit long mode, x86_64 requires a valid GDT. The bootloader sets one up, but ClaudioOS replaces it with a custom GDT containing a TSS (for IST stacks) and a kernel data segment.

GDT Entry Map:
  Entry 0:   Null descriptor (required by x86)
  Entry 1:   Kernel code segment (64-bit, Execute/Read, DPL=0)
  Entry 2:   Kernel data segment (64-bit, Read/Write, DPL=0)
  Entry 3-4: TSS descriptor (16 bytes, spans two GDT entries)

IST Stack Allocations:
  IST[0] = Double-fault handler (20 KiB, static .bss)
  IST[1] = Timer interrupt handler (16 KiB, static .bss)

The Data Segment Bug (Critical Phase 1 Fix)

This was the single hardest bug in Phase 1. After enabling interrupts, the first hardware interrupt caused an immediate double fault.

Root cause: The bootloader's GDT has no data segment, so SS = 0. When an interrupt fires, the CPU pushes SS onto the stack. On iretq, loading SS = 0x0 triggers a #GP fault, which cascades into a double fault.

// The fix: GDT must include a kernel data segment
let data_selector = gdt.append(Descriptor::kernel_data_segment());

// And all data segment registers must be loaded
DS::set_reg(GDT.1.data_selector);
ES::set_reg(GDT.1.data_selector);
SS::set_reg(GDT.1.data_selector);

Lesson: In long mode, SS is still used by the interrupt frame push/pop cycle. A valid, non-null SS selector is mandatory.

Memory Management

Source: kernel/src/memory.rs

Two-tier system: a physical frame bump allocator (BootInfoFrameAllocator) doles out 4 KiB frames from the UEFI memory map, and linked_list_allocator manages the kernel heap at 0x4444_4444_0000.

Heap Init:
  1. Read CR3 -> active L4 page table
  2. Create OffsetPageTable mapper
  3. For each 4 KiB page in [HEAP_START, HEAP_START + HEAP_SIZE):
     - Allocate physical frame
     - Map virtual page -> physical frame (PRESENT | WRITABLE)
  4. Initialize linked_list_allocator
  -> Box, Vec, String, BTreeMap now work

Interrupt System

Source: kernel/src/interrupts.rs

ClaudioOS uses the dual 8259 PIC. The Local APIC is explicitly disabled to prevent conflicting timer delivery.

PIC Configuration:
  PIC1: offset 32, PIC2: offset 40
  Unmasked: IRQ0 (timer, vec 32), IRQ1 (keyboard, vec 33)
  All others masked

IDT Entries:
  Vec 3:  breakpoint   (raw serial write, no log)
  Vec 8:  double_fault (IST[0], 20 KiB stack)
  Vec 14: page_fault   (reads CR2, logs, halts)
  Vec 32: timer        (EOI only, no logging)
  Vec 33: keyboard     (read port 0x60, push scancode, wake async)

Serial UART

Source: kernel/src/serial.rs

16550 UART at I/O base 0x3F8 (COM1). 115200 baud, 8N1. The _print() function disables interrupts while holding the serial lock to prevent deadlocks.

force_println! is used in the panic handler -- it calls force_unlock() to break any held lock, which is safe because the panic handler never returns.

Framebuffer

Source: kernel/src/framebuffer.rs

The UEFI GOP framebuffer is accessed indirectly: the kernel walks the page table to find the physical address, then accesses it through the phys_mem_offset mapping which is guaranteed PRESENT + WRITABLE. BGR pixel format, 4 bytes per pixel.

PCI Enumeration

Source: kernel/src/pci.rs

Legacy I/O port PCI config space access (ports 0xCF8/0xCFC). Scans bus 0, devices 0-31. Identifies VirtIO-net (1AF4:1000), e1000 (8086:100E), enables bus mastering for DMA-capable devices.

Terminal Overview

Source: crates/terminal/src/

The terminal crate is #![no_std] with extern crate alloc. It renders through a DrawTarget trait:

pub trait DrawTarget {
    fn put_pixel(&mut self, x: usize, y: usize, r: u8, g: u8, b: u8);
    fn width(&self) -> usize;
    fn height(&self) -> usize;
}

Data flow: raw bytes -> VTE parser -> cell grid -> noto-sans-mono-bitmap glyphs -> DrawTarget::put_pixel() -> framebuffer.

Font Rendering Pipeline

Source: crates/terminal/src/render.rs

Characters are rendered using pre-rasterized bitmap glyphs from noto-sans-mono-bitmap. No font file loading, no TrueType parsing. Binary threshold at intensity 128 (foreground if > 128, background otherwise).

Font height: 16 pixels. Width: compile-time computed from the font crate.

VTE Parser Integration

Source: crates/terminal/src/pane.rs

Each Pane contains a vte::Parser (v0.15) that classifies incoming bytes as printable characters, control codes, or escape sequences. The parser ownership uses mem::replace to avoid double-mutable-borrow.

Supported: SGR colors (standard, bright, 256-color basic, truecolor RGB), cursor positioning (CUP, CUU/D/F/B, CHA, VPA), erase (ED, EL), scroll (SU), line insert/delete (IL, DL), control codes (LF, CR, BS, HT, BEL).

Split-Pane Layout Tree

Source: crates/terminal/src/layout.rs

The layout is a binary tree: leaf nodes contain a pane ID and viewport, split nodes contain a direction (Vertical/Horizontal), ratio, and two children.

Example: Three panes

           Split(Vertical, 0.5)
          /                     \
    Leaf(pane 0)         Split(Horizontal, 0.5)
                         /                      \
                    Leaf(pane 1)           Leaf(pane 2)

+------------------+--+------------------+
|                  |  |     Pane 1       |
|     Pane 0       |  +--+--------------+
|                  |  |     Pane 2       |
+------------------+--+------------------+

Separators are 2 pixels wide, rendered in BRIGHT_BLACK. Viewports are recomputed top-down on split/close. Focus wraps cyclically.

Color System

16-color CGA-derived palette (SGR 30-37 standard, 90-97 bright). 256-color mode maps indices 0-15 to the palette; 16-255 are ignored. Truecolor (38;2;r;g;b / 48;2;r;g;b) is fully supported.

Default foreground: (204, 204, 204). Default background: (16, 16, 16) -- not pure black, to distinguish from unused framebuffer regions.

Networking Stack Architecture

Source: crates/net/src/

HTTP client (http.rs)
    |
    v  raw bytes over TLS
TLS stream (tls.rs)
    |
    v  encrypted TLS records
TCP socket (smoltcp)
    |
    v  TCP segments
IP / Ethernet (smoltcp)
    |
    v  Ethernet frames
NIC driver (nic.rs) -- VirtIO virtqueues (DMA)
    |
    v
Hardware / QEMU SLIRP

VirtIO-net Driver

Source: crates/net/src/nic.rs (~757 lines)

Legacy VirtIO (0.9.5) PCI driver. Initialization: reset, acknowledge, negotiate features (MAC + STATUS), read MAC address, set up RX queue (256 descriptors with 2048-byte DMA buffers) and TX queue, then DRIVER_OK.

TX flow: reclaim completed descriptors from used ring, allocate descriptor, write 10-byte VirtIO-net header (all zeros) + Ethernet frame, push to available ring, notify device. RX flow: check used ring, strip 10-byte header, copy frame, recycle descriptor.

virt_to_phys() performs a full 4-level page table walk for DMA address translation of heap-allocated buffers.

smoltcp Integration

Source: crates/net/src/stack.rs

SmoltcpDevice wraps VirtioNet and implements smoltcp's Device trait. MTU 1514, medium Ethernet. NetworkStack owns the smoltcp Interface, SocketSet, and device. DHCP via smoltcp's built-in DHCPv4 socket -- QEMU SLIRP provides 10.0.2.x.

DNS Resolution

Source: crates/net/src/dns.rs

Synchronous DNS via smoltcp's DNS socket. Creates A record query, polls network stack in a loop (up to 10,000 iterations), returns first IPv4 address. Uses DHCP-provided DNS server addresses.

TLS Strategy

Source: crates/net/src/tls.rs

TLS in #![no_std] is one of the hardest parts. Current plan: embedded-tls 0.17 (designed for no_std, but triggers LLVM codegen crashes). Fallback: rustls no_std port. TCP helpers (tcp_connect, tcp_send, tcp_recv) are functional; TLS handshake methods contain todo!() markers.

HTTP/1.1 Client

Source: crates/net/src/http.rs (~564 lines)

Minimal HTTP/1.1: request building with headers, response parsing (status line, headers, body via Content-Length), chunked transfer encoding decoder, and pre-configured helpers for Anthropic API and OAuth requests. Host-side unit tested.

SSE Parser

Server-Sent Events parser for Anthropic's streaming API. parse_sse_events(data) returns complete events and bytes consumed; incomplete events are preserved for the next read cycle. Each SseEvent has an event type and data (JSON payload).

Messages API

Source: crates/api-client/src/lib.rs

POST to https://api.anthropic.com/v1/messages with JSON body. Required headers: Content-Type, anthropic-version, x-api-key or Authorization: Bearer, Accept: text/event-stream. Raw HTTP/1.1 bytes over TLS -- no reqwest, no hyper.

pub fn anthropic_messages_request(api_key: &str, body_json: &[u8]) -> HttpRequest {
    HttpRequest::post("api.anthropic.com", "/v1/messages", body_json.to_vec())
        .header("Content-Type", "application/json")
        .header("x-api-key", api_key)
        .header("anthropic-version", "2023-06-01")
        .header("Accept", "text/event-stream")
        .header("Connection", "close")
}

SSE Streaming Protocol

When "stream": true, the API responds with SSE events: message_start, content_block_start, content_block_delta (repeated, contains text chunks), content_block_stop, message_delta (stop_reason, usage), message_stop.

Text deltas are written directly to the agent's terminal pane as they arrive. Tool use blocks accumulate input_json_delta fragments until content_block_stop.

Tool Use Protocol

When Claude requests a tool, the SSE stream contains tool_use content blocks with incremental JSON input. After accumulating and parsing, ClaudioOS executes the tool and sends a tool_result message in the next conversation turn.

Available tools are restricted to file I/O on FAT32 (read_file, write_file, list_files). No shell execution -- ClaudioOS has no subprocess capability.

OAuth 2.0 Device Authorization Grant

Source: crates/auth/src/lib.rs

RFC 8628 device flow: POST to /oauth/device/code, display user code on framebuffer, user authorizes on phone/laptop, ClaudioOS polls for token. Tokens persisted to FAT32. Background async task refreshes before expiry. CLAUDIO_API_KEY env var bypasses OAuth for development.

pub enum Credentials {
    ApiKey(String),
    OAuth {
        access_token: String,
        refresh_token: String,
        expires_at: u64,
    },
}

Token Persistence

FAT32 layout via the fatfs crate:

/claudio/
    config.json
    auth/
        token.json     (access + refresh tokens)
        api_key.txt    (optional dev key)
    agents/
        session_0.json (conversation history)
    logs/
        boot.log

Prerequisites

Nightly Rust (auto-installed via rust-toolchain.toml), QEMU, and OVMF (for UEFI boot). Windows needs MSVC Build Tools for the image builder.

# Linux
sudo apt install qemu-system-x86 ovmf

# macOS
brew install qemu

# Windows: install QEMU + Visual Studio Build Tools

Two-Step Build Process

# Step 1: Compile the kernel
cargo build

# Step 2: Create bootable disk images
cargo run --manifest-path tools/image-builder/Cargo.toml -- \
    target/x86_64-unknown-none/debug/claudio-os

The image builder is a host-side binary excluded from the workspace to avoid inheriting the x86_64-unknown-none target. It produces both UEFI and BIOS disk images.

Running in QEMU

# BIOS boot (simplest)
qemu-system-x86_64 \
    -drive format=raw,file=target/x86_64-unknown-none/debug/claudio-os-bios.img \
    -serial stdio -m 512M

# UEFI boot
qemu-system-x86_64 \
    -bios /usr/share/OVMF/OVMF_CODE.fd \
    -drive format=raw,file=target/x86_64-unknown-none/debug/claudio-os-uefi.img \
    -serial stdio -m 512M

# With VirtIO networking
qemu-system-x86_64 \
    -bios /usr/share/OVMF/OVMF_CODE.fd \
    -drive format=raw,file=target/x86_64-unknown-none/debug/claudio-os-uefi.img \
    -device virtio-net-pci,netdev=net0 \
    -netdev user,id=net0 \
    -serial stdio -m 512M -smp 4

Troubleshooting

Double Fault After Enabling Interrupts

  • Missing data segment: SS must be loaded with a valid selector. See The Data Segment Bug.
  • APIC not disabled: Clear bit 11 of IA32_APIC_BASE MSR before PIC init.
  • Stack overflow: The bootloader's 128 KiB stack is exhausted. The heap stack switch fixes this.

Windows MSVC Linker Errors

Install "Desktop development with C++" in Visual Studio. Set LIB environment variable if libraries are not found.

embedded-tls LLVM Crashes

Set opt-level = 1 in [profile.dev] or codegen-units = 1.

Environment Variables

VariableDefaultDescription
CLAUDIO_API_KEY(none)Baked-in API key, skips OAuth (dev only)
CLAUDIO_LOG_LEVELinfoLog level: trace/debug/info/warn/error
CLAUDIO_QEMU0QEMU-friendly defaults (VirtIO, SLIRP)

Development Workflow

# Edit -> Build -> Image -> QEMU
cargo build && \
cargo run --manifest-path tools/image-builder/Cargo.toml -- \
    target/x86_64-unknown-none/debug/claudio-os && \
qemu-system-x86_64 \
    -drive format=raw,file=target/x86_64-unknown-none/debug/claudio-os-bios.img \
    -serial stdio -m 512M -no-reboot

Code Conventions

  • All crates are #![no_std] with extern crate alloc
  • Use log crate macros with [module] prefix for all output
  • spin::Mutex for shared state, spin::Lazy for lazy init
  • Disable interrupts while holding locks (without_interrupts)
  • panic = "abort" -- no unwinding, no catch_unwind
  • Unsafe code with // SAFETY: comments

Testing

Pure logic crates can be tested on the host:

cd crates/net && cargo test     # HTTP/SSE parser tests
cd crates/terminal && cargo test  # terminal logic tests

Kernel testing is manual in QEMU: boot, watch serial output, verify no panics, type on keyboard.

Common Pitfalls

  • Stack overflow in ISR handlers: No log::* calls. Send EOI, push to queue, return.
  • Deadlock from lock ordering: Use without_interrupts. Keep ISR locks separate.
  • Forgetting EOI: System hangs if interrupt handler skips End-of-Interrupt.
  • Physical vs virtual addresses: DMA devices need physical. Use page table walks for heap.
  • Framebuffer not writable: Access through phys_mem_offset, not bootloader mapping.
  • mem::forget for long-lived allocations: Heap stack must be leaked.