causa-runtime 0.1.4

Causa runtime — optional components: material execution, bound tool processing, streaming
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
//! Tool processors read the bound tools' declared hints and the host's run
//! data from their context. The binding fixes the hints; the data passes
//! through as given, so a shared handle in it is read live.
mod common;
mod tool_fixtures;

use async_trait::async_trait;
use causa_kernel::*;
use causa_runtime::{ToolExecutorOptions, TurnResult, TurnRunner, new_block_id};
use serde_json::json;
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
};
use tokio::sync::{mpsc, oneshot};

/// A static tool that declares hints.
struct HintedTool {
    name: &'static str,
    hints: ToolHints,
}

#[async_trait]
impl Tool for HintedTool {
    fn definition(&self) -> ToolDefinition {
        tool_fixtures::definition(self.name)
    }
    fn hints(&self) -> ToolHints {
        self.hints.clone()
    }
    async fn execute(
        &self,
        call: &ToolCallContext,
        _control: &CallControl,
        _store: Option<&dyn ArtifactStore>,
    ) -> ToolResultPayload {
        tool_fixtures::result(call, ToolResultStatus::Succeeded, json!("static"))
    }
}

/// A dynamic source whose one tool declares hints that can change. A call
/// flips the tool to destructive, as a server that re-annotates would, and
/// bumps the version, as the listing contract asks.
struct HintedSource {
    hints: Mutex<ToolHints>,
    version: AtomicU64,
    describes: AtomicUsize,
    flip_on_call: bool,
}

impl HintedSource {
    fn new(hints: ToolHints, flip_on_call: bool) -> Arc<Self> {
        Arc::new(Self {
            hints: Mutex::new(hints),
            version: AtomicU64::new(0),
            describes: AtomicUsize::new(0),
            flip_on_call,
        })
    }

    fn set_hints(&self, hints: ToolHints) {
        *self.hints.lock().unwrap() = hints;
        self.version.fetch_add(1, Ordering::SeqCst);
    }
}

#[async_trait]
impl DynamicToolSource for HintedSource {
    fn id(&self) -> &str {
        "remote"
    }
    fn version(&self) -> u64 {
        self.version.load(Ordering::SeqCst)
    }
    async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError> {
        Ok(vec![tool_fixtures::definition("remote_lookup")])
    }
    async fn describe(&self) -> Result<Vec<ToolDescription>, SourceError> {
        self.describes.fetch_add(1, Ordering::SeqCst);
        Ok(vec![
            ToolDescription::new(tool_fixtures::definition("remote_lookup"))
                .with_hints(self.hints.lock().unwrap().clone()),
        ])
    }
    async fn invoke(
        &self,
        call: &ToolCallContext,
        _control: &CallControl,
        _store: Option<&dyn ArtifactStore>,
    ) -> Result<ToolResultPayload, ToolExecutionError> {
        if self.flip_on_call {
            self.set_hints(
                ToolHints::default()
                    .with_read_only(false)
                    .with_destructive(true),
            );
        }
        Ok(tool_fixtures::result(
            call,
            ToolResultStatus::Succeeded,
            json!("remote"),
        ))
    }
}

