causa-provider 0.3.0

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
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
//! Real HTTP streaming through the material-returning runtime, without live APIs.
mod runtime_streaming_support;

use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use causa_kernel::*;
use causa_provider::{
    AnthropicMessagesGateway, OpenAiChatCompletionsGateway, OpenAiResponsesGateway,
};
use causa_runtime::*;
use runtime_streaming_support::*;
use serde_json::json;

fn runner(gateway: Arc<dyn ModelGateway>, tools: Vec<Arc<dyn Tool>>) -> TurnRunner {
    TurnRunner::new(
        gateway,
        Arc::new(ToolExecutor::new(tools, ToolExecutorOptions::default()).unwrap()),
    )
}

fn input() -> Context {
    Context::from_blocks(vec![ContextBlock::text(
        new_block_id(),
        Role::User,
        "original",
    )])
    .unwrap()
}

fn invocation(round: u32) -> InvocationId {
    InvocationId {
        turn_id: TurnId::new("http-stream"),
        round_id: RoundId(round),
    }
}

fn control() -> CallControl {
    CallControl::new(CancellationToken::new(), None)
}

#[tokio::test]
async fn all_builtin_gateways_observe_http_text_before_terminal_and_commit_only_final_output() {
    for protocol in 0..3 {
        let (prefix, suffix, expected) = match protocol {
            0 => (chat_text("你好🙂"), chat_terminal("stop"), "你好🙂"),
            1 => (
                responses_prefix("advisory"),
                responses_terminal("authoritative"),
                "authoritative",
            ),
            _ => (anthropic_prefix("你好🙂"), anthropic_terminal(), "你好🙂"),
        };
        let (round, release) = Round::gated(prefix, suffix);
        let mut server = Server::start(vec![round]);
        let gateway: Arc<dyn ModelGateway> = match protocol {
            0 => Arc::new(
                OpenAiChatCompletionsGateway::new("key")
                    .with_base_url(format!("{}/v1", server.url)),
            ),
            1 => Arc::new(
                OpenAiResponsesGateway::new("key").with_base_url(format!("{}/v1", server.url)),
            ),
            _ => Arc::new(
                AnthropicMessagesGateway::new("key").with_base_url(format!("{}/v1", server.url)),
            ),
        };
        let seen = Arc::new(Mutex::new(Vec::new()));
        let recorded = seen.clone();
        let mut options = TurnRunOptions::new(ModelRef::new("fixture"));
        // The Anthropic leg requires an explicit output limit.
        options.generation.max_tokens = Some(1024);
        options.observer = Some(Arc::new(move |event| match event {
            RunEvent::ModelDelta {
                invocation_id,
                delta: StreamDelta::TextDelta { delta },
                ..
            } => {
                assert_eq!(*invocation_id, &invocation(0));
                assert_eq!(recorded.lock().unwrap().as_slice(), [] as [&str; 0]);
                assert!(!delta.is_empty());
                recorded.lock().unwrap().push("delta");
                release.send(()).unwrap();
            }
            RunEvent::ModelOutput {
                invocation_id,
                output,
                ..
            } => {
                assert_eq!(*invocation_id, &invocation(0));
                assert_eq!(output.response.text(), expected);
                recorded.lock().unwrap().push("output");
            }
            RunEvent::BlocksCommitted { .. } => recorded.lock().unwrap().push("commit"),
            _ => {}
        }));
        let outcome = tokio::time::timeout(
            Duration::from_secs(5),
            runner(gateway, vec![]).run_streaming(
                TurnId::new("http-stream"),
                input(),
                options,
                control(),
            ),
        )
        .await
        .expect("terminal gate must be released by an actual delta");
        assert!(
            matches!(outcome.result, TurnResult::Completed { .. }),
            "{:#?}",
            outcome.result
        );
        assert_eq!(
            seen.lock().unwrap().as_slice(),
            ["delta", "output", "commit"]
        );
        let material = serde_json::to_string(&outcome.context).unwrap();
        assert!(material.contains(expected));
        assert!(!material.contains("advisory"));
        assert_eq!(outcome.context.blocks().len(), 2);
        assert!(outcome.uncommitted_tool_batch.is_none());
        server.finish();
        let requests = server.requests.lock().unwrap();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0]["stream"], true);
    }
}

