chio-kernel 0.1.2

Chio runtime kernel: capability validation, guard evaluation, receipt signing
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
//! Provider-fabric verdict shim.
//!
//! Wires the provider-agnostic [`chio_tool_call_fabric`] crate into the kernel
//! via a thin conversion layer. Lifts a [`ToolInvocation`] into a kernel
//! [`ToolCallRequest`] (when paired with the surrounding capability context)
//! and lowers a kernel [`ToolCallResponse`] into a fabric [`VerdictResult`].
//! The shim is a single conversion point so the fabric vocabulary never leaks
//! into the kernel's internals.

use chio_core::canonical::canonical_json_bytes;
use chio_core::session::OperationTerminalState;
use chio_tool_call_fabric::{DenyReason, ProviderId, ReceiptId, ToolInvocation, VerdictResult};

use crate::runtime::{ToolCallRequest, ToolCallResponse, Verdict};
use crate::{AgentId, ServerId};
use chio_core::capability::token::CapabilityToken;

/// Errors surfaced when adapting fabric types into the kernel's MCP path.
///
/// The shim is conversion-only; the underlying MCP pipeline still owns its
/// own [`crate::KernelError`] surface. This enum is scoped to the bytes-to-
/// JSON translation step that bridges the fabric's canonical-JSON argument
/// payload into [`serde_json::Value`].
#[derive(Debug, thiserror::Error)]
pub enum ProviderVerdictError {
    /// The fabric arguments payload was not valid JSON. Fabric promises
    /// canonical-JSON bytes (RFC 8785); a parse failure here is a contract
    /// violation by the upstream adapter.
    #[error("fabric arguments payload is not valid JSON: {0}")]
    InvalidArguments(#[source] serde_json::Error),
}

/// Build a [`ToolCallRequest`] from a fabric [`ToolInvocation`] plus the
/// surrounding kernel context (capability token, calling agent, target tool
/// server). All policy decisions remain with `evaluate_tool_call*`; this
/// helper only translates the wire shape.
///
/// `request_id` defaults to `invocation.provenance.request_id` so the
/// upstream provider's request id flows into the kernel verdict and into the
/// resulting receipt without a second round of bookkeeping.
pub fn build_tool_call_request(
    invocation: &ToolInvocation,
    capability: CapabilityToken,
    agent_id: AgentId,
    server_id: ServerId,
) -> Result<ToolCallRequest, ProviderVerdictError> {
    let arguments = if invocation.arguments.is_empty() {
        serde_json::Value::Null
    } else {
        serde_json::from_slice(&invocation.arguments)
            .map_err(ProviderVerdictError::InvalidArguments)?
    };

    Ok(ToolCallRequest {
        request_id: invocation.provenance.request_id.clone(),
        capability,
        tool_name: invocation.tool_name.clone(),
        server_id,
        agent_id,
        arguments,
        dpop_proof: None,
        execution_nonce: None,
        governed_intent: None,
        approval_token: None,
        approval_tokens: Vec::new(),
        threshold_approval_proposal: None,
        supplemental_authorization: None,
        model_metadata: None,
        federated_origin_kernel_id: None,
    })
}

/// Lower a kernel [`ToolCallResponse`] into a fabric [`VerdictResult`].
///
/// The mapping is structural and lossless within the fabric's vocabulary:
///
/// - `Verdict::Allow` -> `VerdictResult::Allow { redactions: [], receipt_id }`
/// - `Verdict::Deny` (and the non-allow terminal variants) ->
///   `VerdictResult::Deny { reason, receipt_id }`
/// - `Verdict::PendingApproval` -> `VerdictResult::Deny { reason, receipt_id }`
///   so callers fail-closed if they ignore the approval channel. The fabric
///   verdict vocabulary has no pending state, so an approval-gated outcome
///   maps to a denial here.
///
/// Redactions are emitted as an empty list: the fabric verdict does not
/// carry data-guard redaction detail.
#[must_use]
pub fn verdict_result_from_response(
    invocation: &ToolInvocation,
    response: &ToolCallResponse,
) -> VerdictResult {
    let receipt_id = ReceiptId(response.receipt.id.clone());
    match response.verdict {
        Verdict::Allow if matches!(response.terminal_state, OperationTerminalState::Completed) => {
            VerdictResult::Allow {
                redactions: Vec::new(),
                receipt_id,
            }
        }
        Verdict::Allow => VerdictResult::Deny {
            reason: DenyReason::PolicyDeny {
                rule_id: "kernel.execution_nonce_preflight".to_string(),
            },
            receipt_id,
        },
        Verdict::Deny => VerdictResult::Deny {
            reason: classify_deny_reason(invocation, response),
            receipt_id,
        },
        Verdict::PendingApproval => VerdictResult::Deny {
            reason: DenyReason::PolicyDeny {
                rule_id: "kernel.pending_approval".to_string(),
            },
            receipt_id,
        },
    }
}

/// Pick a [`DenyReason`] variant from the kernel response.
///
/// The kernel's deny pathway encodes its rationale as a free-form
/// [`ToolCallResponse::reason`] string. We surface this as
/// [`DenyReason::PolicyDeny`] with the kernel's reason as the `rule_id`,
/// preserving information for auditors without inventing a richer mapping.
/// Specialized variants (`CapabilityExpired`, `BudgetExceeded`, etc.) would
/// require kernel-side classification; this shim maps every deny to the
/// single [`DenyReason::PolicyDeny`] form.
fn classify_deny_reason(_invocation: &ToolInvocation, response: &ToolCallResponse) -> DenyReason {
    let detail = response
        .reason
        .clone()
        .unwrap_or_else(|| "kernel.deny".to_string());
    DenyReason::PolicyDeny { rule_id: detail }
}

/// Stable canonical-JSON byte form of a [`ToolInvocation`].
///
/// Adapters frequently need a stable hash of the invocation for telemetry
/// and replay correlation. The kernel exposes its canonical-JSON helper
/// already; this is a typed wrapper so callers do not import the helper
/// directly. The wrapped helper returns the workspace's own
/// [`chio_core::error::Error`]; callers that already work in that error
/// space can map straight through `?`.
pub fn canonical_invocation_bytes(
    invocation: &ToolInvocation,
) -> chio_core::error::Result<Vec<u8>> {
    canonical_json_bytes(invocation)
}

/// Marker constant tying the shim to the fabric crate version it was built
/// against. Used by the workspace's drift checks to flag when the fabric
/// trait surface evolves without the kernel shim being revisited.
pub const FABRIC_SHIM_PROVIDER_LANES: &[ProviderId] = &[
    ProviderId::OpenAi,
    ProviderId::Anthropic,
    ProviderId::Bedrock,
];

impl crate::ChioKernel {
    /// Compute a fabric [`VerdictResult`] for a provider-native tool
    /// invocation by routing through the existing MCP verdict path.
    ///
    /// The shim builds a [`ToolCallRequest`] from the supplied invocation
    /// plus the surrounding capability context, calls
    /// [`crate::ChioKernel::evaluate_tool_call_blocking`], and lowers the
    /// kernel response into a fabric verdict via
    /// [`verdict_result_from_response`].
    ///
    /// The kernel-side fabric integration point. Adapters call this method
    /// with an invocation already lifted from the upstream wire format and a
    /// capability token resolved from their authentication path.
    pub fn verdict_for_provider_invocation(
        &self,
        invocation: &ToolInvocation,
        capability: CapabilityToken,
        agent_id: AgentId,
        server_id: ServerId,
    ) -> Result<VerdictResult, crate::KernelError> {
        let request = build_tool_call_request(invocation, capability, agent_id, server_id)
            .map_err(|e| {
                crate::KernelError::Internal(format!(
                    "fabric arguments could not be lowered into kernel JSON: {e}"
                ))
            })?;
        let response = self.evaluate_tool_call_blocking(&request)?;
        Ok(verdict_result_from_response(invocation, &response))
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use chio_core::receipt::{body::ChioReceipt, decision::Decision, decision::ToolCallAction};
    use chio_core::session::OperationTerminalState;
    use chio_tool_call_fabric::{Principal, ProvenanceStamp};
    use std::time::{Duration, SystemTime};

    fn sample_invocation() -> ToolInvocation {
        ToolInvocation {
            provider: ProviderId::OpenAi,
            tool_name: "search_web".to_string(),
            arguments: br#"{"query":"chio"}"#.to_vec(),
            provenance: ProvenanceStamp {
                provider: ProviderId::OpenAi,
                request_id: "call_abc123".to_string(),
                api_version: "responses.2026-04-25".to_string(),
                principal: Principal::OpenAiOrg {
                    org_id: "org_123".to_string(),
                },
                received_at: SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000),
            },
        }
    }