#[derive(Debug, PartialEq)]
struct Tag(&'static str);

/// What one processor saw for one call.
#[derive(Debug, Clone, PartialEq)]
struct Seen {
    phase: &'static str,
    round: u32,
    tool: String,
    hints: Option<ToolHints>,
    tag: Option<&'static str>,
    other_type: bool,
}

struct Recorder {
    phase: &'static str,
    seen: Arc<Mutex<Vec<Seen>>>,
}

impl Recorder {
    fn pair(seen: &Arc<Mutex<Vec<Seen>>>) -> ToolExecutorOptions {
        ToolExecutorOptions::default()
            .with_before(vec![Arc::new(Recorder {
                phase: "before",
                seen: seen.clone(),
            })])
            .with_after(vec![Arc::new(Recorder {
                phase: "after",
                seen: seen.clone(),
            })])
    }
}

#[async_trait]
impl ToolBatchProcessor for Recorder {
    async fn process(
        &self,
        batch: &mut ToolBatch,
        ctx: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError> {
        let mut seen = self.seen.lock().unwrap();
        for entry in batch.results().iter().chain(batch.calls()) {
            let tool = entry.call().input.tool_name.clone();
            seen.push(Seen {
                phase: self.phase,
                round: ctx.round_id.0,
                hints: ctx.hints(&tool).cloned(),
                tool,
                tag: ctx.data::<Tag>().map(|tag| tag.0),
                other_type: ctx.data::<String>().is_some(),
            });
        }
        Ok(())
    }
}

fn read_only() -> ToolHints {
    ToolHints::default()
        .with_read_only(true)
        .with_open_world(false)
}

fn destructive() -> ToolHints {
    ToolHints::default()
        .with_read_only(false)
        .with_destructive(true)
}

#[tokio::test]
async fn tools_and_sources_that_declare_nothing_bind_with_default_hints() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let executor = tool_fixtures::executor(
        vec![tool_fixtures::NamedTool::new("local")],
        Recorder::pair(&seen),
    );
    executor
        .register_dynamic(tool_fixtures::Source::new("src", "dynamic", &["remote"]))
        .unwrap();
    let mut batch = tool_fixtures::batch(&["local", "remote"]);
    executor
        .bind(tool_fixtures::invocation(), tool_fixtures::control())
        .await
        .unwrap()
        .process(&mut batch)
        .await
        .unwrap();
    let seen = seen.lock().unwrap();
    assert_eq!(seen.len(), 4);
    for entry in seen.iter() {
        assert_eq!(entry.hints, Some(ToolHints::default()), "{entry:?}");
        assert_eq!(entry.tag, None);
    }
}

#[tokio::test]
async fn before_and_after_processors_see_static_and_dynamic_hints() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let executor = tool_fixtures::executor(
        vec![Arc::new(HintedTool {
            name: "read_file",
            hints: read_only(),
        })],
        Recorder::pair(&seen),
    );
    executor
        .register_dynamic(HintedSource::new(destructive(), false))
        .unwrap();
    let bound = executor
        .bind(tool_fixtures::invocation(), tool_fixtures::control())
        .await
        .unwrap();
    let mut batch = tool_fixtures::batch(&["read_file", "remote_lookup"]);
    bound.process(&mut batch).await.unwrap();
    let hints_in = |phase: &str, tool: &str| {
        seen.lock()
            .unwrap()
            .iter()
            .find(|entry| entry.phase == phase && entry.tool == tool)
            .and_then(|entry| entry.hints.clone())
    };
    for phase in ["before", "after"] {
        assert_eq!(hints_in(phase, "read_file"), Some(read_only()), "{phase}");
        assert_eq!(
            hints_in(phase, "remote_lookup"),
            Some(destructive()),
            "{phase}"
        );
    }
}

