1use axum::extract::rejection::JsonRejection;
23use axum::extract::State;
24use axum::http::StatusCode;
25use axum::response::{IntoResponse, Response};
26use axum::{Extension, Json};
27use serde_json::json;
28
29use agentmux_common::api_types::WpsPublishRequest;
30use agentmux_common::client_events::ToolChunk;
31
32use crate::backend::container::credential::ContainerGrant;
33use crate::server::AppState;
34
35pub(crate) const MAX_BODY_BYTES: usize = 64 * 1024;
37
38const PERSIST: usize = 1024;
41
42fn refuse(status: StatusCode, why: impl Into<String>) -> Response {
43 (status, Json(json!({ "error": why.into() }))).into_response()
44}
45
46fn check(block_id: &str, req: &WpsPublishRequest) -> Result<ToolChunk, Response> {
48 if req.event != "tool_chunk" {
49 return Err(refuse(StatusCode::FORBIDDEN, "this route takes tool_chunk only"));
50 }
51 if req.scopes != [format!("block:{block_id}")] {
52 return Err(refuse(StatusCode::FORBIDDEN, "a container agent's output goes to its own pane only"));
53 }
54 serde_json::from_value::<ToolChunk>(req.data.clone()).map_err(|e| refuse(StatusCode::BAD_REQUEST, format!("tool_chunk: {e}")))
55}
56
57pub(crate) async fn handle_container_tool_chunk(
58 State(state): State<AppState>,
59 grant: Option<Extension<ContainerGrant>>,
60 body: Result<Json<WpsPublishRequest>, JsonRejection>,
61) -> Response {
62 let Some(Extension(grant)) = grant else {
63 return refuse(StatusCode::FORBIDDEN, "this route is for container agents");
64 };
65 let req = match body {
66 Ok(Json(req)) => req,
67 Err(rejection) => return refuse(rejection.status(), rejection.body_text()),
68 };
69 let chunk = match check(&grant.block_id, &req) {
70 Ok(chunk) => chunk,
71 Err(refusal) => return refusal,
72 };
73 if matches!(chunk, ToolChunk::Chunk { .. } | ToolChunk::Terminal { .. }) {
74 state.broker.publish_event::<crate::backend::mps_events::ToolChunk>(&chunk, req.scopes, PERSIST);
75 } else {
76 file_report(&state, &grant.block_id, &chunk).await;
77 }
78 Json(json!({ "ok": true })).into_response()
79}
80
81fn is_call_id(id: &str) -> bool {
83 !id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
84}
85
86async fn file_report(state: &AppState, block_id: &str, chunk: &ToolChunk) {
90 let (tool_id, pid, description) = match chunk {
91 ToolChunk::Pid { tool_id, pid, .. } => (tool_id.clone(), *pid, None),
92 ToolChunk::Call { tool_id, pid, description, .. } => (tool_id.clone(), *pid, crate::backend::storage::background_container_calls::clean_description(description)),
93 _ => return,
94 };
95 if !is_call_id(&tool_id) {
96 return;
97 }
98 let (store, broker, block_id) = (state.mstore.clone(), state.broker.clone(), block_id.to_string());
99 let _ = tokio::task::spawn_blocking(move || {
100 let Some(container) = store.get::<crate::backend::obj::Block>(&block_id).ok().flatten().and_then(|b| crate::backend::container::container_of_meta(&b.meta)) else {
101 return;
102 };
103 let now_ms = agentmux_common::time::now_ms();
104 let pid = (pid > 0).then_some(i64::from(pid));
106 if let Err(e) = store.background_container_call_file(&block_id, &tool_id, &container, pid, description.as_deref(), now_ms) {
107 tracing::warn!(target: "background_tasks", block_id = %block_id, node_id = %tool_id, error = %e, "could not file a container agent's call report");
108 return;
109 }
110 if let Some(label) = description {
112 if store.background_task_describe_if_generic(&block_id, &tool_id, &label).unwrap_or(false) {
113 crate::backend::background_task_feed::publish_background_task_updated(&broker, &block_id);
114 }
115 }
116 })
117 .await;
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123 use axum::body::Body;
124 use axum::http::Request;
125 use tower::ServiceExt;
126
127 fn chunk(content: &str) -> serde_json::Value {
128 json!({ "op": "chunk", "tool_id": "toolu_1", "kind": "stdout", "content": content, "timestamp": 1 })
129 }
130
131 fn body(event: &str, scopes: &[&str], data: serde_json::Value) -> serde_json::Value {
132 json!({ "event": event, "scopes": scopes, "persist": 999_999, "data": data })
133 }
134
135 async fn post(token: &str, body: String) -> (StatusCode, serde_json::Value) {
136 let state = crate::server::tests::test_state();
137 let app = crate::server::build_router(state);
138 let req = Request::builder()
139 .method("POST")
140 .uri("/api/v1/agent/tool-chunk")
141 .header("X-AuthKey", token)
142 .header("Content-Type", "application/json")
143 .body(Body::from(body))
144 .unwrap();
145 let resp = app.oneshot(req).await.unwrap();
146 let status = resp.status();
147 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
148 (status, serde_json::from_slice(&bytes).unwrap_or_default())
149 }
150
151 #[tokio::test]
152 async fn a_container_streams_into_its_own_pane_only() {
153 let mine = crate::backend::container::credential::token_for_block("tc-block-a", None);
154 let own = ["block:tc-block-a"];
155 let (status, _) = post(&mine, body("tool_chunk", &own, chunk("hello")).to_string()).await;
156 assert_eq!(status, StatusCode::OK);
157
158 for scopes in [&["block:tc-block-b"][..], &[], &["block:tc-block-a", "block:tc-block-b"], &["tab:tc-block-a"]] {
160 let (status, _) = post(&mine, body("tool_chunk", scopes, chunk("x")).to_string()).await;
161 assert_eq!(status, StatusCode::FORBIDDEN, "{scopes:?}");
162 }
163 for event in ["compaction_started", "agent_event:tc-block-a", "controllerstatus", "custom:thing"] {
165 let (status, _) = post(&mine, body(event, &own, json!({ "anything": true })).to_string()).await;
166 assert_eq!(status, StatusCode::FORBIDDEN, "{event}");
167 }
168 let (status, _) = post(&mine, body("tool_chunk", &own, json!({ "op": "chunk", "tool_id": "t" })).to_string()).await;
170 assert_eq!(status, StatusCode::BAD_REQUEST);
171 }
172
173 #[tokio::test]
174 async fn a_request_over_the_cap_is_413() {
175 let mine = crate::backend::container::credential::token_for_block("tc-block-big", None);
176 let huge = "x".repeat(MAX_BODY_BYTES);
177 let (status, _) = post(&mine, body("tool_chunk", &["block:tc-block-big"], chunk(&huge)).to_string()).await;
178 assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
179 let fits = "x".repeat(MAX_BODY_BYTES / 2);
180 let (status, _) = post(&mine, body("tool_chunk", &["block:tc-block-big"], chunk(&fits)).to_string()).await;
181 assert_eq!(status, StatusCode::OK);
182 }
183
184 #[tokio::test]
185 async fn the_route_is_a_container_agents_and_the_generic_relay_stays_refused() {
186 let (status, _) = post("test-secret-key", body("tool_chunk", &["block:b"], chunk("x")).to_string()).await;
188 assert_eq!(status, StatusCode::FORBIDDEN);
189 assert!(!crate::backend::container::credential::container_route_allowed("/agentmux/wps/publish", crate::server::route_table::serves));
190 assert!(crate::backend::container::credential::container_route_allowed("/api/v1/agent/tool-chunk", crate::server::route_table::serves));
191 }
192
193 #[test]
194 fn pid_and_call_reports_are_valid_but_never_published() {
195 let pid = json!({ "op": "pid", "tool_id": "t", "pid": 7, "timestamp": 1 });
196 let call = json!({ "op": "call", "tool_id": "t", "pid": 7, "description": "Run it", "timestamp": 1 });
197 for data in [pid, call] {
198 let req: WpsPublishRequest = serde_json::from_value(body("tool_chunk", &["block:b"], data)).unwrap();
199 let chunk = check("b", &req).unwrap_or_else(|_| panic!("valid"));
200 assert!(!matches!(chunk, ToolChunk::Chunk { .. } | ToolChunk::Terminal { .. }));
201 }
202 }
203
204 async fn send(app: &axum::Router, token: &str, block: &str, data: serde_json::Value) {
205 let scope = format!("block:{block}");
206 let req = Request::builder()
207 .method("POST")
208 .uri("/api/v1/agent/tool-chunk")
209 .header("X-AuthKey", token)
210 .header("Content-Type", "application/json")
211 .body(Body::from(body("tool_chunk", &[scope.as_str()], data).to_string()))
212 .unwrap();
213 assert_eq!(app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);
214 }
215
216 fn pane(state: &crate::server::AppState, block_id: &str, meta: serde_json::Value) {
217 let mut block = crate::backend::obj::Block { oid: block_id.to_string(), ..Default::default() };
218 for (k, v) in meta.as_object().unwrap() {
219 block.meta.insert(k.clone(), v.clone());
220 }
221 state.mstore.insert(&mut block).unwrap();
222 }
223
224 #[tokio::test]
227 async fn a_container_pid_and_description_are_filed_apart_and_the_description_labels_the_row() {
228 let state = crate::server::tests::test_state();
229 pane(&state, "tc-file-a", json!({ "agentMode": "container", "agentId": "ag-file" }));
230 let token = crate::backend::container::credential::token_for_block("tc-file-a", None);
231 let app = crate::server::build_router(state.clone());
232 let host_pid = 4_242_417u32;
233 state.mstore.background_task_observe("toolu_a", "tc-file-a", "Bash", 100, 100).unwrap();
235 send(&app, &token, "tc-file-a", json!({ "op": "pid", "tool_id": "toolu_a", "pid": host_pid, "timestamp": 1 })).await;
236 send(&app, &token, "tc-file-a", json!({ "op": "call", "tool_id": "toolu_a", "pid": host_pid, "description": "Run the build\n", "timestamp": 2 })).await;
237 send(&app, &token, "tc-file-a", json!({ "op": "call", "tool_id": "toolu_b", "pid": 9, "description": "Watch the tests", "timestamp": 3 })).await;
238 state.mstore.background_task_observe("toolu_b", "tc-file-a", "Bash", 100, 100).unwrap();
239
240 let row = state.mstore.background_task_get("toolu_a").unwrap().unwrap();
241 assert_eq!((row.pid, row.label.as_str()), (None, "Run the build"), "no host pid; the call's description is the label");
242 assert_eq!(state.mstore.background_task_get("toolu_b").unwrap().unwrap().label, "Watch the tests", "filed before the row, found by it");
243 let filed = state.mstore.background_container_running().unwrap();
244 let mine = filed.iter().find(|t| t.id == "toolu_a").unwrap();
245 assert_eq!((mine.container.as_str(), mine.pid), ("agentmux-ag-file", i64::from(host_pid)));
246 assert!(crate::backend::tool_calls::lookup(host_pid, None).is_none(), "a container pid never labels a host process");
247 }
248
249 #[tokio::test]
251 async fn a_report_from_a_pane_that_is_not_a_container_or_with_an_odd_id_is_dropped() {
252 let state = crate::server::tests::test_state();
253 pane(&state, "tc-file-host", json!({ "agentId": "plain" }));
254 pane(&state, "tc-file-b", json!({ "agentMode": "container", "agentId": "ag-b" }));
255 pane(&state, "tc-file-c", json!({ "agentMode": "container", "agentId": "ag-c" }));
256 let app = crate::server::build_router(state.clone());
257 state.mstore.background_task_observe("toolu_x", "tc-file-c", "Bash", 100, 100).unwrap();
258 let host = crate::backend::container::credential::token_for_block("tc-file-host", None);
259 let b = crate::backend::container::credential::token_for_block("tc-file-b", None);
260 send(&app, &host, "tc-file-host", json!({ "op": "pid", "tool_id": "toolu_h", "pid": 5, "timestamp": 1 })).await;
261 send(&app, &b, "tc-file-b", json!({ "op": "pid", "tool_id": "../odd id", "pid": 5, "timestamp": 1 })).await;
262 send(&app, &b, "tc-file-b", json!({ "op": "call", "tool_id": "toolu_x", "pid": 6, "description": "Not yours", "timestamp": 1 })).await;
264 assert!(state.mstore.background_container_running().unwrap().is_empty());
265 assert_eq!(state.mstore.background_task_get("toolu_x").unwrap().unwrap().label, "Bash", "another pane's row is not relabelled");
266 assert_eq!(state.mstore.background_container_call_description("tc-file-host", "toolu_h").unwrap(), None);
267 }
268
269 #[tokio::test]
270 async fn a_chunk_reaches_the_panes_subscribers_and_a_pid_does_not() {
271 let state = crate::server::tests::test_state();
272 let token = crate::backend::container::credential::token_for_block("tc-block-live", None);
273 let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
274 let sink = seen.clone();
275 state.broker.add_observer(std::sync::Arc::new(move |e: &crate::backend::mps::MuxEvent| {
276 if e.scopes == ["block:tc-block-live"] {
277 sink.lock().unwrap().push(e.clone());
278 }
279 }));
280 let app = crate::server::build_router(state);
281 for data in [json!({ "op": "pid", "tool_id": "t", "pid": 7, "timestamp": 1 }), chunk("streamed\n")] {
282 let req = Request::builder()
283 .method("POST")
284 .uri("/api/v1/agent/tool-chunk")
285 .header("X-AuthKey", &token)
286 .header("Content-Type", "application/json")
287 .body(Body::from(body("tool_chunk", &["block:tc-block-live"], data).to_string()))
288 .unwrap();
289 assert_eq!(app.clone().oneshot(req).await.unwrap().status(), StatusCode::OK);
290 }
291 let seen = seen.lock().unwrap();
292 assert_eq!(seen.len(), 1, "only the chunk was published, not the pid");
293 assert_eq!(seen[0].event, "tool_chunk");
294 assert_eq!(seen[0].data.as_ref().unwrap()["content"], "streamed\n");
295 assert_eq!(seen[0].persist, PERSIST, "srv sets how much is kept, not the container");
296 }
297}