Skip to main content

lean_ctx/core/agent_connector/
traits.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3use std::process::Command;
4
5#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
6pub(crate) struct AgentInfo {
7    pub name: String,
8    pub version: Option<String>,
9    pub path: PathBuf,
10    pub capabilities: Vec<String>,
11    pub available: bool,
12}
13
14/// Shared task input for CLI connectors and the OCLA agent adapter.
15#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
16pub struct TaskRequest {
17    pub id: String,
18    pub prompt: String,
19    pub working_dir: PathBuf,
20    pub timeout_ms: u64,
21    pub model: Option<String>,
22    pub max_turns: Option<u32>,
23    /// Profile selected for this isolated agent invocation.
24    ///
25    /// Connectors pass this through as `LEAN_CTX_PROFILE` so the child agent
26    /// and every LeanCTX tool it launches resolve the same profile.
27    #[serde(default)]
28    pub profile_name: Option<String>,
29    pub profile_hash: Option<String>,
30    /// Explicit host-provided child identity; never inherited from the parent.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub delivery_profile: Option<Box<ChildDeliveryProfileV1>>,
33}
34
35#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct ChildDeliveryProfileV1 {
38    pub task_id: String,
39    pub expires_at: chrono::DateTime<chrono::Utc>,
40    pub profile: crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1,
41}
42
43impl ChildDeliveryProfileV1 {
44    fn environment_for(&self, request: &TaskRequest) -> Option<String> {
45        if self.task_id != request.id
46            || self.expires_at <= chrono::Utc::now()
47            || self.profile.schema_version != 1
48            || !self.profile.project_root.is_absolute()
49        {
50            return None;
51        }
52        let root = self.profile.project_root.canonicalize().ok()?;
53        if self.profile.delegation.as_ref().is_some_and(|certificate| {
54            certificate.execution.task_id != request.id
55                || self.expires_at > certificate.expires_at
56                || certificate.schema_version != 1
57                || certificate.issued_at > chrono::Utc::now()
58                || certificate.project_root != root
59                || certificate.privacy != self.profile.privacy
60                || certificate.child_agent != self.profile.agent_id
61                || certificate.child_key_id != self.profile.key_id
62                || certificate.recipient != self.profile.recipient
63                || certificate.tenant_id != self.profile.tenant_id
64                || certificate.project_id != self.profile.project_id
65                || certificate.read_grant_id != self.profile.read_grant_id
66                || certificate
67                    .write_grant_id
68                    .as_ref()
69                    .is_some_and(|grant| grant != &self.profile.write_grant_id)
70                || !crate::core::agent_identity::get_stored_public_key(&self.profile.agent_id)
71                    .is_ok_and(|key| {
72                        crate::core::agent_identity::hex_encode(key.as_bytes())
73                            == certificate.child_public_key
74                    })
75        }) {
76            return None;
77        }
78        if !root.is_dir() || root != request.working_dir.canonicalize().ok()? {
79            return None;
80        }
81        let raw = serde_json::to_string(&self.profile).ok()?;
82        (raw.len() <= 16_384).then_some(raw)
83    }
84}
85
86pub(crate) fn apply_profile_environment(command: &mut Command, request: &TaskRequest) {
87    // CLI children are distinct agents. Only an explicit, task/project-bound
88    // host profile may replace the fail-closed default.
89    // An invalid explicit profile disables delivery without legacy fallback;
90    // removing the variable would silently re-enable unscoped delivery.
91    command.env("LEAN_CTX_DELIVERY_PROFILE", "{}");
92    // Child delivery permission never includes the parent's issuer configuration.
93    command.env_remove("LEAN_CTX_DELIVERY_ISSUER_PROFILE");
94    if let Some(profile) = &request.delivery_profile {
95        if let Some(raw) = profile.environment_for(request) {
96            command.env("LEAN_CTX_DELIVERY_PROFILE", raw);
97        } else {
98            tracing::warn!(
99                event = "invalid_child_delivery_profile",
100                "Child context sharing disabled: explicit profile failed launch validation"
101            );
102        }
103    }
104    if let Some(profile_name) = request
105        .profile_name
106        .as_deref()
107        .filter(|profile_name| !profile_name.trim().is_empty())
108    {
109        command.env("LEAN_CTX_PROFILE", profile_name);
110    }
111}
112
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub(crate) struct TaskResult {
115    pub task_id: String,
116    pub agent: String,
117    pub model: String,
118    pub success: bool,
119    pub exit_code: i32,
120    pub stdout: String,
121    pub stderr: String,
122    pub duration_ms: u64,
123    pub tokens_used: Option<TokenUsage>,
124    /// Explicit provider-reported charge, never a table-derived estimate.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub provider_cost_micros: Option<u64>,
127    /// Canonical receipt emitted from explicit provider usage and cost evidence.
128    /// It remains absent when CLI output does not carry both observations.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub execution_receipt_ref: Option<String>,
131    /// Process outcome, independent of stderr text and provider task quality.
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub termination: Option<TaskTermination>,
134}
135
136#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub(crate) enum TaskTermination {
139    Exited,
140    Signalled,
141    TimedOut,
142}
143
144impl TaskTermination {
145    pub(crate) fn from_process(status: std::process::ExitStatus, timed_out: bool) -> Self {
146        if timed_out {
147            Self::TimedOut
148        } else if status.code().is_none() {
149            Self::Signalled
150        } else {
151            Self::Exited
152        }
153    }
154}
155
156/// Reject controls the chosen CLI cannot enforce before any process is started.
157pub(crate) fn validate_request(
158    request: &TaskRequest,
159    supports_turn_limit: bool,
160) -> anyhow::Result<()> {
161    anyhow::ensure!(!request.id.trim().is_empty(), "task ID is required");
162    anyhow::ensure!(!request.prompt.trim().is_empty(), "task prompt is required");
163    anyhow::ensure!(request.timeout_ms > 0, "task timeout must be positive");
164    anyhow::ensure!(
165        request
166            .model
167            .as_ref()
168            .is_none_or(|model| !model.trim().is_empty()),
169        "model must not be empty"
170    );
171    anyhow::ensure!(request.max_turns != Some(0), "turn limit must be positive");
172    anyhow::ensure!(
173        supports_turn_limit || request.max_turns.is_none(),
174        "connector does not support a turn limit"
175    );
176    Ok(())
177}
178
179#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
180pub(crate) struct TokenUsage {
181    pub input_tokens: u64,
182    pub output_tokens: u64,
183    pub cache_read_tokens: u64,
184    pub cache_write_tokens: u64,
185}
186
187pub(crate) trait AgentConnector: Send + Sync {
188    fn info(&self) -> AgentInfo;
189    fn health_check(&self) -> anyhow::Result<bool> {
190        self.health_check_with_timeout(2_000)
191    }
192    fn health_check_with_timeout(&self, timeout_ms: u64) -> anyhow::Result<bool>;
193    fn execute(&self, request: &TaskRequest) -> anyhow::Result<TaskResult>;
194    fn name(&self) -> &'static str;
195    fn supports_model_selection(&self) -> bool {
196        false
197    }
198    fn supports_turn_limit(&self) -> bool {
199        false
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn task_request_roundtrip() {
209        let req = TaskRequest {
210            id: "t1".into(),
211            prompt: "Explore codebase".into(),
212            working_dir: PathBuf::from("/tmp/test"),
213            timeout_ms: 60_000,
214            model: Some("gpt-4".into()),
215            max_turns: Some(10),
216            profile_name: Some("benchmark-candidate".into()),
217            profile_hash: Some("abc".into()),
218            delivery_profile: None,
219        };
220        let json = serde_json::to_string(&req).unwrap();
221        let restored: TaskRequest = serde_json::from_str(&json).unwrap();
222        assert_eq!(restored.id, "t1");
223        assert_eq!(
224            restored.profile_name.as_deref(),
225            Some("benchmark-candidate")
226        );
227    }
228
229    #[test]
230    fn profile_environment_is_set_only_for_named_profiles() {
231        let mut command = Command::new("echo");
232        let request = TaskRequest {
233            id: "t1".into(),
234            prompt: "Explore codebase".into(),
235            working_dir: PathBuf::from("/tmp/test"),
236            timeout_ms: 60_000,
237            model: None,
238            max_turns: None,
239            profile_name: Some("benchmark-candidate".into()),
240            profile_hash: None,
241            delivery_profile: None,
242        };
243
244        apply_profile_environment(&mut command, &request);
245        let profile = command
246            .get_envs()
247            .find(|(key, _)| *key == std::ffi::OsStr::new("LEAN_CTX_PROFILE"))
248            .and_then(|(_, value)| value);
249        assert_eq!(profile, Some(std::ffi::OsStr::new("benchmark-candidate")));
250        let delivery_profile = command
251            .get_envs()
252            .find(|(key, _)| *key == std::ffi::OsStr::new("LEAN_CTX_DELIVERY_PROFILE"))
253            .and_then(|(_, value)| value);
254        assert_eq!(delivery_profile, Some(std::ffi::OsStr::new("{}")));
255    }
256
257    #[test]
258    fn child_cannot_inherit_parent_delivery_authority() {
259        let mut command = Command::new("echo");
260        command.env("LEAN_CTX_DELIVERY_PROFILE", "parent-authority");
261        let request = TaskRequest {
262            id: "child-task".into(),
263            prompt: "Inspect".into(),
264            working_dir: PathBuf::from("/tmp/test"),
265            timeout_ms: 1000,
266            model: None,
267            max_turns: None,
268            profile_name: None,
269            profile_hash: None,
270            delivery_profile: None,
271        };
272        apply_profile_environment(&mut command, &request);
273        let (_, value) = command
274            .get_envs()
275            .find(|(key, _)| *key == std::ffi::OsStr::new("LEAN_CTX_DELIVERY_PROFILE"))
276            .unwrap();
277        let value = value.unwrap().to_str().unwrap();
278        assert_eq!(value, "{}");
279        assert!(
280            serde_json::from_str::<
281                crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1,
282            >(value)
283            .is_err()
284        );
285    }
286
287    #[test]
288    fn task_result_roundtrip() {
289        let result = TaskResult {
290            task_id: "t1".into(),
291            agent: "codex".into(),
292            model: "gpt-4".into(),
293            success: true,
294            exit_code: 0,
295            stdout: "done".into(),
296            stderr: String::new(),
297            duration_ms: 5000,
298            tokens_used: Some(TokenUsage {
299                input_tokens: 1000,
300                output_tokens: 200,
301                cache_read_tokens: 500,
302                cache_write_tokens: 100,
303            }),
304            provider_cost_micros: Some(1_500),
305            execution_receipt_ref: Some("receipt:test".into()),
306            termination: None,
307        };
308        let json = serde_json::to_string(&result).unwrap();
309        let restored: TaskResult = serde_json::from_str(&json).unwrap();
310        assert_eq!(restored.agent, "codex");
311        assert_eq!(restored.provider_cost_micros, Some(1_500));
312        assert!(restored.termination.is_none());
313        assert!(!json.contains("termination"));
314    }
315
316    #[test]
317    fn child_delivery_profile_is_bound_to_task_project_and_expiry() {
318        let _isolated = crate::core::data_dir::isolated_data_dir();
319        let root = tempfile::tempdir().unwrap();
320        let other = tempfile::tempdir().unwrap();
321        let binding = ChildDeliveryProfileV1 {
322            task_id: "child-task".into(),
323            expires_at: chrono::Utc::now() + chrono::Duration::minutes(2),
324            profile: crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1 {
325                schema_version: 1,
326                agent_id: "child-agent".into(),
327                delegation: None,
328                recipient: "host".into(),
329                tenant_id: "tenant".into(),
330                project_id: "project".into(),
331                project_root: root.path().to_path_buf(),
332                key_id: "child-key".into(),
333                read_grant_id: "child-read".into(),
334                write_grant_id: "child-write".into(),
335                privacy: lean_ctx_ocla::delivery_scope::DeliveryPrivacyV1::Project,
336            },
337        };
338        let mut request = TaskRequest {
339            id: "child-task".into(),
340            prompt: "Inspect".into(),
341            working_dir: root.path().to_path_buf(),
342            timeout_ms: 1000,
343            model: None,
344            max_turns: None,
345            profile_name: None,
346            profile_hash: None,
347            delivery_profile: Some(Box::new(binding.clone())),
348        };
349        let profile_value = |request: &TaskRequest| {
350            let mut command = Command::new("echo");
351            command.env("LEAN_CTX_DELIVERY_PROFILE", "parent-authority");
352            command.env("LEAN_CTX_DELIVERY_ISSUER_PROFILE", "parent-issuer");
353            apply_profile_environment(&mut command, request);
354            assert!(command.get_envs().any(|(key, value)| key
355                == std::ffi::OsStr::new("LEAN_CTX_DELIVERY_ISSUER_PROFILE")
356                && value.is_none()));
357            command
358                .get_envs()
359                .find(|(key, _)| *key == std::ffi::OsStr::new("LEAN_CTX_DELIVERY_PROFILE"))
360                .unwrap()
361                .1
362                .unwrap()
363                .to_str()
364                .unwrap()
365                .to_owned()
366        };
367        let raw = profile_value(&request);
368        let profile: crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1 =
369            serde_json::from_str(&raw).unwrap();
370        assert_eq!(profile.agent_id, "child-agent");
371        assert_eq!(profile, binding.profile);
372        let encoded = serde_json::to_value(&request).unwrap();
373        assert_eq!(
374            serde_json::from_value::<TaskRequest>(encoded.clone()).unwrap(),
375            request
376        );
377        let mut legacy = encoded;
378        legacy.as_object_mut().unwrap().remove("delivery_profile");
379        assert!(
380            serde_json::from_value::<TaskRequest>(legacy)
381                .unwrap()
382                .delivery_profile
383                .is_none()
384        );
385
386        let (mut certificate, _, host_key) =
387            crate::core::a2a::task::delivery_delegation::tests::fixture();
388        certificate.execution.task_id = request.id.clone();
389        certificate.child_agent = binding.profile.agent_id.clone();
390        certificate.child_key_id = binding.profile.key_id.clone();
391        certificate.recipient = binding.profile.recipient.clone();
392        certificate.tenant_id = binding.profile.tenant_id.clone();
393        certificate.project_id = binding.profile.project_id.clone();
394        certificate.project_root = root.path().canonicalize().unwrap();
395        certificate.privacy = binding.profile.privacy;
396        certificate.read_grant_id = binding.profile.read_grant_id.clone();
397        let child_key =
398            crate::core::agent_identity::get_or_create_keypair(&certificate.child_agent).unwrap();
399        certificate.child_public_key =
400            crate::core::agent_identity::hex_encode(child_key.verifying_key().as_bytes());
401        certificate.sign(&host_key);
402        request
403            .delivery_profile
404            .as_mut()
405            .unwrap()
406            .profile
407            .delegation = Some(Box::new(certificate.clone()));
408        assert_ne!(profile_value(&request), "{}");
409        let delegated_profile: crate::core::a2a::task::delivery_authority::DeliverySigningProfileV1 =
410            serde_json::from_str(&profile_value(&request)).unwrap();
411        assert_eq!(delegated_profile.delegation.as_deref(), Some(&certificate));
412        for field in [
413            "child_agent",
414            "child_key_id",
415            "recipient",
416            "tenant_id",
417            "project_id",
418            "read_grant_id",
419            "child_public_key",
420        ] {
421            let mut value = serde_json::to_value(&certificate).unwrap();
422            value[field] = serde_json::json!("mismatch");
423            request
424                .delivery_profile
425                .as_mut()
426                .unwrap()
427                .profile
428                .delegation = Some(Box::new(serde_json::from_value(value).unwrap()));
429            assert_eq!(profile_value(&request), "{}", "{field}");
430        }
431        certificate.execution.task_id = "other-attempt".into();
432        certificate.sign(&host_key);
433        request
434            .delivery_profile
435            .as_mut()
436            .unwrap()
437            .profile
438            .delegation = Some(Box::new(certificate.clone()));
439        assert_eq!(profile_value(&request), "{}");
440        certificate.execution.task_id = request.id.clone();
441        certificate.expires_at = binding.expires_at - chrono::Duration::seconds(1);
442        certificate.sign(&host_key);
443        request
444            .delivery_profile
445            .as_mut()
446            .unwrap()
447            .profile
448            .delegation = Some(Box::new(certificate));
449        assert_eq!(profile_value(&request), "{}");
450        request.delivery_profile = Some(Box::new(binding.clone()));
451
452        request.delivery_profile.as_mut().unwrap().profile.recipient = "x".repeat(16_384);
453        assert_eq!(profile_value(&request), "{}");
454        request.delivery_profile = Some(Box::new(binding.clone()));
455        request.id = "different-task".into();
456        assert_eq!(profile_value(&request), "{}");
457        request.id = binding.task_id.clone();
458        request.working_dir = other.path().to_path_buf();
459        assert_eq!(profile_value(&request), "{}");
460        request.working_dir = root.path().to_path_buf();
461        request.delivery_profile.as_mut().unwrap().expires_at =
462            chrono::Utc::now() - chrono::Duration::seconds(1);
463        assert_eq!(profile_value(&request), "{}");
464        request.delivery_profile = Some(Box::new(binding));
465        request
466            .delivery_profile
467            .as_mut()
468            .unwrap()
469            .profile
470            .schema_version = 2;
471        assert_eq!(profile_value(&request), "{}");
472    }
473}