synaps-engine 0.3.3

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
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
//! Typed wire model for Anthropic SSE events. Borrowing deserializer:
//! `Cow<'a, str>` borrows from the line buffer on the escape-free fast
//! path, allocates only when JSON escapes force it. NOT &'a str — serde
//! hard-errors on escaped strings for &str targets.

use serde::Deserialize;
use std::borrow::Cow;

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(super) enum AnthropicEvent<'a> {
    ContentBlockStart {
        #[serde(borrow)]
        content_block: ContentBlock<'a>,
    },
    ContentBlockDelta {
        #[serde(borrow)]
        delta: Delta<'a>,
    },
    ContentBlockStop,
    MessageStart {
        #[serde(borrow)]
        message: MessageStartPayload<'a>,
    },
    MessageDelta {
        #[serde(borrow, default)]
        delta: Option<MessageDeltaInner<'a>>,
        #[serde(default)]
        usage: Option<UsagePayload>,
    },
    MessageStop,
    /// Anthropic streams some failures as a 200 response carrying an in-stream
    /// `error` event (e.g. `overloaded_error`, or a context-overflow rejection)
    /// rather than an HTTP error status. Capturing it as a real arm is what
    /// turns the "silent stop" (empty stream → empty turn) into a visible,
    /// actionable error. See `process_data_line` + `build_response_or_error`.
    Error {
        #[serde(borrow, default)]
        error: Option<ApiError<'a>>,
    },
    /// Unit variant required: serde's #[serde(other)] only supports unit
    /// variants under internal tagging. Payload discarded — matches the
    /// current `_ => {}`. Covers `ping` and future event types.
    #[serde(other)]
    Unknown,
}

/// Inner payload of an Anthropic in-stream `error` event:
/// `{"type":"error","error":{"type":"overloaded_error","message":"..."}}`.
#[derive(Debug, Deserialize)]
pub(super) struct ApiError<'a> {
    #[serde(borrow, default, rename = "type")]
    pub error_type: Option<Cow<'a, str>>,
    #[serde(borrow, default)]
    pub message: Option<Cow<'a, str>>,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub(super) enum ContentBlock<'a> {
    Text,     // initial `text` field ignored — current code never reads it
    Thinking, // initial `thinking`/`signature` ignored — same
    ToolUse {
        // #[serde(default)]: current code does .as_str().unwrap_or("") —
        // a missing id/name must not kill the event. Cow: Default = Borrowed("").
        #[serde(borrow, default)]
        id: Cow<'a, str>,
        #[serde(borrow, default)]
        name: Cow<'a, str>,
    },
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
// Variant names mirror the wire tags (`text_delta`, `thinking_delta`, ...) —
// renaming to satisfy the lint would obscure the protocol mapping.
#[allow(clippy::enum_variant_names)]
pub(super) enum Delta<'a> {
    TextDelta {
        #[serde(borrow)]
        text: Cow<'a, str>,
    },
    ThinkingDelta {
        #[serde(borrow)]
        thinking: Cow<'a, str>,
    },
    SignatureDelta {
        #[serde(borrow)]
        signature: Cow<'a, str>,
    },
    InputJsonDelta {
        #[serde(borrow)]
        partial_json: Cow<'a, str>,
    },
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Deserialize)]
pub(super) struct MessageStartPayload<'a> {
    #[serde(borrow, default)]
    pub id: Option<Cow<'a, str>>,
    #[serde(default)]
    pub usage: Option<UsagePayload>,
}

#[derive(Debug, Deserialize)]
pub(super) struct MessageDeltaInner<'a> {
    #[serde(borrow, default)]
    pub stop_reason: Option<Cow<'a, str>>,
}

#[derive(Debug, Default, Deserialize)]
pub(super) struct UsagePayload {
    // #[serde(default)] mirrors .as_u64().unwrap_or(0)
    #[serde(default)]
    pub input_tokens: u64,
    #[serde(default)]
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_read_input_tokens: u64,
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
    #[serde(default)]
    pub cache_creation: Option<CacheCreationDetail>,
}