struct Echo {
    calls: Arc<Mutex<Vec<ToolCallContext>>>,
    status: ToolResultStatus,
}

#[async_trait]
impl Tool for Echo {
    fn definition(&self) -> ToolDefinition {
        ToolDefinition::new("echo", "echo", json!({"type":"object"}))
    }
    async fn execute(
        &self,
        call: &ToolCallContext,
        _: &CallControl,
        _store: Option<&dyn causa_kernel::ArtifactStore>,
    ) -> ToolResultPayload {
        self.calls.lock().unwrap().push(call.clone());
        ToolResultPayload::new(
            call.call_block_id,
            self.status.clone(),
            ToolOutput::new(call.input.arguments.clone()),
        )
    }
}

fn echo(calls: Arc<Mutex<Vec<ToolCallContext>>>) -> Arc<dyn Tool> {
    Arc::new(Echo {
        calls,
        status: ToolResultStatus::Succeeded,
    })
}

#[tokio::test]
async fn terminal_tool_executes_once_with_round_identity_and_provider_id_then_next_round_streams() {
    let calls = Arc::new(Mutex::new(Vec::new()));
    let (round, release) = Round::gated(
        chat_tool("{\"message\":\"你好🙂\"}"),
        chat_terminal("tool_calls"),
    );
    let mut server = Server::start(vec![
        round,
        Round::immediate(chat_text("final") + &chat_terminal("stop")),
    ]);
    let mut options = TurnRunOptions::new(ModelRef::new("fixture"));
    let observed = calls.clone();
    let released = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let released_in_observer = released.clone();
    options.observer = Some(Arc::new(move |event| match event {
        RunEvent::ModelDelta {
            invocation_id,
            delta:
                StreamDelta::ToolCallDelta {
                    call_index,
                    provider_call_id,
                    ..
                },
            ..
        } => {
            assert_eq!(*invocation_id, &invocation(0));
            assert_eq!(*call_index, 0);
            assert_eq!(provider_call_id.as_deref(), Some("call_wire"));
            assert!(
                observed.lock().unwrap().is_empty(),
                "draft tool must not execute"
            );
            if !released_in_observer.swap(true, std::sync::atomic::Ordering::SeqCst) {
                release.send(()).unwrap();
            }
        }
        RunEvent::ToolBatchReady { invocation_id, .. } => {
            assert_eq!(*invocation_id, &invocation(0));
            assert!(released_in_observer.load(std::sync::atomic::Ordering::SeqCst));
        }
        RunEvent::ModelDelta {
            invocation_id,
            delta: StreamDelta::TextDelta { .. },
            ..
        } => assert_eq!(*invocation_id, &invocation(1)),
        _ => {}
    }));
    let gateway = Arc::new(
        OpenAiChatCompletionsGateway::new("key").with_base_url(format!("{}/v1", server.url)),
    );
    let outcome = tokio::time::timeout(
        Duration::from_secs(5),
        runner(gateway, vec![echo(calls.clone())]).run_streaming(
            TurnId::new("http-stream"),
            input(),
            options,
            control(),
        ),
    )
    .await
    .unwrap();
    assert!(
        matches!(outcome.result, TurnResult::Completed { .. }),
        "{:#?}",
        outcome.result
    );
    assert_eq!(calls.lock().unwrap().len(), 1);
    let call = calls.lock().unwrap()[0].clone();
    assert_eq!(call.input.arguments, json!({"message":"你好🙂"}));
    let declaration = outcome
        .context
        .blocks()
        .iter()
        .find(|block| block.id() == call.call_block_id)
        .unwrap();
    assert_eq!(
        declaration.meta().provider_call_id.as_deref(),
        Some("call_wire")
    );
    assert_eq!(outcome.context.blocks().len(), 5);
    assert!(outcome.uncommitted_tool_batch.is_none());
    server.finish();
    let requests = server.requests.lock().unwrap();
    assert_eq!(requests.len(), 2);
    assert_eq!(requests[1]["messages"][2]["tool_call_id"], "call_wire");
}