#[tokio::test]
async fn a_binding_keeps_the_hints_it_bound() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let source = HintedSource::new(read_only(), false);
    let executor = tool_fixtures::executor(vec![], Recorder::pair(&seen));
    executor.register_dynamic(source.clone()).unwrap();

    let bound = executor
        .bind(tool_fixtures::invocation(), tool_fixtures::control())
        .await
        .unwrap();
    source.set_hints(destructive());
    let mut batch = tool_fixtures::batch(&["remote_lookup"]);
    bound.process(&mut batch).await.unwrap();
    assert!(
        seen.lock()
            .unwrap()
            .iter()
            .all(|entry| entry.hints == Some(read_only()))
    );

    seen.lock().unwrap().clear();
    let mut batch = tool_fixtures::batch(&["remote_lookup"]);
    executor
        .bind(tool_fixtures::invocation(), tool_fixtures::control())
        .await
        .unwrap()
        .process(&mut batch)
        .await
        .unwrap();
    assert!(
        seen.lock()
            .unwrap()
            .iter()
            .all(|entry| entry.hints == Some(destructive()))
    );
    assert_eq!(source.describes.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn a_change_in_hints_alone_records_no_tool_change() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let source = HintedSource::new(read_only(), true);
    let executor = tool_fixtures::executor(vec![], Recorder::pair(&seen));
    executor.register_dynamic(source.clone()).unwrap();
    let gateway = common::RecordingGateway::scripted(vec![
        Ok(common::tooluse_output("one", "remote_lookup", json!({}))),
        Ok(common::tooluse_output("two", "remote_lookup", json!({}))),
        Ok(common::endturn_output("done")),
    ]);
    let runner = TurnRunner::new(gateway.clone(), Arc::new(executor));
    let outcome = runner
        .run(
            TurnId::new("hints"),
            common::input("look it up"),
            common::options(),
            common::ctrl(),
        )
        .await;
    assert!(matches!(outcome.result, TurnResult::Completed { .. }));

    // The second round bound the new hints ...
    let before: Vec<_> = seen
        .lock()
        .unwrap()
        .iter()
        .filter(|entry| entry.phase == "before")
        .map(|entry| (entry.round, entry.hints.clone()))
        .collect();
    assert_eq!(
        before,
        vec![(0, Some(read_only())), (1, Some(destructive()))]
    );
    assert!(source.describes.load(Ordering::SeqCst) >= 2);

    // ... and the context and every request still hold one tool declaration.
    let tool_changes = |blocks: &[ContextBlock]| {
        blocks
            .iter()
            .filter(|block| matches!(block.content(), BlockContent::ToolChange(_)))
            .count()
    };
    assert_eq!(tool_changes(outcome.context.blocks()), 1);
    let requests = gateway.recorded.lock().unwrap();
    assert_eq!(requests.len(), 3);
    let declared = current_tools(&requests[0].frame.blocks);
    for request in requests.iter() {
        assert_eq!(tool_changes(&request.frame.blocks), 1);
        assert_eq!(current_tools(&request.frame.blocks), declared);
    }
    // Each request extends the one before it, so the rendered prefix of an
    // earlier round is unchanged in the next.
    for pair in requests.windows(2) {
        assert!(pair[1].frame.blocks.starts_with(&pair[0].frame.blocks));
    }
}

#[tokio::test]
async fn run_data_reaches_every_processor_of_every_round() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let executor = tool_fixtures::executor(
        vec![tool_fixtures::NamedTool::new("local")],
        Recorder::pair(&seen),
    );
    let gateway = common::RecordingGateway::scripted(vec![
        Ok(common::tooluse_output("one", "local", json!({}))),
        Ok(common::tooluse_output("two", "local", json!({}))),
        Ok(common::endturn_output("done")),
        Ok(common::tooluse_output("three", "local", json!({}))),
        Ok(common::endturn_output("done")),
    ]);
    let runner = TurnRunner::new(gateway, Arc::new(executor));
    let outcome = runner
        .run(
            TurnId::new("with-data"),
            common::input("go"),
            common::options().with_processor_data(ProcessorData::new(Tag("run-a"))),
            common::ctrl(),
        )
        .await;
    assert!(matches!(outcome.result, TurnResult::Completed { .. }));
    {
        let seen = seen.lock().unwrap();
        assert_eq!(seen.len(), 4);
        for entry in seen.iter() {
            assert_eq!(entry.tag, Some("run-a"), "{entry:?}");
            assert!(!entry.other_type);
        }
        assert_eq!(
            seen.iter().map(|entry| entry.round).collect::<Vec<_>>(),
            vec![0, 0, 1, 1]
        );
    }

    // The same executor serves a run without data.
    seen.lock().unwrap().clear();
    let outcome = runner
        .run(
            TurnId::new("without-data"),
            outcome.context,
            common::options(),
            common::ctrl(),
        )
        .await;
    assert!(matches!(outcome.result, TurnResult::Completed { .. }));
    let seen = seen.lock().unwrap();
    assert_eq!(seen.len(), 2);
    assert!(seen.iter().all(|entry| entry.tag.is_none()));
}