    fn synthetic_receipt(id: &str, decision: Decision) -> ChioReceipt {
        // Build a minimal signed receipt for the conversion tests. These
        // tests only exercise the structural mapping from kernel verdict
        // to fabric verdict; signature verification is covered by the
        // kernel's own receipt tests.
        let kp = chio_core::crypto::Keypair::generate();
        let body = chio_core::receipt::body::ChioReceiptBody {
            id: id.to_string(),
            timestamp: 1_700_000_000,
            capability_id: "cap-test".to_string(),
            tool_server: "srv-test".to_string(),
            tool_name: "search_web".to_string(),
            action: ToolCallAction {
                parameters: serde_json::json!({"query": "chio"}),
                parameter_hash: "0".repeat(64),
            },
            decision: Some(decision),
            receipt_kind: chio_core::receipt::kinds::ReceiptKind::MediatedDecision,
            boundary_class: chio_core::receipt::kinds::BoundaryClass::Prevent,
            observation_outcome: None,
            tool_origin: chio_core::receipt::kinds::ToolOrigin::CallerExecuted,
            redaction_mode: chio_core::receipt::kinds::RedactionMode::None,
            actor_chain: Vec::new(),
            content_hash: "0".repeat(64),
            policy_hash: "0".repeat(64),
            evidence: Vec::new(),
            metadata: None,
            trust_level: Default::default(),
            tenant_id: None,
            kernel_key: kp.public_key(),
            bbs_projection_version: None,
        };
        ChioReceipt::sign(body, &kp).unwrap()
    }