#[derive(Debug, Deserialize)]
pub(super) struct CacheCreationDetail {
    #[serde(default)]
    pub ephemeral_5m_input_tokens: Option<u64>,
    #[serde(default)]
    pub ephemeral_1h_input_tokens: Option<u64>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(data: &str) -> AnthropicEvent<'_> {
        serde_json::from_str(data).expect("event should parse")
    }

    #[test]
    fn content_block_start_tool_use() {
        let event = parse(
            r#"{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01ABC","name":"bash","input":{}}}"#,
        );
        match event {
            AnthropicEvent::ContentBlockStart {
                content_block: ContentBlock::ToolUse { id, name },
            } => {
                assert_eq!(id, "toolu_01ABC");
                assert_eq!(name, "bash");
            }
            other => panic!("expected ToolUse start, got {:?}", other),
        }
    }

    #[test]
    fn content_block_start_tool_use_missing_id_name_defaults_empty() {
        let event = parse(
            r#"{"type":"content_block_start","index":1,"content_block":{"type":"tool_use"}}"#,
        );
        match event {
            AnthropicEvent::ContentBlockStart {
                content_block: ContentBlock::ToolUse { id, name },
            } => {
                assert_eq!(id, "");
                assert_eq!(name, "");
            }
            other => panic!("expected ToolUse start, got {:?}", other),
        }
    }

    #[test]
    fn content_block_start_thinking_and_text() {
        let event = parse(
            r#"{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}"#,
        );
        assert!(matches!(
            event,
            AnthropicEvent::ContentBlockStart {
                content_block: ContentBlock::Thinking
            }
        ));

        let event = parse(
            r#"{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}"#,
        );
        assert!(matches!(
            event,
            AnthropicEvent::ContentBlockStart {
                content_block: ContentBlock::Text
            }
        ));
    }

    #[test]
    fn content_block_start_unknown_block_type() {
        let event = parse(
            r#"{"type":"content_block_start","index":0,"content_block":{"type":"server_tool_use","weird":42}}"#,
        );
        assert!(matches!(
            event,
            AnthropicEvent::ContentBlockStart {
                content_block: ContentBlock::Unknown
            }
        ));
    }

    #[test]
    fn text_delta_borrows_when_escape_free() {
        // Borrow tripwire: escape-free input MUST take the zero-copy path.
        // If a #[serde(borrow)] gets dropped, this becomes Cow::Owned and fails.
        let data = r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello world"}}"#;
        let event = parse(data);
        match event {
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::TextDelta { text },
            } => {
                assert!(matches!(text, Cow::Borrowed(_)), "expected borrowed Cow");
                assert_eq!(text, "hello world");
            }
            other => panic!("expected TextDelta, got {:?}", other),
        }
    }

    #[test]
    fn text_delta_with_escapes_is_owned_and_correct() {
        // Escaped input forces decoding — this is why &'a str would hard-fail.
        let data = r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"line\none \u00e9"}}"#;
        let event = parse(data);
        match event {
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::TextDelta { text },
            } => {
                assert!(matches!(text, Cow::Owned(_)), "expected owned Cow");
                assert_eq!(text, "line\none é");
            }
            other => panic!("expected TextDelta, got {:?}", other),
        }
    }

    #[test]
    fn text_delta_multibyte_utf8() {
        // Raw (unescaped) multi-byte UTF-8 stays on the borrow path.
        let data = r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"héllo ✨"}}"#;
        let event = parse(data);
        match event {
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::TextDelta { text },
            } => {
                assert!(matches!(text, Cow::Borrowed(_)), "expected borrowed Cow");
                assert_eq!(text.as_bytes(), "héllo ✨".as_bytes());
            }
            other => panic!("expected TextDelta, got {:?}", other),
        }
    }

    #[test]
    fn thinking_delta_signature_delta_input_json_delta() {
        let event = parse(
            r#"{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hmm"}}"#,
        );
        match event {
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::ThinkingDelta { thinking },
            } => assert_eq!(thinking, "hmm"),
            other => panic!("expected ThinkingDelta, got {:?}", other),
        }

        let event = parse(
            r#"{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig123"}}"#,
        );
        match event {
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::SignatureDelta { signature },
            } => assert_eq!(signature, "sig123"),
            other => panic!("expected SignatureDelta, got {:?}", other),
        }

        let event = parse(
            r#"{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"cmd\":"}}"#,
        );
        match event {
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::InputJsonDelta { partial_json },
            } => assert_eq!(partial_json, "{\"cmd\":"),
            other => panic!("expected InputJsonDelta, got {:?}", other),
        }
    }

    #[test]
    fn delta_unknown_subtype() {
        let event = parse(
            r#"{"type":"content_block_delta","index":0,"delta":{"type":"citations_delta","citation":{}}}"#,
        );
        assert!(matches!(
            event,
            AnthropicEvent::ContentBlockDelta {
                delta: Delta::Unknown
            }
        ));
    }

    #[test]
    fn message_start_full() {
        let event = parse(
            r#"{"type":"message_start","message":{"id":"msg_01XYZ","role":"assistant","model":"claude-sonnet-4-6","usage":{"input_tokens":100,"output_tokens":1,"cache_read_input_tokens":50,"cache_creation_input_tokens":25,"cache_creation":{"ephemeral_5m_input_tokens":20,"ephemeral_1h_input_tokens":5}}}}"#,
        );
        match event {
            AnthropicEvent::MessageStart { message } => {
                assert_eq!(message.id.as_deref(), Some("msg_01XYZ"));
                let usage = message.usage.expect("usage present");
                assert_eq!(usage.input_tokens, 100);
                assert_eq!(usage.output_tokens, 1);
                assert_eq!(usage.cache_read_input_tokens, 50);
                assert_eq!(usage.cache_creation_input_tokens, 25);
                let cc = usage.cache_creation.expect("cache_creation present");
                assert_eq!(cc.ephemeral_5m_input_tokens, Some(20));
                assert_eq!(cc.ephemeral_1h_input_tokens, Some(5));
            }
            other => panic!("expected MessageStart, got {:?}", other),
        }
    }

    #[test]
    fn message_delta_stop_reason_and_usage() {
        let event = parse(
            r#"{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":42,"cache_creation":{"ephemeral_5m_input_tokens":7,"ephemeral_1h_input_tokens":9}}}"#,
        );
        match event {
            AnthropicEvent::MessageDelta { delta, usage } => {
                let delta = delta.expect("delta present");
                assert_eq!(delta.stop_reason.as_deref(), Some("tool_use"));
                let usage = usage.expect("usage present");
                assert_eq!(usage.output_tokens, 42);
                let cc = usage.cache_creation.expect("cache_creation present");
                assert_eq!(cc.ephemeral_5m_input_tokens, Some(7));
                assert_eq!(cc.ephemeral_1h_input_tokens, Some(9));
            }
            other => panic!("expected MessageDelta, got {:?}", other),
        }
    }

    #[test]
    fn usage_missing_fields_default_zero() {
        let usage: UsagePayload = serde_json::from_str("{}").expect("empty usage parses");
        assert_eq!(usage.input_tokens, 0);
        assert_eq!(usage.output_tokens, 0);
        assert_eq!(usage.cache_read_input_tokens, 0);
        assert_eq!(usage.cache_creation_input_tokens, 0);
        assert!(usage.cache_creation.is_none());
    }

    #[test]
    fn unknown_event_type_is_unit_unknown() {
        for data in [
            r#"{"type":"ping"}"#,
            r#"{"type":"fnord","payload":[1,2,3]}"#,
        ] {
            assert!(
                matches!(parse(data), AnthropicEvent::Unknown),
                "expected Unknown for {data}"
            );
        }
    }

    #[test]
    fn error_event_parses_to_error_variant_with_payload() {
        // The `error` tag is a real variant now (task #130) — it must NOT fall
        // through to Unknown, and its type/message must be extractable so the
        // surfaced failure is actionable.
        let data = r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#;
        match parse(data) {
            AnthropicEvent::Error { error } => {
                let e = error.expect("error payload present");
                assert_eq!(e.error_type.as_deref(), Some("overloaded_error"));
                assert_eq!(e.message.as_deref(), Some("Overloaded"));
            }
            other => panic!("expected Error, got {:?}", other),
        }
    }

    #[test]
    fn bare_error_event_parses_to_error_variant_without_payload() {
        match parse(r#"{"type":"error"}"#) {
            AnthropicEvent::Error { error } => assert!(error.is_none()),
            other => panic!("expected Error, got {:?}", other),
        }
    }

    #[test]
    fn content_block_stop_and_message_stop_parse() {
        assert!(matches!(
            parse(r#"{"type":"content_block_stop","index":3}"#),
            AnthropicEvent::ContentBlockStop
        ));
        assert!(matches!(
            parse(r#"{"type":"message_stop","amazon-bedrock-invocationMetrics":{"x":1}}"#),
            AnthropicEvent::MessageStop
        ));
    }
}