Living notes for crates/relay-api. The contract is crates/relay-api/proto/relay/v1/engine.proto; Rust stubs are generated by build.rs (vendored protoc, no system install needed) into relay_api::pb. Generated types are wire types only; the engine crate converts them to validated domain types.
| Platform | Endpoint | Status |
|---|---|---|
| Unix | UDS $XDG_RUNTIME_DIR/relay/engine.sock, else <tmp>/relay-<uid>/engine.sock |
implemented, tested |
| Any | Loopback TCP + bearer token profile file (fallback) | implemented, tested |
| Windows | Named pipe with current-user DACL | unmet spike, not implemented |
- Directory created
0700; an existing directory must be a real directory (no symlink) owned by us, and is tightened to0700if loose. - Socket is
0600. Every accepted connection is checked withpeer_cred(); other uids are dropped and logged. - Stale detection: an existing path must be a socket we own; if connecting gets
ECONNREFUSEDit is removed and rebound, if it connects the bind fails withAlreadyRunning. A non-socket file is never touched. PID files are not used. current_uidandprepare_runtime_dirneed a tokio runtime context.
bind_loopback(path) binds 127.0.0.1:0, writes addr= and token= (64 hex chars from two v4 UUIDs) to a 0600 file. Clients refuse a profile that is group/world accessible, non-loopback, or has a short token. Every RPC needs authorization: Bearer <token> (constant-time compare). No CORS or browser access. Loopback is not authentication against a same-user hostile process. On Windows the file mode is not enforced (ACL hardening unmet).
The daemon serves its endpoint before it has opened the system's secure storage (a keychain prompt can wait for the user). Until the engine is ready, GetInfo returns EngineInfo.startup (Startup{state, reason, detail}): STARTING with WAITING_FOR_KEYCHAIN, or FAILED with KEYCHAIN_UNAVAILABLE (denied, locked, timed out) or IDENTITY_UNREADABLE (corrupt or newer data), detail being the system's text. A ready engine omits it (READY, the default). Every other call, RegisterClient included, is UNAVAILABLE meanwhile (RelayClient::register returns ApiError::Starting). Three calls need no registered client and work in every state: RetryKeychain (read again after FAILED), UseFileStore (choose the less secure file-backed store, then retry; the only way it is used) and ResetIdentity (delete the stored identity; contacts must re-verify; in a ready daemon it then stops it). They answer with the fresh EngineInfo; RetryKeychain and UseFileStore are FAILED_PRECONDITION while STARTING or when ready, ResetIdentity while STARTING. They are guarded like GetInfo (owner-only socket, token on loopback TCP).
GetInfo, RegisterClient and the three start-up calls are the only unauthenticated-by-context methods. All others must carry metadata relay-client-id (32 hex chars) and may carry relay-incarnation. GuardLayer validates these through a ClientValidator (ClientRegistry is a bounded reference implementation, 32 clients) before the handler runs: unknown id is UNAUTHENTICATED, stale incarnation is FAILED_PRECONDITION, malformed is INVALID_ARGUMENT. The engine must still check that the body's ClientContext equals the header. A client id is an identifier, not authentication.
Limits (ApiLimits::DEFAULT): messages of 1 MiB plus 64 KiB of envelope (tonic encode/decode caps plus an early content-length reject, RESOURCE_EXHAUSTED/OUT_OF_RANGE), 64 requests in flight, 96 open streams, 256-event subscriber queues. Streaming handlers must call StreamLimiter::acquire() and keep the guard in their stream task.
Each mutation carries a 16-byte operation_id. Same id + identical request returns the stored outcome; same id + different request is ALREADY_EXISTS (OPERATION_ID_REUSED). Retention (4,096 per client, 10 minutes) is the engine's job. RelayClient::wait_operation polls GetOperation until the state leaves ACCEPTED.
WatchState without after_revision begins with an atomic snapshot. StateTracker rejects non-increasing revisions, revision gaps (unfiltered watches only; filters may legitimately skip), and incarnation changes. ResyncRequired means: open a fresh watch. snapshot_and_watch resumes at snapshot.revision and relies on engine replay; a missed window yields Resync. StateWatch::into_bounded(n) moves reading to a task and ends with SubscriptionOverflow instead of buffering when the consumer lags.
- Ring sounds:
Settings.ringtone_enabled,ringtone_volume(0.0 to 1.0),ringback_enabledandcall_sounds_enabledare changed through the optionalSetGlobalControlsfields of the same names (persisted asaudio.ringtone_enabledand so on; they apply live: a volume change reaches a ring that plays, disabling stops it; a volume outside 0..1 isINVALID_ARGUMENT).SetRingtone(SetRingtoneRequest{context, file_name, data, reset})makes an audio file (MP3, Ogg Vorbis, FLAC, WAV, AAC/M4A) the incoming-call ring of the device that runs the engine, or withresetrestores the built-in chime; the engine decodes it off the real-time thread withinlimits.ringtone_max_kibandlimits.ringtone_max_seconds, stores it as Ogg Opus in its data directory and reportsSettings.ringtone_name(empty = built-in). A file that cannot be a ringtone is aFAILEDoperation withRINGTONE_EMPTY,_TOO_LARGE,_TOO_LONG,_TOO_SHORT,_UNSUPPORTED,_CORRUPTor_SILENT(the UI words them); an empty body or one over 8 MiB isINVALID_ARGUMENT; the name is cut to its base name. The defaultaudio.ringtone_volumeis 0.4.PreviewTone(MutationContext)plays the ring on the daemon's own output for 2 s, for a settings "Test ring" button; it never sends audio to a peer. The daemon rings only while a client holds a state watch. - Audio devices: nothing has to be selected; with empty ids the engine uses the system default input and output.
SelectDevices(input_device_id, output_device_id)pins a device per direction, and an empty id returns that direction to the system default; a named id that is not listed is refused.Settings.input_device_id/output_device_idare the pinned ids (empty = following the default). Derived, read-only state:input_is_default/output_is_default(nothing pinned),input_device_name/output_device_name(the device that will be opened; empty when the system has none),input_pinned_missing/output_pinned_missing(the pinned device is absent, so the system default is used). They are recomputed when the device list changes and aSettingsevent is sent when they do.Device.system_defaultmarks the OS default per direction. Open streams are not moved mid-call; a changed default applies at the next open. A microphone that cannot be opened raises the warningMICROPHONE_UNAVAILABLE(recoverycheck_microphone_access). - Transmit mode:
SetTransmitMode(call, mode)is the single microphone control of a call.TRANSMIT_MODE_UNMUTEDandTRANSMIT_MODE_PUSH_TO_TALKare the explicit consent,TRANSMIT_MODE_MUTEDwithdraws it;authorize_background_open_micapplies to unmuted only.TransmitRoute.consent_grantedis derived (mode is not muted). The default for new calls isSettings.default_transmit_mode(calls.default_transmit_mode).Call.connected_at_unix_msis the engine wall clock when the call became connected (0 otherwise).Peer.portandPeer.last_seen_unix_mscompletelocal_addressesfor contact lists. - Push-to-talk release delay:
Settings.ptt_release_delay_ms(0 to 2000, default 200) is read and changed throughSetGlobalControls.ptt_release_delay_ms(optional; applies live and is persisted asptt.release_delay_ms; above 2000 isINVALID_ARGUMENT).TransmitRoute.releasingis true while the key is up but the gate is still open for the delay;effective_transmittingstays true then. Only an ordinaryINPUT_ACTION_RELEASEis held:RELEASE_ALL, stream closure and every safety close are immediate. - Channel RPCs (
CreateChannel,JoinChannel,LeaveChannel,ListChannels,CreateInvite,RevokeChannelMember) followdocs/channels.md.Snapshot.channels,Peer.shared_channel_ids,Settings.inbound_policyandSettings.advert_modeexpose state;SetPrivacychanges the last two. - Channels on the network:
Snapshot.nearby_channelsandStateEvent.nearby_channels(NearbyChannels, the whole current list, sent only when it changes) carryNearbyChannel{name, devices, ambiguous}for every listed channel another device advertises that this device is not in (at most 32). The id is not exposed: join withJoinChannel{name}.passwordmeans joining needs the channel password (send it inJoinChannel.password). Invite-only channels are never listed, so they never appear here;CreateChannelwithlistedandinvite_onlyboth set isINVALID_ARGUMENT. An entry disappears when the advertising devices withdraw their record (or, as a safety net, ten minutes after the last one was heard).ambiguousmeans two different channels use the name (or it equals a channel this device is in): joining by that name is refused (CHANNEL_DENIED) and the id is required. Seedocs/channels.md. - Failed channel operations carry stable
Problem.codes:CHANNEL_DENIED(uniform for unknown channel, wrong secret, bad or spent invite),CHANNEL_LOCKED_OUT,CHANNEL_LIMIT,CHANNEL_NAME_INVALID. - Passwords and invite secrets live only in request bodies (and the
CreateInviteResponse). The generatedDebugis disabled for those messages and replaced by redacting impls; the guard logs method paths only (SENSITIVE_METHODSlists the affected RPCs). The engine must not put them in events, snapshots, operation results or logs. GetAvatar(hash)returns the canonical avatar (a 256x256 lossless WebP inAvatarImage.image,media_type = "image/webp", withwidth/height) up toAVATAR_MAX_BYTES(1 MiB; the default message limit is that plus 64 KiB of envelope); unknown hash isNOT_FOUND.RelayClient::get_avatarrejects larger answers.UploadAvataraccepts PNG, JPEG, WebP, GIF, BMP or TIFF (sniffed from the bytes, at most 1 MiB, at most 2048x2048; animated GIF/WebP use the first frame) and stores a canonical 256x256 lossless WebP.ClearAvatar(MutationContext)removes it:Settings.avatar_sha256becomes empty, the cache entry is unpinned (it ages out like a received avatar) and every trusted peer is sent a freshProfilewith an empty avatar hash, so they stop showing the old image. It is idempotent (clearing with no avatar isAPPLIED) and survives a restart.RelayClient::clear_avatar()/relay_client::Command::ClearAvatar.- Avatar refusal texts (exact, for client-side pre-checks to mirror; the engine is the authority). Before any decoding,
UploadAvataranswers gRPCINVALID_ARGUMENTwithavatar must be 1 byte to 1 MiB (PNG, JPEG, WebP, GIF, BMP or TIFF)for an empty body or one over 1,048,576 bytes. Otherwise a rejected image is aFAILEDoperation withProblem.code = INVALID_REQUESTandProblem.message = "invalid: avatar rejected: <reason>", where<reason>is one ofunsupported or unrecognised image format (use PNG, JPEG, WebP, GIF, BMP or TIFF),avatar dimensions <w>x<h> exceed the 2048 pixel limit,avatar has zero width or height,avatar would need <n> bytes to decode, limit is 16777216oravatar could not be decoded: <detail>. The format is sniffed from the bytes (the declared media type and file extension are ignored), so a CLI or desktop pre-check should list all six formats and 2048 x 2048 / 1 MiB, not just PNG and JPEG. - Trust, forgetting:
Peer.fingerprint_shortis the stored short form of the key digest (A1B2-C3D4-E5F6-0718-293A, 80 bits; a hint to tell devices apart, never a verification string: verification compares the full digest).ForgetPeer(peer_id | query)(orDecidePeerTrustwithrequested_trust = UNKNOWN, whoseexpected_public_key_sha256may be left empty) removes the stored trust decision, cuts the link and stops reconnecting.queryis a hex fingerprint prefix (at least 8 digits; spaces,-and:and case are ignored, so the short form or its first groups work) or an exact, case-insensitive display name; a fingerprint is tried before a name. The match must be unambiguous. Failed operation codes:NOT_FOUND(nothing stored matches; an empty or oversized query isINVALID_ARGUMENT) andPEER_AMBIGUOUS(the message lists the candidates with their short fingerprints; nothing changes). Event: aRemoved{kind: "peer"}state event with the peer id. A device that still trusts us and calls again is treated as an unknown peer (TRUST_REQUIRED). Needscall-control.RelayClient::forget_peer(peer_id, query)/relay_client::Command::ForgetPeer. - Calling a non-contact and blocking:
Peer.reachableis true for a device that is not trusted when its link is open for a call (this device is visible: a client is attached and the advert mode is not hidden), soStartCall(peer_id)works withoutDecidePeerTrust. A call that is answered pins both keys asTOFU_UNVERIFIED(neverVERIFIED), on the link that carried the invitation; a decline, hang-up or unanswered call pins nothing.DecidePeerTrust(BLOCKED)blocks the device (bounded list of 256 key digests, persisted): its links are refused without any event, a stored contact is forgotten, and it is listed as aPeerwithtrust = BLOCKED,reachable = false.DecidePeerTrust(UNKNOWN)/ForgetPeer(peer_id)on a blocked device unblocks it. A trust decision that cannot be stored is a FAILED operation:TRUST_KEY_MISMATCH(the device answering has another key) orUNAVAILABLE(retryable).API_REVISIONis 7 (revision 7: engine-held presence andSetClientQuiet, below; revision 5: the microphone processing fields ofSettingsreplacedns_backend_id, andSetNoiseSuppressionwas removed; revision 6: auto-answer, background and call alert, below). - Key changes: a device that presents another key under a trusted name is refused and listed as a
Peerwithtrust = KEY_CHANGED,key_changed = true,previous_peer_id(the pinned key digest) andprevious_fingerprint_short; itspeer_idandfingerprint_shortare those of the NEW key.ForgetPeeraccepts either key (and a prefix of either) and removes the pinned record.ReplacePinnedKey{peer_id, expected_fingerprint, verified}(needscall-control) replaces the pinned key bypeer_idonly when the engine remembers that key change,verifiedis true andexpected_fingerprint(64 hex digits, separators and case ignored) is exactly the new key's full fingerprint, carrying over the name and the favorite place and dialling the device; otherwise the operation fails (INVALID_ARGUMENTfor a wrong or short fingerprint, a precondition failure when no key change is remembered) and nothing changes.ConnectAndTrustwith the new key's QR string does the same.RelayClient::replace_pinned_key/relay_client::Command::ReplacePinnedKey. ConnectAndTrust(connection_string): a scannedrelay://host:port#<64 hex>string is an out-of-band exchange of the fingerprint. The engine dials the address with that key pinned, so a device with another key is refused in the handshake before our key is sent; only when the authenticated key matches is the peer trusted asVERIFIED(the same pin asDecidePeerTrust(VERIFIED, out_of_band_verified)). Failures are FAILED operations that store nothing:CONNECT_STRING_INVALID(not a connection string, a short or malformed fingerprint, an address the address policy refuses),CONNECT_FINGERPRINT_MISMATCH(another device answered at that address),CONNECT_UNREACHABLE(retryable; nobody answered within 20 s). Needscall-control.relay_client::Command::ConnectAndTrust.- Favorites:
SetFavorites(SetFavoritesRequest{context, peer_ids})(needscall-control) replaces the favorites, the Calls page quick-call grid, by the ordered list of up to 6 trusted peers (32-byte ids, first = place 0). A list over 6, a repeated peer or a peer that is not trusted FAILS the operation (INVALID_REQUEST, the reason names the rule:You can have up to 6 favorites) and changes nothing. Adding, removing and moving are all this one request.Peer.favoriteandPeer.favorite_position(additive, fields 20 and 21) show the result in the snapshot and in the usualPeerstate event; forgetting a peer removes its favorite and sends the updated peers.RelayClient::set_favorites(&[Vec<u8>]),relay_client::Command::SetFavorites { peer_ids }. - Background and call alert:
Settings.background_available(background.available),Settings.call_alert(calls.alert:"system","ring_and_vibrate","vibrate","silent") andSettings.auto_answer_enabled(calls.auto_answer_enabled). All three are liveSetSettingskeys. The engine only stores and publishesbackground.available; the OS shells act on it. The engine ringtone obeyscalls.alert(no ring forvibrateandsilent); shells apply the vibration and thesystemprofile. - Auto-answer:
SetPeerAutoAnswer(SetPeerAutoAnswerRequest{context, peer_id, enabled})(needscall-control) switches it for one contact. Switching on FAILS (INVALID_REQUEST, "Only verified contacts can answer automatically") unless the contact is stored as verified; switching off always works.Peer.auto_answer(field 40) is the stored flag; it takes effect only for a verified contact, with a live link, whileSettings.auto_answer_enabledis on, no other call is live and a client is attached. The called engine then answers 1.5 s after the call starts ringing (a decline in that window wins), incalls.default_transmit_mode.Call.auto_answered(field 13) is true from that answer to the end of the call (a persistent indicator), and oneStateEvent.auto_answered(AutoAnswered{call_id, peer_id, peer_name}) is sent when the engine connects it, for a notification. Forgetting, blocking or replacing the key of a peer clears its flag.RelayClient::set_peer_auto_answer(&[u8], bool),relay_client::Command::SetPeerAutoAnswer { peer_id, enabled }. - Engine-held presence and quiet clients: while
Settings.background_availableis on the engine counts as attached by itself (the reservedrelay_core::ClientId::HOUSE), so with noWatchStateopen it advertises, listens, rings, auto-answers and does not idle-exit; with it off, presence is held by watching clients as before. An auto-answered call with no client attached is controlled by the engine;AcquireControllerby any client succeeds withoutrequest_explicit_takeoverwhile the engine holds the lease.SetClientQuiet(SetClientQuietRequest{context, quiet})(needscall-control, answers an appliedOperation) says that this client's shell alerts calls itself: the engine plays no ringtone while every attached client is quiet (a non-quiet client or an engine-only presence still rings). The flag lasts while the client holds a watch and ends with its last one.RelayClient::set_client_quiet(bool),relay_client::Command::SetClientQuiet { quiet }. The auto-answer condition "a client is attached" above reads "someone is home". GetConnectionInforeturns eligible LAN addresses, listen port, local fingerprint and an opaqueconnection_stringfilled by the engine.StartCallRequest.targetalso acceptsmanual_connection_string.
GetSettings(ClientContext) (needs observe) answers every preference as flat section.key text in SettingsDump.values, the same vocabulary as relay config get|set|export (relay_config::prefs::flat): strings unquoted, booleans true/false, numbers plain. config_version is not included. RelayClient::get_settings() returns a sorted map. SettingsDump.usage (additive, map<string,uint64>) reports bytes in use next to the limit that bounds them, keyed by that limit's key: limits.avatar_cache_mib, limits.messages_retained_mib (ended chats; limits.messages_retained_calls has no usage entry) and limits.messages_session_mib (the largest running chat); a limit whose usage the engine does not know cheaply has no entry. RelayClient::get_limit_usage() returns it.
SetSettings(MutationContext, map<string,string>) (needs call-control) changes any of them while the daemon runs. Values are parsed like relay config set. At most 64 entries (keys up to 128 bytes, values up to 1 KiB); an empty or oversized request is INVALID_ARGUMENT. The answer is a SetSettingsResponse with an operation (always APPLIED) and one SettingResult per key, sorted by key:
| Outcome | Meaning |
|---|---|
APPLIED_LIVE |
saved and in effect now |
SAVED_NEEDS_RESTART |
saved; the daemon reads it at its next start (reason says so) |
REJECTED |
not saved; reason is the validation error (unknown key, bad value, out of range) |
Valid keys are saved together even when others in the request are rejected. Live: profile.display_name, audio.microphone_gain, audio.playback_gain, audio.noise_suppression, audio.noise_suppression_level, audio.auto_gain, audio.ringtone_enabled, audio.ringtone_volume, audio.ringback_enabled, audio.call_sounds_enabled, privacy.inbound_policy, privacy.advert_mode, ptt.release_delay_ms, calls.default_transmit_mode, clients.autostart_daemon, messages.enabled, messages.max_offer_size_mib, messages.transfer_rate_limit_mbps, history.enabled, and the six limits.* keys (docs/limits.md: validated per key with min and max and rejected, never clamped, with a reason naming the key; all live). Saved for the next start: audio.input_*, audio.output_* (use SelectDevices to change devices live), network.*, hotkeys.* (read by relay hotkey and the desktop app when they start), diagnostics.*, the other privacy.*. A live key whose follow-up fails (for example the media path refusing a microphone gain) is reported as SAVED_NEEDS_RESTART.
Security-sensitive keys cannot be changed over the API: identity.* (where key material lives), diagnostics.record_raw_audio, network.allow_wan and network.allow_overlay_manual. A request that would change one is refused whole with PERMISSION_DENIED (SETTING_RESTRICTED: <key>) and nothing is applied; sending such a key with its current value is a no-op, so the output of GetSettings can be fed back in. Those keys change only with the daemon stopped (relay config set). SetSettings is naturally idempotent and is not tracked by operation id. Helpers: RelayClient::set_settings(pairs) (returns the per-key results), relay_client::Command::SetSettings (operation only). A CLI config set can therefore route every key through a running daemon instead of requiring it to be stopped.
ListCallHistory(ListCallHistoryRequest{client, limit, before_id}) (needs observe) answers a CallHistoryPage{entries, more, revision}, newest first: limit 0 takes the engine default (50), at most 200; before_id continues after the last id of the previous page; more says older entries exist. A CallHistoryEntry is id (the paging cursor), call_id (16 bytes, names the call's chat session), peer_name (as seen at the time), peer_id (32 bytes, the full fingerprint), peer_fingerprint_short, direction (CALL_DIRECTION_INCOMING|OUTGOING), outcome (CALL_OUTCOME_COMPLETED|MISSED|DECLINED|FAILED|CANCELLED), started_at_unix_ms and duration_ms. Metadata only: no audio, no message content, no addresses. ClearCallHistory(MutationContext) (needs call-control) deletes every entry and answers an APPLIED Operation; it is idempotent.
The refresh signal needs no new stream: Settings (snapshot and StateEvent.settings) carries history_enabled (the preference history.enabled, live-applied through SetSettings, default on) and history_revision, which changes whenever an entry is added or the history is cleared; a client reads the list again when it moves (and once when it connects, because the revision restarts with the daemon). While history_enabled is false nothing new is recorded and existing entries stay until cleared. RelayClient::list_call_history(limit, before_id), RelayClient::clear_call_history() and relay_client::Command::ClearCallHistory are the client forms; ListCallHistory is listed in SENSITIVE_METHODS (peer names), so the guard logs only its path. Privacy: docs/config.md, "Call history".
CallTelemetry.rtt_ms is the smoothed round trip to the peer measured with the authenticated keepalives of the control link, with latency_estimate_method = "control_keepalive_rtt"; until the first echo (about 5 s after the link comes up) it is unset and the method is "unmeasured". It is an upper estimate of the media path (the probe is TCP and shares the connection with signaling). rtp_interarrival_jitter_ms and estimated_mouth_to_ear_ms remain unset: nothing measures capture-to-playout latency yet.
WatchCallStats(WatchCallStatsRequest{client, call_id}) streams CallStats about once per
second for one call (capability observe): media path state and reason, sending / receiving
(a packet within 500 ms), packet counters, mic_level_dbfs, rtt_ms with its 10 s minimum and
maximum, RFC 3550 jitter_ms, loss over 5 s and in total, jitter buffer target and depth,
playout delay, an estimated mouth_to_ear_ms, codec bitrate and packet size, local and remote
address, transport (lan or overlay), clock drift and the device buffer sizes. The formulas
are in docs/engine.md ("Call statistics"). Open it only while a debug panel is visible. The
client helper is relay_client::wire::open_call_stats; Call.connected_at_unix_ms stays on the
state stream.
let mut c = RelayClient::connect(&Endpoint::Unix(path)).await?;
c.register("relay-cli", env!("CARGO_PKG_VERSION"), &["observe"]).await?;
let (snapshot, mut watch) = c.snapshot_and_watch().await?;A client names the capabilities it wants at RegisterClient: observe (read state), call-control (every mutation and push-to-talk input), admin and messages (session messaging, see below). Asking for nothing grants the first two; admin and messages are granted only when named, and admin does not imply messages. Shutdown(MutationContext) is the single admin call: it asks the engine to stop gracefully (calls end, microphone released, endpoint removed, process exit 0), is idempotent, and is denied with PERMISSION_DENIED otherwise. RelayClient::shutdown() wraps it; relay_client::daemon::stop registers a separate admin client for it.
Companion to docs/session-messages.md (the design) and docs/engine.md (how the daemon does it). The daemon owns every transcript, so a CLI and the desktop app see the same session. Needs the messages capability on every method below, reads and WatchSession included: without it the answer is PERMISSION_DENIED and no event is ever delivered. Privacy rationale: a transcript is private to the people in the call, so observers, call controllers and admins see nothing unless they asked for messages at registration. A client holding it may read and send in any live session of the daemon and read, search, export and clear any retained transcript (the daemon has one user). Messaging operations are applied synchronously: each answers a final SessionOpResult (operation is APPLIED or FAILED, never ACCEPTED); GetOperation does not track them. Same operation id and identical request returns the stored result; a different request under the same id is ALREADY_EXISTS.
| Method | Purpose |
|---|---|
ListSessions |
Every session, live (ACTIVE) and retained (ENDED), the feed revision and MessagingSettings |
GetTranscript(session, from_ordinal, limit) |
One page (at most 500 entries or about 512 KiB); more/next_ordinal continue; revision is the feed revision at read time, to resume WatchSession without a gap |
WatchSession(after_revision?, session_id?) |
Events (below). Without after_revision the first item is a SessionList; with it the engine replays, or answers SessionResync when its window (2048 events) no longer covers the request |
SendSessionMessage(session, text) |
Text, sanitized and bounded by relay-messages; the answer carries message (ordinal, seq) |
SendSessionImage(session, bytes) |
PNG, JPEG, WebP or GIF, header validated, at most 15 KiB (a control record is 16 KiB; larger images are file offers). The daemon stores the original bytes and never decodes them: the client decodes with its own allocation limit and deadline |
RetrySessionMessage(session, seq) |
Same sequence, fresh attempt budget, for a FAILED local message |
OfferFile(session, path) |
The daemon opens path (see below); the answer carries offer_id |
RespondOffer(session, offer, accept, destination_dir, file_name) |
Accept into an existing absolute directory the client chose, or reject. The daemon sanitizes the name (the suggestion or the offered one) and never overwrites (name (1).ext) |
RequestPreview / ApprovePreview(approve) |
Receiver asks, sender's user approves; the daemon reads at most 100 lines or 15 KiB of valid UTF-8 text from the file on approval. A binary file answers PREVIEW_UNAVAILABLE and the peer is told no |
CancelTransfer(session, offer) |
Cancels a running transfer, withdraws an open outgoing offer, or declines an open incoming one |
SetSessionPermissions(allow_messages?, allow_files?) |
The call's initiator is the host and pushes the pair to the guest; the guest may also change its own pair, which stays local (a later host push overwrites it). Turning files off cancels running transfers and refuses new accepts |
PinMessage(session, outgoing, seq, pinned) |
Local flag |
SearchSession(session, query) |
Case-insensitive substring over text, file names and previews, at most 100 hits (MessageRefs) |
ClearSession(session) |
Active: empties the transcript (ordinals keep counting). Ended: removes it. Local only |
ExportSession(session, embed_images, destination_path?) |
The export JSON in json; nothing is written unless destination_path is given (absolute, must not exist; created owner-only, never replacing). Over about 960 KiB it fails EXPORT_TOO_LARGE unless a path is given |
SetMessagingSettings(enabled?, max_offer_size_mib?, transfer_rate_limit_mbps?) |
The live preferences (docs/config.md) |
Copy actions are client-side: the engine returns the exact stored text (entry_text), code blocks are re-parsed by the client from it.
OfferFile and the filesystem. Clients and daemon run as the same user on the same machine. The path is chosen by the client; the daemon opens it with the user's own filesystem access. It must be absolute with no .., name a regular file and not a symbolic link in its last component (an ancestor directory may be a link; the daemon compares the opened file with the path and refuses a swap), and be at most messages.max_offer_size_mib. The daemon hashes a snapshot (BLAKE3, on a blocking worker) and later re-checks the file (size, modification time, inode) before the first chunk and at the end; a changed source fails the transfer (source_changed). Failures answer FILE_REFUSED, FILE_TOO_LARGE or FILE_CHANGED.
Events (SessionEvent, one revision sequence over all sessions, contiguous when unfiltered): entry (new transcript entry, either direction), delivery (SENDING -> DELIVERED, or FAILED with failure = timeout or the peer's reason), offer (the whole offer record whenever state, progress, preview or approval changes; progress at most every 256 KiB), permissions (by_peer when the host pushed), pin, session (started, ended or counters), cleared, evicted (an ended transcript was dropped: replaced by a new call with the same peer, evicted by the retained budget or the ended-call count (limits.messages_retained_calls), or cleared). Slow consumers: the stream is a bounded drop-oldest queue (256 events); when a watcher lags it receives SessionResync and the stream ends. Recovery is ListSessions + GetTranscript(from_ordinal) + a fresh WatchSession, which RelayClient::watch_session / read_transcript support.
Stable problem codes (on a FAILED SessionOpResult.operation): MESSAGES_DISABLED, SESSION_NOT_FOUND, SESSION_ENDED, SESSION_PERMISSION_OFF, TEXT_INVALID, TEXT_TOO_LONG, IMAGE_INVALID, IMAGE_UNSUPPORTED, IMAGE_TOO_LARGE, HISTORY_FULL, RATE_LIMITED, TOO_MANY_OFFERS, MESSAGE_NOT_FOUND, MESSAGE_STATE, OFFER_NOT_FOUND, OFFER_STATE, FILE_REFUSED, FILE_TOO_LARGE, FILE_CHANGED, TOO_MANY_TRANSFERS, NO_SPACE, DESTINATION_INVALID, PREVIEW_UNAVAILABLE, EXPORT_TOO_LARGE, EXPORT_WRITE_FAILED, INVALID_SETTING. Reads of an unknown session are NOT_FOUND. Message text, file names and paths never appear in a Problem, a log line, a Debug of the request/response types (redacting impls, SENSITIVE_METHODS) or an operation result.
RelayClient has one helper per method (send_session_message, offer_file, watch_session, read_transcript, ...), SessionWatch/SessionTracker do the revision and gap checks like StateWatch, and relay_client::Command has the matching mutation variants (SendSessionMessage, OfferFile, RespondOffer, ...; Command::is_messaging). The fake engine of the contract tests (crates/relay-api/tests/common) implements the capability gate, transcripts, search and the event feed with replay and resync.
Implement pb::engine_server::Engine, own a ClientRegistry (or a custom ClientValidator), bind UdsListener, and call serve_unix (or serve_tcp). engine_server() applies message limits when wiring by hand.
Windows named pipe; Windows ACL on the TCP profile; per-client operation cache and rate limits; telemetry and InputControl stream semantics (engine-side).