causa-protocol 0.1.3

Causa — a minimal context kernel for Rust agents (facts, ports, adapters)
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
use std::collections::BTreeMap;

use causa_kernel::{ModelInvokeError, ModelStopReason, StreamDelta};
use serde_json::{Value, json};

use super::{
    StreamLimits,
    common::{Budget, done, index, merge_usage, provider_error, string, undecodable},
};
use crate::translation::{
    anthropic::parse_anthropic_response, sse_parser::SseEvent, stop_reason,
    usage::model_usage_from_anthropic,
};

struct Block {
    wire: Value,
    arguments: String,
    saw_arguments: bool,
    /// The block closed with arguments that are not complete JSON.
    incomplete: bool,
    closed: bool,
    call_index: Option<usize>,
}

pub(super) struct Anthropic {
    budget: Budget,
    started: bool,
    stopped: bool,
    blocks: BTreeMap<usize, Block>,
    tools: usize,
    stop_reason: Option<String>,
    usage: Value,
    has_usage: bool,
}

impl Anthropic {
    pub fn new(limits: StreamLimits) -> Self {
        Self {
            budget: Budget::new(limits),
            started: false,
            stopped: false,
            blocks: BTreeMap::new(),
            tools: 0,
            stop_reason: None,
            usage: json!({}),
            has_usage: false,
        }
    }
    pub fn event(&mut self, event: &SseEvent) -> Result<Vec<StreamDelta>, ModelInvokeError> {
        let value: Value = serde_json::from_str(&event.data)
            .map_err(|_| undecodable("Anthropic event contains invalid JSON"))?;
        let kind = string(&value, "type")?;
        if let Some(name) = &event.event
            && name != kind
            && name != "message"
        {
            return Err(undecodable("Anthropic SSE event/type mismatch"));
        }
        if kind == "error" {
            return Err(provider_error(
                value
                    .get("error")
                    .ok_or_else(|| undecodable("Anthropic missing error"))?,
            ));
        }
        if kind == "ping" {
            return Ok(Vec::new());
        }
        let mut deltas = Vec::new();
        match kind {
            "message_start" => {
                if self.started {
                    return Err(undecodable("Anthropic duplicate message_start"));
                }
                let message = value
                    .get("message")
                    .and_then(Value::as_object)
                    .ok_or_else(|| undecodable("Anthropic missing message"))?;
                if message
                    .get("content")
                    .and_then(Value::as_array)
                    .is_none_or(|c| !c.is_empty())
                {
                    return Err(undecodable(
                        "Anthropic message_start must have empty content",
                    ));
                }
                if message.get("stop_reason").is_some_and(|r| !r.is_null()) {
                    return Err(undecodable("Anthropic message_start contains stop_reason"));
                }
                self.started = true;
                if let Some(usage) = message.get("usage").filter(|u| !u.is_null()) {
                    merge_usage(&mut self.usage, usage, &mut self.budget)?;
                    self.has_usage = true;
                    deltas.push(StreamDelta::Usage(model_usage_from_anthropic(&self.usage)));
                }
            }
            "content_block_start" => {
                self.require_active()?;
                if self.stopped {
                    return Err(undecodable("Anthropic block after message_delta"));
                }
                self.budget.item(self.blocks.len())?;
                let i = index(&value, "index")?;
                if i != self.blocks.len() {
                    return Err(undecodable(
                        "Anthropic block index must follow declaration order",
                    ));
                }
                let wire = value
                    .get("content_block")
                    .cloned()
                    .ok_or_else(|| undecodable("Anthropic missing content_block"))?;
                let block_type = string(&wire, "type")?.to_owned();
                self.budget.add(block_type.len())?;
                let mut call_index = None;
                match block_type.as_str() {
                    "text" => {
                        let text = string(&wire, "text")?;
                        self.budget.add(text.len())?;
                        if !text.is_empty() {
                            deltas.push(StreamDelta::TextDelta { delta: text.into() });
                        }
                    }
                    "thinking" => {
                        let text = string(&wire, "thinking")?;
                        self.budget.add(text.len())?;
                        if let Some(sig) = wire.get("signature") {
                            self.budget.add(
                                sig.as_str()
                                    .ok_or_else(|| undecodable("Anthropic invalid signature"))?
                                    .len(),
                            )?;
                        }
                        if !text.is_empty() {
                            deltas.push(StreamDelta::ReasoningDelta { delta: text.into() });
                        }
                    }
                    "tool_use" => {
                        let id = string(&wire, "id")?;
                        let name = string(&wire, "name")?;
                        if id.is_empty() || name.is_empty() {
                            return Err(undecodable("Anthropic empty tool identity"));
                        }
                        if self
                            .blocks
                            .values()
                            .any(|b| b.wire.get("id").and_then(Value::as_str) == Some(id))
                        {
                            return Err(undecodable("Anthropic duplicate tool id"));
                        }
                        if !wire.get("input").is_some_and(Value::is_object) {
                            return Err(undecodable("Anthropic tool input must be an object"));
                        }
                        self.budget.add(id.len() + name.len())?;
                        call_index = Some(self.tools);
                        self.tools += 1;
                        deltas.push(StreamDelta::ToolCallDelta {
                            call_index: call_index.expect("tool index"),
                            provider_call_id: Some(id.into()),
                            name_delta: Some(name.into()),
                            arguments_delta: None,
                        });
                    }
                    _ => {}
                }
                // Every block is kept as the complete parser stores it:
                // `text` and `tool_use` residue, `thinking` with its
                // signature, `redacted_thinking` and unknown block types as
                // sealed material. Nothing is stripped; every field the
                // stream delivers is budgeted like any output.
                let object = wire
                    .as_object()
                    .ok_or_else(|| undecodable("Anthropic block must be an object"))?;
                let known: &[&str] = match block_type.as_str() {
                    "text" => &["type", "text"],
                    "tool_use" => &["type", "id", "name", "input"],
                    _ => &[],
                };
                for (key, value) in object.iter() {
                    if !known.contains(&key.as_str()) {
                        self.budget.add(
                            key.len()
                                + serde_json::to_vec(value)
                                    .map_err(|_| undecodable("Anthropic invalid field"))?
                                    .len(),
                        )?;
                    }
                }
                if block_type == "tool_use" {
                    self.budget.add(
                        serde_json::to_vec(&wire["input"])
                            .map_err(|_| undecodable("Anthropic invalid input"))?
                            .len(),
                    )?;
                }
                self.blocks.insert(
                    i,
                    Block {
                        wire,
                        arguments: String::new(),
                        saw_arguments: false,
                        incomplete: false,
                        closed: false,
                        call_index,
                    },
                );
            }
            "content_block_delta" => {
                self.require_active()?;
                if self.stopped {
                    return Err(undecodable("Anthropic delta after message_delta"));
                }
                let i = index(&value, "index")?;
                let block = self
                    .blocks
                    .get_mut(&i)
                    .ok_or_else(|| undecodable("Anthropic delta for undeclared block"))?;
                if block.closed {
                    return Err(undecodable("Anthropic delta for closed block"));
                }
                let delta = value
                    .get("delta")
                    .ok_or_else(|| undecodable("Anthropic missing delta"))?;
                let delta_type = string(delta, "type")?;
                let block_type = string(&block.wire, "type")?;
                let (field, delta_field) = match delta_type {
                    "text_delta" if block_type == "text" => ("text", "text"),
                    "thinking_delta" if block_type == "thinking" => ("thinking", "thinking"),
                    "signature_delta" if block_type == "thinking" => ("signature", "signature"),
                    "input_json_delta" if block_type == "tool_use" => {
                        let text = string(delta, "partial_json")?;
                        self.budget.add(text.len())?;
                        block.arguments.push_str(text);
                        block.saw_arguments = true;
                        deltas.push(StreamDelta::ToolCallDelta {
                            call_index: block.call_index.expect("tool index"),
                            provider_call_id: None,
                            name_delta: None,
                            arguments_delta: Some(text.into()),
                        });
                        return Ok(deltas);
                    }
                    "citations_delta" if block_type == "text" => {
                        // Citations arrive as deltas and belong to the block's
                        // wire residue, appended in delivery order.
                        let citation = delta
                            .get("citation")
                            .ok_or_else(|| undecodable("Anthropic missing citation"))?;
                        self.budget.add(
                            serde_json::to_vec(citation)
                                .map_err(|_| undecodable("Anthropic invalid citation"))?
                                .len(),
                        )?;
                        let object = block.wire.as_object_mut().expect("validated block");
                        let citations = object.entry("citations").or_insert_with(|| json!([]));
                        if !citations.is_array() {
                            *citations = json!([]);
                        }
                        citations
                            .as_array_mut()
                            .expect("citations array")
                            .push(citation.clone());
                        return Ok(deltas);
                    }
                    // Any other block that declared an object `input` (a
                    // server-side tool call, kept as sealed material) receives
                    // it the same way. The fragments rebuild the block so it
                    // matches the batch form; they are not client tool-call
                    // observations.
                    "input_json_delta"
                        if !matches!(block_type, "text" | "thinking")
                            && block.wire.get("input").is_some_and(Value::is_object) =>
                    {
                        let text = string(delta, "partial_json")?;
                        self.budget.add(text.len())?;
                        block.arguments.push_str(text);
                        block.saw_arguments = true;
                        return Ok(deltas);
                    }
                    "text_delta" | "thinking_delta" | "signature_delta" | "input_json_delta"
                    | "citations_delta" => {
                        return Err(undecodable("Anthropic delta/block type conflict"));
                    }
                    // A delta this decoder has no rule for cannot be applied,
                    // and a block missing part of its content must not become
                    // material that is replayed verbatim. The diagnostic is
                    // static: the wire value is provider-controlled.
                    _ => {
                        return Err(undecodable(
                            "Anthropic unsupported content block delta type",
                        ));
                    }
                };
                let text = string(delta, delta_field)?;
                self.budget.add(text.len())?;
                let target = block
                    .wire
                    .as_object_mut()
                    .expect("validated block")
                    .entry(field)
                    .or_insert_with(|| Value::String(String::new()));
                if !target.is_string() {
                    return Err(undecodable("Anthropic invalid block field"));
                }
                // serde_json strings have no mutable string accessor; take the
                // existing value to append without copying its accumulated prefix.
                let mut accumulated = match std::mem::replace(&mut block.wire[field], Value::Null) {
                    Value::String(s) => s,
                    _ => unreachable!("validated string"),
                };
                accumulated.push_str(text);
                block.wire[field] = Value::String(accumulated);
                if field == "text" {
                    deltas.push(StreamDelta::TextDelta { delta: text.into() });
                }
                if field == "thinking" {
                    deltas.push(StreamDelta::ReasoningDelta { delta: text.into() });
                }
            }
            "content_block_stop" => {
                self.require_active()?;
                if self.stopped {
                    return Err(undecodable("Anthropic block stop after message_delta"));
                }
                let block = self
                    .blocks
                    .get_mut(&index(&value, "index")?)
                    .ok_or_else(|| undecodable("Anthropic stop for undeclared block"))?;
                if block.closed {
                    return Err(undecodable("Anthropic duplicate block stop"));
                }
                if block.saw_arguments {
                    // Arguments that do not parse are judged at the message
                    // end, which knows why the response stopped.
                    match serde_json::from_str::<Value>(&block.arguments) {
                        Ok(input) if input.is_object() => block.wire["input"] = input,
                        Ok(_) => {
                            return Err(undecodable("Anthropic tool arguments must be an object"));
                        }
                        Err(_) => block.incomplete = true,
                    }
                    block.arguments.clear();
                }
                block.closed = true;
            }
            "message_delta" => {
                self.require_active()?;
                if self.blocks.values().any(|b| !b.closed) {
                    return Err(undecodable("Anthropic message_delta before block closure"));
                }
                let delta = value
                    .get("delta")
                    .ok_or_else(|| undecodable("Anthropic missing message delta"))?;
                if let Some(reason) = delta.get("stop_reason").filter(|r| !r.is_null()) {
                    let reason = reason
                        .as_str()
                        .ok_or_else(|| undecodable("Anthropic invalid stop_reason"))?;
                    // The value is recorded verbatim and classified by the same
                    // mapping table the batch parser uses. An unknown value is
                    // not an error here: it becomes Unrecognized downstream.
                    if self.stop_reason.as_deref().is_some_and(|old| old != reason) {
                        return Err(undecodable("Anthropic stop_reason changed"));
                    }
                    self.stop_reason = Some(reason.into());
                    self.stopped = true;
                }
                if let Some(usage) = value.get("usage").filter(|u| !u.is_null()) {
                    merge_usage(&mut self.usage, usage, &mut self.budget)?;
                    self.has_usage = true;
                    deltas.push(StreamDelta::Usage(model_usage_from_anthropic(&self.usage)));
                }
            }
            "message_stop" => {
                self.require_active()?;
                if self.blocks.values().any(|b| !b.closed) {
                    return Err(undecodable("Anthropic message_stop with open blocks"));
                }
                let reason = self
                    .stop_reason
                    .as_ref()
                    .ok_or_else(|| undecodable("Anthropic message_stop without stop_reason"))?;
                // The token limit can stop the response inside its last
                // block. That block is left out: nothing could execute the
                // call, and the stop reason says what happened. Incomplete
                // arguments anywhere else are a broken stream.
                let cut_off = stop_reason::anthropic(reason) == ModelStopReason::MaxTokens;
                let mut blocks = std::mem::take(&mut self.blocks);
                if cut_off && blocks.last_key_value().is_some_and(|(_, b)| b.incomplete) {
                    blocks.pop_last();
                }
                if blocks.values().any(|b| b.incomplete) {
                    return Err(undecodable("Anthropic malformed tool arguments"));
                }
                let content: Vec<Value> = blocks.into_values().map(|b| b.wire).collect();
                let mut wire = json!({"content":content,"stop_reason":reason});
                if self.has_usage {
                    wire["usage"] = std::mem::take(&mut self.usage);
                }
                deltas.push(done(parse_anthropic_response(&wire)?));
            }
            _ => {}
        }
        Ok(deltas)
    }
    fn require_active(&self) -> Result<(), ModelInvokeError> {
        if !self.started {
            return Err(undecodable("Anthropic event before message_start"));
        }
        Ok(())
    }
}