Skip to main content

ChioKernel

Struct ChioKernel 

Source
pub struct ChioKernel { /* private fields */ }
Expand description

The Chio Runtime Kernel.

This is the central component of the Chio protocol. It validates capabilities, runs guards, dispatches tool calls, and signs receipts.

The kernel is designed to be the sole trusted mediator. It never exposes its signing key, address, or internal state to the agent.

Implementations§

Source§

impl ChioKernel

Source

pub fn open_session( &self, agent_id: AgentId, issued_capabilities: Vec<CapabilityToken>, ) -> SessionId

Source

pub fn open_session_with_id( &self, session_id: SessionId, agent_id: AgentId, issued_capabilities: Vec<CapabilityToken>, ) -> Result<SessionId, KernelError>

Source

pub fn activate_session( &self, session_id: &SessionId, ) -> Result<(), KernelError>

Transition a session into the ready state once setup is complete.

Source

pub fn set_session_auth_context( &self, session_id: &SessionId, auth_context: SessionAuthContext, ) -> Result<(), KernelError>

Persist transport/session authentication context for a session.

Source

pub fn set_session_peer_capabilities( &self, session_id: &SessionId, peer_capabilities: PeerCapabilities, ) -> Result<(), KernelError>

Persist peer capabilities negotiated at the edge for a session.

Source

pub fn replace_session_roots( &self, session_id: &SessionId, roots: Vec<RootDefinition>, ) -> Result<(), KernelError>

Replace the session’s current root snapshot.

Source

pub fn normalized_session_roots( &self, session_id: &SessionId, ) -> Result<Vec<NormalizedRoot>, KernelError>

Return the runtime’s normalized root view for a session.

Source

pub fn enforceable_filesystem_root_paths( &self, session_id: &SessionId, ) -> Result<Vec<String>, KernelError>

Return only the enforceable filesystem root paths for a session.

Source

pub fn subscribe_session_resource( &self, session_id: &SessionId, capability: &CapabilityToken, agent_id: &str, uri: &str, ) -> Result<(), KernelError>

Subscribe the session to update notifications for a concrete resource URI.

Source

pub fn unsubscribe_session_resource( &self, session_id: &SessionId, uri: &str, ) -> Result<(), KernelError>

Remove a session-scoped resource subscription. Missing subscriptions are ignored.

Source

pub fn session_has_resource_subscription( &self, session_id: &SessionId, uri: &str, ) -> Result<bool, KernelError>

Check whether a session currently holds a resource subscription.

Source

pub fn begin_draining_session( &self, session_id: &SessionId, ) -> Result<(), KernelError>

Mark a session as draining. New tool calls are rejected after this point.

Source

pub fn close_session(&self, session_id: &SessionId) -> Result<(), KernelError>

Close a session and clear transient session-scoped state.

Source

pub fn session(&self, session_id: &SessionId) -> Option<Session>

Inspect an existing session.

Source

pub fn session_count(&self) -> usize

Source

pub fn resource_provider_count(&self) -> usize

Source

pub fn prompt_provider_count(&self) -> usize

Source

pub fn begin_session_request( &self, context: &OperationContext, operation_kind: OperationKind, cancellable: bool, ) -> Result<(), KernelError>

Validate a session-scoped operation and register it as in flight.

Source

pub fn begin_child_request( &self, parent_context: &OperationContext, request_id: RequestId, operation_kind: OperationKind, progress_token: Option<ProgressToken>, cancellable: bool, ) -> Result<OperationContext, KernelError>

Construct and register a child request under an existing parent request.

Source

pub fn complete_session_request( &self, session_id: &SessionId, request_id: &RequestId, ) -> Result<(), KernelError>

Complete an in-flight session request.

Source

pub fn complete_session_request_with_terminal_state( &self, session_id: &SessionId, request_id: &RequestId, terminal_state: OperationTerminalState, ) -> Result<(), KernelError>

Complete an in-flight session request with an explicit terminal state.

Source

pub fn request_session_cancellation( &self, session_id: &SessionId, request_id: &RequestId, ) -> Result<(), KernelError>

Mark an in-flight session request as cancelled.