#[tokio::test]
async fn stream_error_missing_terminal_and_truncated_tool_leave_original_context_and_no_execution()
{
    for (body, kind) in [
        (chat_tool("{"), ModelInvokeErrorKind::UnknownOutcome),
        (
            chat_tool("{") + &chat_terminal("tool_calls"),
            ModelInvokeErrorKind::Undecodable,
        ),
        (
            chat_tool("{")
                + &event(json!({"error":{"type":"server_error","message":"fixture failure"}})),
            ModelInvokeErrorKind::Transient,
        ),
    ] {
        let mut server = Server::start(vec![Round::immediate(body)]);
        let original = input();
        let saved = original.blocks().to_vec();
        let calls = Arc::new(Mutex::new(Vec::new()));
        let outcome = runner(
            Arc::new(
                OpenAiChatCompletionsGateway::new("key")
                    .with_base_url(format!("{}/v1", server.url)),
            ),
            vec![echo(calls.clone())],
        )
        .run_streaming(
            TurnId::new("http-stream"),
            original,
            TurnRunOptions::new(ModelRef::new("fixture")),
            control(),
        )
        .await;
        let TurnResult::Interrupted {
            cause:
                TurnInterruption::ModelCallFailed {
                    invocation_id,
                    error,
                    ..
                },
        } = outcome.result
        else {
            panic!("expected classified model failure: {:?}", outcome.result);
        };
        assert_eq!(invocation_id, invocation(0));
        assert_eq!(error.kind, kind);
        // The original material plus only the declaration of the bound tools.
        let blocks = outcome.context.blocks();
        assert_eq!(blocks[..saved.len()], saved[..]);
        assert_eq!(blocks.len(), saved.len() + 1);
        assert!(matches!(
            blocks[saved.len()].content(),
            BlockContent::ToolChange(_)
        ));
        assert!(calls.lock().unwrap().is_empty());
        assert!(outcome.uncommitted_tool_batch.is_none());
        server.finish();
        assert_eq!(server.requests.lock().unwrap().len(), 1);
    }
}

#[tokio::test]
async fn observer_cancelled_partial_second_round_preserves_completed_first_round_and_no_pending_batch()
 {
    let (second, release) = Round::gated(chat_tool("{"), String::new());
    let mut server = Server::start(vec![
        Round::immediate(chat_tool("{}") + &chat_terminal("tool_calls")),
        second,
    ]);
    let calls = Arc::new(Mutex::new(Vec::new()));
    let token = CancellationToken::new();
    let cancel = token.clone();
    let mut options = TurnRunOptions::new(ModelRef::new("fixture"));
    options.observer = Some(Arc::new(move |event| {
        if let RunEvent::ModelDelta {
            invocation_id,
            delta: StreamDelta::ToolCallDelta { .. },
            ..
        } = event
            && invocation_id.round_id == RoundId(1)
        {
            cancel.cancel();
            let _ = release.send(());
        }
    }));
    let outcome = runner(
        Arc::new(
            OpenAiChatCompletionsGateway::new("key").with_base_url(format!("{}/v1", server.url)),
        ),
        vec![echo(calls.clone())],
    )
    .run_streaming(
        TurnId::new("http-stream"),
        input(),
        options,
        CallControl::new(token, None),
    )
    .await;
    assert!(
        matches!(outcome.result, TurnResult::Interrupted { cause: TurnInterruption::Cancelled { invocation_id: Some(ref id), .. } } if id == &invocation(1))
    );
    assert_eq!(calls.lock().unwrap().len(), 1);
    assert_eq!(outcome.context.blocks().len(), 4);
    assert!(
        outcome
            .context
            .blocks()
            .iter()
            .any(|b| matches!(b.content(), BlockContent::ToolResult(_)))
    );
    assert!(outcome.uncommitted_tool_batch.is_none());
    server.finish();
    assert_eq!(server.requests.lock().unwrap().len(), 2);
}

