causa-kernel 0.1.2

Causa kernel — primitive facts (ContextBlock) and behavior contracts (ports)
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
//! Controlled tool-batch facts and the processor contract.

use crate::context::block::{MediaRef, TextPayload, ToolCallPayload};
use crate::context::ids::BlockId;
use crate::context::ids::{RoundId, TurnId};
use crate::context::tool_data::{ToolOutput, ToolResultPayload};
use crate::ports::control::CallControl;
use crate::ports::tool::{ToolCallContext, ToolDescription, ToolHints};
use async_trait::async_trait;
use std::any::Any;
use std::collections::HashSet;
use std::sync::Arc;

/// A declaration plus its optional completed result.
#[derive(Debug)]
pub struct ToolCallEntry {
    call: ToolCallContext,
    result: Option<(BlockId, ToolResultPayload)>,
}

impl ToolCallEntry {
    /// Borrows the declaration and effective execution input.
    pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
        &self.call
    }

    /// Mutably borrows the input while this call is still pending.
    pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
        self.result.is_none().then_some(&mut self.call.input)
    }

    /// Borrows the result block ID and result payload when completed.
    pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
        self.result.as_ref().map(|(id, result)| (id, result))
    }

    /// Mutably borrows output when this call has a result.
    pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
        self.result.as_mut().map(|(_, result)| &mut result.output)
    }

    /// Mutably borrows result media when this call has a result.
    pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
        self.result.as_mut().map(|(_, result)| &mut result.media)
    }

    /// Adds a note to the pending call or completed result as appropriate.
    pub fn push_note(&mut self, note: TextPayload) {
        match self.result.as_mut() {
            Some((_, result)) => result.notes.push(note),
            None => self.call.result_notes.push(note),
        }
    }
}

/// One tool batch with a completed prefix and pending suffix.
///
/// Each result joins the end of the completed prefix as it is resolved, so
/// the prefix is in resolution order: with concurrent dispatch, the order the
/// calls completed in, not the order the model declared them in. That order
/// is what [`ToolBatch::into_results`] returns and what a runner commits. To
/// keep declaration order instead, sort [`ToolBatch::results_mut`] by
/// [`ProcessorContext::declaration_order`] in a processor that runs after
/// dispatch.
#[derive(Debug)]
pub struct ToolBatch {
    entries: Vec<ToolCallEntry>,
    completed: usize,
}