Source

pub fn validate_sampling_request( &self, context: &OperationContext, operation: &CreateMessageOperation, ) -> Result<(), KernelError>

Validate whether a sampling child request is allowed for this session.

Source

pub fn validate_elicitation_request( &self, context: &OperationContext, operation: &CreateElicitationOperation, ) -> Result<(), KernelError>

Validate whether an elicitation child request is allowed for this session.

Source

pub fn evaluate_tool_call_operation_with_nested_flow_client<C: NestedFlowClient>( &self, context: &OperationContext, operation: &ToolCallOperation, client: &mut C, ) -> Result<ToolCallResponse, KernelError>

Evaluate a session-scoped tool call while allowing the target tool server to proxy negotiated nested flows back through a client transport owned by the edge.

Source

pub fn evaluate_session_operation( &self, context: &OperationContext, operation: &SessionOperation, ) -> Result<SessionOperationResponse, KernelError>

Evaluate a normalized operation against a specific session.

This is the higher-level entry point that future JSON-RPC or MCP edges should target. The current stdio loop normalizes raw frames into these operations before invoking the kernel.

Source§

impl ChioKernel

Source

pub fn new(config: KernelConfig) -> Self

Source

pub fn set_receipt_store(&mut self, receipt_store: Box<dyn ReceiptStore>)

Source

pub fn set_payment_adapter(&mut self, payment_adapter: Box<dyn PaymentAdapter>)

Source

pub fn set_price_oracle(&mut self, price_oracle: Box<dyn PriceOracle>)

Source

pub fn set_attestation_trust_policy( &mut self, attestation_trust_policy: AttestationTrustPolicy, )

Source

pub fn set_revocation_store( &mut self, revocation_store: Box<dyn RevocationStore>, )

Source

pub fn set_capability_authority( &mut self, capability_authority: Box<dyn CapabilityAuthority>, )

Source

pub fn set_budget_store(&mut self, budget_store: Box<dyn BudgetStore>)

Source

pub fn set_post_invocation_pipeline(&mut self, pipeline: PostInvocationPipeline)

Source

pub fn add_post_invocation_hook(&mut self, hook: Box<dyn PostInvocationHook>)

Source

pub fn set_memory_provenance_store( &mut self, store: Arc<dyn MemoryProvenanceStore>, )

Phase 18.2: install a memory-provenance chain.

Once installed, every governed MemoryWrite-shaped tool call appends an entry to the chain after the allow receipt is signed. A chain-store failure on that path is fatal: the call surfaces KernelError::Internal(...) so operators can detect and repair the drift rather than silently shipping a write without provenance evidence.

Every MemoryRead-shaped tool call looks the entry up by (store, key) and attaches the result to the receipt as memory_provenance evidence metadata. Reads with no chain entry or with a tampered chain surface as crate::memory_provenance::ProvenanceVerification::Unverified so the receipt unambiguously records the gap.

Source

pub fn memory_provenance_store(&self) -> Option<Arc<dyn MemoryProvenanceStore>>

Return a clone of the active memory-provenance store handle, or None when no provenance chain has been installed.

Useful for integration tests that want to assert on the chain state directly after driving evaluate_tool_call.

Source

pub fn with_federation_peers(self, peers: Vec<FederationPeer>) -> Self

Phase 20.3: install a set of chio_federation::FederationPeers this kernel trusts for bilateral co-signing. Overwrites any previously declared set. Callers typically obtain these peers from chio_federation::KernelTrustExchange::accept_envelope after a successful mTLS handshake.

Builder-style so deployments can chain .with_federation_peers(...) onto ChioKernel::new(config).

Source

pub fn set_federation_cosigner( &mut self, cosigner: Arc<dyn BilateralCoSigningProtocol>, )

Phase 20.3: install the bilateral cosigner responsible for contacting a peer kernel to obtain a co-signature. Production deployments plug in an mTLS-backed RPC client; tests can use chio_federation::InProcessCoSigner.

Source

pub fn set_federation_local_kernel_id(&self, kernel_id: impl Into<String>)

