xynthe 0.1.0

A unified orchestration framework for autonomous intelligence with temporal continuity
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
417
418
419
420
421
422
423
424
425
426
427
//! Capability Bindings - Type-safe interfaces to tools and services
//!
//! Capability bindings formalize tool integration through four interfaces:
//! - describe(): Returns formal specification
//! - invoke(state): Executes with current cognitive state
//! - simulate(state): Predicts effects without execution
//! - reflect(trace): Analyzes past invocations for learning
//!
//! Bindings enforce capability contracts that prevent runtime errors through
//! static verification of preconditions.

use crate::types::StructuredContent;
use crate::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;

/// Metadata about a capability's effects
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CapabilityMetadata {
    /// Success status
    pub success: bool,

    /// Execution duration
    pub duration_ms: u64,

    /// Side effects produced
    pub side_effects: Vec<String>,

    /// Timestamp of invocation
    pub timestamp: crate::types::Timestamp,
}

impl CapabilityMetadata {
    /// Create successful metadata
    pub fn success() -> Self {
        Self {
            success: true,
            duration_ms: 0,
            side_effects: Vec::new(),
            timestamp: crate::types::Timestamp::now(),
        }
    }

    /// Create failed metadata
    pub fn failure(error: String) -> Self {
        Self {
            success: false,
            duration_ms: 0,
            side_effects: vec![error],
            timestamp: crate::types::Timestamp::now(),
        }
    }

    /// Add a side effect
    pub fn with_side_effect(mut self, effect: String) -> Self {
        self.side_effects.push(effect);
        self
    }

    /// Set the duration
    pub fn with_duration(mut self, ms: u64) -> Self {
        self.duration_ms = ms;
        self
    }
}

impl Default for CapabilityMetadata {
    fn default() -> Self {
        Self::success()
    }
}

/// Result from invoking a capability
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CapabilityResult<D = StructuredContent> {
    /// Result data
    pub data: D,

    /// Execution metadata
    pub metadata: CapabilityMetadata,
}

impl<D> CapabilityResult<D> {
    /// Create a new capability result
    pub fn new(data: D, metadata: CapabilityMetadata) -> Self {
        Self { data, metadata }
    }

    /// Create a successful result
    pub fn success(data: D) -> Self {
        Self::new(data, CapabilityMetadata::success())
    }

    /// Create a failed result
    pub fn failure(data: D, error: String) -> Self {
        Self::new(data, CapabilityMetadata::failure(error))
    }

    /// Check if the result was successful
    pub fn is_success(&self) -> bool {
        self.metadata.success
    }

    /// Get the data
    pub fn data(&self) -> &D {
        &self.data
    }

    /// Unwrap the data, panicking if not successful
    pub fn unwrap(self) -> D
    where
        D: Debug,
    {
        if !self.is_success() {
            panic!("Called unwrap on failed capability result");
        }
        self.data
    }
}

/// Trait for capabilities that can be invoked
#[async_trait]
pub trait Capability: Send + Sync {
    /// Get the capability name
    fn name(&self) -> &str;

    /// Describe the capability's interface
    fn describe(&self) -> CapabilityContract;

    /// Check if preconditions are satisfied
    fn can_invoke(&self, state: &StructuredContent) -> bool {
        let contract = self.describe();
        contract.preconditions.iter().all(|pre| self.check_precondition(pre, state))
    }

    /// Check a specific precondition
    fn check_precondition(&self, precondition: &str, state: &StructuredContent) -> bool;

    /// Invoke the capability with current state
    async fn invoke(&self, input: StructuredContent) -> Result<CapabilityResult>;

    /// Simulate capability execution without side effects
    fn simulate(&self, input: &StructuredContent) -> Result<CapabilityResult> {
        Ok(CapabilityResult::success(StructuredContent::text("Simulation completed")))
    }

    /// Reflect on past invocations
    async fn reflect(&self, traces: &[CapabilityTrace]) -> Result<StructuredContent> {
        Ok(StructuredContent::json(serde_json::json!({
            "reflection": "Default reflection",
            "traces_analyzed": traces.len()
        })))
    }
}

/// Contract defining capability requirements and effects
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct CapabilityContract {
    /// Preconditions that must be satisfied
    pub preconditions: Vec<String>,

    /// Effects produced by the capability
    pub effects: Vec<String>,

    /// Failure modes and their semantics
    pub failure_modes: Vec<String>,

    /// Required permissions
    pub permissions: Vec<String>,

    /// Resource constraints
    pub constraints: HashMap<String, String>,
}

impl CapabilityContract {
    /// Create a new empty contract
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a precondition
    pub fn with_precondition(mut self, precondition: impl Into<String>) -> Self {
        self.preconditions.push(precondition.into());
        self
    }

    /// Add an effect
    pub fn with_effect(mut self, effect: impl Into<String>) -> Self {
        self.effects.push(effect.into());
        self
    }

    /// Add a failure mode
    pub fn with_failure_mode(mut self, failure: impl Into<String>) -> Self {
        self.failure_modes.push(failure.into());
        self
    }

    /// Build the contract
    pub fn build(self) -> Self {
        self
    }
}

