@ondeinference / ed Mirror · read-only / commits / d562e8f
Fork 0

Read-only mirror of github.com/ondeinference/ed.

Mirrored from https://github.com/ondeinference/ed.git

Synced Nov 23, 01:00 UTC

Return the endpoint's error message and status to ACP hosts

A non-2xx answer from the LLM endpoint used to surface as "Internal error: LLM endpoint returned 429 Too Many Requests: {raw json}". llm.rs now parses the body into an EndpointError (source, status, message), taking error.message, then message, then a string error field, then the raw text. The Display output keeps the old prefix. agent.rs maps these to an internal error whose data is { "message", "status" }. Other failures keep string data. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

Seto Elkahfi committed Oct 31, 2026 at 15:28 UTC d562e8f53a6360e0f7215f67442c3d52b006aafd
2 files changed +144 -12
crates/ed-acp/src/agent.rs
+34 -4
@@ -29,7 +29,7 @@ use ed_mcp::{ClientInfo, McpToolset, ToolsetConfig};
29
30 use crate::auth::{AuthCtx, AuthProvider};
31 use crate::content as prompt;
32 -use crate::llm::{Delta, LlmClient, LlmConfig, LlmEnv};
32 +use crate::llm::{Delta, EndpointError, LlmClient, LlmConfig, LlmEnv};
33 use crate::store::{SessionStore, StoredSession};
34 use crate::tools::{self, ToolCtx, ToolOutcome, Toolset, absolutize, normalize};
35 use crate::{CommandCtx, Profile, PromptCtx, SessionCtx};
@@ -218,6 +218,16 @@ pub fn session_title(prompt: &str) -> String {
218 }
219 }
220
221 +/// Map a failed turn to an ACP internal error. Endpoint failures carry `{ message, status }`
222 +/// so hosts can show the provider's message without parsing it out of a string.
223 +fn internal(e: &anyhow::Error) -> agent_client_protocol::Error {
224 + match e.chain().find_map(|c| c.downcast_ref::<EndpointError>()) {
225 + Some(ep) => agent_client_protocol::Error::internal_error()
226 + .data(json!({ "message": ep.message, "status": ep.status })),
227 + None => agent_client_protocol::Error::internal_error().data(format!("{e:#}")),
228 + }
229 +}
230 +
231 fn invalid(msg: impl Into<String>) -> agent_client_protocol::Error {
232 agent_client_protocol::Error::invalid_params().data(msg.into())
233 }
@@ -1101,9 +1111,7 @@ impl AcpServer {
1111 Err(e) if e.downcast_ref::<UnknownSession>().is_some() => {
1112 responder.respond_with_error(invalid(e.to_string()))
1113 }
1104 - Err(e) => responder.respond_with_error(
1105 - agent_client_protocol::Error::internal_error().data(format!("{e:#}")),
1106 - ),
1114 + Err(e) => responder.respond_with_error(internal(&e)),
1115 }
1116 }
1117
@@ -1394,6 +1402,28 @@ impl std::error::Error for UnknownSession {}
1402 #[cfg(test)]
1403 mod tests {
1404 use super::*;
1405 + use crate::llm::EndpointError;
1406 +
1407 + #[test]
1408 + fn internal_exposes_endpoint_status_and_message() {
1409 + let e = anyhow::Error::new(EndpointError {
1410 + source_name: "LLM endpoint".into(),
1411 + status: 429,
1412 + message: "slow down".into(),
1413 + })
1414 + .context("running turn");
1415 + let err = internal(&e);
1416 + assert_eq!(
1417 + err.data,
1418 + Some(json!({ "message": "slow down", "status": 429 }))
1419 + );
1420 + }
1421 +
1422 + #[test]
1423 + fn internal_falls_back_to_string_data() {
1424 + let err = internal(&anyhow::anyhow!("boom"));
1425 + assert_eq!(err.data, Some(json!("boom")));
1426 + }
1427
1428 #[test]
1429 fn iso8601_known_dates() {
crates/ed-acp/src/llm.rs
+110 -8
@@ -253,10 +253,117 @@ impl LlmConfig {
253 }
254 }
255
256 +/// A non-2xx answer from the LLM endpoint, with the provider's message pulled out of the body.
257 +#[derive(Debug, Clone)]
258 +pub struct EndpointError {
259 + pub source_name: String,
260 + pub status: u16,
261 + pub message: String,
262 +}
263 +
264 +impl std::fmt::Display for EndpointError {
265 + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266 + match reqwest::StatusCode::from_u16(self.status) {
267 + Ok(status) => write!(
268 + f,
269 + "{} returned {status}: {}",
270 + self.source_name, self.message
271 + ),
272 + Err(_) => write!(
273 + f,
274 + "{} returned {}: {}",
275 + self.source_name, self.status, self.message
276 + ),
277 + }
278 + }
279 +}
280 +
281 +impl std::error::Error for EndpointError {}
282 +
283 +/// Best human-readable text in an error body: `error.message`, `message`, or a string `error`
284 +/// from a JSON body; otherwise the trimmed raw text, or the status reason when it is empty.
285 +fn endpoint_message(status: u16, body: &str) -> String {
286 + if let Ok(v) = serde_json::from_str::<Value>(body) {
287 + let found = v
288 + .pointer("/error/message")
289 + .and_then(Value::as_str)
290 + .or_else(|| v.get("message").and_then(Value::as_str))
291 + .or_else(|| v.get("error").and_then(Value::as_str))
292 + .map(str::trim)
293 + .filter(|m| !m.is_empty());
294 + if let Some(m) = found {
295 + return m.to_string();
296 + }
297 + }
298 + let text = body.trim();
299 + if text.is_empty() {
300 + return reqwest::StatusCode::from_u16(status)
301 + .ok()
302 + .and_then(|s| s.canonical_reason())
303 + .unwrap_or("no response body")
304 + .to_string();
305 + }
306 + text.to_string()
307 +}
308 +
309 +async fn endpoint_error(source_name: &str, resp: reqwest::Response) -> anyhow::Error {
310 + let status = resp.status().as_u16();
311 + let body = resp.text().await.unwrap_or_default();
312 + anyhow::Error::new(EndpointError {
313 + source_name: source_name.to_string(),
314 + status,
315 + message: endpoint_message(status, &body),
316 + })
317 +}
318 +
319 #[cfg(test)]
320 mod tests {
321 use super::*;
322
323 + #[test]
324 + fn endpoint_message_prefers_error_message() {
325 + let body = r#"{"error":{"message":"Rate limit reached","type":"rate_limit"}}"#;
326 + assert_eq!(endpoint_message(429, body), "Rate limit reached");
327 + }
328 +
329 + #[test]
330 + fn endpoint_message_falls_back_to_top_level_fields() {
331 + assert_eq!(endpoint_message(400, r#"{"message":"bad"}"#), "bad");
332 + assert_eq!(endpoint_message(400, r#"{"error":"nope"}"#), "nope");
333 + }
334 +
335 + #[test]
336 + fn endpoint_message_keeps_non_json_text() {
337 + assert_eq!(
338 + endpoint_message(502, " <html>Bad Gateway</html>\n"),
339 + "<html>Bad Gateway</html>"
340 + );
341 + }
342 +
343 + #[test]
344 + fn endpoint_message_json_without_message_keeps_raw() {
345 + let body = r#"{"detail":"x"}"#;
346 + assert_eq!(endpoint_message(422, body), body);
347 + }
348 +
349 + #[test]
350 + fn endpoint_message_empty_body_uses_reason() {
351 + assert_eq!(endpoint_message(503, " "), "Service Unavailable");
352 + }
353 +
354 + #[test]
355 + fn endpoint_error_display_keeps_prefix() {
356 + let e = EndpointError {
357 + source_name: "LLM endpoint".into(),
358 + status: 429,
359 + message: "slow down".into(),
360 + };
361 + assert_eq!(
362 + e.to_string(),
363 + "LLM endpoint returned 429 Too Many Requests: slow down"
364 + );
365 + }
366 +
367 const ENV: LlmEnv = LlmEnv {
368 prefix: "SPLITFIRE",
369 dir_name: "splitfire-agent",
@@ -623,8 +730,7 @@ impl LlmClient {
730 );
731 }
732 if !status.is_success() {
626 - let text = resp.text().await.unwrap_or_default();
627 - bail!("{} returned {status}: {text}", provider.display_name());
733 + return Err(endpoint_error(provider.display_name(), resp).await);
734 }
735 Ok(())
736 }
@@ -651,9 +757,7 @@ impl LlmClient {
757 .context("sending models request")?;
758 }
759 if !resp.status().is_success() {
654 - let status = resp.status();
655 - let text = resp.text().await.unwrap_or_default();
656 - bail!("models endpoint returned {status}: {text}");
760 + return Err(endpoint_error("models endpoint", resp).await);
761 }
762 let mut models = resp
763 .json::<ModelsResponse>()
@@ -709,9 +813,7 @@ impl LlmClient {
813 .context("sending chat completion request")?;
814 }
815 if !resp.status().is_success() {
712 - let status = resp.status();
713 - let text = resp.text().await.unwrap_or_default();
714 - bail!("LLM endpoint returned {status}: {text}");
816 + return Err(endpoint_error("LLM endpoint", resp).await);
817 }
818
819 let mut out = Completion::default();