Phase 20.3: advertise this kernel’s stable identifier as seen by remote federation peers. When unset, the hex encoding of the signing public key is used. Setting this is recommended in production so receipts reference DNS names rather than raw keys.

Source

pub fn federation_peer( &self, remote_kernel_id: &str, now: u64, ) -> Option<FederationPeer>

Phase 20.3: resolve the active federation peer for remote_kernel_id, refusing stale pins fail-closed.

Source

pub fn federation_peers_snapshot(&self) -> Vec<FederationPeer>

Phase 20.3: snapshot the currently-pinned federation peer set.

Source

pub fn dual_signed_receipt(&self, receipt_id: &str) -> Option<DualSignedReceipt>

Phase 20.3: look up a dual-signed receipt by the underlying chio_core::receipt::ChioReceipt id. Returns None when the receipt did not cross a federation boundary or when the co-signing hook has not yet produced a dual-signed artifact for it.

Source

pub fn federation_local_kernel_id(&self) -> String

Local kernel identifier used in bilateral co-signing. Falls back to the hex encoding of the signing public key.

Source

pub fn emergency_stop(&self, reason: &str) -> Result<(), KernelError>

Engage the emergency kill switch.

After this call, every evaluate_tool_call* path returns a signed deny receipt with reason "kernel emergency stop active" before touching capability validation or the guard pipeline. The kernel remains running so orchestrators and health probes see a live process; it is simply inert.

The active capability set is NOT purged from the revocation store: the current RevocationStore trait has no bulk revoke API and capability expiration plus the kill-switch flag together satisfy Phase 1.4 acceptance. When a future revision adds revoke_all, this method should call it; until then, capability revocation is delegated to natural expiration.

Fails closed: if the reason mutex is poisoned we still leave the kernel in the stopped state (the flag is set before any fallible step) and surface the poison to the caller.

Source

pub fn emergency_resume(&self) -> Result<(), KernelError>

Disengage the emergency kill switch and resume normal operation.

Subsequent evaluate_tool_call* calls follow the full validation pipeline again. Capabilities that naturally expired while the kernel was stopped remain expired; the kill switch does not retroactively grant anything.

Source

pub fn is_emergency_stopped(&self) -> bool

Return true when the emergency kill switch is engaged.

Source

pub fn emergency_stopped_since(&self) -> Option<u64>

Return the unix timestamp (seconds) at which the kill switch was engaged, or None when the kernel is currently running normally.

Source

pub fn emergency_stop_reason(&self) -> Option<String>

Return the operator-supplied reason for the current emergency stop, or None when the kernel is running normally or the mutex is poisoned (fail-closed readers should treat None as “no reason available”).

Source

pub fn set_dpop_store( &mut self, nonce_store: DpopNonceStore, config: DpopConfig, )

Install a DPoP nonce replay store and verification config.

Once installed, any invocation whose matched grant has dpop_required == Some(true) must carry a valid DpopProof on the ToolCallRequest. Requests that lack a proof or whose proof fails verification are denied fail-closed.

Source

pub fn set_execution_nonce_store( &mut self, config: ExecutionNonceConfig, store: Box<dyn ExecutionNonceStore>, )

Phase 1.1: install an execution-nonce config and replay store.

Once installed, every Verdict::Allow carries a short-lived signed nonce on ToolCallResponse::execution_nonce. Tool servers re-present that nonce via ToolCallRequest::execution_nonce and the kernel’s verify_presented_execution_nonce helper (or directly via the free-standing verify_execution_nonce function) before executing.

Set config.require_nonce = true to put the kernel into strict mode: any call that reaches require_presented_execution_nonce without a nonce is denied. When require_nonce == false the feature is opt-in per tool server and non-nonce callers continue to work (backward compatibility).

Source

pub fn execution_nonce_required(&self) -> bool

Returns true when execution-nonce strict mode is active.

Strict mode requires every presented tool call to carry a fresh, valid, single-use nonce. When false the kernel is either not minting nonces at all (no config installed) or is in opt-in mode where tool servers can verify presented nonces but non-nonce calls are not outright rejected.

Source

pub fn verify_presented_execution_nonce( &self, presented: &SignedExecutionNonce, expected: &NonceBinding, ) -> Result<(), ExecutionNonceError>

