Map: exarch / agent
Every Agent attends on its own joined thread; frontends address it by id
through Port. AgentHandle is the crate-private address. The laws are
an-agent-is-a-thread and
a-frontend-holds-a-port;
agents fixes state ownership (F1–F6), parentage, snapshots and
authority.
Owner, address and loan
agent.rs::AgentownsAgentMailbox,Loanable<Body>,Option<Engine>, engine generation, fleet and reservedName, in teardown-safe field order.Bodydirectly holdsAgentLog(seam andContext), immutableArc<Provider>client, nursery, timer registry, pins, readings, staged reply and failures. Shared facts are the cell’sMail,SchedulesandModel, not another owner-state register.agent/handle.rs::AgentHandle(Arc<Shared>)holds identity, directories, start time, fixedparent: Option<AgentHandle>, fuel, search andAgentAddress. It retains no engine or attending owner.Noneparent means the human.AgentHandle::founderwalks parentage to the human’s child this agent descends from, itself for a human child.returnsis read only fromMail;Admissionindependently chooses which inputs may open a job at rest.Body.clientis an immutable resource stamped withSelected. Birth, switch and reopen install that stamp inModel; subsequent agent reads ask the fold. Each request reads the current client. Helpers inherit it or use a launch-bound role.Status.selectedandAgentRow.selectedproject the cell’s model; learned windows are agent-local.agent/loan.rs::Loanable::lendmoves the body intoArc<Loan<Body>>for one foreground dispatch, returning it on success or unwind.Loan::getrefuses after return. Workers and pipeline stages have no desk.agent/shell.rs::Agent::ralbuildsRunHost { desk, apply }for that call.desk.rs::Callcontains only per-call values andAtomicRefCell<Vec<(DeskAct, Option<String>)>>for committed acts. The desk borrows the body through the loan, not persistent shared registers.
Mailbox, exchanges and jobs
bus/mailbox.rs owns three folds and pending payloads under one mutex.
AgentMailboxis the life-ending owner end;AgentAddressis cloneable.WeakAgentAddressweakens their shared allocation directly.Inputcarries human text (Input::Human { text, preface }, the preface the harness’s), a parent’s openingTask, messages, child reports, wakeups or deferred surface batches. Commands are posts too;Goneis separate join plumbing.Txn::postcommitsPostedbefore queuing its payload. Every other commit prunes payloads toMail::pending, the equality at every live unlock. Addressed posts and commands sync after unlocking before acknowledgement;Refused::Unsyncedpreserves queued/possibly-read delivery on failed sync.nextanddraincommitTakenbefore handing payloads over. Human runs are maximal over posts;Gonedoes not split one.PartandGroupcarry a run’s preface in its head, so only a run’s head is prefaced, by type, and prefaces never coalesce across runs.AgentAddress::transactandAgentMailbox::transactexpose closure-scopedTxn, never a guard.Txnreads folds and offers post, report, schedule, unschedule, fire, model change, narrowing and clear operations, not lines;Txn::narrowaccepts a window only ifModel::narrowsdoes. Poison latches the journal and ends life; debug builds detect re-entry. The mail’s job determines working/resting; release, Stop and loop clocks are cell plumbing.Statusreads report, debt, job and selected model from folds beside live loop observations.AgentMailbox::nextselects an admissible item and takes anActivitylease from the fleet’sBarrier(bus/barrier.rs, one atomic count of leases, or held) for every item it takes up: inputs, commands andGonealike. Only an input mints an exchangeLeaseunder home; commands run without one. The activity stays in the cell until the owner next callsnext, and mailbox drop returns it. While the barrier is held, an admissible item waits: the agent neither takes it up, settles nor idles out. A parked owner sees the hold’s release at its nextPARK_POLL(100 ms); waking it on drop would need the registry abovebus.Agent::admitrejects stale generations and already-claimed completions beforebegincommitsJobOpened; that commit number names the job.- With a job open, queued input is taken in order; human fragments
coalesce across intervening
Gonenotices, not across other posts.drainhears input through the first rewrite only while the exchange is live. Human uptake records before polling cancellation. nextcommitsJobSettledand clears the job under the same lock that finds the queue empty, no helper pending and no returning-agent schedule armed. The owner syncsNext::Settledoutside the cell before acting.Next::Settledcarries the debt read in that same transaction, so a post accepted afterwards is never taken for the ended job’s. A post either joins that job or sees rest.Admission::Freeadmits any input at rest.Gatedrequires a release, consumed by opening one job.AgentAddress::revokewithdraws an unused release:Gate::Revoked,Shutwhen none was pending, orBusy, changing nothing, while an input that may open a job is in hand (an exchange) or a job is open; a command orGonetaken up does not make itBusy.Parent { idle }admits only human and parent input; peer messages to a resting helper are refused. Commands,ChildandGoneare quiet and never held by admission.AgentAddress::stop(job)marks that open job stopped, cancels its latest exchange withInterruptedand takes back queued human text under the same lock;stop_current(desk Stop, SIGINT) stops whatever job is open and leaves the queue. At rest or for a stale id it does nothing. Helpers and schedules survive; later exchanges can run within the same stopped job.- Lock order is descendant cell → ancestor cell → journal → channel.
Names and deadline heap are leaves; the timer registry has no lock.
Only reporting nests cells; no transaction spans a provider request,
dispatch, join or
Contextaccess. The owner reads helper status without holding its own mailbox.
Reports and structured teardown
agent/nursery.rs::Nursery owns adopted children and their join guards.
Mail::owesderives debt from taken-but-unanswered parent input and pending parent posts, gated byreturns. Every mail starts owing nothing. A helper owes from its task’s post; a returning child of the human owes at human post time.Input::TaskpostsVoice::Peer, bare text and the parent’s id; arrival admits it bare, unlike later rendered messages. Recall returns only human text, never a helper’s task. Withdrawal removes unread debt, uptake keeps it.AgentHandle::reportcallsTxn::report(status, notice), wherenoticebuilds theInputfrom aChildStatus: commitControl::Status, schedule retirements and queued-wakeup withdrawals, then sync the helper and postInput::Childto the fixed parent iff owed, still under the helper lock. The parent’s post unlocks its cell before syncing. After life ends, every pending post is withdrawn. A poisoned helper reportsFaileddirectly to its parent. A failed append or sync notifies iff the captured pre-commit mail owed; failed append leaves the folds unchanged, while a successfulStatusfold already cleared debt before a failed sync.AgentAddress::reportowns both fallback paths, guarded by the mailbox’sShared.failure_noticed: at most oneFailedreaches the parent, however often teardown retries.AgentAddress::try_transactistransactfor closures returningResult<_, Unavailable>.failure_noticedexists because a failedStatusappend leaves the mail owing: teardown’s report would fail again and post a secondFailed.Agent::reportdrops its timers.Rest::pendingsnapshotsNursery::owing: an unjoined helper is pending exactly whileStatus.owesis true. An ended reported helper owes nothing, even beforeGoneis joined.Status::workingis a view: parent obligation or open job.- An owing agent is reminded only when no worker runs,
Restis empty, no returning schedule is armed and noHuman,Task,MessageorChildis queued.Restis read before the queue, so a reminder never overtakes a helper’s report. Agent::admitonInput::ChildrecordsDisplay::SubagentDoneand supplies the model notice only for an adopted, unjoined helper.Next::GoneandDrained::Gonejoin and collect failures without a model prompt.readreaches the newest own helper by name and refuses only whileStatus::reply_pending: a debt, or a running job that has reported nothing.Agent::teardownends life, reports owed failure, dismisses and joins helpers, takesOption<Engine>and retires it once; a repeat finds no engine and does nothing.Body::retire_enginerecordsTeardownFailedand retains failures for the joiner; joiners propagate, never record them again.EngineSeveredrecords the loss, read once before intentional engine end; a launch’sFactory::losthears it first, so a machine’s factory captures its console toengine.logfor every front end.Joinedjoins on drop. On unwind, mailbox drop ends life before nursery join guards run, then the engine drops and the name leaves the directory. NormalAgent::droptears down if no owner did and recordsSessionEnded.Agent::launchspawns a thread awaiting the agent on a one-shot channel, then announcesBorn, queues the first input and hands it over. A failed spawn keeps the agent, soAgent::discard, the teardown of every agent no thread attended (unlaunched or failed resumed children of the human), runs on the caller and returnsLaunchErrorwith spawn cause and failures. After owner/name drop, the thread’s terminal guard adds any final recording failure toDied { failures }, then postsGonelast. A panic reports failure through the surviving address.
Engines, construction and host
agent/engine.rs::Engineholds either identity transport with optionalRebirth, or wire transport withEngineSpec.readmakes rejected probes terminal;endcertifies teardown. Wire end requiresDetach → Ended.Engine::installstamps deferred batches with generation.inherittransfers the outgoing transport’s home binding to its replacement before retiring it. Loose ral workers belong to the engine and survive Stop/reply.App::{own, project, new_run}persist layout entries in their held parents;Fleet::foundsyncs the run after makingsessions/, andAgentLog::open_freshsyncs the sessions directory after making a session.Log::createsyncs the session after makingrecord.jsonl.agent/build.rs::Agent::bornmints the id, computesParent::terms, resolves the prompt and opensAgentLog::createwithOpening(privatehatch). Born and reopen meet inassemble, which binds writer failure and transport severance to home, then the address to its reserved name.Parent::termsis the one construction case split: human children take launch fuel, search, admission andreturns, with home under the fleet root; helpers take their parent’s search and one less fuel, nested home,Parentadmission andreturns: true.LaunchConfigsupplies launch policy.RootEngine::{Identity, Wire}selects engine construction;RootEngine::guestadopts guest control with guest paths and unresolved grants.agent/fleet.rs::FleetownsLaunch,Arc<Registry>andhuman: Mutex<Nursery>, the human’s adopted children and joins.RegistryownsDurableRootand the name directory;Namereserves before construction and removes on drop through a weak registry.unnamedreserves the least unusedagent-N,N ≥ 1, under that lock.get,resolve,liveandhuman_childrenproject live addresses;liveis in id order.Launch::engineuses the optional identityRebirth.host.rs::Host::{found, resume, adopt}launches the human’s children, owns the session bus and ambient-signal guard, and exposes a port, feed and run directory.Host::children()reads the human’s nursery: every adopted child in birth order, joined or not, including/newand/branch.finish, shared byendandDrop, ends the registry root and repeatedly callsjoin_childrento include racing births. The human receives noGone; the frontend observesDied. A retainedPortholds registry and usage meter, never the fleet or its engine factory.Host::try_holdreturns aHoldonly while no agent of the fleet is taking up an item; it never blocks, and dropping it releases. While it lives no agent takes up an item: no exchange or command runs and no engine is dialled, though an open job may still settle.Host::revoke(root) -> Result<Gate, Ended>revokes a gated root’s release. Synod uses both (hot-shared-folders).spawn::human_childmakes/newand/branchbirths throughAgent::born(Parent::Human, …)with fresh engines; branch imports context, not shell state.AgentLog::reopenfolds context and control, quiesces an unready context and commits one resume line withdrawing pending posts, settling the open job and retiring bookings, with a note naming withdrawn inputs. It returns reconciled folds for a fresh cell, preserving only taken debt and a same-model narrowing. Engines and working memory are fresh. Headless reopens exactly one session; the run lock belongs to the launcher.
Attend and gestures
agent/attend.rs::Agent::runhandlesTake,Command,Settled,Gone,RungandEndedfor every agent. Pending helpers publishWaitingOnAgents, otherwiseReady. Nudges are exchange-local continuations; no nudge enters the queue. After each exchange the owner emitsTransient::ExchangeEnded, however it ended.agent/deliberate.rsstreams provider output, records the assistant turn and executes complete ordered tool batches.Agent::deliberatetakes anarrival::Prompt, which carries the preface beside the text and voice. Provider/tool effects follow their synced records; failed append or sync prevents the effect. The outer request sync precedes allowance polling, and every attempt/retry callback precedes transport preparation.Agent::ralsyncs before dispatch;ExarchDesk::handlesyncs before both success and error answers. Reply is harvested after its batch only while the exchange remains live, then quiesced and reported. Failed mandatory protocol repair ends the session.enquiry.rs::Start { spec, parent: Marshalled }carries the same parent bytes on both seats.desk/agents.rs::child_enginecallsIdentityTransport::child(&parent)in process, sharing the parent’s runtime, ormake_engine(engine, parent): the factory makes one engine, attached withAttach::child(engine, parent). The host relays the image unread; core’sShell::child_ofreads and narrows it, with no root recipe (transport).desk/agents.rschecks log availability, constructs the helper throughAgent::born(Parent::Agent, …)over that child engine, and launches it with its parent’sInput::Task. The nursery adopts its thread. Fuel decreases by one, bounding depth.replyreadsMail::returnsthrough the address transaction; a conversing agent holds no reply.roster.rsemitsSpawner::Human(`human) or the parent’s name and restricts the roster to agents sharing the reader’sfounder.`stopaddresses descendants;`dismissends and joins only an own helper, keeping teardown failures.Agent::clearpreflights context and prepares a fresh engine without mutation, then dismisses helpers and commitsCleared. Commit failure retires the prepared engine and ends life. Success transfers the home binding, replaces/retires the outgoing engine, advances generation, resets registers, commits queued-report/wakeup/surface withdrawals and schedule retirements throughTxn::clear, then drops timers and queuedGones (dismissal already joined them). Human text, messages and commands survive; preparation failure changes nothing.Agent::rebindservesHost::rebind_engine, which refuses a helper; the request waits in the root’s cell, andnextreturnsNext::Rebindbefore taking up any item. It returns oneRebindOutcome, sent once by the loop. UnderRebindMode::SpareBusya live worker orNursery::unjoined_names()givesBusy. A wire engine has no rebirth and givesFailed. Otherwise it boots the rebirth under the new grants and cwd, renders the prompt from the new template (else the launch’s) and records it withset_system. A failure to boot or render changes nothing (Failed); a log that refuses the prompt givesLogRefused, and the root ends. Each retires the fresh engine it made. Only then does it dismiss every helper, clear queuedGones, swap and end the old engine, and store the template and rebirth together under one lock (Recipe), returningRebound { teardown_failures }.agent/command.rs::Agent::switch_modelhandlesCommand::Model(Pick)at rest or a mid-exchange drain. It builds throughBureauwith launchmax_tokens, commitsTxn::change_model(built.selected()), then swapsBody.clientafter syncing outside the cell. Build failure changes nothing; append or sync failure ends life. The next request uses the new client, even in the same deliberation./rewindwithdraws context and rebirths nudges, not shell effects./closerecordsSessionClosedand ends life;/quitreturns from the TUI beforelib::runends and joins the host.- A resting helper ends itself under the mailbox lock after
launch.idlewith no admissible input.HELPER_IDLEis five hours;--helper-idleoverrides it. Views, reads and probes renew nothing. schedule.rs::ScheduleRegistryis an unlocked owner resource, one timer per booked label. A deadline upgradesWeakAgentAddressand only rings; the owner callsfirein a transaction onNext::Rungand before every deliberation drain. It ignores superseded ids, checks wall time, commits a coalesced wakeup plus booking update/retirement and retimes/drops the timer. List and rest readSchedules. Clear/report retire before timer drop, so stale rings need no epochs. Conversing schedules survive jobs; returning schedules hold a job open until reporting.signals::facereadsRegistry::human_childrento stop their current exchanges on SIGINT and ends the fleet on shutdown; cancellation never writes to an engine from the cancelling thread.
Context and accounting
gauge.rsmeasures pressure and forced eviction against the cell’s model window, plus disk/scratch readings;nudge.rsowns wording and repair budgets;latch.rsowns rung changes. Nudges and prefaces sharerecord/context.rs::wrap_reminder, crate-private./resourcesis an owner-thread read over transport and local mailbox/log probes; the frontend contributes only its own accumulators.digest.rsbounds model-visible results;Agent::ralappendsTURN: <id>outside those caps. Replies remain faithful values, checked byread.net_policy::loadreads/etc/exarch/net-policy.ralon Unix; Windows uses the embedded policy only.net_policy::for_baseis a session’s policy under a base:confinedadmits nothing (NetPolicy::offline), every other base whatloadreads. Only search rides agent launch. The network ledger belongs to netgate.
exarch, frontend, provider, shell-eval, cancellation, session-record.