impl ToolBatch {
    /// Creates a batch from declarations in their original order.
    pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
        let mut declarations = HashSet::with_capacity(calls.len());
        for call in &calls {
            if !declarations.insert(call.call_block_id) {
                return Err(BatchError::DuplicateDeclaration(call.call_block_id));
            }
        }
        let batch = Self {
            entries: calls
                .into_iter()
                .map(|call| ToolCallEntry { call, result: None })
                .collect(),
            completed: 0,
        };
        batch.validate()?;
        Ok(batch)
    }

    /// Returns the pending suffix.
    pub fn calls(&self) -> &[ToolCallEntry] {
        &self.entries[self.completed..]
    }

    /// Mutably returns the pending suffix.
    pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
        &mut self.entries[self.completed..]
    }

    /// Returns the completed prefix.
    pub fn results(&self) -> &[ToolCallEntry] {
        &self.entries[..self.completed]
    }

    /// Mutably returns the completed prefix for output editing and ordering.
    pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
        &mut self.entries[..self.completed]
    }

    /// Returns the number of completed entries.
    pub fn completed_len(&self) -> usize {
        self.completed
    }

    /// Returns declaration identities in the batch's current entry order.
    pub fn declaration_ids(&self) -> Vec<BlockId> {
        self.entries
            .iter()
            .map(|entry| entry.call.call_block_id)
            .collect()
    }

    /// Validates the completed-prefix/pending-suffix and identity invariants.
    pub fn validate(&self) -> Result<(), BatchError> {
        if self.completed > self.entries.len() {
            return Err(BatchError::InvalidPartition(format!(
                "completed count {} exceeds entry count {}",
                self.completed,
                self.entries.len()
            )));
        }
        let mut declarations = HashSet::with_capacity(self.entries.len());
        for entry in &self.entries {
            let declaration_id = entry.call.call_block_id;
            if !declarations.insert(declaration_id) {
                return Err(BatchError::DuplicateDeclaration(declaration_id));
            }
        }
        let mut all_ids = declarations.clone();
        for (index, entry) in self.entries.iter().enumerate() {
            let declaration_id = entry.call.call_block_id;
            match (index < self.completed, &entry.result) {
                (true, Some((result_id, result))) => {
                    if result.call_block_id != declaration_id {
                        return Err(BatchError::MismatchedCall {
                            expected: declaration_id,
                            actual: result.call_block_id,
                        });
                    }
                    if !all_ids.insert(*result_id) {
                        return Err(BatchError::DuplicateResultBlockId(*result_id));
                    }
                }
                (false, None) => {}
                (true, None) => {
                    return Err(BatchError::InvalidPartition(format!(
                        "completed entry {index} has no result"
                    )));
                }
                (false, Some(_)) => {
                    return Err(BatchError::InvalidPartition(format!(
                        "pending entry {index} already has a result"
                    )));
                }
            }
        }
        Ok(())
    }

    /// Installs a result at an absolute entry index and advances the prefix.
    /// A refused result leaves the batch unchanged and is handed back with
    /// the reason, so a caller can retry or report it without a copy.
    pub fn resolve_at(
        &mut self,
        index: usize,
        result_block_id: BlockId,
        mut result: ToolResultPayload,
    ) -> Result<(), RejectedToolResult> {
        if let Err(error) = self.check_resolve(index, result_block_id, &result) {
            return Err(RejectedToolResult { error, result });
        }
        let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
        notes.append(&mut result.notes);
        result.notes = notes;
        self.entries[index].result = Some((result_block_id, result));
        self.entries.swap(index, self.completed);
        self.completed += 1;
        Ok(())
    }

    fn check_resolve(
        &self,
        index: usize,
        result_block_id: BlockId,
        result: &ToolResultPayload,
    ) -> Result<(), BatchError> {
        self.validate()?;
        if index < self.completed || index >= self.entries.len() {
            return Err(BatchError::InvalidIndex {
                index,
                completed: self.completed,
                total: self.entries.len(),
            });
        }
        let expected = self.entries[index].call.call_block_id;
        if result.call_block_id != expected {
            return Err(BatchError::MismatchedCall {
                expected,
                actual: result.call_block_id,
            });
        }
        if self.entries[index].result.is_some() {
            return Err(BatchError::InvalidPartition(format!(
                "pending entry {index} already has a result"
            )));
        }
        if self.entries.iter().any(|entry| {
            entry.call.call_block_id == result_block_id
                || entry
                    .result
                    .as_ref()
                    .is_some_and(|(id, _)| *id == result_block_id)
        }) {
            return Err(BatchError::DuplicateResultBlockId(result_block_id));
        }
        Ok(())
    }

    /// Validates the invariants and that every entry has a result.
    pub fn validate_complete(&self) -> Result<(), BatchError> {
        self.validate()?;
        if self.completed != self.entries.len() {
            return Err(BatchError::Incomplete {
                completed: self.completed,
                total: self.entries.len(),
            });
        }
        Ok(())
    }

    /// Consumes a fully completed batch into result blocks in current order.
    pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
        if let Err(error) = self.validate_complete() {
            return Err((error, self));
        }
        Ok(self
            .entries
            .into_iter()
            .map(|entry| entry.result.expect("validated complete entry"))
            .collect())
    }
}

/// Context made available to tool batch processors.
#[non_exhaustive]
pub struct ProcessorContext<'a> {
    /// Turn identity for the active tool batch.
    pub turn_id: &'a TurnId,
    /// Model round that declared this batch.
    pub round_id: RoundId,
    /// Original declaration order, represented by stable block IDs. The batch's
    /// own entry order changes as results are resolved; this does not.
    pub declaration_order: &'a [BlockId],
    /// Cooperative cancellation and deadline control.
    pub control: &'a CallControl,
    /// The tools bound for this batch, in offer order, with their declared
    /// hints. The reference executor fixes them when it binds, so they stay
    /// the same for every processor of the batch. Empty unless set with
    /// [`ProcessorContext::with_tools`].
    pub tools: &'a [ToolDescription],
    /// The host's data for this run, passed through unchanged. `None` unless
    /// set with [`ProcessorContext::with_data`].
    pub data: Option<&'a ProcessorData>,
}
impl<'a> ProcessorContext<'a> {
    /// The context one processor run sees, with no bound tools and no host
    /// data.
    pub fn new(
        turn_id: &'a TurnId,
        round_id: RoundId,
        declaration_order: &'a [BlockId],
        control: &'a CallControl,
    ) -> Self {
        Self {
            turn_id,
            round_id,
            declaration_order,
            control,
            tools: &[],
            data: None,
        }
    }

