exomonad-core 0.1.0

ExoMonad core: effect system, WASM hosting, MCP server, built-in handlers, shared types
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
use super::{ExternalService, ServiceError};
use crate::protocol::{
    ChatMessage, ContentBlock, ServiceRequest, ServiceResponse, StopReason, Tool, Usage,
};
use async_trait::async_trait;
use reqwest::{Client, Url};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use tracing::warn;

/// Service client for the Anthropic Messages API.
///
/// Handles chat completions with support for tools, system prompts, and
/// automatic retry (exponential backoff) for 529 Overloaded errors.
pub struct AnthropicService {
    client: Client,
    api_key: String,
    base_url: Url,
}

impl AnthropicService {
    /// Create a new Anthropic service with the given API key.
    ///
    /// Uses the default endpoint: `https://api.anthropic.com`.
    pub fn new(api_key: String) -> Self {
        Self {
            client: Client::new(),
            api_key,
            base_url: Url::parse("https://api.anthropic.com")
                .expect("hardcoded Anthropic API URL should be valid"),
        }
    }

    /// Create a new Anthropic service with a custom base URL.
    ///
    /// Useful for testing (mock servers) or proxies.
    pub fn with_base_url(api_key: String, base_url: Url) -> Self {
        Self {
            client: Client::new(),
            api_key,
            base_url,
        }
    }

    /// Create a new Anthropic service from environment variables.
    ///
    /// Required: `ANTHROPIC_API_KEY`.
    /// Optional: `ANTHROPIC_BASE_URL`.
    pub fn from_env() -> Result<Self, anyhow::Error> {
        let api_key = std::env::var("ANTHROPIC_API_KEY")?;
        let base_url = std::env::var("ANTHROPIC_BASE_URL")
            .ok()
            .and_then(|s| Url::parse(&s).ok())
            .unwrap_or_else(|| {
                Url::parse("https://api.anthropic.com")
                    .expect("hardcoded Anthropic API URL should be valid")
            });

        Ok(Self::with_base_url(api_key, base_url))
    }
}

#[derive(Serialize)]
struct AnthropicRequestPayload {
    model: String,
    messages: Vec<ChatMessage>,
    max_tokens: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<Tool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    system: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    thinking: Option<serde_json::Value>,
}

#[derive(Deserialize)]
struct AnthropicResponsePayload {
    content: Vec<ContentBlock>,
    stop_reason: Option<String>,
    usage: Usage,
}

#[async_trait]
impl ExternalService for AnthropicService {
    type Request = ServiceRequest;
    type Response = ServiceResponse;

