Skip to main content

supercode_harness/
relay_endpoint.rs

1//! The Messages API a Claude relay talks to: deterministic, no model.
2//!
3//! A relay ([`crate::claude_relay`]) is a real Claude Code process, because
4//! only a live Claude peer's `SendMessage` gets a Claude session's reply back.
5//! What it asks its model is always the same: send the queued message. So a
6//! relay's `ANTHROPIC_BASE_URL` points here, and this endpoint answers as the
7//! model would, from the relay's own queue:
8//!
9//! - a send turn gets one `SendMessage` tool call carrying the queued `to`
10//!   and `message`, byte for byte;
11//! - the turn after a tool result, or with nothing queued, gets
12//!   [`RELAY_STATUS_LINE`] and ends.
13//!
14//! No model runs and nothing is billed. The gate hook still checks every tool
15//! call against the queue, and the receipt is still Claude's own
16//! `SendMessage` result. A relay's API key names its directory under
17//! `<mail root>/relays/`.
18//!
19//! The machine daemon's `supercode message watch` child serves it on
20//! loopback, on the port recorded in `<mail root>/relay-endpoint.json` (a
21//! restarted server binds the same port again, so running relays keep it).
22
23use std::path::PathBuf;
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use serde_json::{json, Value};
28use tokio::io::BufReader;
29use tokio::net::TcpListener;
30
31use crate::claude_relay::{QueuedSend, RelayPaths, RELAY_STATUS_LINE};
32use crate::mailbox::mail_root;
33use crate::server::{read_http_request, write_http_response, HttpRequest};
34
35/// Where the serving port is recorded.
36fn record_path() -> PathBuf {
37    mail_root().join("relay-endpoint.json")
38}
39
40#[derive(Serialize, Deserialize)]
41struct Record {
42    port: u16,
43}
44
45/// The endpoint's base URL, when it is answering.
46pub fn relay_endpoint_url() -> Option<String> {
47    let record: Record = serde_json::from_slice(&std::fs::read(record_path()).ok()?).ok()?;
48    let address = std::net::SocketAddr::from(([127, 0, 0, 1], record.port));
49    std::net::TcpStream::connect_timeout(&address, Duration::from_millis(300)).ok()?;
50    Some(format!("http://127.0.0.1:{}", record.port))
51}
52
53fn write_record(port: u16) -> std::io::Result<()> {
54    let staging = record_path().with_extension("json.tmp");
55    std::fs::write(&staging, serde_json::to_vec(&Record { port })?)?;
56    std::fs::rename(&staging, record_path())
57}
58
59/// Serve the endpoint until the process ends.
60pub async fn serve_relay_endpoint() -> std::io::Result<()> {
61    let recorded = std::fs::read(record_path())
62        .ok()
63        .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok())
64        .map(|record| record.port);
65    let listener = match recorded {
66        Some(port) => match TcpListener::bind(("127.0.0.1", port)).await {
67            Ok(listener) => listener,
68            Err(_) => TcpListener::bind(("127.0.0.1", 0)).await?,
69        },
70        None => TcpListener::bind(("127.0.0.1", 0)).await?,
71    };
72    let port = listener.local_addr()?.port();
73    std::fs::create_dir_all(mail_root())?;
74    write_record(port)?;
75    // The record is how senders find this endpoint. Another watcher (a daemon
76    // started for a moment by another command) can overwrite it and then exit,
77    // leaving it naming a dead port while this one listens unseen: keep it ours.
78    tokio::spawn(async move {
79        loop {
80            tokio::time::sleep(Duration::from_secs(5)).await;
81            let current = std::fs::read(record_path())
82                .ok()
83                .and_then(|bytes| serde_json::from_slice::<Record>(&bytes).ok())
84                .map(|record| record.port);
85            if current != Some(port) {
86                write_record(port).ok();
87            }
88        }
89    });
90    loop {
91        let (stream, _) = listener.accept().await?;
92        tokio::spawn(async move {
93            let (read, mut write) = stream.into_split();
94            let mut reader = BufReader::new(read);
95            let Ok(Some(request)) = read_http_request(&mut reader).await else {
96                return;
97            };
98            let (status, content_type, body) = answer(&request);
99            let reason = if status == 200 { "OK" } else { "Error" };
100            write_http_response(&mut write, status, reason, content_type, &body)
101                .await
102                .ok();
103        });
104    }
105}
106
107/// The relay directory an API key names, if it is one.
108fn relay_paths(request: &HttpRequest) -> Option<RelayPaths> {
109    let key = request.headers.get("x-api-key")?;
110    if key.is_empty() || !key.chars().all(|c| c.is_ascii_hexdigit()) {
111        return None;
112    }
113    let directory = mail_root().join("relays").join(key);
114    directory
115        .is_dir()
116        .then(|| RelayPaths::in_directory(directory))
117}
118
119fn answer(request: &HttpRequest) -> (u16, &'static str, Vec<u8>) {
120    let error = |status: u16, message: &str| {
121        let body = json!({
122            "type": "error",
123            "error": {"type": "invalid_request_error", "message": message},
124        });
125        (status, "application/json", body.to_string().into_bytes())
126    };
127    if request.method != "POST" {
128        return error(404, "not found");
129    }
130    let Some(paths) = relay_paths(request) else {
131        return error(401, "not a supercode relay");
132    };
133    if request.path.ends_with("/v1/messages/count_tokens") {
134        return (
135            200,
136            "application/json",
137            json!({"input_tokens": 1}).to_string().into_bytes(),
138        );
139    }
140    if !request.path.ends_with("/v1/messages") {
141        return error(404, "not found");
142    }
143    let Ok(body) = serde_json::from_slice::<Value>(&request.body) else {
144        return error(400, "unreadable request");
145    };
146    let queued = std::fs::read(&paths.queue)
147        .ok()
148        .and_then(|bytes| serde_json::from_slice::<QueuedSend>(&bytes).ok());
149    let content = match queued {
150        Some(send) if !after_tool_result(&body) => json!({
151            "type": "tool_use",
152            "id": format!("toolu_{}", crate::mailbox::new_message_id().unwrap_or_default()),
153            "name": "SendMessage",
154            "input": {"to": send.to, "message": send.message},
155        }),
156        _ => json!({"type": "text", "text": RELAY_STATUS_LINE}),
157    };
158    let model = body.get("model").cloned().unwrap_or(Value::Null);
159    if body.get("stream").and_then(Value::as_bool) == Some(true) {
160        (
161            200,
162            "text/event-stream",
163            stream(&model, &content).into_bytes(),
164        )
165    } else {
166        (
167            200,
168            "application/json",
169            message(&model, &content).to_string().into_bytes(),
170        )
171    }
172}
173
174/// Whether the conversation's last turn carries a tool result: the send
175/// happened (or was denied), and the turn should end.
176fn after_tool_result(body: &Value) -> bool {
177    body.get("messages")
178        .and_then(Value::as_array)
179        .and_then(|messages| messages.last())
180        .and_then(|last| last.get("content"))
181        .and_then(Value::as_array)
182        .is_some_and(|content| {
183            content
184                .iter()
185                .any(|block| block.get("type").and_then(Value::as_str) == Some("tool_result"))
186        })
187}
188
189fn stop_reason(content: &Value) -> &'static str {
190    if content["type"] == "tool_use" {
191        "tool_use"
192    } else {
193        "end_turn"
194    }
195}
196
197fn message(model: &Value, content: &Value) -> Value {
198    json!({
199        "id": format!("msg_{}", crate::mailbox::new_message_id().unwrap_or_default()),
200        "type": "message",
201        "role": "assistant",
202        "model": model,
203        "content": [content],
204        "stop_reason": stop_reason(content),
205        "stop_sequence": null,
206        "usage": {"input_tokens": 1, "output_tokens": 1},
207    })
208}
209
210/// The same message as the server-sent events a streaming request expects.
211fn stream(model: &Value, content: &Value) -> String {
212    let mut start = message(model, content);
213    start["content"] = json!([]);
214    start["stop_reason"] = Value::Null;
215    let (opening, delta) = if content["type"] == "tool_use" {
216        let mut opening = content.clone();
217        opening["input"] = json!({});
218        let delta =
219            json!({"type": "input_json_delta", "partial_json": content["input"].to_string()});
220        (opening, delta)
221    } else {
222        let delta = json!({"type": "text_delta", "text": content["text"]});
223        (json!({"type": "text", "text": ""}), delta)
224    };
225    let events = [
226        (
227            "message_start",
228            json!({"type": "message_start", "message": start}),
229        ),
230        (
231            "content_block_start",
232            json!({"type": "content_block_start", "index": 0, "content_block": opening}),
233        ),
234        (
235            "content_block_delta",
236            json!({"type": "content_block_delta", "index": 0, "delta": delta}),
237        ),
238        (
239            "content_block_stop",
240            json!({"type": "content_block_stop", "index": 0}),
241        ),
242        (
243            "message_delta",
244            json!({
245                "type": "message_delta",
246                "delta": {"stop_reason": stop_reason(content), "stop_sequence": null},
247                "usage": {"output_tokens": 1},
248            }),
249        ),
250        ("message_stop", json!({"type": "message_stop"})),
251    ];
252    events
253        .iter()
254        .map(|(name, data)| format!("event: {name}\ndata: {data}\n\n"))
255        .collect()
256}