Skip to main content

kian_plugin/hooks/
registry.rs

1//! The hook-scoped tier-0 registry (PLUGIN-SPEC §5.3, ADR-028 R13).
2//!
3//! The existing `Ctx` dispatch keys handlers by kind and `TypeId` and
4//! carries no plugin/hook/session metadata, so the hook bus keeps its own
5//! registry here. Registration is reversible through the existing
6//! [`Disposer`](crate::ctx::Disposer) — disposal order is
7//! registration-reverse, identical to today's semantics. Raw
8//! `Ctx::on`/`on_waterfall`/`on_bail` stay exactly as they are for
9//! non-hook typed events.
10//!
11//! [`register`]/[`register_scoped`] are free functions over the
12//! process-global registry (§5.3's sketch); [`Registry`] instances are
13//! also constructible directly so [`HookBus`](super::bus::HookBus) tests
14//! — and later the assembly — can hold isolated registries.
15
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::sync::{Arc, OnceLock, RwLock};
18
19use futures::future::BoxFuture;
20use kian_core::model::SessionId;
21
22use super::grants::GrantSet;
23use super::ids::HookId;
24use super::views::{
25    AdmitDraft, AdmitReceiptView, FrameInfo, RecoveryView, RequestMeta, ResponseView, SettleView,
26    ToolCallView, ToolPostView,
27};
28use crate::ctx::Disposer;
29
30/// Registration scope (§1 "Session scope vs server scope"): a tier-0
31/// registration made at process start is **server scope** (applies to
32/// every session); a `register_scoped` registration applies only to
33/// sessions whose effective set contains it — at tier 0, approximated by
34/// the dispatch's target session id (K5: exactly two variants in v1).
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum SessionScope {
37    Server,
38    Session(SessionId),
39}
40
41impl SessionScope {
42    /// Whether a dispatch with this frame identity falls inside the scope.
43    /// A dispatch with no frame identity can only match server scope —
44    /// firing a session-scoped handler without knowing the session would
45    /// be a guess, and the contract forbids implicit identity (R11).
46    fn matches(&self, frame: Option<&FrameInfo>) -> bool {
47        match self {
48            SessionScope::Server => true,
49            SessionScope::Session(scoped) => frame.is_some_and(|f| f.session == *scoped),
50        }
51    }
52}
53
54/// A tier-0 handler registration's identity (§5.3's sketch, verbatim).
55#[derive(Debug, Clone)]
56pub struct HandlerId {
57    pub plugin: &'static str,
58    pub hook: HookId,
59    pub grants: GrantSet,
60    /// Dispatch order within the hook; ties break by declaration index
61    /// (§8.3.1 — the sidecar `[plugin].order`/name tiebreak is the
62    /// sidecar tier's own rule).
63    pub order: i32,
64}
65
66/// One dispatched payload, wrapping the §3.2 view of the hook being
67/// dispatched. Handlers receive the same Rust struct the tier-1 ABI
68/// serializes, so both tiers observe identical fields (§1 "View").
69#[derive(Debug, Clone)]
70pub enum HookPayload {
71    AdmitDraft(AdmitDraft),
72    AdmitReceipt(AdmitReceiptView),
73    TurnRequest(RequestMeta),
74    TurnResponse(ResponseView),
75    ToolPre(ToolCallView),
76    ToolPost(ToolPostView),
77    Recovery(RecoveryView),
78    Settle(SettleView),
79}
80
81impl HookPayload {
82    /// The hook this payload dispatches to.
83    pub fn hook(&self) -> HookId {
84        match self {
85            HookPayload::AdmitDraft(_) => HookId::AdmitPre,
86            HookPayload::AdmitReceipt(_) => HookId::AdmitPost,
87            HookPayload::TurnRequest(_) => HookId::TurnRequest,
88            HookPayload::TurnResponse(_) => HookId::TurnResponse,
89            HookPayload::ToolPre(_) => HookId::ToolPre,
90            HookPayload::ToolPost(_) => HookId::ToolPost,
91            HookPayload::Recovery(_) => HookId::RecoverDecided,
92            HookPayload::Settle(_) => HookId::SettlePre,
93        }
94    }
95
96    /// The embedded dispatch identity (wire-skipped; §7.3 frame metadata).
97    pub fn frame(&self) -> Option<&FrameInfo> {
98        match self {
99            HookPayload::AdmitDraft(d) => d.frames.first(),
100            HookPayload::AdmitReceipt(v) => v.frame.as_ref(),
101            HookPayload::TurnRequest(v) => v.frame.as_ref(),
102            HookPayload::TurnResponse(v) => v.frame.as_ref(),
103            HookPayload::ToolPre(v) => v.frame.as_ref(),
104            HookPayload::ToolPost(v) => v.frame.as_ref(),
105            HookPayload::Recovery(v) => v.frame.as_ref(),
106            HookPayload::Settle(v) => v.frame.as_ref(),
107        }
108    }
109}
110
111/// A tier-0 handler's answer, shaped by the §3.3 reply vocabulary. The
112/// `Err` variant mirrors the ABI's closed code set (§7.2): `deadline` and
113/// `crashed` are self-declared unreachability, everything else is a
114/// speech defect (§11.1).
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub enum HookReply {
117    Ack { note: Option<String> },
118    FlowNext,
119    FlowStop { reason: String },
120    BailNone,
121    BailDeny { reason: String },
122    Err { code: ReplyErrCode, message: String },
123}
124
125/// The closed `err.code` set of the ABI (§7.2). A code outside the set is
126/// itself `malformed`.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum ReplyErrCode {
129    Deadline,
130    Crashed,
131    Malformed,
132    Unauthorized,
133    UnsupportedHook,
134    ProtocolViolation,
135}
136
137impl ReplyErrCode {
138    pub fn as_str(self) -> &'static str {
139        match self {
140            ReplyErrCode::Deadline => "deadline",
141            ReplyErrCode::Crashed => "crashed",
142            ReplyErrCode::Malformed => "malformed",
143            ReplyErrCode::Unauthorized => "unauthorized",
144            ReplyErrCode::UnsupportedHook => "unsupported_hook",
145            ReplyErrCode::ProtocolViolation => "protocol_violation",
146        }
147    }
148}
149
150/// A tier-0 hook handler: an async function over the dispatched payload.
151pub type HookFn = Arc<dyn for<'a> Fn(&'a HookPayload) -> BoxFuture<'a, HookReply> + Send + Sync>;
152
153/// The hook registry: a list of reversible registrations, snapshotted per
154/// dispatch in §8.3 order.
155#[derive(Default)]
156pub struct Registry {
157    next_id: AtomicU64,
158    entries: RwLock<Vec<Option<Arc<Entry>>>>,
159}
160
161/// One live registration.
162pub(crate) struct Entry {
163    pub(crate) id: u64,
164    pub(crate) handler: HandlerId,
165    pub(crate) scope: SessionScope,
166    pub(crate) f: HookFn,
167}
168
169impl std::fmt::Debug for Entry {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        f.debug_struct("Entry")
172            .field("id", &self.id)
173            .field("plugin", &self.handler.plugin)
174            .field("hook", &self.handler.hook)
175            .field("scope", &self.scope)
176            .finish()
177    }
178}
179
180impl Registry {
181    pub fn new() -> Self {
182        Self::default()
183    }
184
185    /// Registers a server-scope handler (applies to every session, §5.3)
186    /// and returns the [`Disposer`] removing exactly this registration.
187    pub fn register(self: &Arc<Self>, handler: HandlerId, f: HookFn) -> Disposer {
188        self.register_scoped(SessionScope::Server, handler, f)
189    }
190
191    /// Registers a session-scoped handler (§5.3): it participates only in
192    /// dispatches whose frame targets that session.
193    pub fn register_scoped(
194        self: &Arc<Self>,
195        scope: SessionScope,
196        handler: HandlerId,
197        f: HookFn,
198    ) -> Disposer {
199        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
200        let entry = Arc::new(Entry {
201            id,
202            handler,
203            scope,
204            f,
205        });
206        {
207            let mut entries = self
208                .entries
209                .write()
210                .expect("kian-plugin: hook registry lock poisoned");
211            entries.push(Some(Arc::clone(&entry)));
212        }
213        let registry = Arc::clone(self);
214        Disposer::from_fn(move || {
215            let mut entries = registry
216                .entries
217                .write()
218                .expect("kian-plugin: hook registry lock poisoned");
219            // Remove only this registration's own slot — a stale disposer
220            // must never unregister a replacement.
221            for slot in entries.iter_mut() {
222                if let Some(live) = slot
223                    && live.id == id
224                {
225                    *slot = None;
226                }
227            }
228        })
229    }
230
231    /// The handlers subscribed to `hook` whose scope matches the
232    /// dispatch's frame identity, in §8.3 tier-0 order: ascending
233    /// `order`, tiebroken by declaration index.
234    pub(crate) fn snapshot(&self, hook: &HookId, frame: Option<&FrameInfo>) -> Vec<Arc<Entry>> {
235        let entries = self
236            .entries
237            .read()
238            .expect("kian-plugin: hook registry lock poisoned");
239        let mut matched: Vec<(i32, usize, Arc<Entry>)> = entries
240            .iter()
241            .enumerate()
242            .filter_map(|(index, slot)| {
243                let entry = slot.as_ref()?;
244                (entry.handler.hook == *hook && entry.scope.matches(frame))
245                    .then(|| (entry.handler.order, index, Arc::clone(entry)))
246            })
247            .collect();
248        matched.sort_by_key(|(order, index, _)| (*order, *index));
249        matched.into_iter().map(|(_, _, entry)| entry).collect()
250    }
251}
252
253static GLOBAL: OnceLock<Arc<Registry>> = OnceLock::new();
254
255/// The process-global registry backing the §5.3 free functions.
256pub fn global_registry() -> &'static Arc<Registry> {
257    GLOBAL.get_or_init(|| Arc::new(Registry::new()))
258}
259
260/// Server-scope registration over the process-global registry (§5.3).
261pub fn register(handler: HandlerId, f: HookFn) -> Disposer {
262    global_registry().register(handler, f)
263}
264
265/// Session-scoped registration over the process-global registry (§5.3).
266pub fn register_scoped(scope: SessionScope, handler: HandlerId, f: HookFn) -> Disposer {
267    global_registry().register_scoped(scope, handler, f)
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use std::sync::Mutex;
274
275    use futures::FutureExt;
276
277    use super::super::grants::Grant;
278
279    fn recording_handler(
280        plugin: &'static str,
281        grants: &[Grant],
282        reply: HookReply,
283        log: Arc<Mutex<Vec<String>>>,
284    ) -> (HandlerId, HookFn) {
285        let handler = HandlerId {
286            plugin,
287            hook: HookId::ToolPre,
288            grants: GrantSet::from_grants(grants.iter().copied()),
289            order: 0,
290        };
291        let f: HookFn = Arc::new(move |_payload: &HookPayload| {
292            let log = Arc::clone(&log);
293            let reply = reply.clone();
294            async move {
295                log.lock().unwrap().push(plugin.to_string());
296                reply
297            }
298            .boxed()
299        });
300        (handler, f)
301    }
302
303    fn tool_pre_payload(frame: Option<FrameInfo>) -> HookPayload {
304        HookPayload::ToolPre(ToolCallView {
305            call_id: "call_1".to_string(),
306            name: "exec".to_string(),
307            iteration: 1,
308            arguments: serde_json::json!({}),
309            arguments_bytes: 2,
310            arguments_sha256: "ab".to_string(),
311            arguments_truncated: false,
312            permission: super::super::views::PermissionView {
313                evaluated: "allow".to_string(),
314                policy: "default".to_string(),
315                matched: "exec".to_string(),
316                reason: None,
317            },
318            surface: "react".to_string(),
319            frame,
320        })
321    }
322
323    #[test]
324    fn disposer_reverses_registration() {
325        let registry = Arc::new(Registry::new());
326        let log = Arc::new(Mutex::new(Vec::new()));
327
328        let (id_a, f_a) = recording_handler(
329            "a",
330            &[Grant::ObserveTool],
331            HookReply::Ack { note: None },
332            Arc::clone(&log),
333        );
334        let (id_b, f_b) = recording_handler(
335            "b",
336            &[Grant::ObserveTool],
337            HookReply::Ack { note: None },
338            Arc::clone(&log),
339        );
340        let keep_a = registry.register(id_a, f_a);
341        let keep_b = registry.register(id_b, f_b);
342
343        // Merged disposal unwinds in reverse registration order (the
344        // existing Disposer semantics): `later.extend` runs the later
345        // registration's teardown first.
346        let merged = Disposer::new().extend(keep_a).extend(keep_b);
347        assert_eq!(registry.snapshot(&HookId::ToolPre, None).len(), 2);
348        merged.dispose();
349        assert!(
350            registry.snapshot(&HookId::ToolPre, None).is_empty(),
351            "disposal removes exactly its own registrations"
352        );
353
354        // A stale disposer never unregisters a replacement (the same
355        // guard `Ctx::provide` carries).
356        let (id_c, f_c) = recording_handler(
357            "c",
358            &[Grant::ObserveTool],
359            HookReply::Ack { note: None },
360            Arc::clone(&log),
361        );
362        let stale = {
363            let (id_x, f_x) = recording_handler(
364                "x",
365                &[Grant::ObserveTool],
366                HookReply::Ack { note: None },
367                Arc::clone(&log),
368            );
369            registry.register(id_x, f_x)
370        };
371        let _keep_c = registry.register(id_c, f_c);
372        stale.dispose();
373        assert_eq!(
374            registry.snapshot(&HookId::ToolPre, None).len(),
375            1,
376            "the stale disposer removed its own slot only"
377        );
378    }
379
380    #[tokio::test]
381    async fn scoped_registration_is_session_filtered() {
382        let registry = Arc::new(Registry::new());
383        let hits = Arc::new(Mutex::new(Vec::new()));
384
385        let session_a: SessionId =
386            serde_json::from_str("\"0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b\"").unwrap();
387        let session_b: SessionId =
388            serde_json::from_str("\"1f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b\"").unwrap();
389
390        let scoped_hits = Arc::clone(&hits);
391        let _keep_scoped = registry.register_scoped(
392            SessionScope::Session(session_a),
393            HandlerId {
394                plugin: "scoped",
395                hook: HookId::ToolPre,
396                grants: GrantSet::from_grants([Grant::ObserveTool]),
397                order: 0,
398            },
399            Arc::new(move |_payload: &HookPayload| {
400                let hits = Arc::clone(&scoped_hits);
401                async move {
402                    hits.lock().unwrap().push("scoped".to_string());
403                    HookReply::Ack { note: None }
404                }
405                .boxed()
406            }),
407        );
408        let server_hits = Arc::clone(&hits);
409        let _keep_server = registry.register(
410            HandlerId {
411                plugin: "server",
412                hook: HookId::ToolPre,
413                grants: GrantSet::from_grants([Grant::ObserveTool]),
414                order: 0,
415            },
416            Arc::new(move |_payload: &HookPayload| {
417                let hits = Arc::clone(&server_hits);
418                async move {
419                    hits.lock().unwrap().push("server".to_string());
420                    HookReply::Ack { note: None }
421                }
422                .boxed()
423            }),
424        );
425
426        // Dispatch at session B: only the server-scope handler fires.
427        let payload = tool_pre_payload(Some(FrameInfo::new(session_b)));
428        for entry in registry.snapshot(&payload.hook(), payload.frame()) {
429            (entry.f)(&payload).await;
430        }
431        assert_eq!(*hits.lock().unwrap(), vec!["server".to_string()]);
432
433        // Dispatch at session A: both fire — scoped was declared first, so
434        // the declaration-index tiebreak puts it first (§8.3.1).
435        hits.lock().unwrap().clear();
436        let payload = tool_pre_payload(Some(FrameInfo::new(session_a)));
437        for entry in registry.snapshot(&payload.hook(), payload.frame()) {
438            (entry.f)(&payload).await;
439        }
440        assert_eq!(
441            *hits.lock().unwrap(),
442            vec!["scoped".to_string(), "server".to_string()]
443        );
444
445        // A dispatch with no frame identity matches server scope only —
446        // never a guess at the session (R11).
447        hits.lock().unwrap().clear();
448        let payload = tool_pre_payload(None);
449        for entry in registry.snapshot(&payload.hook(), payload.frame()) {
450            (entry.f)(&payload).await;
451        }
452        assert_eq!(*hits.lock().unwrap(), vec!["server".to_string()]);
453    }
454}