Phase 1.1: verify a caller-presented execution nonce against the expected binding, consuming it in the replay store on success.

Returns Ok(()) when the nonce is fresh, correctly bound, signed by this kernel, and has not been consumed. Returns an error wrapping ExecutionNonceError on any failure (expired, tampered, replayed, binding mismatch, store unreachable).

Source

pub fn require_presented_execution_nonce( &self, request: &ToolCallRequest, cap: &CapabilityToken, presented: Option<&SignedExecutionNonce>, ) -> Result<(), KernelError>

Phase 1.1: strict-mode gate. Denies the call fail-closed when the kernel is configured to require nonces on every execution-bound tool call but the caller did not present one.

presented is the nonce the tool server forwarded with the execution attempt (for example, lifted from the X-Chio-Execution-Nonce header). Passing the nonce as a separate argument keeps ToolCallRequest wire-stable: every other call site that builds a request (guards, adapters, tests) continues to compile unchanged, and strict mode is gated on the integration layer that knows how to shuttle the nonce header.

Returns Ok(()) when:

  • strict mode is disabled (backward-compat path), OR
  • a nonce is presented, signed by this kernel, correctly bound, non-expired, and has not been consumed.

Returns Err(KernelError::Internal(...)) fail-closed otherwise.

Source

pub fn requires_web3_evidence(&self) -> bool

Source

pub fn validate_web3_evidence_prerequisites(&self) -> Result<(), KernelError>

Source

pub fn add_guard(&mut self, guard: Box<dyn Guard>)

Register a policy guard. Guards are evaluated in registration order. If any guard denies, the request is denied.

Source

pub fn register_tool_server( &mut self, connection: Box<dyn ToolServerConnection>, )

Register a tool server connection.

Source

pub fn register_resource_provider( &mut self, provider: Box<dyn ResourceProvider>, )

Register a resource provider.

Source

pub fn register_prompt_provider(&mut self, provider: Box<dyn PromptProvider>)

Register a prompt provider.

Source

pub async fn evaluate_tool_call( &self, request: &ToolCallRequest, ) -> Result<ToolCallResponse, KernelError>

Evaluate a tool call request.

This is the kernel’s main entry point. It performs the full validation pipeline:

  1. Verify capability signature against known CA public keys.
  2. Check time bounds (not expired, not-before satisfied).
  3. Check revocation status of the capability and its delegation chain.
  4. Verify the requested tool is within the capability’s scope.
  5. Check and decrement invocation budget.
  6. Run all registered guards.
  7. If all pass: forward to tool server, sign allow receipt.
  8. If any fail: sign deny receipt.

Every call – whether allowed or denied – produces exactly one signed receipt.

Source

pub fn evaluate_tool_call_blocking( &self, request: &ToolCallRequest, ) -> Result<ToolCallResponse, KernelError>

Source

pub fn evaluate_tool_call_blocking_with_metadata( &self, request: &ToolCallRequest, extra_metadata: Option<Value>, ) -> Result<ToolCallResponse, KernelError>

Source

pub fn sign_planned_deny_response( &self, request: &ToolCallRequest, reason: &str, extra_metadata: Option<Value>, ) -> Result<ToolCallResponse, KernelError>

Source

pub async fn evaluate_plan( &self, req: PlanEvaluationRequest, ) -> PlanEvaluationResponse

Phase 2.4 plan-level evaluation.

Takes an ordered list of planned tool calls under a single capability token and evaluates every step INDEPENDENTLY against the pre-invocation portion of the evaluation pipeline: capability signature / time-bound / revocation / subject binding, the request-matching pass (scope + constraints + model constraint), and the registered guard pipeline. No tool-server dispatch, no budget mutation, no receipt emission, and no cross-step state propagation take place: this is a stateless pre-flight check.

Dependencies between planned steps are advisory metadata only in v1: the kernel does not topologically sort the graph, refuse on cycles, or short-circuit downstream steps when an earlier step denies. Callers are expected to make that decision themselves once they have the per-step verdict list.

