causa_runtime/hook.rs
1//! The tool-use filter seam.
2//!
3//! `ToolUseHook` is THE extension point for the tool-use batch between
4//! model output and tool dispatch: `TurnRunner` calls it here, and the
5//! concrete filter policies (`DedupFilter`, `DenyAllFilter`,
6//! `FilterChain`) in this crate implement it directly. Defining the trait
7//! next to both its consumer (the driver) and its policies (the filters)
8//! keeps the seam, its only consumer, and its implementations together.
9//!
10//! ## Minimum invariant, not a policy
11//!
12//! This crate ships **no opinion** in the trait: the only built-in impl is
13//! `PassthroughHook` — a zero-sized type that admits every call unchanged.
14//! That is the literal absence of behavior, the minimum the trait requires
15//! to be callable.
16//!
17//! Specific filter policies (dedup by `(tool_name, arguments)`,
18//! approval-rewrites-amount, kill-switch denial, etc.) are host concerns;
19//! the driver applies whatever hook the caller plugged via
20//! `TurnRunner::with_hook(_, _, your_hook)`; `TurnRunner::new()` defaults
21//! to `PassthroughHook`.
22
23use async_trait::async_trait;
24
25use crate::config::UnknownOutcomePolicy;
26use causa_kernel::ToolResultPayload;
27use causa_kernel::{CallControl, ConversationId, RoundId, ToolCallId, ToolCallPayload, TurnId};
28
29// This trait is deliberately NOT a `causa_kernel::ports` item:
30// a port there is a host-facing contract third parties implement against
31// the facts crate alone. The hook's sole consumer is this crate's driver,
32// so the contract lives with the driver.
33
34/// One explicit per-call unknown-outcome decision —
35/// host decision / checkpoint data attached to a precomputed result whose
36/// status is `UnknownOutcome`, not a result envelope: the recorded result
37/// is committed verbatim either way. Where a decision set is a *new* host
38/// input (hook, `BatchDecision::Reject`, resume), entries may be omitted —
39/// the missing ones resolve through [`UnknownOutcomeConfig`](crate::config::UnknownOutcomeConfig)
40/// by the executed tool name. Where it is a checkpoint
41/// ([`PreparedApproval`](crate::driver::PreparedApproval)), it must
42/// exactly cover the saved `UnknownOutcome` results.
43#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
44pub struct UnknownDecision {
45 /// The precomputed result's call id — must be one of the same
46 /// decision's rejected results, and its status must be
47 /// `UnknownOutcome`.
48 pub call_id: ToolCallId,
49 /// The fixed action for that result.
50 pub policy: UnknownOutcomePolicy,
51}
52
53/// Context supplied to every hook invocation.
54///
55/// `control: &CallControl` exposes the bounded attempt / call cancellation
56/// so a filter can `select!` on user-approval responses.
57#[derive(Debug)]
58pub struct HookCtx<'a> {
59 /// The turn whose batch is being filtered.
60 pub turn_id: &'a TurnId,
61 /// `Some` on the conversation entries, `None` for bare turns.
62 pub conversation_id: Option<&'a ConversationId>,
63 /// The round that emitted the batch.
64 pub round_id: RoundId,
65 /// Attempt/call-scoped control for `select!`-ing on approval
66 /// responses or deadlines.
67 pub control: &'a CallControl,
68}
69
70/// Result of a hook pass.
71///
72/// Invariant: `rejected` must reuse the original `payload.call_id` from
73/// the input batch; forging a new id would make `append_tool_results`
74/// reject the entry with `UnpairedToolResult`. `to_execute` may rewrite
75/// `arguments` (open `FilterResult` — approval can rewrite, defer, split).
76///
77/// `rejected` carries the recorded results only. A host precomputing an
78/// `UnknownOutcome` result may pin its continuation action in
79/// `unknown_decisions`; entries may be omitted and the driver then resolves
80/// through its unknown-outcome configuration by the executed tool name.
81/// Rejections with any other status take no action and need no entry.
82#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
83pub struct HookOutcome {
84 /// Calls that pass the hook and reach the executor (arguments may
85 /// have been rewritten).
86 pub to_execute: Vec<ToolCallPayload>,
87 /// Calls the hook rejected; each result must reuse the input's
88 /// `call_id`.
89 pub rejected: Vec<ToolResultPayload>,
90 /// Explicit unknown-outcome actions for precomputed results whose
91 /// status is `UnknownOutcome`. Optional per entry; must not point at
92 /// `to_execute`, foreign ids, or results with any other status.
93 pub unknown_decisions: Vec<UnknownDecision>,
94}
95
96impl HookOutcome {
97 /// Admit every call unchanged — no rejections.
98 pub fn passthrough(calls: Vec<ToolCallPayload>) -> Self {
99 Self {
100 to_execute: calls,
101 rejected: Vec::new(),
102 unknown_decisions: Vec::new(),
103 }
104 }
105
106 /// Builder: pin an explicit unknown-outcome action for one precomputed
107 /// result (its `call_id`, which must appear in `rejected` with status
108 /// `UnknownOutcome`).
109 pub fn with_unknown_decision(
110 mut self,
111 call_id: ToolCallId,
112 policy: UnknownOutcomePolicy,
113 ) -> Self {
114 self.unknown_decisions
115 .push(UnknownDecision { call_id, policy });
116 self
117 }
118}
119
120/// The tool-use filter seam this component exposes.
121///
122/// Filters in `causa_runtime::filter` (`FilterChain` and friends)
123/// implement this trait. The driver calls `hook.apply(calls, ctx).await`
124/// between receiving the model's `ToolCallPayload` batch and dispatching
125/// it to `ToolExecutor`.
126#[async_trait]
127pub trait ToolUseHook: Send + Sync {
128 /// Filter the model-emitted batch between receipt and dispatch:
129 /// return what to execute and what to reject.
130 async fn apply(&self, calls: Vec<ToolCallPayload>, ctx: &HookCtx<'_>) -> HookOutcome;
131}
132
133/// Zero-sized hook that admits every call unchanged — the literal
134/// absence of behavior, not a policy.
135///
136/// `TurnRunner::new()` defaults to this hook: callers who want a filter
137/// chain opt in via `TurnRunner::with_hook(_, _, filter_chain)`.
138/// Concrete filter policies (dedup, approval, kill-switch) are host
139/// concerns and live in `causa_runtime::filter` or beyond.
140#[derive(Debug, Default, Clone, Copy)]
141pub struct PassthroughHook;
142
143#[async_trait]
144impl ToolUseHook for PassthroughHook {
145 async fn apply(&self, calls: Vec<ToolCallPayload>, _ctx: &HookCtx<'_>) -> HookOutcome {
146 HookOutcome::passthrough(calls)
147 }
148}