/// Trace of a capability invocation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CapabilityTrace {
    /// Unique trace ID
    pub id: Uuid,

    /// Capability name
    pub capability_name: String,

    /// Input provided
    pub input: StructuredContent,

    /// Output produced
    pub output: StructuredContent,

    /// Execution metadata
    pub metadata: CapabilityMetadata,

    /// Success status
    pub success: bool,

    /// Error message if failed
    pub error: Option<String>,
}

impl CapabilityTrace {
    /// Create a new trace
    pub fn new(capability_name: impl Into<String>, input: StructuredContent, output: StructuredContent, metadata: CapabilityMetadata, success: bool) -> Self {
        Self {
            id: Uuid::new_v4(),
            capability_name: capability_name.into(),
            input,
            output,
            metadata,
            success,
            error: None,
        }
    }

    /// Create a failed trace
    pub fn failed(capability_name: impl Into<String>, input: StructuredContent, error: String) -> Self {
        Self {
            id: Uuid::new_v4(),
            capability_name: capability_name.into(),
            input,
            output: StructuredContent::json(serde_json::json!({"error": &error})),
            metadata: CapabilityMetadata::failure(error.clone()),
            success: false,
            error: Some(error),
        }
    }
}

/// Registry for managing capability bindings
pub struct CapabilityRegistry {
    /// Registered capabilities
    capabilities: Arc<RwLock<HashMap<String, Arc<dyn Capability>>>>,

    /// Execution traces
    traces: Arc<RwLock<Vec<CapabilityTrace>>>,
}

impl CapabilityRegistry {
    /// Create a new registry
    pub fn new() -> Self {
        Self {
            capabilities: Arc::new(RwLock::new(HashMap::new())),
            traces: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Register a capability
    pub async fn register(&self, capability: Arc<dyn Capability>) -> Result<()> {
        let mut caps = self.capabilities.write().await;
        caps.insert(capability.name().to_string(), capability);
        Ok(())
    }

    /// Get a capability by name
    pub async fn get(&self, name: &str) -> Result<Arc<dyn Capability>> {
        let caps = self.capabilities.read().await;
        caps.get(name)
            .cloned()
            .ok_or_else(|| crate::Error::NotFound(format!("Capability '{}' not found", name)))
    }

    /// List all capability names
    pub async fn list(&self) -> Vec<String> {
        let caps = self.capabilities.read().await;
        caps.keys().cloned().collect()
    }

    /// Invoke a capability by name
    pub async fn invoke(&self, name: &str, input: StructuredContent) -> Result<CapabilityResult> {
        let cap = self.get(name).await?;

        if !cap.can_invoke(&input) {
            return Err(crate::Error::PreconditionNotMet(
                format!("Preconditions not met for capability '{}'", name)
            ));
        }

        let result = cap.invoke(input.clone()).await?;

        // Record trace
        let trace = CapabilityTrace::new(
            name,
            input,
            result.data.clone(),
            result.metadata.clone(),
            result.is_success(),
        );

        self.record_trace(trace).await;

        Ok(result)
    }

    /// Record an execution trace
    pub async fn record_trace(&self, trace: CapabilityTrace) {
        let mut traces = self.traces.write().await;
        traces.push(trace);
    }

    /// Get all traces
    pub async fn traces(&self) -> Vec<CapabilityTrace> {
        let traces = self.traces.read().await;
        traces.clone()
    }

    /// Clear all traces
    pub async fn clear_traces(&self) {
        let mut traces = self.traces.write().await;
        traces.clear();
    }

    /// Invoke a capability with simulation mode
    pub async fn simulate(&self, name: &str, input: &StructuredContent) -> Result<CapabilityResult> {
        let cap = self.get(name).await?;
        cap.simulate(input)
    }
}

impl Default for CapabilityRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Result;

    struct MockCapability {
        name: String,
    }

    #[async_trait]
    impl Capability for MockCapability {
        fn name(&self) -> &str {
            &self.name
        }

        fn describe(&self) -> CapabilityContract {
            CapabilityContract::new()
                .with_precondition("has_input")
                .with_effect("produces_output")
                .build()
        }

        fn check_precondition(&self, precondition: &str, _state: &StructuredContent) -> bool {
            precondition == "has_input"
        }

        async fn invoke(&self, input: StructuredContent) -> Result<CapabilityResult> {
            Ok(CapabilityResult::success(input))
        }
    }

    #[tokio::test]
    async fn test_capability_registry() {
        let registry = CapabilityRegistry::new();
        let mock = Arc::new(MockCapability {
            name: "test".into(),
        });

        registry.register(mock).await.unwrap();

        let caps = registry.list().await;
        assert_eq!(caps, vec!["test"]);

        let cap = registry.get("test").await.unwrap();
        assert_eq!(cap.name(), "test");
    }

    #[test]
    fn test_capability_contract() {
        let contract = CapabilityContract::new()
            .with_precondition("needs_input")
            .with_effect("produces_output")
            .with_failure_mode("may_fail")
            .build();

        assert_eq!(contract.preconditions, vec!["needs_input"]);
        assert_eq!(contract.effects, vec!["produces_output"]);
        assert_eq!(contract.failure_modes, vec!["may_fail"]);
    }

    #[test]
    fn test_capability_result() {
        let result = CapabilityResult::success(StructuredContent::text("success"));
        assert!(result.is_success());

        let data = result.data.as_text().unwrap();
        assert_eq!(data, "success");
    }
}