Skip to main content

lean_ctx/core/ocla/
invocation.rs

1//! Common invocation and measurement envelopes for OCLA capability adapters.
2
3use std::collections::BTreeMap;
4
5use lean_ctx_protocol::CapabilityManifestV1;
6use serde::{Deserialize, Serialize};
7
8use super::{OclaError, OclaResult};
9
10pub use crate::core::agent_connector::traits::TaskRequest as AgentTaskRequest;
11
12/// Version of the public observation shape emitted by native adapters.
13pub const CAPABILITY_OBSERVATION_SCHEMA_VERSION: u32 = 1;
14
15/// Input accepted by a capability adapter.
16#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18pub enum CapabilityInput {
19    ContextRequest {
20        paths: Vec<String>,
21        mode: String,
22        budget_tokens: Option<u64>,
23    },
24    ShellCommand {
25        command: String,
26        workdir: Option<String>,
27    },
28    ModelRequest {
29        prompt: String,
30        model: Option<String>,
31    },
32    AgentTask(AgentTaskRequest),
33}
34
35impl CapabilityInput {
36    /// Returns the payload measured by the common token envelope.
37    #[must_use]
38    pub fn payload(&self) -> &str {
39        match self {
40            Self::ContextRequest { paths, .. } => paths.first().map(String::as_str).unwrap_or(""),
41            Self::ShellCommand { command, .. } => command,
42            Self::ModelRequest { prompt, .. } => prompt,
43            Self::AgentTask(request) => &request.prompt,
44        }
45    }
46}
47
48/// Policy limits applied uniformly before and after adapter execution.
49#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
50#[serde(default)]
51pub struct PolicyConstraints {
52    pub max_input_tokens: Option<u64>,
53    pub max_output_tokens: Option<u64>,
54    pub max_latency_ms: Option<u64>,
55    pub allowed_models: Vec<String>,
56    pub allowed_paths: Vec<String>,
57    pub allowed_data_classifications: Vec<String>,
58    pub allow_remote: bool,
59    pub require_deterministic: bool,
60    pub require_reversible: bool,
61}
62
63impl PolicyConstraints {
64    /// Validate internal policy invariants.
65    pub fn validate(&self) -> OclaResult<()> {
66        if self
67            .allowed_models
68            .iter()
69            .chain(self.allowed_paths.iter())
70            .chain(self.allowed_data_classifications.iter())
71            .any(|value| value.trim().is_empty())
72        {
73            return Err(OclaError::InvalidRequest(
74                "policy constraint lists must not contain empty values".into(),
75            ));
76        }
77        Ok(())
78    }
79
80    /// Apply the model/path portions of policy to an invocation.
81    pub fn check_input(&self, input: &CapabilityInput) -> OclaResult<()> {
82        self.validate()?;
83        match input {
84            CapabilityInput::ContextRequest { paths, .. } => {
85                if !self.allowed_paths.is_empty()
86                    && paths
87                        .iter()
88                        .any(|path| !self.allowed_paths.iter().any(|allowed| path == allowed))
89                {
90                    return Err(OclaError::InvalidRequest(
91                        "context path is outside policy allowlist".into(),
92                    ));
93                }
94            }
95            CapabilityInput::ModelRequest { model, .. }
96            | CapabilityInput::AgentTask(AgentTaskRequest { model, .. }) => {
97                if !self.allowed_models.is_empty()
98                    && model.as_ref().is_none_or(|model| {
99                        !self.allowed_models.iter().any(|allowed| allowed == model)
100                    })
101                {
102                    return Err(OclaError::InvalidRequest(
103                        "model is outside policy allowlist".into(),
104                    ));
105                }
106            }
107            CapabilityInput::ShellCommand { .. } => {}
108        }
109        if let CapabilityInput::AgentTask(request) = input
110            && !self.allowed_paths.is_empty()
111            && !self
112                .allowed_paths
113                .iter()
114                .any(|path| std::path::Path::new(path) == request.working_dir)
115        {
116            return Err(OclaError::InvalidRequest(
117                "agent working directory is outside policy allowlist".into(),
118            ));
119        }
120        Ok(())
121    }
122}
123
124/// A single capability invocation with task and policy lineage attached.
125#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
126#[serde(deny_unknown_fields)]
127pub struct CapabilityInvocation {
128    pub task_id: String,
129    pub capability_id: String,
130    pub capability_version: String,
131    pub input: CapabilityInput,
132    pub policy_constraints: PolicyConstraints,
133    pub timeout_ms: u64,
134}
135
136impl CapabilityInvocation {
137    /// Validate identity and policy fields before dispatch.
138    pub fn validate(&self) -> OclaResult<()> {
139        for (label, value) in [
140            ("task_id", &self.task_id),
141            ("capability_id", &self.capability_id),
142            ("capability_version", &self.capability_version),
143        ] {
144            if value.trim().is_empty() {
145                return Err(OclaError::InvalidRequest(format!("{label} is required")));
146            }
147        }
148        self.policy_constraints.check_input(&self.input)
149    }
150}
151
152/// Failure taxonomy shared by all adapters.
153#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum CapabilityFailureMode {
156    Timeout,
157    Unavailable,
158    RejectedByPolicy,
159    InvalidOutput,
160    Partial,
161    FallbackToNative,
162    Internal,
163}
164
165/// Comparable, payload-free measurement emitted for one invocation.
166#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
167#[serde(deny_unknown_fields)]
168pub struct CapabilityObservationV1 {
169    pub schema_version: u32,
170    pub task_id: String,
171    pub capability_id: String,
172    pub capability_version: String,
173    pub success: bool,
174    pub input_tokens: u64,
175    pub output_tokens: u64,
176    pub latency_ms: u64,
177    pub failure_mode: Option<CapabilityFailureMode>,
178    pub output_ref: Option<String>,
179    pub metrics: BTreeMap<String, u64>,
180}
181
182impl CapabilityObservationV1 {
183    /// Build the successful observation shared by native adapters.
184    #[must_use]
185    pub fn success(
186        invocation: &CapabilityInvocation,
187        input_tokens: u64,
188        output_tokens: u64,
189        latency_ms: u64,
190        output_ref: Option<String>,
191    ) -> Self {
192        Self {
193            schema_version: CAPABILITY_OBSERVATION_SCHEMA_VERSION,
194            task_id: invocation.task_id.clone(),
195            capability_id: invocation.capability_id.clone(),
196            capability_version: invocation.capability_version.clone(),
197            success: true,
198            input_tokens,
199            output_tokens,
200            latency_ms,
201            failure_mode: None,
202            output_ref,
203            metrics: BTreeMap::new(),
204        }
205    }
206}
207
208/// Result returned by every adapter through the common invocation path.
209#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
210#[serde(deny_unknown_fields)]
211pub struct CapabilityResult {
212    pub success: bool,
213    pub output_tokens: u64,
214    pub latency_ms: u64,
215    pub observation: CapabilityObservationV1,
216    pub evidence_ref: Option<String>,
217}
218
219/// Adapter boundary shared by native, reference, and enterprise capabilities.
220pub trait CapabilityAdapter: Send + Sync {
221    fn manifest(&self) -> &CapabilityManifestV1;
222    fn invoke(&self, invocation: CapabilityInvocation) -> OclaResult<CapabilityResult>;
223    fn health_check(&self) -> OclaResult<bool>;
224}
225
226/// Create a stable content-addressed evidence reference without exposing data.
227#[must_use]
228pub(crate) fn evidence_ref(content: &str) -> String {
229    format!("blake3:{}", blake3::hash(content.as_bytes()).to_hex())
230}
231
232/// Enforce the invocation timeout after a synchronous adapter operation.
233pub(crate) fn check_timeout(start: std::time::Instant, timeout_ms: u64) -> OclaResult<u64> {
234    let elapsed_ms = start.elapsed().as_millis() as u64;
235    if timeout_ms != 0 && elapsed_ms > timeout_ms {
236        return Err(OclaError::InvalidRequest(format!(
237            "capability invocation exceeded timeout ({elapsed_ms}ms > {timeout_ms}ms)"
238        )));
239    }
240    Ok(elapsed_ms)
241}