    fn allow_response() -> ToolCallResponse {
        ToolCallResponse {
            request_id: "call_abc123".to_string(),
            verdict: Verdict::Allow,
            output: None,
            reason: None,
            terminal_state: OperationTerminalState::Completed,
            receipt: synthetic_receipt("rcpt_allow", Decision::Allow),
            execution_nonce: None,
        }
    }

    fn deny_response(reason: &str) -> ToolCallResponse {
        let dec = Decision::Deny {
            reason: reason.to_string(),
            guard: "policy.deny".to_string(),
        };
        ToolCallResponse {
            request_id: "call_abc123".to_string(),
            verdict: Verdict::Deny,
            output: None,
            reason: Some(reason.to_string()),
            terminal_state: OperationTerminalState::Completed,
            receipt: synthetic_receipt("rcpt_deny", dec),
            execution_nonce: None,
        }
    }

    fn pending_response() -> ToolCallResponse {
        ToolCallResponse {
            request_id: "call_abc123".to_string(),
            verdict: Verdict::PendingApproval,
            output: None,
            reason: Some("approval pending".to_string()),
            terminal_state: OperationTerminalState::Incomplete {
                reason: "approval pending".to_string(),
            },
            receipt: synthetic_receipt("rcpt_pending", Decision::Allow),
            execution_nonce: None,
        }
    }

    fn nonce_preflight_response() -> ToolCallResponse {
        ToolCallResponse {
            request_id: "call_abc123".to_string(),
            verdict: Verdict::Allow,
            output: None,
            reason: None,
            terminal_state: OperationTerminalState::Incomplete {
                reason: "execution nonce preflight requires retry with presented nonce".to_string(),
            },
            receipt: synthetic_receipt("rcpt_preflight", Decision::Allow),
            execution_nonce: None,
        }
    }