#[tokio::test]
async fn cancellation_after_declaration_commit_returns_complete_pending_tool_batch() {
    let mut server = Server::start(vec![Round::immediate(
        chat_tool("{}") + &chat_terminal("tool_calls"),
    )]);
    let calls = Arc::new(Mutex::new(Vec::new()));
    let token = CancellationToken::new();
    let cancel = token.clone();
    let mut options = TurnRunOptions::new(ModelRef::new("fixture"));
    options.observer = Some(Arc::new(move |event| {
        if let RunEvent::BlocksCommitted { blocks, .. } = event
            && blocks
                .iter()
                .any(|block| matches!(block.content(), BlockContent::ToolCall(_)))
        {
            cancel.cancel();
        }
    }));
    let outcome = runner(
        Arc::new(
            OpenAiChatCompletionsGateway::new("key").with_base_url(format!("{}/v1", server.url)),
        ),
        vec![echo(calls.clone())],
    )
    .run_streaming(
        TurnId::new("http-stream"),
        input(),
        options,
        CallControl::new(token, None),
    )
    .await;
    assert!(matches!(
        outcome.result,
        TurnResult::Interrupted {
            cause: TurnInterruption::Cancelled { .. }
        }
    ));
    assert_eq!(outcome.context.blocks().len(), 3);
    assert!(calls.lock().unwrap().is_empty());
    assert_eq!(outcome.uncommitted_tool_batch.unwrap().calls().len(), 1);
    server.finish();
}

#[tokio::test]
async fn failed_later_round_preserves_completed_tool_material_and_original_block_identity() {
    let mut server = Server::start(vec![
        Round::immediate(chat_tool("{}") + &chat_terminal("tool_calls")),
        Round::immediate(chat_tool("{")),
    ]);
    let original = input();
    let first = original.blocks()[0].clone();
    let calls = Arc::new(Mutex::new(Vec::new()));
    let outcome = runner(
        Arc::new(
            OpenAiChatCompletionsGateway::new("key").with_base_url(format!("{}/v1", server.url)),
        ),
        vec![echo(calls.clone())],
    )
    .run_streaming(
        TurnId::new("http-stream"),
        original,
        TurnRunOptions::new(ModelRef::new("fixture")),
        control(),
    )
    .await;
    assert!(
        matches!(outcome.result, TurnResult::Interrupted { cause: TurnInterruption::ModelCallFailed { invocation_id, error, .. } } if invocation_id == invocation(1) && error.kind == ModelInvokeErrorKind::UnknownOutcome)
    );
    assert_eq!(outcome.context.blocks()[0], first);
    assert_eq!(outcome.context.blocks().len(), 4);
    assert_eq!(calls.lock().unwrap().len(), 1);
    assert!(outcome.uncommitted_tool_batch.is_none());
    server.finish();
    assert_eq!(server.requests.lock().unwrap().len(), 2);
}

#[tokio::test]
async fn unknown_tool_result_commits_and_stops_without_another_model_round() {
    let mut server = Server::start(vec![Round::immediate(
        chat_tool("{}") + &chat_terminal("tool_calls"),
    )]);
    let calls = Arc::new(Mutex::new(Vec::new()));
    let tool = Arc::new(Echo {
        calls: calls.clone(),
        status: ToolResultStatus::UnknownOutcome,
    });
    let outcome = runner(
        Arc::new(
            OpenAiChatCompletionsGateway::new("key").with_base_url(format!("{}/v1", server.url)),
        ),
        vec![tool],
    )
    .run_streaming(
        TurnId::new("http-stream"),
        input(),
        TurnRunOptions::new(ModelRef::new("fixture")),
        control(),
    )
    .await;
    assert!(
        matches!(outcome.result, TurnResult::Interrupted { cause: TurnInterruption::UnknownToolOutcome { invocation_id, .. } } if invocation_id == invocation(0))
    );
    assert_eq!(calls.lock().unwrap().len(), 1);
    assert_eq!(outcome.context.blocks().len(), 4);
    assert!(outcome.uncommitted_tool_batch.is_none());
    server.finish();
    assert_eq!(server.requests.lock().unwrap().len(), 1);
}