Skip to main content

agentmux_srv_core/backend/reactive/
mod.rs

1// Copyright 2025, Command Line Inc.
2// Copyright 2025-2026, AgentMux Corp.
3// SPDX-License-Identifier: Apache-2.0
4
5//! Reactive messaging system for agent-to-agent terminal communication.
6//! Port of Go's pkg/reactive/.
7//!
8//! Provides message injection into terminal panes, agent registration,
9//! rate limiting, message sanitization, audit logging, and cross-host
10//! polling via AgentMux Cloud service.
11
12pub mod activity_watcher;
13pub mod action_audit;
14pub mod audit_store;
15pub mod controller_wait;
16pub mod cli_native_audit;
17pub mod turn_audit;
18pub mod handler;
19mod handler_lock;
20pub mod held_notes;
21pub mod held_request;
22pub mod progress_watcher;
23pub mod poller;
24pub mod rate_limiter;
25pub mod registry;
26pub mod post_secrets;
27pub mod sanitize;
28pub mod sender;
29pub mod sensitive_audit;
30pub mod system_turn;
31pub mod sent_audit;
32pub mod transcript_request;
33pub mod types;
34#[cfg(test)]
35mod tests;
36#[cfg(test)]
37mod newer_peer_tests;
38
39
40// ---- Constants ----
41
42/// Maximum message length in bytes.
43pub const MAX_MESSAGE_LENGTH: usize = 10_000;
44
45/// Suffix appended when a message is truncated.
46pub const TRUNCATION_SUFFIX: &str = "\n[Message truncated]";
47
48/// Maximum entries in the audit log ring buffer.
49const AUDIT_LOG_MAX: usize = 100;
50
51/// Woken whenever an agent registers, so jekts held for an absent agent are
52/// replayed promptly (`SPEC_DURABLE_JEKT_DELIVERY_2026_09_24.md` §2.3).
53/// `notify_one` does no I/O, so it is safe under the handler lock.
54pub fn held_jekt_wake() -> &'static tokio::sync::Notify {
55    static WAKE: std::sync::LazyLock<tokio::sync::Notify> =
56        std::sync::LazyLock::new(tokio::sync::Notify::new);
57    &WAKE
58}
59
60/// Woken whenever an agent registers, so the input held for an agent that was stopped goes out as soon
61/// as it starts (`server/held_input.rs`). Its own, as a `Notify` hands one wake to one waiter.
62pub fn held_input_wake() -> &'static tokio::sync::Notify {
63    static WAKE: std::sync::LazyLock<tokio::sync::Notify> = std::sync::LazyLock::new(tokio::sync::Notify::new);
64    &WAKE
65}
66
67/// Whether a delivery error is the target's spawn gate refusing to start it
68/// (`run_agent_turn`'s "identity spawn gate: …"): not signed in. Recoverable
69/// once the receiver signs in (SPEC_JEKT_DELIVERY_STATES_AND_MAILBOX_2026_10_01.md
70/// Phase 0 item 4, G4).
71pub fn is_spawn_gate_refusal(error: &str) -> bool {
72    error.starts_with("identity spawn gate")
73}
74
75/// How a refusal to deliver to an agent that can't work now begins: its
76/// account is out of quota or signed out (`SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md` §5).
77/// Only where the message can't be
78/// held: a LAN or cross-channel hop, a cron fire, a Swarm broadcast.
79pub const UNAVAILABLE_PREFIX: &str = "agent unavailable: ";
80
81/// Whether a delivery error is [`UNAVAILABLE_PREFIX`]'s refusal: recoverable
82/// at the reset, confirmed sign-in or an account move.
83pub fn is_unavailable_refusal(error: &str) -> bool {
84    error.starts_with(UNAVAILABLE_PREFIX)
85}
86
87/// Whether a delivery error is worth retrying shortly, as is: the target is
88/// still absent, rate-limited, its queue is full, it is starting,
89/// restarting or stopping ("… try again shortly"), or its pane is open and
90/// its controller is not there yet (`controller_wait`). Shared by the
91/// held-jekt replay and the cron scheduler's pending fires, which must agree.
92pub fn is_transient_delivery_error(error: &str) -> bool {
93    error.starts_with("agent not found")
94        || controller_wait::is_no_controller(error)
95        || error.contains("rate limit")
96        || error.contains("queue is full")
97        || error.contains("try again shortly")
98}
99
100/// An agent just registered in `block_id`: replay what was held for it, wake
101/// the relay subscription to take its names, and after an upgrade tell a
102/// resumed agent once, whatever runs it
103/// (`SPEC_UPGRADE_FOR_USERS_AND_AGENTS_2026_10_15.md` §5.2). No I/O here:
104/// safe under the handler lock (the note is sent from a task of its own).
105pub fn registered(block_id: &str) {
106    held_jekt_wake().notify_one();
107    held_input_wake().notify_one();
108    crate::backend::jobs::pending_wake().notify_one();
109    crate::backend::upgrade_notice::on_registered(block_id);
110    crate::backend::background_work::on_registered(block_id);
111    crate::muxbus::cloud_subscriber::live_names::registration_changed();
112}
113
114/// Rate limit: max tokens (requests per second).
115const RATE_LIMIT_MAX: u32 = 10;
116
117/// Default poll interval for AgentMux poller (seconds).
118pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 30;
119
120// ---- Re-exports ----
121
122#[allow(unused_imports)]
123pub use handler::{get_global_handler, Handler, ReactiveHandler};
124#[allow(unused_imports)]
125pub use poller::Poller;
126#[allow(unused_imports)]
127pub use sanitize::{
128    broadcast_turn_message, device_turn_message, format_injected_message, sanitize_message, validate_agent_id,
129    validate_muxbus_url,
130};
131#[allow(unused_imports)]
132pub use types::*;
133
134// ---- Helpers ----
135
136/// Get current time as Unix milliseconds.
137fn now_unix_millis() -> u64 {
138    agentmux_common::time::now_ms_u64()
139}
140
141/// A short hex hash of a message, so the audit log can tell messages apart
142/// without storing their text. `DefaultHasher`, not SHA-256: privacy, not
143/// security (it was named `sha256_hex` until the §5.3 #7 cleanup).
144fn audit_hash(input: &str) -> String {
145    use std::collections::hash_map::DefaultHasher;
146    use std::hash::{Hash, Hasher};
147    // Use a fast non-crypto hash for audit log (privacy, not security)
148    let mut hasher = DefaultHasher::new();
149    input.hash(&mut hasher);
150    format!("{:016x}", hasher.finish())
151}