    #[test]
    fn provider_verdict_allow_maps_to_fabric_allow() {
        let inv = sample_invocation();
        let resp = allow_response();
        let v = verdict_result_from_response(&inv, &resp);
        match v {
            VerdictResult::Allow {
                redactions,
                receipt_id,
            } => {
                assert!(redactions.is_empty());
                assert_eq!(receipt_id, ReceiptId(resp.receipt.id.clone()));
            }
            other => panic!("expected allow, got {other:?}"),
        }
    }

    #[test]
    fn provider_verdict_deny_carries_kernel_reason_as_rule_id() {
        let inv = sample_invocation();
        let resp = deny_response("budget exhausted");
        let v = verdict_result_from_response(&inv, &resp);
        match v {
            VerdictResult::Deny { reason, receipt_id } => {
                assert_eq!(receipt_id, ReceiptId(resp.receipt.id.clone()));
                match reason {
                    DenyReason::PolicyDeny { rule_id } => {
                        assert_eq!(rule_id, "budget exhausted");
                    }
                    other => panic!("expected policy_deny, got {other:?}"),
                }
            }
            other => panic!("expected deny, got {other:?}"),
        }
    }

    #[test]
    fn provider_verdict_deny_falls_back_to_default_rule_id_when_reason_missing() {
        let inv = sample_invocation();
        let mut resp = deny_response("unused");
        resp.reason = None;
        let v = verdict_result_from_response(&inv, &resp);
        let VerdictResult::Deny { reason, .. } = v else {
            panic!("expected deny");
        };
        let DenyReason::PolicyDeny { rule_id } = reason else {
            panic!("expected policy_deny");
        };
        assert_eq!(rule_id, "kernel.deny");
    }

    #[test]
    fn provider_verdict_pending_approval_fails_closed() {
        let inv = sample_invocation();
        let resp = pending_response();
        let v = verdict_result_from_response(&inv, &resp);
        match v {
            VerdictResult::Deny { reason, .. } => match reason {
                DenyReason::PolicyDeny { rule_id } => {
                    assert_eq!(rule_id, "kernel.pending_approval");
                }
                other => panic!("expected policy_deny for pending, got {other:?}"),
            },
            other => panic!("expected deny for pending approval, got {other:?}"),
        }
    }

    #[test]
    fn provider_verdict_nonce_preflight_fails_closed() {
        let inv = sample_invocation();
        let resp = nonce_preflight_response();
        let v = verdict_result_from_response(&inv, &resp);
        match v {
            VerdictResult::Deny { reason, receipt_id } => {
                assert_eq!(receipt_id, ReceiptId(resp.receipt.id.clone()));
                match reason {
                    DenyReason::PolicyDeny { rule_id } => {
                        assert_eq!(rule_id, "kernel.execution_nonce_preflight");
                    }
                    other => panic!("expected policy_deny for nonce preflight, got {other:?}"),
                }
            }
            other => panic!("expected deny for nonce preflight, got {other:?}"),
        }
    }

    #[test]
    fn provider_verdict_receipt_id_round_trips() {
        let inv = sample_invocation();
        let resp = allow_response();
        let v = verdict_result_from_response(&inv, &resp);
        let json = serde_json::to_string(&v).unwrap();
        let back: VerdictResult = serde_json::from_str(&json).unwrap();
        assert_eq!(v, back);
    }

    #[test]
    fn provider_verdict_canonical_invocation_bytes_are_stable() {
        let inv = sample_invocation();
        let a = canonical_invocation_bytes(&inv).unwrap();
        let b = canonical_invocation_bytes(&inv).unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn provider_verdict_known_provider_lanes_are_three() {
        // Sanity check that the provider-id constant tracks the fabric.
        assert_eq!(FABRIC_SHIM_PROVIDER_LANES.len(), 3);
    }
}