What it brings
The agent loop for WeirdBrains apps, with the safety rules built in rather than left to each app. Morph's Companions are its first user. The app brings a model, its tools and an approval UI; the crate runs each task, decides when to ask the user, enforces research budgets and records a trace that every citation has to match.
What it is
The shared agent loop for WeirdBrains apps; Morph’s Companions are its first user. The app brings the model, the tools and the approval UI; the crate runs each task, enforces the policy and budget, and records what happened. It has no app-specific types.
Tool results reach the model wrapped as untrusted data, and nothing inside them can widen a permission. Local inference (weirdnet-model, with its agent feature) plugs in through its ModelBackend trait, and any MCP server’s tools through weirdnet-mcp (feature agent, McpSource, a ToolSource). Since 0.2.0 the remote module runs model turns and whole tasks on another of the user’s own nodes; the core supplies only protocols over an app-supplied Dialer, so it does not depend on weirdnet-net.
0.4.0 adds /weirdnet-agent/infer/2 (CBOR, with priorities and a queue, reasoning and tool-call frames, embeddings and resume), a model catalog protocol, and a Pool that fails over and resumes an answer on another node without repeating text. The pool and serve features wire these to weirdnet-net 0.8 and weirdnet-sync 0.5: finding inference nodes among the user’s linked devices, and serving them only to those devices.
How it works
One task
AgentSession::run(task, events, cancel)asks theModelBackendfor a turn (text and tool calls), streaming text deltas asAgentEvents.- Each tool call is checked against the
Policyfor this agent, the tool's tier and the site. When the policy says ask, the app'sApproveranswers (once, or for the task). - The call is charged to the
Budget, run with a timeout and the task'sCancelToken, and its result goes back to the model wrapped as untrusted data, with the trace step ids it may cite. Nothing in a tool result can widen a permission. - The loop ends when the model stops calling tools, the budget runs out or the task is cancelled; the
Outcomehas the text, the stop reason and theTrace.
Policy
Tiers: Read (attached content), Navigate, Research, Interact,
Never. Per-agent, per-site levels Off, Ask, Act. Revocable standing allows
("Always allow") for navigate (one site or everywhere) and research (optionally one provider), for one agent or all. Off always
wins, signed-in research is never covered by a standing allow, and an all-agents allow covers an external agent only after its
first approval. Tools come from ToolSources in a ToolRegistry (LocalTools in process
now), with per-source and per-tool switches; tier overrides can only make a tool stricter.
Budgets and traces
Budget defaults: 3 searches, 12 pages (+5 on extension), 2 at a time, 15 s per page, 90 s of tool time per task, 4k
tokens kept per page, and a cap on model steps. Since 0.3.0, per_task counts only time inside tool calls (a
ToolTimer from BudgetTracker::time_tool wraps each one, and overlapping calls count once): model turns and
waiting for the user to answer an approval card don't use it, and a model turn is no longer cut off when it runs out
(max_steps and cancellation bound turns). BudgetTracker::wall_elapsed gives the task's wall-clock time for display. Every search, fetch, tool call, approval and notice is a TraceStep with its
agent, node and session (logged out or signed in). validate_citations rejects a cited URL that none of its steps
fetched, and retain_valid drops such citations before display. Everything stored or synced implements serde.
Media limits (0.5.7)
A client that sizes images, audio or a video's frames for one model needs that model's limits. Catalog entries carry them
as CatalogModel::limits, a MediaLimits: max_images per request, image_tokens (what
one image costs, or with image_patch the most it costs), image_patch (pixels per token edge for models whose
cost grows with size), image_edge (the longest edge the model uses), audio_max_seconds,
audio_tokens_per_minute and max_request_bytes. Each is absent when the node doesn't know it, never
defaulted, so a client asks the user rather than guessing. image_cost(w, h) and audio_cost(ms) give token
costs, tightest merges copies field by field and or puts an operator's numbers over measured ones. The
context window stays in CatalogModel::context. Entries without limits look as before on the wire.
Speech to text (0.5.8)
A video's soundtrack can become text for a model that doesn't take audio. A speech-to-text model's catalog entry has purpose
transcribe (Purpose::Transcribe, the same name as weirdnet-model 0.5.4's role); it is
never picked for chat. Catalog::route_transcribe(model) picks one: a named model must transcribe, and with none named the
best one is taken (warm first, then more replicas); otherwise it is a BadRequest.
The request goes over infer/2 as ClientFrame::Transcribe(TranscribeRequest): the audio as raw bytes (a CBOR byte
string, not base64) with its format (wav, mp3, ...), and optionally model,
language, prompt (names and terms to guide spelling) and timestamps. It queues like any request;
the node answers Accepted, a Working frame every few seconds while the model runs, one Transcript
(text, language, duration_ms and, when asked and the backend can, Segments with
start_ms and end_ms) and Done with usage. Apps call Pool::transcribe, which fails over
between nodes and returns a Transcription; hosts implement InferHost::open_transcribe with a
TranscribeBackend. A node before 0.5.8 closes the stream, which the pool counts as unsupported. The whole request must fit
in one 32 MiB message, so long soundtracks go in pieces.
Peers before 0.5.8 can't read a transcribe entry, so a node leaves those entries out of their catalog;
catalog::query and catalog::subscribe from 0.5.8 ask for everything, and an entry they can't read is skipped
rather than failing the whole catalog.
Native video (0.5.10)
A model that reads video natively can take a whole clip instead of frames sampled by the client. ContentPart::video(url)
builds a video_url part, {"type": "video_url", "video_url": {"url": "data:video/mp4;base64,..."}}, the same in
infer/2 CBOR and in JSON (the part vLLM and mistral.rs take); ContentPart::video_bytes(&bytes, "video/mp4") makes the
data: URL for you. Only data:video/... URLs are accepted (Content::check); remote URLs are never
fetched. VideoUrl::data_len() gives the decoded size without decoding. The clip travels inside the request, so it must fit
in one 32 MiB stream message with everything else.
A request with a video part needs Modalities::VIDEO. Catalog entries say inputs.video when the model reads
video (Modalities::with_video(true)); entries from nodes before 0.5.10 lack it and count as not reading video, and older
peers simply ignore it. Catalog::route and the pool send a clip only to a chat model that reads video: a named model that
doesn't, or a pool with none, is a BadRequest whose message ends with catalog::VIDEO_FALLBACK, "send the video
as frames (image_url parts) instead", so a client can fall back to sampling frames. PoolModel reroutes a chosen model that
can't read the clip, as for images.
MediaLimits carries the model's video limits when the node knows them: video_max_seconds,
video_max_bytes (decoded) and video_frames_per_minute (per minute so 0.5 frames a second stays exact;
video_frame_rate() gives frames per second). Each is absent when unknown, never defaulted. video_frames(ms)
says how many frames the model reads from a clip, check_video(ms, bytes) names the first known limit a clip exceeds, and
tightest and or merge them like the other limits.
Pooled models (0.5.13)
Some models are too big for any one machine and are served by several together, such as vLLM over Ray. A catalog lists such a
model once, by the node that answers for it, with CatalogModel::pooled: a Pooled with served_by
(the head, where requests for it go), members (every machine holding part of it, the head first; Pooled::new
puts it first when it is missing and drops duplicates), backend (how it is split, such as vllm-ray or
llamacpp-rpc; empty when not said, set with with_backend) and up (whether the members are running
it now; the model may stay listed while they are stopped and start on the first request; with_up).
CatalogModel::with_pooled sets it and is_pooled asks. It is absent, and left off the wire, for a model each node
serves on its own, and catalogs from 0.5.12 and earlier read without it.
Speech out (0.5.11)
A model can speak: text in, audio out. Its catalog purpose is speak (Purpose::Speak, the same name as
weirdnet-model's role) and its entry carries a SpeechProfile (CatalogModel::speech)
that says what it does: named presets, design (a voice from a description), instructions (style or
emotion), clone (a voice from a reference clip, with a CloneMode saying whether the clip's transcript is
unused, optional or required), script_speakers (multi-speaker scripts), raw engine input, speed and
streaming; what it takes: languages, formats (AudioFormat: wav,
pcm16, mp3, opus, flac) and sample_rate; and its limits
(max_input_chars, max_reference_seconds, max_reference_bytes, max_output_seconds).
A feature is on only when the node knows the model has it, and a list or limit is absent when nobody reported it.
SpeechProfile::tightest merges copies across nodes (a feature only when every copy has it), and
narrowed_by applies an operator's overrides, refusing anything that would widen what the engine reports.
The request is ClientFrame::Speak(SpeakRequest): SpeakInput::Text, a Script of
ScriptTurn { speaker, text } or Raw input; an optional Voice (Preset { name },
Design { description } or Clone { audio, format, text, consent }, the clip as raw bytes, never stored);
per-speaker voices, instructions, language, speed in per mille, seed,
format, sample_rate and stream. SpeakRequest::check refuses empty input, a clone
without consent and a reference over 30 MiB before any backend opens. SpeakRequest::needs() gives the
SpeechNeeds that SpeechProfile::covers and Catalog::route_speak check, and a refusal names what the
model lacks, such as the list of presets when a voice like alloy isn't one of them (no voice is ever swapped for another).
The node answers Accepted, a Working frame every few seconds until the audio starts, one
SpeechStart { format, sample_rate, channels }, then Audio { offset, data } chunks of at most 256 KiB in order,
then Done with Usage::input_chars and audio_ms (and Meta::ignored naming fields the
model doesn't use, such as a reference transcript). Pool::speak returns the whole Speech;
Pool::speak_stream returns a SpeechStream once the audio has started. Both fail over to another node only
before SpeechStart: after that a failure is final, because another node would start again with another voice. Hosts
implement InferHost::open_speak, which sees the whole request (so a host can refuse a guest's voice clone), with a
SpeakBackend that returns an AudioStream: AudioStream::from_file for a finished file, or
AudioStream::channel and its AudioSink to stream. Speech goes through the same authorization as chat, so a
guest of a shared pool needs the infer scope for it too. Askers before 0.5.8 get catalogs without speak
entries, askers from 0.5.8 to 0.5.10 skip them, and a node before 0.5.11 closes the stream, which the pool counts as unsupported.
Cold speakers (0.5.12)
A speaking model that hasn't loaded yet may have no speech profile in the catalog: its engine reports its voices only when it
loads. CatalogModel::speech_unknown says so (no profile published, or an empty one). When a request names such a speaker,
Catalog::route_speak leaves it to the speaker's node, which loads the model and checks the request against what its
engine reports, so a preset voice is no longer refused up front. A request that names no model still goes only to a speaker whose
profile is known to cover it.
Sharing a pool with another identity (0.5.9)
Someone with a different Weirdnet identity, or your own identity in another app, can use your pool (for example Ymir) without its root identity: the guest presents its own device certificate and gets catalog/1 and infer/2 (chat, embeddings, transcription, and since 0.5.11 speech out) only, never synced data, task/1 or anything else.
The owner hands out a PoolShare link: the owner's user id, an optional name and expiry, and the inference nodes'
peer ids with addresses to dial them (direct or relay circuit). It reads wnet-pool1:<base64url JSON> or
weirdnet-pool://share/<base64url JSON> and holds no secret: it only says where to dial. The guest's app calls
pool::connect_shared(node, &share, &user_key, &cert), which gives a Pool over the share's nodes in
order (failover as usual, no roster discovery) that presents a guest credential with every request:
encode_credential, the device's NodeCert plus its user's public key, since a certificate names its user only
by id.
On the owner's inference nodes, serve::GuestAuth::new(profile, &owner_key, policy) checks the credential as
strictly as the roster checks the owner's own devices: the key must hash to the certificate's user id, the signature must verify,
the certificate must be for the peer on the connection, not revoked and not issued in the future. Then the host's policy, a
closure over its synced guest list, sees the Guest and a GuestScope (Catalog or
Infer) and decides, on every request. SharedPoolAuth::new(roster_auth).with_guests(guests) puts it next
to RosterAuth: authorize_for(caller, GuestScope::Infer) in InferHost::authorize,
identify to tell a guest from an own device (for example to refuse it server-side context), and
scoped(GuestScope::Catalog) for a CatalogFeed. Without with_guests, and on every node before
0.5.9, guests are refused.
Revoking is immediate: take the guest off the list and its next request is refused. CatalogFeed::rechecking()
(CatalogHost::recheck) re-checks a catalog subscription before each update and every 5 seconds and closes it with the
refusal; an answer already streaming finishes. Refusals reach the guest as RemoteError::Refused with the reason
(not-shared, wrong-peer, guest-bad-cert, revoked and so on).
Synced jobs (0.5.6, feature jobs)
A long job, such as training a model, should survive the device running it: another of the user's devices picks it up from
its last checkpoint. JobBoard<P> is a typed layer over the weirdnet-sync 0.8.2 job
log and leases, not a second log: every job is signed events in the op log, sealed and synced like any other record, and every
device folds them into the same JobRecord<P>. The app brings only its payload type P.
- Open and post:
JobBoard::open(&sync, "ymir.train")with aSyncHandle(the sync node and state, orLeases).post(NewJob::new(id, base_revision, dataset, payload).with_policy(policy))needs a policy with a role (JobPolicy::for_role) or candidates. Payloads are up to 64 KiB. - Voters: every device with the role votes, with limits that allow the job's claim time:
policy.configure_voter(voter, kind), orpolicy.voter(kind)for a new one. - Claim:
claim(id, |job| ...).awaittakes the job's majority-vote lease (kind/id), with the app's own check on top of the role and candidates. TheClaimrenews in the background and gives theterm, the checkpoint toresume_from, andlost().await, which says why the claim ended (lease lost, superseded, paused or cancelled by the owner, released). - Work:
checkpoint(CheckpointRef)records a pointer (a content hash, its size and the devices holding a copy; the app moves the bytes),set_holdersupdates who holds a copy, andprogresskeeps a small value, written at most every 30 s.fence()gives a token to check against a resource'sFenceGuard, so a holder that lost its claim can't write. - End:
finish(result),fail(reason, retry)orpause(). Dropping a claim releases it.
JobPolicy defaults: 60 s claims renewed every 20 s, a 300 s takeover wait, 3 attempts and a 60 s retry backoff. If a
holder disappears, voters wait out the takeover wait after its claim lapsed before another device may claim, so a short network
drop doesn't move a long job; the holder can renew back inside the wait. A failure with retry reopens the job after
the backoff until the attempts run out (lapsed claims count); pauses never count. The owner's pause and
cancel reach the holder, which stops and lets go; resume reopens a paused job. get, list (with a
JobFilter; jobs that ended more than 30 days ago are left out unless asked for), checkpoints (the last
eight) and watch (a stream of changes) read the board.
More pages (0.3.0)
When a task's page budget runs out, the session asks Approver::extend_pages(&PagesPrompt) (the "+5 pages" card).
PagesPrompt has the agent, the task id, the pages used so far and the extension size (Budget::page_extension).
An answer of true adds one extension and the page is read; the next time the extended limit runs out it asks again, and
after a false it never asks again in that task. Waiting for the answer does not use the task's time. The default
implementation answers no, so existing approvers behave as before. remote::task does not forward this question yet, so a
remote task still stops at its page budget.
Remote inference and remote tasks (0.2.0)
The remote module has two protocols between one user's own nodes. The app supplies the transport: a
Dialer opens a Channel (a FrameTx and a FrameRx) to a node for a protocol id, and
the serving app must check that the caller is one of the user's linked devices before it calls serve. Messages are
JSON; remote::codec frames them on byte streams (a big-endian u32 length, messages up to 32 MiB since 0.5.0, 8 MiB before), and
MemoryDialer and memory_pair are in-process channels for tests. Failures are a RemoteError:
unreachable, busy, refused, unavailable, failed, protocol, closed or timed out.
- Remote inference (
remote::infer,/weirdnet-agent/infer/1): offload one model turn. The asker sends the messages and tool specs (and optionally a model id); the node answersAcceptedwith the model it chose, streamsDeltatext, thenDonewith the turn, orFailedorCancelled. ACancelcan go the other way at any time. The serving app implementsInferHostto open aModelBackendfor the requested model, andAdmission::new(n)limits concurrent turns; more are answeredBusy. If the asker goes away the turn is cancelled. RemoteModelis aModelBackendover that protocol:RemoteModel::new(dialer, nodes).with_model(..).with_fallback(local).with_accept_timeout(..). It tries the nodes in order, then the local fallback, whenever a node fails before any token has streamed: unreachable, busy, no such model, an error, or noAcceptedwithin the accept timeout (default 10 s). Once tokens have streamed, a failure is returned as is, because the text already shown cannot be taken back.last_route()says where the last turn ran (Route::Nodewith the node and model, orRoute::Fallback), and the backend name in traces readsmodel@node.- Remote tasks (
remote::task,/weirdnet-agent/task/1): run a whole agent task on another node (Node companions).task::run(dialer, node, request, events, approver, cancel)sends aTaskRequest(the companion'sAgentId, the input and the conversation so far) and the node'sAgentSessionruns it, under that node's tools, budget and policy. Its events come back as ordinaryAgentEvents, so an app's panel code is the same as for a local session. When the session needs approval, the node sends anAskand the card is answered by theApproveron the asking device; a lost asker denies. TheCancelTokenstops the task there (the asker waits 5 s for the node to wind down). The result is aRemoteOutcomewith theOutcomeand the updated conversation: the history lives with the asker, which sends it with each task. The serving app implementsTaskHostto build a session for the companion, and refuses companions that do not run there.
Inference (weirdnet-model) and MCP client transports (weirdnet-mcp) implement this crate's traits in their own crates. Since
0.4.0 the pool and serve features wire the protocols to weirdnet-net streams; apps can still supply
their own Dialer.
Inference v2 (0.4.0)
/weirdnet-agent/infer/2 (remote::infer::v2) carries CBOR frames; /weirdnet-agent/infer/1
stays JSON and is still served, so 0.3 nodes keep working. A Request has an id, an optional job_id and
attempt, a model, a Priority (Interactive by default, Batch or
Background), the input (inline messages, or a context_ref to a stored conversation), sampling settings,
a seed, a response_format (text, JSON or a JSON schema), tools, and raw for a node that should skip
its own prompt handling. Optionally it carries an assistant prefix and its length in characters: the part of the answer already
shown, which a node continues from.
- The node checks the caller (see below). When all its slots are busy it answers
Queued{position}and repeats it every few seconds; each one resets the asker's accept timeout, so a queued request is not mistaken for a dead node. Higher priorities go first; a full queue answersBusy. Acceptednames the model and says whether the node can resume from a prefix.Delta(text),ReasoningandToolCallframes stream with their character offset in the answer, thenUsageandDonewith the finish reason and metadata: the node that served it, queue and first-token timings, and any resumes.Cancelcan go the other way at any time.- Embedding requests get one
Embeddingframe per input, the vector as little-endian f32 in a CBOR byte string.
Hosts implement InferBackend (and EmbedBackend); a plain ModelBackend is adapted.
DeltaSink::reasoning and AgentEvent::ReasoningDelta carry reasoning text to the app (task/1 does not
forward it).
Answer cache per request (0.5.1)
Request::cache is a CacheMode: use (the default), bypass (the node neither
reads nor stores a cached answer, for evals and freshly fine-tuned weights) or refresh (skip the read, run the model
and store the fresh answer over the old one). Set it with Request::with_cache; CacheMode::may_read and
may_store say what a cache may do. Unlike raw, it keeps the node's context lookups and stand-ins. The
field is left off the wire when it is use, so older nodes read every request as before; nodes before 0.5.1 ignore
it and may still answer from their cache, which Meta::cache_hit reports. Request::with_wait_for_model
(0.5.1) sets wait_for_model.
A pool as one model (0.5.3)
remote::pool_model::PoolModel turns a Pool of inference nodes (for example a
Ymir cloud on the user's own devices) into one ModelBackend, so an
agent app runs its turns there like on a local model. Text and reasoning stream to the DeltaSink, tool calls come
back in the turn, and cancel stops the node. A node that dies mid-answer is resumed on another one, shown as
ModelNotice::Continued; when the chosen model can't read a turn's images or audio, the pool picks one that can, shown as
ModelNotice::Rerouted (on by default; with_reroute(false) refuses the turn instead). When the
pool can't take a turn before any text has streamed, an optional fallback, usually the local model (with_fallback),
runs it, shown as ModelNotice::FellBack; without one the error is ModelError::PoolUnreachable. Notices
reach the app as AgentEvent::ModelNotice through DeltaSink::notice.
PoolWatch follows the pool catalog (catalog/1 subscribe) as a PoolStatus for a model picker: live,
searching or unreachable, with each model's state and speed. It knows which nodes answered (CatalogNodes, a
NodeSource through PoolWatch::nodes), so turns go only to real inference nodes, and
PoolWatch::retry asks the nodes again now instead of after the backoff.
Origin and license (0.5.4)
Catalog entries can say where a model came from and its license: CatalogModel::origin (ORIGIN_HUB,
ORIGIN_UPLOAD or ORIGIN_TRAIN, as in a weirdnet-model provenance record) and
license, set with with_origin and with_license. Both are left off the wire when unset.
LoRA adapters (0.5.2)
A model node can serve LoRA adapters on a base model (weirdnet-backends 0.4), each under its own
model id. CatalogModel::base names an adapter's base model (set with with_base; is_adapter
tests it), so an app can show the adapter as a variant of the base; requests still name the adapter's id.
Request::adapter_scale, set with with_adapter_scale, is how strongly the requested adapter applies for
this request on nodes that scale per request (llama.cpp); None keeps the adapter's own scale, and base models ignore
it. Neither field is sent when unset, and nodes and catalogs from 0.5.1 and earlier ignore or lack them.
Pool, failover and resume (0.4.0)
remote::pool::Pool runs a request across nodes from a NodeSource, best first. It moves to the next
node when one is unreachable, busy, refuses, lacks the model or does not accept in time, and uses infer/1 with nodes that do not
serve infer/2. Once a stream has started, the pool cancels it when no frame arrives for max(15 s, 3 × the recent
gap between tokens) (25 s at most, and 25 s for the first token), under weirdnet-net's 30 s stream resume window. It then
resumes on a node that supports it: the same job_id and seed, the next attempt, and the text already
shown as the prefix. Frames are placed by offset, so nothing is shown twice, and a gap fails that attempt. At most two resumes
per answer by default; if nothing can take over, the partial answer comes back with the error.
The pool also runs embeddings, background jobs (submit returns a Job to watch, wait for or cancel), and
catalog queries and subscriptions (/weirdnet-agent/catalog/1: each model's purpose, state, replicas, speed and
context) that move to another node when one goes away. RemoteModel is a thin ModelBackend over a pool;
resume is opt-in there (with_resume(true)).
Continuing an answer (0.4.2)
When the user stops an answer or it is cut off, a Continue button can send the same conversation with the partial answer as
the request's assistant_prefix: the model carries on from that text (assistant prefill: llama.cpp continues a trailing
assistant message, vLLM gets continue_final_message). Request::continuing() builds such a request from
messages that end in an assistant message without tool calls. The wire is unchanged: it is the same prefix a resume uses.
- Only nodes whose
Acceptedsaysresume: truetake it; others, and infer/1 nodes, are skipped asUnsupported. With none left, the error comes back with the prefix as the partial answer. - The
Answerstarts from the prefix:textandreasoninginclude it,Answer::prefixis what was given andAnswer::continuation()the text after it. Events carry only the new text. - Failover keeps the prefix, whether or not resume is on; if a node dies part-way, the next one resumes from everything shown,
and that resume is recorded in
Meta::resumesas usual.
Images and audio (0.5.0)
Message::content is a Content: text, or OpenAI-style parts. ContentPart::text,
ContentPart::image (an image_url with a data:image/... URL) and ContentPart::audio
(input_audio with base64 data and a format) build them; Message::user takes a string or a list of parts.
Text still goes on the wire as a plain string, so text-only messages reach 0.4 peers as before; parts need 0.5 on both ends.
Message::text() gives the text alone, and Message::needs() / Request::needs() the
Modalities (vision, audio) a model must take.
Routing by input (0.5.0)
Catalog entries say which inputs beyond text a model takes (CatalogModel::inputs, set with
with_inputs; entries without it are text-only). Catalog::route(model, needed) picks the model for a
request: a named model must take the request's inputs, and with no model it picks one that does. The pool routes with it, so an
image or audio request never lands on a text-only model: a named model that can't read it, or a pool with no model that can, is a
BadRequest before any node runs it. Requests with parts skip infer/1 nodes, and a model node refuses parts its model
can't take, so a pool moves on. Model nodes from weirdnet-backends 0.2 report these inputs
(Capabilities::inputs).
Serving inference to linked devices (0.4.0)
The serving side gets a Caller: the transport-authenticated peer plus any certificate the request presented.
InferHost::authorize and CatalogHost::authorize run before anything else; a refusal is sent with its reason.
With the serve feature, serve::RosterAuth does this with weirdnet-sync's
caller check, and Server::start(&node, Serving { infer, catalog, announce }) accepts
infer/1, infer/2 and catalog/1 streams and announces the node as an inference node. With the pool feature,
pool::connect(node, roster, Some(&my_cert)) builds a pool over LinkedNodes: the roster's active devices
that announce inference, direct connections first.
Device roles and tasks (0.4.4)
RosterAuth::require_roles(&["ymir.inference"], roles) admits only linked devices the user granted one of the
roles (the signed grants in the weirdnet-sync 0.7 roster: roles is
|peer| roster.roles_of(peer)); others are refused with role. Never authorize on a certificate label,
which is not signed. Authorize::admit returns Admitted { peer, roles }, and
Server::start_with(node, serving, ServingExtras::default().tasks(host, auth)) serves task/1 next to inference: each
task is admitted first and built by TaskHost::session_for(&admitted, ..), so a host can scope tools per device
or role, and the INFERENCE_APP announcement then lists task/1. All of it is additive; the pool and
serve features accept weirdnet-sync 0.5.2 to 0.7 (to 0.8 since 0.5.5). 0.4.3 stopped offline devices from slowing every request.
Moving to 0.5.0
- Message content:
Message::contentis aContent, not aString. Constructors takeimpl Into<Content>, soMessage::user("hi")is unchanged; where code readsm.contentas text, usem.text()(orm.content.text()).AgentSession::runtakesimpl Into<Content>. - Inference nodes: put each model's inputs in its catalog entry (
CatalogModel::with_inputs, from weirdnet-backends'Capabilities::inputs()), or image and audio requests will find no model to route to. - Dependents: move together with weirdnet-backends 0.2.0, weirdnet-openai 0.2.0 and weirdnet-model 0.5.0; weirdnet-mcp 0.5.3 takes agent 0.4 or 0.5.
Moving to 0.4.0
- Serving inference: implement
InferHost::authorize(&self, caller: &Caller)(for Weirdnet,RosterAuth);InferHost::openis nowopen(&self, caller: &Caller, model: Option<&str>)andinfer::serveisserve(channel, caller: &Caller, host, admission). The caller check that apps did before callingservenow lives inauthorize. - Enums are
#[non_exhaustive]: add a wildcard arm where you matchAgentEvent(new:ReasoningDelta),RemoteError(new:Unsupported,BadRequest,Cancelled,Stalled; infer/1 sends them asfailed),Role,ModelErrorand the others. RemoteModelkeeps its API; it now tries infer/2 first and falls back to infer/1, so it works with 0.3 nodes.- weirdnet-model 0.4.0 and weirdnet-mcp 0.5.0 move their
agentfeatures to weirdnet-agent=0.4.0; move all three together.
Moving to 0.3.0
- No source changes are needed: the new API is additive (
ToolTimer,PagesPrompt,BudgetTracker::time_toolandwall_elapsed, andApprover::extend_pages, which has a default body). The wire protocols are unchanged:/weirdnet-agent/infer/1and/weirdnet-agent/task/1, so 0.2 and 0.3 nodes still talk to each other. - Behaviour change:
Budget::per_tasknow counts tool time only, not wall-clock time. A task can run longer thanper_taskin wall time, because model turns and approval waits no longer count. If you relied on it as a deadline, cancel with your own timer (usewall_elapsedto show elapsed time). - To offer "+5 pages", implement
Approver::extend_pages. - weirdnet-model 0.3.0 and weirdnet-mcp 0.4.0 move their
agentfeatures to weirdnet-agent=0.3.0(breaking foragentusers only; no source changes). An app that usesLocalModelorMcpSourcemoves all three together; versions before those still pin=0.2.0and can't be mixed with agent 0.3.
Key types and modules
- Pooled models (0.5.13):
CatalogModel::pooledis aPooled { served_by, members, backend, up }for one model served by several machines together, such as vLLM over Ray, so a catalog lists it once: the node that answers for it (requests for it go there), every machine holding part of it (served_byfirst;Pooled::newputs it first and drops duplicates), how it is split (such asvllm-rayorllamacpp-rpc;with_backend) and whether the members are running it now (with_up).CatalogModel::with_pooledandis_pooled; absent and off the wire for a model each node serves on its own, and catalogs from 0.5.12 and earlier read without it. - Cold speakers (0.5.12):
Catalog::route_speakleaves a request that names a speaker with no speech profile yet (CatalogModel::speech_unknown: none published, or an empty one, such as a cold model whose engine reports its voices when it loads) to its node, which loads it and checks the request against what the engine reports, instead of refusing a preset voice up front. A request that names no model still goes only to a speaker whose profile covers it. - Speech out (0.5.11):
Purpose::Speak(speakon the wire) with aspeech::SpeechProfileper model (CatalogModel::speech: preset voices, designed and cloned voices, style instructions, multi-speaker scripts, raw input, speed, streaming, languages, formats, sample rate and limits, each absent when unknown;tightest,narrowed_by,covers) andCatalog::route_speak. infer/2ClientFrame::Speak(SpeakRequest)(SpeakInput::Text,ScriptorRaw;Voice::Preset,DesignorClonewith the reference clip as raw bytes andconsent) answered byWorking, oneSpeechStart,Audiochunks of at most 256 KiB andDonewithUsage::input_charsandaudio_ms. Hosts implementInferHost::open_speakwith aSpeakBackendreturning anAudioStream; apps callPool::speakorPool::speak_stream, which fail over only before the audio starts. - Native video (0.5.10):
ContentPart::videoandContentPart::video_bytesbuild avideo_urlpart (ContentPart::VideoUrl, a whole clip as adata:video/...URL, the part vLLM and mistral.rs take;VideoUrl::mime_type,VideoUrl::data_len) for models that read video natively.Modalities::VIDEOandModalities::with_video; catalog entries sayinputs.video(absent from older nodes, so their models never get a clip).Catalog::routeand the pool send a clip only to a model that reads video, and a refusal ends withcatalog::VIDEO_FALLBACK(send frames instead).MediaLimitsgainsvideo_max_seconds,video_max_bytesandvideo_frames_per_minute, each absent when unknown, withvideo_frame_rate,video_framesandcheck_video. - Pool sharing (0.5.9): another Weirdnet identity uses a pool with its own device certificate, never the pool’s root identity, for catalog/1 and infer/2 only.
remote::share::PoolShareis the share link (owner user id, optional name and expiry, inference node peer ids and addresses;wnet-pool1:token orweirdnet-pool://share/link, no secrets). Hosts:serve::GuestAuthverifies the guest credential (encode_credential: itsNodeCertplus its user key) against the transport peer and asks the host’sGuestPolicyperGuestScopeon every request;SharedPoolAuthcombines it withRosterAuth(identify,authorize_for,scoped), andCatalogFeed::recheckingcloses a revoked guest’s subscription. Guests:pool::connect_shared. - Transcription (0.5.8):
Purpose::Transcribe(transcribeon the wire),Catalog::route_transcribeandCatalog::transcribers; infer/2ClientFrame::Transcribe(TranscribeRequest)(audio as raw bytes with itsformat, optionallanguage,promptandtimestamps) answered byWorkingkeepalives, oneTranscript(text, language, duration and timedSegments) andDone; hosts implementInferHost::open_transcribeandTranscribeBackend, apps callPool::transcribe. - Media limits (0.5.7):
MediaLimitsandCatalogModel::limits(with_limits): per-modelmax_images,image_tokens,image_patch,image_edge,audio_max_seconds,audio_tokens_per_minuteandmax_request_bytes, each absent when the node doesn’t know it, never defaulted, and left off the wire then;image_cost,audio_cost,tightestandorsize and merge them. AgentSession::run: one task. Calls theModelBackend, checks each tool call against thePolicy, asks the app’sApproverwhen needed, charges the budget, runs the tool with a timeout and aCancelToken, and streamsAgentEvents: text, approvals, skipped-approval notices, tool start and finish, trace steps.Tool,ToolSource,ToolRegistry: in-process tools now, MCP servers and remote nodes as further sources. Per-source and per-tool switches; a tier override can only make a tool stricter.Policy: tiersRead(attached content),Navigate,Research,InteractandNever; per-agent, per-siteOff,AskandAct; approvals for once or for the task; revocable “Always allow” for navigate (a site or everywhere) and research (optionally one provider), for one agent or all. Off always wins, signed-in research is never covered by Always allow, and an all-agents allow covers an outside agent only after its first approval.Budget: searches, pages (with extensions), concurrency, per-page time and per-task tool time, tokens kept per page, model steps. Defaults: 3 searches, 12 pages (+5), 2 at a time, 15 s a page, 90 s of tool time a task (model turns and approval waits don’t count, since 0.3.0). When the page budget runs out,Approver::extend_pagescan offer “+5 pages” (PagesPrompt; default no).Trace,Citation: every search, fetch, tool call, approval and notice is a step with its agent, node and session (logged out or signed in).validate_citationsrejects a cited URL that none of its steps fetched; a citation without a step is never shown.remote::infer,RemoteModel: one model turn on another node, streamed, cancellable, with fallback to the next node or a local model (0.2.0). Since 0.4.0RemoteModelspeaks infer/2 and falls back to infer/1 for 0.3 nodes.remote::infer::v2(0.4.0):/weirdnet-agent/infer/2in CBOR. Priorities (Interactive,Batch,Background) behindQueued{position}, sampling, seed, response format, tools and raw mode;Delta,ReasoningandToolCallframes with character offsets,Usage, andDonewith metadata; f32 embeddings as byte strings. Hosts implementInferBackendandEmbedBackend, or keep a plainModelBackend.remote::pool::Pool(0.4.0): tries nodes in order, cancels a stalled stream and resumes it elsewhere from the text already shown, runs embeddings and background jobs, and queries or subscribes to the catalog with failover.remote::catalog:/weirdnet-agent/catalog/1, the models nodes have and their state.- Images and audio (0.5.0):
Message::contentis aContent, text or OpenAI-style parts (ContentPart::text,ContentPart::imagewith adata:image/...URL,ContentPart::audio). Plain text keeps its wire form.Message::needsandRequest::needsgive theModalities(vision, audio) a model must take;Message::textgives the text alone. remote::pool_model(0.5.3):PoolModelis a model pool (such as Ymir on the user’s own devices) as oneModelBackend, with mid-answer resume on another node, rerouting for images and audio, and an optional local fallback (with_fallback), reported asModelNotices (AgentEvent::ModelNotice,DeltaSink::notice) orModelError::PoolUnreachable.PoolWatchfollows the pool catalog as aPoolStatusfor model pickers, knows which nodes answered (CatalogNodes) and can ask again at once (retry).- Origin and license (0.5.4):
CatalogModel::originandlicense, set withwith_originandwith_license;ORIGIN_HUB,ORIGIN_UPLOADandORIGIN_TRAINname where a model came from. Both are left off the wire when unset. - LoRA adapters (0.5.2):
Request::adapter_scaleandwith_adapter_scaleset how strongly an adapter applies for one request on nodes that scale per request (weirdnet-backends 0.4.1 on llama.cpp);CatalogModel::base,with_baseandis_adaptermark a catalog entry as an adapter on a base model, so apps can show it as a variant. Both are left off the wire when unset. - Routing by input (0.5.0): catalog entries say which inputs a model takes (
CatalogModel::inputs,with_inputs; entries without it are text-only) andCatalog::routepicks a model for a request with images or audio. The pool uses it, so such a request never reaches a text-only model: a named model that can’t read it, or a pool with no model that can, is aBadRequestbefore any node runs it. - Answer cache per request (0.5.1):
Request::cacheis aCacheMode,use,bypassorrefresh, set withRequest::with_cache, so an eval can skip or refresh a node’s answer cache without raw mode. It is left off the wire whenuse.Request::with_wait_for_modelsetswait_for_model. - Continuing an answer (0.4.2): a request that carries an
assistant_prefixcontinues that text (assistant prefill).Request::continuingmakes one from a trailing assistant message;Answer::prefixandAnswer::continuationseparate the given text from the new. poolandservefeatures (0.4.0):LinkedNodes,NetDialerandconnecton the app side;ServerandRosterAuthon inference nodes, admitting only linked devices.jobsfeature (0.5.6):JobBoard,JobRecord,Claim,JobPolicy,CheckpointRef: long jobs (such as training) that one device starts and another resumes from its last checkpoint, over the weirdnet-sync job log.remote::task: a whole agent task on another node, events streamed back, approvals answered on the asking device (0.2.0).- Serde on everything that is stored or synced. The
testingfeature has a scripted model, approver and closure tools.
Feature flags
pool(0.4.0): the pool over weirdnet-net 0.8:LinkedNodesfinds inference nodes among the user’s linked devices (weirdnet-sync 0.5 to 0.8 roster; 0.8 since 0.5.5),NetDialeropens streams,connectbuilds thePool.serve(0.4.0):Serverserves infer/1, infer/2 and catalog/1 on a weirdnet-net node and announces it;RosterAuthadmits only linked devices.jobs(0.5.6): synced jobs over the weirdnet-sync 0.8.2 job log (JobBoard,Claim,JobPolicy); pulls in weirdnet-net and weirdnet-sync likepool.testing:ScriptedModel,ScriptedApproverandFnToolfor tests in downstream crates (the example below uses them).
Usage
In Cargo.toml:
[dependencies]
weirdnet-agent = { version = "0.5.2", features = ["testing"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }Then (built and run against the published crate when this page was made):
// One task through the agent loop with the `testing` feature's scripted model and approver.
// A real app implements ModelBackend (for example over weirdnet-model) and Approver (its UI).
use std::sync::Arc;
use weirdnet_agent::testing::{ScriptedApprover, ScriptedModel};
use weirdnet_agent::{AgentConfig, AgentIdentity, AgentKind, AgentSession, CancelToken, ModelTurn, Policy, StopReason, ToolRegistry};
#[tokio::main]
async fn main() {
let model = ScriptedModel::new(vec![ModelTurn { text: "hello there".into(), tool_calls: vec![] }]);
let mut tools = ToolRegistry::new();
tools.refresh().await.unwrap();
let cfg = AgentConfig::new(AgentIdentity::new("atlas", "Atlas", AgentKind::Local));
let mut session = AgentSession::new(cfg, Arc::new(model), Arc::new(tools), Policy::new().shared(), Arc::new(ScriptedApprover::default()));
let (events, mut rx) = tokio::sync::mpsc::unbounded_channel();
let outcome = session.run("say hello", Some(events), CancelToken::new()).await;
assert_eq!(outcome.stop, StopReason::Completed);
while let Ok(event) = rx.try_recv() {
println!("{event:?}");
}
println!("{} ({} trace steps)", outcome.text, outcome.trace.steps.len());
}
Where it fits
- Builds on weirdnet-net, weirdnet-sync.
- Used by Morph (Companions, in progress).
- License: BSD-3-Clause.
CatalogModel::pooled (Pooled, with_pooled, is_pooled) names the head and members of a model served by several machines together; it is left off the wire when absent, and catalogs from 0.5.12 and earlier read without it. 0.5.12 fixes speech routing and adds CatalogModel::speech_unknown: Catalog::route_speak leaves a request that names a speaker with no profile yet to its node instead of refusing a preset voice up front (release). 0.5.11 is additive: speech out (Purpose::Speak, SpeechProfile, Catalog::route_speak, infer/2 Speak, Pool::speak and speak_stream, see the guide). Askers before 0.5.8 get catalogs without speak entries and 0.5.8 to 0.5.10 askers skip them; nodes before 0.5.11 can’t read a speech request and the pool moves on. 0.5.10 is additive: native video (a video_url content part, Modalities::VIDEO, catalog inputs.video, video limits and routing, see the guide). Peers before 0.5.10 can’t read a video part; routing keeps clips away from them. 0.5.9 is additive: sharing a pool with another Weirdnet identity (guest credentials, GuestAuth, SharedPoolAuth, PoolShare links, connect_shared, see the guide). Hosts that don’t opt in refuse guests as before. 0.5.8 is additive: speech to text (Purpose::Transcribe, Catalog::route_transcribe, infer/2 transcription, Pool::transcribe, see the guide). Catalogs leave transcription models out for askers before 0.5.8, which could not read them, and from 0.5.8 an entry a peer can’t read is skipped instead of failing the catalog. 0.5.7 is additive: per-model media and request limits in catalog entries (MediaLimits, CatalogModel::limits); entries without them look as before. 0.5.6 is additive: the opt-in jobs feature (synced jobs, see the guide), which needs weirdnet-sync 0.8.2; nothing changes without it. 0.5.5 changes no API: the pool and serve features accept weirdnet-sync 0.8 (>=0.5.2, <0.9). 0.5.4 is additive: CatalogModel::origin and license, with_origin, with_license and the ORIGIN_HUB, ORIGIN_UPLOAD and ORIGIN_TRAIN names, left off the wire when unset. 0.5.3 is additive: remote::pool_model::PoolModel, PoolWatch (with retry), PoolStatus and CatalogNodes, ModelError::PoolUnreachable, ModelNotice, AgentEvent::ModelNotice and DeltaSink::notice. 0.5.2 is additive: Request::adapter_scale and with_adapter_scale, and CatalogModel::base, with_base and is_adapter for LoRA adapters; neither is sent when unset, and older nodes ignore them. 0.5.1 is additive: CacheMode and Request::cache, Request::with_cache and Request::with_wait_for_model; older nodes ignore the new field. 0.5.0 adds image and audio content parts and routes them by model input; it is breaking: Message::content is a Content, not a String, so code that reads m.content as text uses m.text(), and AgentSession::run takes impl Into<Content> (see Moving to 0.5.0 below). Text-only messages keep their wire form, so 0.4 peers still read them; parts need 0.5 on both ends, and requests with parts skip infer/1 nodes. Frames may be up to 32 MiB (8 MiB before). 0.4.5 changes only package metadata and docs, with no API changes; 0.1.0 to 0.4.4 are yanked. 0.4.4 is additive: device roles in RosterAuth::require_roles (the user-signed grants in the weirdnet-sync 0.7 roster), Authorize::admit and Admitted, TaskHost::session_for and task::serve_for, and Server::start_with with ServingExtras::tasks to serve task/1; the pool and serve features accept weirdnet-sync 0.5.2 to 0.7. 0.4.3 stops offline linked devices from slowing every request (LinkedNodes::with_retry_after) and accepts weirdnet-sync 0.6. 0.4.2 is additive: the pool continues an answer from a caller’s assistant_prefix on nodes that can resume (no wire change; before, such a request failed with missing characters), a remote task’s approval card no longer arrives before the events sent ahead of it, and the pool and serve features need weirdnet-sync 0.5.2 (a device linked elsewhere reaches the others in one pass). 0.4.1 is additive: infer/2 raw prompts (Input::Prompt, Request::prompt; 0.4.0 servers close the stream and the pool moves on), early metadata (Request::early_meta, ServerFrame::Meta, PoolEvent::Meta, so a cache hit is known before the answer), embedding usage (EmbedBackend::embed_counted, Embeddings::usage), and a Pool that keeps error kinds: request errors (BadRequest, Cancelled) come back at once, and when every node fails the last node answer wins over a transport error. Weirdnet crates depend on it with caret requirements ("0.4", or "0.4.1" where they use these APIs), so agent patch releases don’t force re-releases. 0.4.0 is breaking for hosts that serve inference (InferHost now authorizes a Caller) and for code that matches the crate’s enums, which are now #[non_exhaustive]; see Moving to 0.4.0 below. weirdnet-net and weirdnet-sync are only pulled in by the pool and serve features. The API may change while Morph’s Companions are built on it.