Guards that require post-invocation output (response-shaping, streaming sanitizers, etc.) are inherently skipped because no tool output exists; in Phase 2.4 every registered guard is invoked against the synthesised pre-flight request, matching the set of guards that run in evaluate_tool_call before dispatch.

Receipt emission is deferred to a future phase. The kernel emits structured trace spans for the plan and every per-step verdict so operators can correlate plan evaluations with subsequent tool-call receipts.

Source

pub fn evaluate_plan_blocking( &self, req: &PlanEvaluationRequest, ) -> PlanEvaluationResponse

Synchronous variant of Self::evaluate_plan for substrate adapters that do not run on an async runtime.

Plan evaluation never touches the network, so the async method is a thin wrapper over this blocking implementation.

Source

pub fn issue_capability( &self, subject: &PublicKey, scope: ChioScope, ttl_seconds: u64, ) -> Result<CapabilityToken, KernelError>

Issue a new capability for an agent.

The kernel delegates issuance to the configured capability authority.

Source

pub fn revoke_capability( &self, capability_id: &CapabilityId, ) -> Result<(), KernelError>

Revoke a capability and all descendants in its delegation subtree.

When a root capability is revoked, every capability whose delegation_chain contains the revoked ID will also be rejected on presentation (the kernel checks all chain entries against the revocation store).

Source

pub fn receipt_log(&self) -> ReceiptLog

Read-only access to the receipt log.

Source

pub fn child_receipt_log(&self) -> ChildReceiptLog

Source

pub fn guard_count(&self) -> usize

Source

pub fn post_invocation_hook_count(&self) -> usize

Source

pub fn drain_tool_server_events(&self) -> Vec<ToolServerEvent>

Source

pub fn register_session_pending_url_elicitation( &self, session_id: &SessionId, elicitation_id: impl Into<String>, related_task_id: Option<String>, ) -> Result<(), KernelError>

Source

pub fn register_session_required_url_elicitations( &self, session_id: &SessionId, elicitations: &[CreateElicitationOperation], related_task_id: Option<&str>, ) -> Result<(), KernelError>

Source

pub fn queue_session_elicitation_completion( &self, session_id: &SessionId, elicitation_id: &str, ) -> Result<(), KernelError>

Source

pub fn queue_session_late_event( &self, session_id: &SessionId, event: LateSessionEvent, ) -> Result<(), KernelError>

Source

pub fn queue_session_tool_server_event( &self, session_id: &SessionId, event: ToolServerEvent, ) -> Result<(), KernelError>

Source

pub fn queue_session_tool_server_events( &self, session_id: &SessionId, ) -> Result<(), KernelError>

Source

pub fn drain_session_late_events( &self, session_id: &SessionId, ) -> Result<Vec<LateSessionEvent>, KernelError>

Source

pub fn ca_count(&self) -> usize

Source

pub fn public_key(&self) -> PublicKey

Source

pub fn capability_issuer_is_trusted(&self, issuer: &PublicKey) -> bool

Source

pub fn evaluate_portable_verdict<'a>( &self, capability: &'a CapabilityToken, request: &PortableToolCallRequest, guards: &'a [&'a dyn Guard], clock: &'a dyn Clock, session_filesystem_roots: Option<&'a [String]>, ) -> EvaluationVerdict

Phase 14.1 – run the portable pure-compute verdict path provided by chio-kernel-core.

This exposes the same synchronous checks the core kernel performs (capability signature, issuer trust, time bounds, subject binding, scope match, sync guard pipeline) in isolation from the chio-kernel-only concerns (budget mutation, revocation lookup, governed-transaction evaluation, tool dispatch, receipt persistence).

Adapters that run the kernel on constrained platforms (wasm32, edge workers, mobile via FFI) should prefer this entry point – it does not require a tokio runtime, a sqlite database, or any IO adapter. The full evaluate_tool_call_* API remains the authoritative path for the desktop sidecar.

Verified-core boundary note: formal/proof-manifest.toml treats this shell method as the one chio-kernel entrypoint inside the current bounded verified core, because it delegates directly to chio_kernel_core::evaluate after supplying trusted issuers and portable guard/context wiring.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more