Map: core / engine protocol
core/src/engine.rs is the one engine; core/src/protocol.rs is the frame
algebra and nothing that carries it — protocol/probe.rs its probe
vocabulary, protocol/channel.rs the duplex byte channel and the one
liveness law; core/src/carrier.rs and carrier/ are the two carriers that
interpret the algebra — the identity transport in process, the wire
transport’s front-end half — with carrier/wire/serve.rs the wire’s engine
half; core/src/shell/run/report.rs projects a run onto the algebra; a wire-seat
child is made by the host’s factory and born from an Attach carrying its
marshalled parent, so core holds no spawn machinery for it. The why is
engine-protocol; this page only points at symbols.
core/src/engine.rs
EngineInstaller { tag, runtime, root, narrow }— one compiled-in installer, in two halves.runtime: fn(&EngineSpec) -> Result<Runtime, Error>is the process half (Σ, builtins, docs; a root and a child engine each derive their own, an in-process child shares its parent’s);root: fn(&Root, &mut Shell) -> Result<(), Error>is the root-only recipe (libraries, hints, boot bindings, ledgers), which refuses in its own words;narrow: GrantNarroweris the policy every child is held to. OnlytagcrossesAttach, never the function.Runtime: what the binary supplies, and the only place builtins are installed (install_builtins,install_captured_builtins); aShellis built over one and cannot hand it back.Engine— one session’s engine: theShell, itsArc<Runtime>, itsScopes, the installer it was born from.Engine::boot(installers, &attach)is the one boot both carriers call:resolve_installer(version check, then tag lookup), the installer’sruntime, then byattach.origin:Origin::Root(root)isShell::root, the root recipe, cwd and env, thenreholdand permanent installation ofRoot::grants;Origin::Child(parent)isShell::child_of(Arc::clone(&runtime), parent, installer.narrow), and no recipe runs. There is noKeep: the attach is the birth, and the scratch is the host’s, named in a root’s env.Engine::runruns one dispatch under the viewScopes::openhands it;Scopeskeeps the node, its one writer;Engine::probe(engine/probe.rs) answers oneProbe.--guest-engine <cgroup-root>: the Linux x86-64/aarch64 process role namesguest_abi::layout::ENGINE_FLAGand installs the jail beforecarrier::run_engine;Engine::bootperforms no process-global jail setup.PROTOCOL_VERSIONversions the whole engine contract, frames and command confinement, and every attach refuses a mismatch. Version 31 requires the guest deny-set, including on development media (boot-contract-is-versioned).Rails— one dispatch’s host-facing rails as its carrier lays them: theOutletits events leave by, the deferred sink and the desk. The carriers differ in these and nowhere else.Scopes— what stops an engine’s runs, shared with whichever thread carriesControl: the dispatch scope root, the durable root, and a slot holding the current dispatch and a foretold strike with its cause.openmints a dispatch’s scope ahead of its frame (struck already if a strike foretold it).open(id, within)parents beneath the host scope when supplied, otherwise beneath the dispatch root.applygivesStrike(id, cause)its one meaning: strike only that dispatch with the exact cause, or foretell it.End(cause)cancels the durable root and current dispatch with itsRootCause, including one beneath a foreign host scope.
core/src/protocol.rs
The frame algebra. Everything on it is a wire type; nothing here carries.
PROTOCOL_VERSION(currently 50): checked atAttach; a mismatch refuses. The contract includesStart’sparentrecord field and parent-decode facts. An engine’s ceiling ridesRoot.configas a grant value, decoded where it lands; guest media must be rebuilt withjust vm::boot.- build-tools’
manifest::checkcompares the same number at build time, against theproto_version=linemedia-manifestcompiles into the guest media;check-media, tauri’sbeforeBuildCommand, refuses to package media that disagrees. Frame— the whole wire enum:Attach,Dispatch,Probe,Event,Session,Control,Answer,Ping,Pong;Frame::kindnames a variant for the diagnostic about a frame out of place.Attach { engine: EngineSpec, origin: Origin }— what every engine is born from, under either carrier.EngineSpecnames the engine:proto_version,installer,terminal,home.OriginisRoot(Root { cwd, env, grants, config })(env: per-session variables the host seeds;grants: host-resolved layers installed once after the recipe;config: the installer’s own settings, anFOValueits recipe decodes) orChild(Marshalled)(a child’s parent, carrying its own cwd and env).homeandcwdarepath::EnginePaths (path/namespace.rs): a path on the engine’s machine, named in the namespace the front-end can name it in —Host(PathBuf)for an engine sharing the front-end’s computer (in process, or a child process),Guest(GuestPath)for one inside a Posix guest, a/-separated string that a Windows front-end has noPathBuffor. The engine reads either as its own throughEnginePath::native, crate-private, since only the engine’s side has the OS a guest path is native to.Attach::newis a plain root’s, at this build’s version;Attach::rootpairs anEngineSpecwith aRoot, whosewith_env,with_grantsandwith_configedit it. A root’s env is anenviron::EnvVars, so an attach bindingPWDorOLDPWDdoes not decode;Attach::childpairs anEngineSpecwithparent: Marshalled;with_terminaledits either.protocol/json.rs::RawOrigin::Childcarries those opaque bytes as base64.Run/Program— one dispatch’s payload: the policy fields plusProgram::Source/Program::Hook.Run’s field types are the run regime, held by session state, and live below the wire:RunIoandRunStdin(io/regime.rs),Captured(io/sink.rs) andRequestedTerminalAccess(process/lease.rs);ral_corere-exports them at the root.Run.lastasks a returning run to claim and wait for still-unclaimed session workers, replay their bytes and drop their endings inside its frame. Batch sets it on its script; ordinary REPL and exarch calls leave it false.Event— engine→front-end, inside a dispatch’s window:Surface,Enquiry,Reading,Report. Every surfaced value is a tagged variant; an audit observation rides as`observed <record>(Observation::to_surface).Reading(Result<FOValue, ProbeFailure>)answers aFrame::Probeunder itsDispatchId: the probe’s own event, not a run that ended.SessionEvent— engine→front-end with no dispatch to ride:Attached/Refused(WireError)(the attach verdict) andDeferredSurface(Vec<FOValue>)(a worker’s batch, and a watched worker’s lines).WireError { reason: Reason, context: Option<String>, hints: Vec<String> }— a refusal envelope forFrame::Answer,SessionEvent::RefusedandSevered::Refused.of(&Error)borrows the live error and clones only these portable facts;to_error(&self) -> Errorrestores them without changing the reason or hint order.message(&self) -> Stringderives presentation only. Both carriers normalize through this pair. Intrinsic advice and code are derived from the preserved reason; provenance, witnesses, compiler rejections and unwind facts do not cross. The enquiring operation claims its own site.ErrorFactis the separate{frame, reason, site}failure, not this report envelope.Control—Strike(DispatchId, CancelCause)andEnd(RootCause), the closedCancelled | Terminated | Aborted; applied byScopes::applyunder both carriers. Even a terminal dispatch-local cause never ends the engine.Report—Static { rendered, status }before evaluation;Ran(Ran { ending, rendered, single_command, captured, trail })after it;Faulted { rendered, status }only when the report was lost (engine-worker panic or report plumbing/fuse failure), so what ran is unknown.Ending = fact::Ending<FOValue, ErrorFact, CancelCause>has five cases:Ok(value),Err(fact),Exited(u8),Stopped(cause),Panic(text). A non-data result becomes a typedInvaliderror, status 1, with its fact and reason-derived advice. TheErrorFactis the failure behind the recordtryhands its handler (ErrorFact::record); serde goes through its first-order encoding, typed reason included, and exarch reads itsreason()for the command-exit tip.Report::Ran(Ran)holds the ending with its rendering, captured streams and trail.- The wire failure is exactly
{frame, reason, site}, with a total site; themessageandstatusa program reads are derived from the reason, not stored.Report::code() -> u8reads theNonZeroU8host status forStatic/Faultedand delegates to the ending forRan, whose errors project through the oneReasoncode table. Desk refusals retain their typed causes. Hosts exit throughstd::process::ExitCode::from(u8). The versioned wire carries the new fact unchanged, without backwards compatibility (the error record). - Serde externally tags the ending in kebab-case:
{"exited":3},{"stopped":"timed-out"},{"panic":"…"}.Okcarries anFOValue({"ok":"unit"}for Unit), andErrcarries the record. This is not theDatumencoding used for language values and stored worker endings (endings).
core/src/shell/run/report.rs
RunReport::into_report projects the engine’s End onto the wire alias.
It first turns a value into first-order data, or into Err(not_data(..));
then renders that ending once (Ran.rendered, empty for Ok, Exited and a
reader-gone stop; single_command records the compact-drawing context); then
maps an error to its record and a Stop to its cause.
A caught run panic is Ran with Panic, status 101, after checkpoint restore,
with no capture or trail. Static diagnostics render against their own source
(static-diagnostics-render-at-the-seam).
Report::refused renders a typed Reason spanlessly: nothing ran.
Report::faulted renders ReportFault directly: the report is unavailable,
not a recoverable error or an evaluation that returned a panic ending.
core/src/protocol/probe.rs
The probe vocabulary, typed once for both ends.
Probe— the payload ofFrame::Probe:BindingCount,LeasedBindingCount,LargestBindingBytes,EnvVar(String),Cwd,Home,BuiltinNames,PathBytes(PathBuf),Workers,SessionEnded,CompletionNames,Bindings,PathEntries(PathBuf),Grants;WorkerCountexists only undertest-util. Each variant states what it takes, so a payload its probe does not take is not representable.- The rows the answers come in, rendered engine-side, each a
record!:WorkerRow,BindingRow/HandleRow,CompletionNames,PathEntry.WorkerState::Ready(Done)holds the shared worker ending;WorkerState::unclaimedisRunning | Ready(_). A missing row also means claimed, so an announcing host requires a present unclaimed row.Probe::GrantsanswersGrants, arecord!: each layer of the session’s stack a reader needs (GrantLayer::is_shown: it restricts, or its exec runs something), oldest first, as itsLayerValue(the grant, and the fragment that extends it where the layer runs every program), andwithholds-gpu, whether the engine’s host holds a withheld GPU. Plain ral data, not the opaque codecRoot.grantsand a marshalled parent ride (a-grant-has-one-outward-form).
core/src/protocol/channel.rs
WireStream—UnixStreamon Unix,TcpStreamon Windows: std’s owner of a connected stream socket, never a statement about address family (vm-managerhands back anAF_VSOCKsocket on macOS, and on Windows anAF_UNIXsocket that OpenVMM relays to the guest’s vsock, through the same type).WireChannel— length-prefixed JSON framing (io/frame.rs) over oneWireStream;pair()(test-only: a socketpair on Unix, a loopback accept on Windows),from_stream,try_clone.poll_readable(Unix) — wait for a frame or a timeout, byrustix::event::pollagainst aTimespecdeadline, without blocking insideread_frame; howengine_sessionnotices a silent front-end with no dedicated thread. Windows has no engine half, so no twin.set_write_deadline— bounds everyputon every clone of the channel (SO_SNDTIMEOlives on the shared file description), turning a stalled write into the same fatal error a severed pipe already gives.write_or_sever/WriteError— the severance law itself, enforced once for both doors (carrier::Line::write,engine_write, which differ only in what they record): the frame is encoded before the lock is taken, and a frame the fuse refuses isUnencodable, the wire untouched, for its writer to answer where it stands; a failed write isSevered, recorded and the channel shut down before the lock is released, so nothing appends a frame after a truncated one and no window leaves the record calling an already-shut socket healthy. Only failed I/O severs.Liveness/ticks— how briskly a front-end pings and how much silence it tolerates; the deadline is judged as a count of unanswered pings (Liveness::probes), never as elapsed clock.HOST_SILENCE_DEADLINE, the engine’s armed read silence, is six default ping intervals, written besideLiveness::default.
core/src/carrier.rs
The two interpretations of the algebra, and what they share.
Severed— why no further frame will cross:Refused/Closed/Silent/Faulted,Displayed as the sentence a front-end shows, andcode()the stable name it is quoted by; the first cause stands.ProbeError—Rejected(a probe mid-run, a panicked reading, or one the fuse refused before it was sent) orSevered.Hosttrait — one run’s host-facing surface:surface,enquire;impl Host for ()is the mute host.Ends— the front-end state both carriers hold in one value: theControlSender, theEventReceiver, the severance, aFatal<Severed>, and the session sink. A carrier suppliesTransport::endsand the verbs that differ in carriage (dispatch,probe,answer);control,events,severed,sever,bind,unbindandset_deferred_sinkare provided. The wire carrier overridesseveronly to shut the socket too, through itsLine.Transporttrait — the front-end side of the protocol. Construction is attach, so the trait has no attach of its own;severlets a front-end record a fault it observed.bind(life)ends a life when the transport severs;unbind()releases it unended. It also provides the host’s typed probe doors, one perProbe:cwd,home,env_var,builtin_names,path_bytes,binding_count,leased_binding_count,largest_binding_bytes,workers,session_ended,completion_names,bindings,path_entries, each decoding throughDatumand severing the transportFaultedon an answer outside its shape (read). It has no explicit session-ending verb; acknowledged detach belongs toWireTransport::end.forbid_reentry/Dispatching— the carrier-uniform reentrancy law: a thread-local registry of the transports this thread is dispatching on, entered bydispatch_to_reportand checked by every typed reading and the identity carrier’sprobe, panicking with a didactic sentence.dispatch_to_report— mint aDispatchId, aim the control door at it, calltransport.dispatch(which refuses with the standingSevereditself; itsOkpromises the run’sReportor the stream’s close), drainevents()to that dispatch’s ownReport, forwardingSurface/Enquirytohost;Result<Report, Severed>. Withwithin, it polls everyPOLL_SLICEand sends an addressed strike before dispatch and whenever the observed cause rises.ControlSender—interrupt(),cancel(id),end(RootCause)over one of two routes:ControlRoute::Identityapplies the verb straight onto the engine’sScopes;ControlRoute::Wireholds its transport’sLineweakly and writes aControlframe through it, a no-op once the line is gone.aim(id)records the dispatch in flight with theinterrupt_epochit was sent at, until itsAimedguard drops;interrupt()names that dispatch, andhear(ambient)names it only if the epoch has moved since, sendingControl::End(cause)for a root cause;end(cause)sends one itself, andIdentityTransport::endends withCancelled;forward_signals()holds a process listener forwarding through that route.EventReceiver— the front-end’s single-drainer event queue; itsstashhands back an event a probe’s or a desk’s pre-drain read past, in arrival order, rather than dropping it.Line— the wire front-end’s write end, owned by itsWireTransportalone:writeis the severance law’s front-end half, andseverlatches a cause and shuts the never-locked duplicate.
carrier/identity.rs
IdentityTransport/SessionLock— the in-process carrier: anEnginebehind a poison-recovering session lock.ScopesandArc<Runtime>are held outside the lock, so control and child construction need not re-enter a dispatching engine.boot(installers, &attach)gives the wire attach’s verdict;child(&Marshalled)reads a parent throughShell::child_of, shares this runtime and applies this installer’snarrow, returning a new transport.overretains the runtime before locking the engine away. Nothing yields or accepts aShell.dispatchlaysRailswith an in-process outlet andIdentityDesk.IdentityDesk— the identity binding’sEnquiryDesk: drains queuedSurfaceevents before callinghost.enquire, so a handler can never outrun its own run’s earlier output.
carrier/wire/front.rs
WireTransport— the wire carrier’s front-end half.adopt(stream, Liveness)drives an existing duplex stream;attach(Attach)writes the only legal first frame and only then starts the heartbeat;await_attached()blocks on the reader’sAttached/Refusedverdict or its own patience, counted in waits observed. A probe writesFrame::Probeand drains the event queue to theEvent::Readingunder its id, stashing what it reads past. A frame the fuse refuses is answered where its writer stands: aDispatchby aReport::refusedstashed on its own event stream, aProbebyProbeError::Rejected, anAnswerby anErranswer; anAttach, with no session yet to refuse into, seversRefused. It owns itsLinealone.end()sendsDetachand waits forEnded, proof of engine and session-worker teardown.Dropsevers and shuts the socket, ending an unattended connection without certifying remote teardown.spawn_wire_reader/spawn_heartbeat— the reader severs before droppingevent_tx, on every exit path, and seversFaultedon a frame only a front-end sends; the heartbeat pings onLiveness::interval, holding the line weakly and upgrading it once per tick, never across its sleep, seversSilentonceLiveness::probespings go unanswered, and never takes the write lock on that path.
carrier/wire/serve.rs
The wire carrier’s engine half: a connection-lived engine process.
run_engine(installers)— adoptsguest_abi::layout::ENGINE_FD(fd 3) as the wire channel and callsengine_session.engine_session— readsAttach(the only legal first frame),restore_process_dirs(the process-level half of an attach, which only a carrier owning its process performs: a root’s cwd, every engine’sHOME, each readEnginePath::native; a child restores no cwd),Engine::boot, writesAttached/Refused, moves the engine onto a worker thread, then runs the reader loop; returns the process exit code. The loop distinguishesDetached(Detach, requiring anEndedacknowledgment),Closed(EOF, requiring no reply), andCorrupt(a read error, dead worker, silence past the deadline, or frame only an engine sends). A wire fault demotes either clean end to1.engine_write/engine_send— every engine-side write. AReportorReadingthe fuse refuses is replaced by afault; any other refusal goes back to its writer,engine_senddiagnosing and dropping a frame with no writer to refuse into (a session frame, aPong).- The worker’s
Rails— an outlet writingFrame::Eventthroughengine_write(anOutletanswersResult<(), WriteError>), aChannelDeferredSinkwritingFrame::Session, and aWireDesk. WorkItem/refusal/fault— what the worker is handed, a run or a probe, and the refusal or fault in the shape each waits on: a busy engine’s run ends in aReport::refused, a panicked worker’s or fuse-refused one in aReport::faulted, a probe in anEvent::Reading(Err(..))either way.WireDesk/Parks— the wire engine’sEnquiryDesk: writesEvent::Enquiry(a refused or severed write is its ownErr), then parks on a oneshot registered under itsEnquiryIduntilFrame::Answerfills it or the run’s own cancel scope fires. A park that gave up has deregistered its sender, so a late answer is dropped.Dispatch— the one-run-or-probe rendezvous; claiming is the only way to mint one, so “engine busy” is never raised without work in flight.Patience— the engine’s own read-silence and write-stall deadlines, armed once the firstPingarrives (bothHOST_SILENCE_DEADLINEin production, a test gets a brisker pair).- The teardown settle — on any loop exit:
Scopes::end, close the work channel, then wait for the engine thread underSETTLE_TIMEOUT(wait_ended). Join includes engine destruction and its roster drain. Only a successful join withWorkerRegistry::is_drained()may sendEnded; timeout, panic or a surviving worker exits without acknowledging teardown.
carrier/testkit.rs
Core’s own test engines, booted as every engine is (BARE, boot, eval).
core/src/engine/probe.rs
The engine’s answers: Engine::probe reads one Probe off the shell
(answer), rendering rows engine-side — never a live handle.
probe/fs.rs — entries and bytes (behind Probe::PathEntries and
Probe::PathBytes): read-only metadata walks of the engine’s own filesystem,
under its cwd, judged for reading under the live grant; bytes sizes a
path::tree::Walk (Granted::bytes, as path::tree::bytes does exarch’s
own trees under no grant).
core/src/shell/grant/spawn.rs
SpawnGrant—Inherit,Base(name), orRestrict(record)carried unfrozen.layerresolves it against aFreezeCtx;narrow_ontopushes that layer onto a shell as a session frame, usingShell::freeze_ctxfor the child’s env, logical cwd and scratch — the one layering step, whichShell::child_oftakes forIdentityTransport::childandEngine::bootalike, so neither seat holds a narrowing decision of its own (a-spawn-is-one-layer). A`restrictrecord crosses undecoded and is decoded there, which keepsGrantLayer’s resolved-by-construction invariant true of every layer pushed.GrantNarrower—fn(&str, &FreezeCtx) -> Result<GrantLayer, Error>, a field ofEngineInstallerrather than a registered hook: core has no base-tag lexicon of its own, so a`basearm is always resolved by the host that boots the engine (exarch::policy::base_layer), and the policy is demanded of every host that boots an engine instead of left in a slot one could forget to fill.
A child’s Attach carries Marshalled, one JSON document with no inner
frame. marshal::read wraps every read refusal once as a path-bearing
ProtocolFailure::Decode { kind: Parent, operation: "child" } —
transport’s marshalling section.
See also
engine-protocol (the why — one engine and two
carriers, the channel table, the laws of an enquiry, liveness and severance),
transport (io/frame.rs’s framing, Datum,
marshal/Marshalled), agent (the seat, the wire-seat
spawn that dials the factory), loop (the REPL as an
identity front-end), synod (WireTransport::adopt over a
guest VM’s virtual socket).