    async fn call(&self, req: Self::Request) -> Result<Self::Response, ServiceError> {
        let (model, messages, max_tokens, tools, system, thinking) = match req {
            ServiceRequest::AnthropicChat {
                model,
                messages,
                max_tokens,
                tools,
                system,
                thinking,
            } => (model, messages, max_tokens, tools, system, thinking),
            _ => panic!("Invalid request type for AnthropicService"),
        };

        let payload = AnthropicRequestPayload {
            model,
            messages,
            max_tokens,
            tools,
            system,
            thinking,
        };
        let url = self.base_url.join("/v1/messages").unwrap();
        let mut attempts = 0;
        let max_attempts = 3;
        let mut backoff = Duration::from_millis(500);

        loop {
            attempts += 1;
            let response = self
                .client
                .post(url.clone())
                .header("x-api-key", &self.api_key)
                .header("anthropic-version", "2023-06-01")
                .header("content-type", "application/json")
                .json(&payload)
                .send()
                .await?;

            if response.status().as_u16() == 529 {
                if attempts >= max_attempts {
                    return Err(ServiceError::RateLimited {
                        retry_after_ms: backoff.as_millis() as u64,
                    });
                }
                warn!("Anthropic overloaded (529), retrying in {:?}...", backoff);
                tokio::time::sleep(backoff).await;
                backoff *= 2;
                continue;
            }

            if !response.status().is_success() {
                return Err(ServiceError::Api {
                    code: response.status().as_u16() as i32,
                    message: response.text().await.unwrap_or_default(),
                });
            }

            let body: AnthropicResponsePayload = response.json().await?;

            let stop_reason = match body.stop_reason.as_deref() {
                Some("end_turn") => StopReason::EndTurn,
                Some("max_tokens") => StopReason::MaxTokens,
                Some("stop_sequence") => StopReason::StopSequence,
                Some("tool_use") => StopReason::ToolUse,
                _ => StopReason::EndTurn, // Default or unknown
            };

            return Ok(ServiceResponse::AnthropicChat {
                content: body.content,
                stop_reason,
                usage: body.usage,
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn get_fixture_path(subpath: &str) -> PathBuf {
        let manifest_dir = env!("CARGO_MANIFEST_DIR");
        PathBuf::from(manifest_dir)
            .join("test/fixtures/claude-api")
            .join(subpath)
    }

    fn load_fixture(subpath: &str) -> serde_json::Value {
        let path = get_fixture_path(subpath);
        let content = std::fs::read_to_string(&path)
            .unwrap_or_else(|err| panic!("Failed to read fixture {:?}: {}", path, err));
        serde_json::from_str(&content).expect("Invalid JSON in fixture")
    }

    #[tokio::test]
    async fn test_anthropic_chat() {
        let mock_server = MockServer::start().await;

        let mock_response = serde_json::json!({
            "content": [{"type": "text", "text": "Hello"}],
            "stop_reason": "end_turn",
            "usage": {"input_tokens": 10, "output_tokens": 5}
        });

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(200).set_body_json(mock_response))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![ChatMessage {
                role: "user".into(),
                content: "Hi".into(),
            }],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        match service.call(req).await.unwrap() {
            ServiceResponse::AnthropicChat {
                content,
                stop_reason,
                ..
            } => {
                assert_eq!(content[0].text.as_deref(), Some("Hello"));
                assert_eq!(stop_reason, StopReason::EndTurn);
            }
            _ => panic!("Wrong response type"),
        }
    }

    #[tokio::test]
    async fn test_request_golden_simple_message() {
        let mock_server = MockServer::start().await;
        let expected_json = load_fixture("request/simple_message.json");

        // Verify the request body matches the golden fixture
        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .and(move |req: &wiremock::Request| {
                let body: serde_json::Value = req.body_json().unwrap();
                // Compare body with expected_json
                // Note: expected_json has "system" but our simple request might not if None.
                // The fixture has "system": "You are a helpful assistant."

                // We need to construct the ServiceRequest to match the fixture exactly.
                body == expected_json
            })
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "content": [], "stop_reason": "end_turn", "usage": {"input_tokens": 0, "output_tokens": 0}
            })))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        // Construct request matching request/simple_message.json
        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus-20240229".into(),
            max_tokens: 1024,
            system: Some("You are a helpful assistant.".into()),
            messages: vec![ChatMessage {
                role: "user".into(),
                content: "Hello".into(),
            }],
            tools: None,
            thinking: None,
        };

        service.call(req).await.unwrap();
    }

    #[tokio::test]
    async fn test_request_golden_with_tools() {
        let mock_server = MockServer::start().await;
        let expected_json = load_fixture("request/with_tools.json");

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .and(move |req: &wiremock::Request| {
                let body: serde_json::Value = req.body_json().unwrap();
                body == expected_json
            })
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "content": [], "stop_reason": "end_turn", "usage": {"input_tokens": 0, "output_tokens": 0}
            })))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        // Construct request matching request/with_tools.json
        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus-20240229".into(),
            max_tokens: 1024,
            messages: vec![ChatMessage {
                role: "user".into(),
                content: "What is the weather?".into(),
            }],
            tools: Some(vec![Tool {
                name: "get_weather".into(),
                description: "Get weather for a location".into(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "location": {"type": "string"}
                    },
                    "required": ["location"]
                }),
            }]),
            system: None, // Fixture doesn't have system
            thinking: None,
        };

        service.call(req).await.unwrap();
    }

    #[tokio::test]
    async fn test_response_golden_text() {
        let mock_server = MockServer::start().await;
        let response_json = load_fixture("response/text_response.json");

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(200).set_body_json(response_json))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![],
            max_tokens: 10,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await.unwrap();

        match resp {
            ServiceResponse::AnthropicChat {
                content,
                stop_reason,
                usage,
            } => {
                assert_eq!(content.len(), 1);
                assert_eq!(content[0].block_type, "text");
                assert_eq!(content[0].text.as_deref(), Some("Hello!"));
                assert_eq!(stop_reason, StopReason::EndTurn);
                assert_eq!(usage.input_tokens, 10);
                assert_eq!(usage.output_tokens, 5);
            }
            _ => panic!("Wrong response type"),
        }
    }

    #[tokio::test]
    async fn test_response_golden_tool_use() {
        let mock_server = MockServer::start().await;
        let response_json = load_fixture("response/tool_use_response.json");

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(200).set_body_json(response_json))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![],
            max_tokens: 10,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await.unwrap();

        match resp {
            ServiceResponse::AnthropicChat {
                content,
                stop_reason,
                usage,
            } => {
                assert_eq!(content.len(), 2);

                // Block 1: Text
                assert_eq!(content[0].block_type, "text");
                assert_eq!(
                    content[0].text.as_deref(),
                    Some("I will check the weather.")
                );

                // Block 2: Tool Use
                assert_eq!(content[1].block_type, "tool_use");
                assert_eq!(content[1].id.as_deref(), Some("toolu_01234"));
                assert_eq!(content[1].name.as_deref(), Some("get_weather"));

                let input = content[1].input.as_ref().unwrap();
                assert_eq!(input["location"], "San Francisco");

                assert_eq!(stop_reason, StopReason::ToolUse);
                assert_eq!(usage.input_tokens, 20);
                assert_eq!(usage.output_tokens, 30);
            }
            _ => panic!("Wrong response type"),
        }
    }

    // === Error path tests ===

    #[tokio::test]
    async fn test_529_retry_once_then_success() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        let mock_server = MockServer::start().await;
        let call_count = Arc::new(AtomicUsize::new(0));
        let call_count_clone = call_count.clone();

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(move |_req: &wiremock::Request| {
                let count = call_count_clone.fetch_add(1, Ordering::SeqCst);
                if count == 0 {
                    // First call: return 529
                    ResponseTemplate::new(529)
                } else {
                    // Second call: return success
                    ResponseTemplate::new(200).set_body_json(serde_json::json!({
                        "content": [{"type": "text", "text": "Success!"}],
                        "stop_reason": "end_turn",
                        "usage": {"input_tokens": 10, "output_tokens": 5}
                    }))
                }
            })
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![ChatMessage {
                role: "user".into(),
                content: "Hi".into(),
            }],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await;
        assert!(resp.is_ok());
        assert_eq!(call_count.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn test_529_retry_exhausted() {
        let mock_server = MockServer::start().await;

        // Always return 529
        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(529))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![ChatMessage {
                role: "user".into(),
                content: "Hi".into(),
            }],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await;
        assert!(resp.is_err());
        match resp.unwrap_err() {
            ServiceError::RateLimited { .. } => {} // Expected
            other => panic!("Expected RateLimited error, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_api_error_400() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(400).set_body_string("Bad request"))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await;
        assert!(resp.is_err());
        match resp.unwrap_err() {
            ServiceError::Api { code, message } => {
                assert_eq!(code, 400);
                assert!(message.contains("Bad request"));
            }
            other => panic!("Expected Api error, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_api_error_500() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal server error"))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await;
        assert!(resp.is_err());
        match resp.unwrap_err() {
            ServiceError::Api { code, .. } => {
                assert_eq!(code, 500);
            }
            other => panic!("Expected Api error, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_api_error_401_unauthorized() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(401).set_body_string("Unauthorized"))
            .mount(&mock_server)
            .await;

        let service = AnthropicService::with_base_url(
            "invalid-key".into(),
            mock_server.uri().parse().unwrap(),
        );

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await;
        assert!(resp.is_err());
        match resp.unwrap_err() {
            ServiceError::Api { code, .. } => {
                assert_eq!(code, 401);
            }
            other => panic!("Expected Api error, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn test_malformed_json_response() {
        let mock_server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/v1/messages"))
            .respond_with(ResponseTemplate::new(200).set_body_string("not valid json"))
            .mount(&mock_server)
            .await;

        let service =
            AnthropicService::with_base_url("test-key".into(), mock_server.uri().parse().unwrap());

        let req = ServiceRequest::AnthropicChat {
            model: "claude-3-opus".into(),
            messages: vec![],
            max_tokens: 100,
            tools: None,
            system: None,
            thinking: None,
        };

        let resp = service.call(req).await;
        assert!(resp.is_err());
        // Should be an HTTP error (deserialization failed)
        match resp.unwrap_err() {
            ServiceError::Http(_) => {} // Expected
            other => panic!("Expected Http error (from json parse), got {:?}", other),
        }
    }
}