#[tokio::test]
async fn a_binding_carries_data_without_the_runner() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let executor = tool_fixtures::executor(
        vec![tool_fixtures::NamedTool::new("local")],
        Recorder::pair(&seen),
    );
    let mut batch = tool_fixtures::batch(&["local"]);
    executor
        .bind(tool_fixtures::invocation(), tool_fixtures::control())
        .await
        .unwrap()
        .with_processor_data(ProcessorData::new(Tag("standalone")))
        .process(&mut batch)
        .await
        .unwrap();
    let seen = seen.lock().unwrap();
    assert_eq!(seen.len(), 2);
    assert!(seen.iter().all(|entry| entry.tag == Some("standalone")));
}

/// The host's mode: `true` runs every call, `false` asks first.
type AllowAll = Arc<AtomicBool>;

/// Decides calls one by one, reading the mode each time. Asking sends the
/// call's name to the host and waits for the answer.
struct Ask(mpsc::Sender<(String, oneshot::Sender<bool>)>);

#[async_trait]
impl ToolBatchProcessor for Ask {
    async fn process(
        &self,
        batch: &mut ToolBatch,
        ctx: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError> {
        let mut offset = 0;
        while offset < batch.calls().len() {
            let allow_all = ctx
                .data::<AllowAll>()
                .ok_or_else(|| ProcessorError::Failed("no mode".into()))?;
            if allow_all.load(Ordering::SeqCst) {
                offset += 1;
                continue;
            }
            let call = batch.calls()[offset].call();
            let (name, id) = (call.input.tool_name.clone(), call.call_block_id);
            let (reply, answer) = oneshot::channel();
            self.0
                .send((name, reply))
                .await
                .map_err(|error| ProcessorError::Failed(error.to_string()))?;
            if answer
                .await
                .map_err(|error| ProcessorError::Failed(error.to_string()))?
            {
                offset += 1;
            } else {
                batch
                    .resolve_at(
                        batch.completed_len() + offset,
                        new_block_id(),
                        ToolResultPayload::new(
                            id,
                            ToolResultStatus::Rejected,
                            ToolOutput::new(json!({"error": "declined"})),
                        ),
                    )
                    .map_err(|error| ProcessorError::Failed(error.to_string()))?;
            }
        }
        Ok(())
    }
}

#[tokio::test]
async fn a_handle_in_the_data_is_read_live_within_one_batch() {
    let (asks, mut asked) = mpsc::channel(4);
    let tool = tool_fixtures::NamedTool::new("write");
    let executor = tool_fixtures::executor(
        vec![tool.clone()],
        ToolExecutorOptions::default().with_before(vec![Arc::new(Ask(asks))]),
    );
    let allow_all: AllowAll = Arc::new(AtomicBool::new(false));
    // The host declines the first call and, from the same prompt, switches
    // the run to allow everything.
    let host = {
        let allow_all = allow_all.clone();
        tokio::spawn(async move {
            let mut asked_about = Vec::new();
            while let Some((name, reply)) = asked.recv().await {
                asked_about.push(name);
                allow_all.store(true, Ordering::SeqCst);
                reply.send(false).unwrap();
            }
            asked_about
        })
    };
    let mut batch = tool_fixtures::batch(&["write", "write"]);
    executor
        .bind(tool_fixtures::invocation(), tool_fixtures::control())
        .await
        .unwrap()
        .with_processor_data(ProcessorData::new(allow_all.clone()))
        .process(&mut batch)
        .await
        .unwrap();
    drop(executor);
    assert_eq!(host.await.unwrap(), vec!["write".to_owned()]);
    assert_eq!(
        tool_fixtures::statuses(&batch),
        vec![ToolResultStatus::Rejected, ToolResultStatus::Succeeded]
    );
    assert_eq!(tool.count.load(Ordering::SeqCst), 1);
}