    /// Sets the bound tools and their hints.
    pub fn with_tools(mut self, tools: &'a [ToolDescription]) -> Self {
        self.tools = tools;
        self
    }

    /// Sets the host's data for this run.
    pub fn with_data(mut self, data: &'a ProcessorData) -> Self {
        self.data = Some(data);
        self
    }

    /// The declared hints of the bound tool named `name`, or `None` when no
    /// bound tool has that name. The reference executor rejects calls to
    /// unbound names before the first processor runs, so every pending call
    /// it hands to a processor resolves here.
    pub fn hints(&self, name: &str) -> Option<&'a ToolHints> {
        self.tools
            .iter()
            .find(|tool| tool.definition.name == name)
            .map(|tool| &tool.hints)
    }

    /// The host's data when it is a `T`: `None` when no data is set or it
    /// holds another type.
    pub fn data<T: Any>(&self) -> Option<&'a T> {
        self.data.and_then(ProcessorData::get)
    }
}

/// Host data for one run, handed to every tool processor through
/// [`ProcessorContext::data`].
///
/// Processors belong to an executor that serves many runs, so state that
/// differs from run to run — a permission mode, the acting user — travels
/// here rather than in the processor. The host chooses the type; a host with
/// several values passes one struct of its own. Causa passes the value
/// through and never inspects or copies it, so a host whose state changes
/// during a run stores a shared handle (an `Arc` around a lock or an atomic)
/// and a processor reads the current value when it decides each call.
#[derive(Clone)]
pub struct ProcessorData(Arc<dyn Any + Send + Sync>);

impl ProcessorData {
    /// Wraps the host's value.
    pub fn new<T: Any + Send + Sync>(value: T) -> Self {
        Self(Arc::new(value))
    }

    /// The value when it is exactly a `T`, the type given to
    /// [`ProcessorData::new`]; `None` otherwise.
    pub fn get<T: Any>(&self) -> Option<&T> {
        self.0.downcast_ref()
    }
}

impl std::fmt::Debug for ProcessorData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProcessorData").finish_non_exhaustive()
    }
}

/// Failure to finish a processing phase. Per-call rejection is a result,
/// and should be recorded on the batch while returning `Ok(())`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProcessorError {
    /// The processor could not complete its phase.
    #[error("processor failed: {0}")]
    Failed(String),
}

/// A pre- or post-processing phase over one exclusively borrowed tool batch.
#[async_trait]
pub trait ToolBatchProcessor: Send + Sync {
    /// Processes the batch in place; errors leave its current materials with
    /// the caller and stop the chain.
    async fn process(
        &self,
        batch: &mut ToolBatch,
        ctx: &ProcessorContext<'_>,
    ) -> Result<(), ProcessorError>;
}

/// Invalid batch construction, completion, or partition state.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BatchError {
    /// A declaration appears more than once in a batch.
    #[error("duplicate declaration block id: {0:?}")]
    DuplicateDeclaration(BlockId),
    /// The requested absolute index is not in the pending suffix.
    #[error("index {index} is not pending (completed {completed}, total {total})")]
    #[non_exhaustive]
    InvalidIndex {
        /// Requested entry index.
        index: usize,
        /// Number of entries in the completed prefix.
        completed: usize,
        /// Total entry count.
        total: usize,
    },
    /// A result references a different declaration than its entry.
    #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
    #[non_exhaustive]
    MismatchedCall {
        /// Declaration identity expected by the entry.
        expected: BlockId,
        /// Declaration identity carried by the result.
        actual: BlockId,
    },
    /// A result's own block identity collides within the batch.
    #[error("duplicate result block ID: {0:?}")]
    DuplicateResultBlockId(BlockId),
    /// The completed prefix and pending suffix disagree with entry contents.
    #[error("invalid batch partition: {0}")]
    InvalidPartition(String),
    /// Not all entries have results.
    #[error("batch is incomplete: {completed} of {total} entries completed")]
    #[non_exhaustive]
    Incomplete {
        /// Number of completed entries.
        completed: usize,
        /// Total number of entries.
        total: usize,
    },
}

/// A result [`ToolBatch::resolve_at`] refused, returned with the reason.
#[derive(Debug, thiserror::Error)]
#[error("{error}")]
#[non_exhaustive]
pub struct RejectedToolResult {
    /// Why the batch refused the result.
    pub error: BatchError,
    /// The refused result, unchanged.
    pub result: ToolResultPayload,
}