IPC
Session handshake, shared memory layout and record rules for custom clients of the local agent's IPC interface
Use this reference when implementing a client for the local agent's Linux shared memory interface. The transaction senders include Rust, Go and TypeScript clients; the standalone C example is also available. For agent setup, see Local interfaces.
All multi-byte integers are little-endian. Access control words with aligned 32-bit or 64-bit atomic operations and the memory ordering below. Plain loads and stores are not sufficient for those words.
Session setup
- Connect a Unix
SOCK_STREAMsocket to the configuredlisten.ipcpath. - Send the four ASCII bytes
ZCI1(5A 43 49 31) within 2 seconds. The hello carries no API key: the local agent sends under its executable's license. - Read the nine-byte reply with
recvmsg, collecting the shared-memory file descriptor fromSCM_RIGHTSancillary data. A stream read can be partial; collect all nine bytes and the descriptor before proceeding. - Validate the capacities and use
fstatto check the descriptor holds at least4096 + submission capacity + completion capacitybytes. Map that length from offset 0 withPROT_READ | PROT_WRITEandMAP_SHARED. - Validate the mapping header against the reply, including magic
ZCR1and version1. - Keep the socket open and switch it to nonblocking mode. It carries wake-up bytes; closing it ends the session.
| Reply offset | Size | Field |
|---|---|---|
| 0 | 1 | Reply code, 0 |
| 1 | 4 | Submission capacity in bytes |
| 5 | 4 | Completion capacity in bytes |
Read capacities from the reply; do not hard-code them. Each must be a power of two of at least 16 bytes. Treat a nonzero reply code as a refused session. An invalid hello closes the socket without a reply.
Each connection has its own mapping. Use one producer and one consumer per ring, or serialize access within your process. Separate sending threads can use separate sessions.
Shared-memory layout
| Offset | Size | Field | Writer |
|---|---|---|---|
| 0 | 4 | Magic ZCR1 | Agent, once |
| 4 | 4 | Version 1 | Agent, once |
| 8 | 4 | Submission capacity | Agent, once |
| 12 | 4 | Completion capacity | Agent, once |
| 64 | 8 | Submission tail | Client |
| 128 | 8 | Submission head | Agent |
| 192 | 8 | Completion tail | Agent |
| 256 | 8 | Completion head | Client |
| 320 | 4 | Agent parked flag | Agent sets; client clears |
| 384 | 4 | Client parked flag | Client sets; agent clears |
| 4096 | Submission capacity | Submission ring | Client |
| 4096 + submission capacity | Completion capacity | Completion ring | Agent |
The remaining header bytes are reserved. Leave them unchanged.
Ring rules
The client produces submissions and consumes completions. Each ring has one producer and one consumer.
Positions
Head and tail are monotonically increasing 64-bit byte counters, not offsets that wrap at the capacity. Both are multiples of 16, head <= tail, and tail - head <= capacity. The byte offset of a position is position % capacity.
Use acquire loads for the peer's counter and release stores to publish your own counter. Do not wrap a counter through zero.
Records
A record contains a 16-byte header, the payload, then zero padding to a multiple of 16 bytes. Its total size is (16 + payload_length + 15) & ~15.
| Header offset | Size | Field |
|---|---|---|
| 0 | 4 | Payload length, excluding header and padding |
| 4 | 1 | Kind |
| 5 | 1 | Flags |
| 6 | 2 | Reserved; write 0 |
| 8 | 8 | Request ID |
A record must not cross the ring boundary. If it would, publish a pad record in the remaining bytes before writing the real record at offset 0. The pad header has kind, flags, reserved and ID all zero; its length is remaining bytes - 16. Consumers skip the whole remainder, without interpreting its payload.
Writing a record
- Load your tail and acquire-load the consumer's head. Validate the positions.
- Calculate the aligned record size and any boundary pad. If their sum exceeds
capacity - (tail - head), wait for space without publishing the record. - Write any pad header, then the real header, payload and alignment padding.
- Release-store
tail + pad size + record sizeas the new tail. - Issue a sequentially consistent fence and wake the consumer if parked.
Reading a record
- Load your head and acquire-load the producer's tail. Validate alignment, ordering and the number of bytes in use. Equal positions mean the ring is empty.
- Validate the header and payload length before reading. A real record must fit within the ring boundary, the published bytes and the payload limit for its kind. A pad must have the required zero fields and cover exactly the published remainder of the ring.
- Copy the payload before advancing the head.
- Release-store
head + record size, orhead + remaining bytesfor a pad. The producer can overwrite those bytes after this store.
Submissions
| Kind | Payload | Flags |
|---|---|---|
1 | One signed transaction, bare or inside a payload envelope | 0x01 requests a completion. Also set 0x02 for preflight at processed commitment: flags 0x03 request both. |
3 | Bundle envelope containing one to four signed transactions | 0x01 requests a completion |
Payloads use the payload envelope; IPC has no QUIC stream header. The submission payload limit is 16,403 bytes; the transaction limits still apply to each member.
Kind 1 requires a transaction payload and kind 3 requires a bundle payload. A mismatch produces malformed with problem: "expected_transaction" or "expected_bundle". Other kinds produce "invalid_record_kind"; unsupported flag bits produce "invalid_record_flags". The session stays open after these refusals.
The completion echoes the 64-bit request ID. Keep IDs distinct among outstanding requests in a session. Completions can arrive out of order.
Without 0x01, there is no completion, including on rejection, and no preflight. Use requests with replies while integrating.
Completions
| Field | Meaning |
|---|---|
| Kind | 3 for a bundle submission, otherwise 1 |
| Flags | Reply code; 0 means accepted |
| Request ID | The submission's ID |
Kind 1 payload | Empty on acceptance; rejection detail otherwise |
Kind 3 payload | 32-byte bundle ID, followed by rejection detail on refusal; a refused bundle has an all-zero ID |
Rejection detail is UTF-8 JSON of at most 65,535 bytes, using the error fields. The bundle ID is the raw 32 byte value returned as hexadecimal by sendBundle.
An accepted reply is not proof of landing. See local interfaces and confirmation and retries.
Keep draining completions. If an error detail will not fit, the completion can contain only its code: an empty payload for kind 1, or 32 zero bytes for kind 3. If the completion ring has no room even for that, the completion is lost. Give every outstanding request a timeout.
Doorbells
A parked consumer blocks on the Unix socket. The producer clears the consumer's parked flag and writes one byte to wake it. The byte's value is irrelevant.
To wait for completions:
- Release-store
1in the client parked flag at offset 384, then issue a sequentially consistent fence. - Acquire-load the completion tail again. If data arrived, clear the parked flag and read it without sleeping.
- Otherwise wait for socket readability, for example with
polland a request timeout. - Clear the flag with a release store, then drain wake-up bytes until the nonblocking read would block. A read of 0 means the session ended.
After publishing a submission:
- Issue a sequentially consistent fence after the release store to the submission tail.
- Acquire-load the agent parked flag at offset 320. If it is
1, exchange it with0using sequentially consistent ordering. - If the exchange returned
1, write a byte to the socket withMSG_NOSIGNAL. A failed or would-block wake-up write does not invalidate the published record.
The agent wakes the client the same way after publishing a completion. Implement doorbells even when busy polling is enabled, so the client also works with it disabled.
Session end and errors
- Closing the socket ends the session, but does not cancel submissions already published.
- A stop or update closes the agent's socket.
pollcan reportPOLLHUP, or a read returns 0. Completions already published remain readable in the mapping. - Invalid submission positions or record boundaries close the session without an error completion. Fix the producer before reconnecting.
Drain any published completions, unmap the old memory and connect again with a fresh handshake. Do not reuse the old mapping. Check transaction signatures before replaying requests whose outcomes are unknown.
Transaction sender
These clients send one transaction with request ID 1 and no preflight, wait up to five seconds for its completion and exit with status 0 only for acceptance. Save raw signed wire bytes in a file; the clients do not construct or sign a transaction. They validate the handshake, mapping and record boundaries, copy a completion before releasing its ring space, and implement both doorbells. Empty rejection detail is allowed when the agent cannot fit the JSON in the completion ring.
Use Linux x86_64. Rust and Go are files in the example project; Rust also needs the libc crate. TypeScript requires Bun, glibc (libc.so.6) and GCC's atomic runtime (libatomic.so.1). It calls those libraries through Bun's experimental FFI, which Bun does not recommend for production. It does not run in Node.js, browsers or on musl Linux. Atomic control words use native acquire/release operations and sequentially consistent exchanges; JavaScript buffer reads alone cannot implement the ring protocol.
Download Rust, Go or TypeScript. Save the Rust file as src/bin/ipc_send.rs and the Go file as ipc-send/main.go in the example project; keep the TypeScript filename unchanged. The C client remains available, with build instructions.
use std::{
fs::File,
io::{self, Read, Write},
mem,
os::fd::{AsRawFd, FromRawFd, OwnedFd},
os::unix::net::UnixStream,
ptr::NonNull,
sync::atomic::{AtomicU32, AtomicU64, Ordering, fence},
time::{Duration, Instant},
};
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
const HEADER: usize = 4096;
const MAX_PAYLOAD: usize = 16403;
const MAX_DETAIL: usize = 65535;
struct Session {
socket: UnixStream,
base: NonNull<u8>,
length: usize,
submission: u64,
completion: u64,
}
impl Drop for Session {
fn drop(&mut self) {
unsafe { libc::munmap(self.base.as_ptr().cast(), self.length); }
}
}
fn capacity(value: u64) -> bool { value >= 16 && value.is_power_of_two() }
fn size(length: u64) -> u64 { (16 + length + 15) & !15 }
fn u32_at(bytes: &[u8], at: usize) -> u32 {
u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
}
fn u64_at(bytes: &[u8], at: usize) -> u64 {
u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap())
}
fn positions(head: u64, tail: u64, cap: u64) -> Result<()> {
if (head | tail) & 15 != 0 || head > tail || tail - head > cap {
return Err("invalid ring positions".into());
}
Ok(())
}
impl Session {
fn connect(path: &str) -> Result<Self> {
let mut socket = UnixStream::connect(path)?;
socket.set_write_timeout(Some(Duration::from_secs(2)))?;
let deadline = Instant::now() + Duration::from_secs(2);
socket.write_all(b"ZCI1")?;
let mut reply = [0u8; 9];
let mut received = 0;
let mut descriptor: Option<OwnedFd> = None;
while received < reply.len() {
let left = deadline.checked_duration_since(Instant::now())
.ok_or("IPC handshake timed out")?;
socket.set_read_timeout(Some(left))?;
// usize storage gives cmsghdr its required alignment.
let mut control = [0usize; 3];
let mut part = libc::iovec {
iov_base: reply[received..].as_mut_ptr().cast(),
iov_len: reply.len() - received,
};
let mut message: libc::msghdr = unsafe { mem::zeroed() };
message.msg_iov = &mut part;
message.msg_iovlen = 1;
message.msg_control = control.as_mut_ptr().cast();
message.msg_controllen = mem::size_of_val(&control);
let count = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC) };
if count < 0 {
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted { continue; }
return Err(error.into());
}
if count == 0 { return Err("agent closed during handshake".into()); }
unsafe {
let mut entry = libc::CMSG_FIRSTHDR(&message);
while !entry.is_null() {
if (*entry).cmsg_level == libc::SOL_SOCKET && (*entry).cmsg_type == libc::SCM_RIGHTS {
let header = libc::CMSG_LEN(0) as usize;
let length = (*entry).cmsg_len;
if length < header || (length - header) % mem::size_of::<i32>() != 0 {
return Err("invalid descriptor message".into());
}
let count = (length - header) / mem::size_of::<i32>();
for index in 0..count {
let fd = std::ptr::read_unaligned(libc::CMSG_DATA(entry).cast::<i32>().add(index));
let owned = OwnedFd::from_raw_fd(fd);
if descriptor.is_some() || count != 1 {
return Err("unexpected descriptors in handshake".into());
}
descriptor = Some(owned);
}
}
entry = libc::CMSG_NXTHDR(&message, entry);
}
}
if message.msg_flags & (libc::MSG_CTRUNC | libc::MSG_TRUNC) != 0 {
return Err("truncated handshake".into());
}
received += count as usize;
}
if reply[0] != 0 { return Err(format!("session refused with code {}", reply[0]).into()); }
let file = File::from(descriptor.ok_or("handshake carried no shared memory")?);
let submission = u64::from(u32_at(&reply, 1));
let completion = u64::from(u32_at(&reply, 5));
if !capacity(submission) || !capacity(completion) { return Err("invalid capacity".into()); }
let length = usize::try_from(HEADER as u64 + submission + completion)?;
if file.metadata()?.len() < length as u64 { return Err("shared memory is too small".into()); }
let mapped = unsafe {
libc::mmap(std::ptr::null_mut(), length, libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED, file.as_raw_fd(), 0)
};
if mapped == libc::MAP_FAILED { return Err(io::Error::last_os_error().into()); }
let session = Self {
socket, base: NonNull::new(mapped.cast()).ok_or("null mapping")?,
length, submission, completion,
};
let header = session.bytes(0, 16);
if &header[..4] != b"ZCR1" || u32_at(header, 4) != 1
|| u64::from(u32_at(header, 8)) != submission
|| u64::from(u32_at(header, 12)) != completion {
return Err("unexpected shared memory header".into());
}
session.socket.set_nonblocking(true)?;
Ok(session)
}
fn bytes(&self, offset: usize, length: usize) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.base.as_ptr().add(offset), length) }
}
fn word64(&self, offset: usize) -> &AtomicU64 {
unsafe { &*self.base.as_ptr().add(offset).cast::<AtomicU64>() }
}
fn word32(&self, offset: usize) -> &AtomicU32 {
unsafe { &*self.base.as_ptr().add(offset).cast::<AtomicU32>() }
}
fn submit(&self, id: u64, payload: &[u8]) -> Result<()> {
let tail = self.word64(64).load(Ordering::Relaxed);
let head = self.word64(128).load(Ordering::Acquire);
positions(head, tail, self.submission)?;
let record_size = size(payload.len() as u64);
let mut offset = tail & (self.submission - 1);
let remaining = self.submission - offset;
let pad = if record_size > remaining { remaining } else { 0 };
if pad + record_size > self.submission - (tail - head) {
return Err("submission ring is full".into());
}
let next = tail.checked_add(pad + record_size).ok_or("submission counter overflow")?;
unsafe {
if pad != 0 {
let record = self.base.as_ptr().add(HEADER + offset as usize);
std::ptr::write_bytes(record, 0, 16);
std::ptr::copy_nonoverlapping(((pad - 16) as u32).to_le_bytes().as_ptr(), record, 4);
offset = 0;
}
let record = std::slice::from_raw_parts_mut(
self.base.as_ptr().add(HEADER + offset as usize), record_size as usize);
record.fill(0);
record[..4].copy_from_slice(&(payload.len() as u32).to_le_bytes());
record[4] = 1;
record[5] = 1; // Request a completion, without preflight.
record[8..16].copy_from_slice(&id.to_le_bytes());
record[16..16 + payload.len()].copy_from_slice(payload);
}
self.word64(64).store(next, Ordering::Release);
fence(Ordering::SeqCst);
if self.word32(320).swap(0, Ordering::SeqCst) == 1 {
let byte = 0u8;
unsafe {
libc::send(self.socket.as_raw_fd(), (&byte as *const u8).cast(), 1,
libc::MSG_NOSIGNAL | libc::MSG_DONTWAIT);
}
}
Ok(())
}
fn read_completion(&self) -> Result<Option<(u64, u8, Vec<u8>)>> {
loop {
let head = self.word64(256).load(Ordering::Relaxed);
let tail = self.word64(192).load(Ordering::Acquire);
positions(head, tail, self.completion)?;
let used = tail - head;
if used == 0 { return Ok(None); }
let offset = head & (self.completion - 1);
let remaining = self.completion - offset;
let record = self.bytes(HEADER + self.submission as usize + offset as usize, 16);
let length = u64::from(u32_at(record, 0));
let id = u64_at(record, 8);
let kind = record[4];
let code = record[5];
if record[6] != 0 || record[7] != 0 { return Err("nonzero reserved bytes".into()); }
if kind == 0 {
if length != remaining - 16 || remaining > used || code != 0 || id != 0 {
return Err("invalid pad record".into());
}
self.word64(256).store(head + remaining, Ordering::Release);
continue;
}
let record_size = size(length);
if kind != 1 || length > MAX_DETAIL as u64 || record_size > remaining
|| record_size > used || code > 13 || (code == 0 && length != 0) {
return Err("invalid transaction completion".into());
}
let payload = self.bytes(HEADER + self.submission as usize + offset as usize + 16,
length as usize).to_vec();
self.word64(256).store(head + record_size, Ordering::Release);
return Ok(Some((id, code, payload)));
}
}
fn wait_for(&mut self, id: u64) -> Result<(u8, Vec<u8>)> {
let deadline = Instant::now() + Duration::from_secs(5);
let mut ended = false;
loop {
while let Some((received_id, code, payload)) = self.read_completion()? {
if received_id == id { return Ok((code, payload)); }
}
if ended { return Err("session ended; check the signature before retrying".into()); }
let left = deadline.checked_duration_since(Instant::now())
.ok_or("no completion within 5 seconds; check the signature before retrying")?;
self.word32(384).store(1, Ordering::Release);
fence(Ordering::SeqCst);
if self.word64(192).load(Ordering::Acquire) != self.word64(256).load(Ordering::Relaxed) {
self.word32(384).store(0, Ordering::Release);
continue;
}
let mut watch = libc::pollfd { fd: self.socket.as_raw_fd(), events: libc::POLLIN, revents: 0 };
let ready = unsafe { libc::poll(&mut watch, 1, left.as_millis().max(1) as i32) };
self.word32(384).store(0, Ordering::Release);
if ready < 0 {
let error = io::Error::last_os_error();
if error.kind() == io::ErrorKind::Interrupted { continue; }
return Err(error.into());
}
if ready > 0 {
ended = watch.revents & (libc::POLLERR | libc::POLLHUP | libc::POLLNVAL) != 0;
let mut bytes = [0u8; 128];
loop {
match self.socket.read(&mut bytes) {
Ok(0) => { ended = true; break; }
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
Err(_) => { ended = true; break; }
}
}
}
}
}
}
fn run() -> Result<bool> {
if !cfg!(all(target_os = "linux", target_arch = "x86_64", target_endian = "little")) {
return Err("this client requires Linux x86_64".into());
}
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 { return Err("usage: ipc_send SOCKET_PATH TRANSACTION_FILE".into()); }
let mut payload = Vec::new();
File::open(&args[2])?.take((MAX_PAYLOAD + 1) as u64).read_to_end(&mut payload)?;
if payload.is_empty() || payload.len() > MAX_PAYLOAD {
return Err("transaction payload must hold 1 to 16403 bytes".into());
}
let mut session = Session::connect(&args[1])?;
session.submit(1, &payload)?;
let (code, detail) = session.wait_for(1)?;
let text = std::str::from_utf8(&detail)?;
if !detail.is_empty() {
let rejection: serde_json::Value = serde_json::from_str(text)?;
if rejection.get("reason").and_then(|value| value.as_str()).filter(|reason| !reason.is_empty()).is_none() {
return Err("invalid rejection detail".into());
}
}
println!("code {code}");
if !text.is_empty() { println!("{text}"); }
Ok(code == 0)
}
fn main() {
match run() {
Ok(true) => {}
Ok(false) => std::process::exit(1),
Err(error) => { eprintln!("{error}"); std::process::exit(1); }
}
}Run the selected client from its project directory, using your configured socket path and signed transaction file:
cargo run --bin ipc_send -- /run/zerocopy/agent.sock signed-transaction.bin
# Or:
go run ./ipc-send /run/zerocopy/agent.sock signed-transaction.bin
# Or:
bun swqos-ipc-send.ts /run/zerocopy/agent.sock signed-transaction.binA successful submission prints code 0. A refusal prints its nonzero reply code and any UTF-8 JSON detail, then exits with status 1. Unknown reply codes, nonempty accepted payloads and malformed rejection details are errors. Acceptance does not prove landing. On a timeout or session failure, check the transaction signature before retrying. A long-running client must assign distinct IDs to outstanding requests, keep draining completions, and use the reconnection rules after a restart.