agentmux_srv/server/jekt_echo.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sender's own copy of a jekt it sent, written into its pane
5//! (SPEC_JEKT_SECURITY_AND_VISIBILITY §3.2). Moved out of `reactive.rs`.
6
7use super::AppState;
8
9/// Echo a successfully-sent jekt into the SENDER's own pane
10/// (SPEC_JEKT_SECURITY_AND_VISIBILITY §3.2).
11///
12/// Appends a `{"type":"user",...}` NDJSON line carrying the same
13/// `[JEKT:...]` marker block the receiver got (re-wrapped with identical
14/// fields) to the sender's `output` blockfile — live MPS append (renders
15/// immediately in an open agent view), persisted history
16/// (`parseHistoryLines` rebuilds on reopen), and global transcript mirror.
17/// The frontend's `tryParseJekt` sees FROM == this pane's agent and renders
18/// it as an *outgoing* JektBubble (stream-parser.ts direction detection —
19/// this is the producer that comment says doesn't exist yet).
20///
21/// No-op when the sender isn't a registered agent on this instance (cron,
22/// external callers) or is messaging itself (the incoming marker already
23/// lands in the same pane).
24///
25/// `reagent_verified`/`lan_verified` should be the SAME values the original
26/// delivery's `Handler::inject_message_inner` computed `effective_tier`/
27/// `requires_stop` from (not re-derived) — see the call site's own doc
28/// comment inline below for why passing anything else produces a
29/// self-contradictory echoed marker (reagentx P1 on PR #2623).
30/// The delivery-tier + verification signals an echoed marker must carry.
31///
32/// Grouped into a named struct rather than left as positionals because
33/// `sig_verified`, `reagent_verified` and `lan_verified` are three consecutive
34/// `Option<bool>`s: any two of them can be transposed at a call site and the
35/// compiler cannot say a word. The failure mode is a silently mislabelled TRUST
36/// field on a security marker, which is not the kind of bug to leave to
37/// argument order.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub(super) struct EchoTrust<'a> {
40 pub delivery_tier: &'a str,
41 pub sig_verified: Option<bool>,
42 pub reagent_verified: Option<bool>,
43 pub lan_verified: Option<bool>,
44 pub channel_verified: Option<bool>,
45}
46
47impl<'a> EchoTrust<'a> {
48 /// The verdicts a delivered request carried: its delivery tier (`host`
49 /// when unset) and each signature check's result.
50 pub(super) fn of(req: &'a crate::backend::reactive::types::InjectionRequest) -> Self {
51 EchoTrust {
52 delivery_tier: req.delivery_tier.as_deref().unwrap_or("host"),
53 sig_verified: req.sig_verified,
54 reagent_verified: req.reagent_verified,
55 lan_verified: req.lan_verified,
56 channel_verified: req.channel_verified,
57 }
58 }
59}
60
61/// The trust an echoed marker should carry after a forward, given the
62/// peer's response body. The RECEIVING instance is the one that computes
63/// `channel_verified` (the forwarder holds the sender's HMAC key, so §D2
64/// step 2 of SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md makes it skip
65/// cross-channel verification) and threads it back via
66/// `InjectionResponse::channel_verified`, exactly as it already does for
67/// `effective_tier`/`requires_stop`. Taking it from the body keeps the
68/// sender's echoed `TRUST=` consistent with the `ESCALATE=` the same body
69/// supplies — otherwise a sensitive cross-channel message could echo as
70/// `TRUST=self-declared … ESCALATE=none`, which contradicts itself (codex
71/// P2 on #3064). A body without the field (an older peer) leaves the
72/// caller's value alone.
73pub(super) fn echo_trust_from_peer_body<'a>(body: &serde_json::Value, base: EchoTrust<'a>) -> EchoTrust<'a> {
74 EchoTrust {
75 channel_verified: body
76 .get("channel_verified")
77 .and_then(|v| v.as_bool())
78 .or(base.channel_verified),
79 ..base
80 }
81}
82
83pub(super) fn echo_jekt_to_sender(
84 state: &AppState,
85 source_agent: Option<&str>,
86 target_agent: &str,
87 message: &str,
88 msgid: &str,
89 effective_tier: Option<&str>,
90 requires_stop: Option<bool>,
91 trust: EchoTrust<'_>,
92 priority: &str,
93) {
94 echo_jekt_to_sender_with_files(state, source_agent, target_agent, message, msgid, effective_tier, requires_stop, trust, priority, None);
95}
96
97/// [`echo_jekt_to_sender`] for a jekt delivered with files: the sender's
98/// echo lists them as the receiver's message did, so its pane shows the
99/// same chips (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §6.2).
100#[allow(clippy::too_many_arguments)]
101pub(super) fn echo_jekt_to_sender_with_files(
102 state: &AppState,
103 source_agent: Option<&str>,
104 target_agent: &str,
105 message: &str,
106 msgid: &str,
107 effective_tier: Option<&str>,
108 requires_stop: Option<bool>,
109 trust: EchoTrust<'_>,
110 priority: &str,
111 files: Option<&crate::backend::reactive::types::FilesDelivery>,
112) {
113 let EchoTrust {
114 delivery_tier,
115 sig_verified,
116 reagent_verified,
117 lan_verified,
118 channel_verified,
119 } = trust;
120 let Some(src) = source_agent.filter(|s| !s.is_empty()) else {
121 return;
122 };
123 if src.eq_ignore_ascii_case(target_agent) {
124 return;
125 }
126 let Some(sender_reg) = state.reactive_handler.get_agent(src) else {
127 return;
128 };
129
130 let sanitized = crate::backend::reactive::sanitize::sanitize_message(message);
131 let wrapped = crate::backend::reactive::sanitize::wrap_jekt_message_with_files(
132 &sanitized,
133 Some(&sender_reg.agent_id),
134 target_agent,
135 effective_tier.unwrap_or("coord"),
136 delivery_tier,
137 sig_verified,
138 // reagentx P1 on PR #2623: these used to be hardcoded `None, None`
139 // ("sender-echo is inherently host-tier, so WAN/LAN verification is
140 // meaningless here") — true for TRUST/SIG rendering alone, but as of
141 // SPEC_JEKT_SENSITIVE_TIER_VERIFIED_SENDER_NO_STOP_2026_08_17.md
142 // that assumption broke: `requires_stop` (just above) already
143 // reflects the REAL delivery's verification, so hardcoding these to
144 // `None` produced a self-contradictory echoed marker — `ESCALATE=none`
145 // (implying a verified sender) next to `TRUST=network-claimed` with
146 // no `SIG=` field (implying an unverified one). Passing the same
147 // verification signals the original decision was made from keeps
148 // the echoed marker internally consistent with its own `ESCALATE=`.
149 reagent_verified,
150 // The echo does not carry the late-signature word: a late genuine notice echoes as `SIG=invalid`.
151 false,
152 lan_verified,
153 channel_verified,
154 // The sender-side echo never has a WAN verdict: WAN verification
155 // happens only at the receiving install (W3-S §2.3), after the echo.
156 None,
157 // Defaults to `true` (STOP) when the caller couldn't tell us —
158 // matches `effective_tier` defaulting to the more-cautious "coord"
159 // rather than assuming "info" above; never silently downgrades a
160 // sensitive echo to tag-only just because this hop lost the signal.
161 requires_stop.unwrap_or(true),
162 msgid,
163 priority,
164 None,
165 files,
166 false,
167 );
168 let line = serde_json::json!({
169 "type": "user",
170 "message": { "role": "user", "content": wrapped }
171 });
172 let data = format!("{line}\n");
173 let global_zone = crate::backend::transcript::append::resolve_global_output_zone(
174 &Some(state.mstore.clone()),
175 &sender_reg.block_id,
176 );
177 crate::backend::blockcontroller::shell::handle_append_block_file(
178 &state.broker,
179 &sender_reg.block_id,
180 crate::backend::agent_session::OUTPUT_FILE,
181 data.as_bytes(),
182 Some(&state.filestore),
183 global_zone.as_deref(),
184 );
185}