dist_agent_lang 1.0.24

Agentic programming with library and CLI support for Off/On-chain network integration
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
// Unified interface abstraction for HTTP and FFI
use crate::runtime::values::Value;
#[cfg(feature = "http-interface")]
use log;
use std::collections::HashMap;

/// Interface type selection
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterfaceType {
    /// HTTP/REST API only
    HTTP,
    /// FFI (Foreign Function Interface) only
    FFI,
    /// Both HTTP and FFI available
    Both,
}

/// Service interface abstraction
pub trait ServiceInterface: Send + Sync {
    /// Call a service function
    fn call_function(
        &self,
        service_name: &str,
        function_name: &str,
        args: &[Value],
    ) -> Result<Value, String>;

    /// Get interface type
    fn interface_type(&self) -> InterfaceType;

    /// Check if interface is available
    fn is_available(&self) -> bool;
}

/// FFI Interface manager
pub struct FFIInterface {
    config: crate::ffi::FFIConfig,
    http_interface: Option<Box<dyn ServiceInterface>>,
    ffi_interface: Option<Box<dyn ServiceInterface>>,
}

impl FFIInterface {
    pub fn new(config: crate::ffi::FFIConfig) -> Self {
        let mut http_interface = None;
        let mut ffi_interface = None;

        if config.enable_http {
            http_interface = Some(Box::new(HttpInterface::new()) as Box<dyn ServiceInterface>);
        }

        if config.enable_ffi {
            if config.rust_enabled {
                ffi_interface =
                    Some(Box::new(RustFFIInterface::new()) as Box<dyn ServiceInterface>);
            }
        }

        Self {
            config,
            http_interface,
            ffi_interface,
        }
    }

    /// Call function using the appropriate interface
    /// If no explicit preference, automatically chooses based on heuristics
    pub fn call(
        &self,
        service_name: &str,
        function_name: &str,
        args: &[Value],
        prefer_ffi: Option<bool>,
    ) -> Result<Value, String> {
        // Auto-detect if no preference specified
        let should_use_ffi = prefer_ffi
            .unwrap_or_else(|| self.auto_detect_interface(service_name, function_name, args));

        match self.config.interface_type {
            InterfaceType::HTTP => {
                if let Some(ref http) = self.http_interface {
                    http.call_function(service_name, function_name, args)
                } else {
                    Err("HTTP interface not available".to_string())
                }
            }
            InterfaceType::FFI => {
                if let Some(ref ffi) = self.ffi_interface {
                    ffi.call_function(service_name, function_name, args)
                } else {
                    Err("FFI interface not available".to_string())
                }
            }
            InterfaceType::Both => {
                // Auto-select based on heuristics or preference
                if should_use_ffi {
                    // Try FFI first
                    if let Some(ref ffi) = self.ffi_interface {
                        if ffi.is_available() {
                            match ffi.call_function(service_name, function_name, args) {
                                Ok(result) => return Ok(result),
                                Err(e) => {
                                    // FFI failed, fallback to HTTP
                                    #[cfg(feature = "http-interface")]
                                    log::warn!("FFI call failed, falling back to HTTP: {}", e);
                                    // Continue to HTTP fallback
                                }
                            }
                        }
                    }
                }

                // Use HTTP (or FFI if HTTP not available)
                if let Some(ref http) = self.http_interface {
                    http.call_function(service_name, function_name, args)
                } else if let Some(ref ffi) = self.ffi_interface {
                    ffi.call_function(service_name, function_name, args)
                } else {
                    Err("No interface available".to_string())
                }
            }
        }
    }

    /// Auto-detect which interface to use based on heuristics
    fn auto_detect_interface(
        &self,
        service_name: &str,
        function_name: &str,
        args: &[Value],
    ) -> bool {
        // Heuristic 1: Check if this is a local call (same process)
        // If we're in the same process, prefer FFI
        if self.ffi_interface.is_some() {
            // Heuristic 2: Function name patterns that suggest high-frequency operations
            let ffi_preferred_patterns = [
                "hash",
                "sign",
                "verify",
                "encrypt",
                "decrypt",
                "compute",
                "calculate",
                "process",
                "transform",
                "batch_",
                "parallel_",
                "fast_",
            ];

            for pattern in &ffi_preferred_patterns {
                if function_name.contains(pattern) {
                    return true; // Prefer FFI for compute-intensive operations
                }
            }

            // Heuristic 3: Small argument size suggests local operation
            // Large arguments might benefit from HTTP's serialization
            let total_arg_size: usize = args.iter().map(|v| self.estimate_value_size(v)).sum();

            if total_arg_size < 1024 {
                // Small data - prefer FFI (low serialization overhead)
                return true;
            }
        }

        // Heuristic 4: Network-bound operations prefer HTTP
        let http_preferred_patterns = [
            "chain::",
            "database::",
            "network_",
            "remote_",
            "fetch",
            "request",
            "api_",
            "http_",
        ];

        for pattern in &http_preferred_patterns {
            if function_name.contains(pattern) || service_name.contains(pattern) {
                return false; // Prefer HTTP for network operations
            }
        }

        // Default: Prefer FFI if available (better performance)
        // Fallback to HTTP if FFI not available
        self.ffi_interface.is_some() && self.ffi_interface.as_ref().unwrap().is_available()
    }

    /// Estimate the size of a value in bytes (rough approximation)
    fn estimate_value_size(&self, value: &Value) -> usize {
        match value {
            Value::Int(_) => 8,
            Value::Float(_) => 8,
            Value::Bool(_) => 1,
            Value::Null => 0,
            Value::String(s) => s.len(),
            Value::List(arr) => arr.iter().map(|v| self.estimate_value_size(v)).sum(),
            Value::Array(arr) => arr.iter().map(|v| self.estimate_value_size(v)).sum(),
            Value::Map(map) => map
                .iter()
                .map(|(k, v)| k.len() + self.estimate_value_size(v))
                .sum(),
            Value::Result(ok_val, err_val) => {
                self.estimate_value_size(ok_val) + self.estimate_value_size(err_val)
            }
            Value::Option(opt) => opt
                .as_ref()
                .map(|v| self.estimate_value_size(v))
                .unwrap_or(0),
            Value::Set(set) => set.len() * 8, // Rough estimate
            Value::Struct(_, fields) => fields
                .iter()
                .map(|(k, v)| k.len() + self.estimate_value_size(v))
                .sum(),
            Value::Closure(id) => id.len() + 8,
        }
    }
}

/// HTTP Interface implementation
#[cfg(feature = "http-interface")]
struct HttpInterface {
    base_url: String,
}

#[cfg(feature = "http-interface")]
impl HttpInterface {
    fn new() -> Self {
        Self {
            base_url: "http://localhost:3000".to_string(),
        }
    }
}

#[cfg(feature = "http-interface")]
impl ServiceInterface for HttpInterface {
    fn call_function(
        &self,
        service_name: &str,
        function_name: &str,
        args: &[Value],
    ) -> Result<Value, String> {
        // Serialize arguments to JSON
        let json_args: Vec<serde_json::Value> = args.iter().map(|v| value_to_json(v)).collect();

        // Make HTTP request
        let url = format!("{}/api/{}/{}", self.base_url, service_name, function_name);
        let client = reqwest::blocking::Client::new();
        let response = client
            .post(&url)
            .json(&json_args)
            .send()
            .map_err(|e| format!("HTTP request failed: {}", e))?;

        let result: serde_json::Value = response
            .json()
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        // Convert JSON back to Value
        json_to_value(&result)
    }

    fn interface_type(&self) -> InterfaceType {
        InterfaceType::HTTP
    }

    fn is_available(&self) -> bool {
        true // HTTP is always available if server is running
    }
}

// Stub when HTTP interface is not available
#[cfg(not(feature = "http-interface"))]
struct HttpInterface;

#[cfg(not(feature = "http-interface"))]
impl HttpInterface {
    fn new() -> Self {
        Self
    }
}

#[cfg(not(feature = "http-interface"))]
impl ServiceInterface for HttpInterface {
    fn call_function(
        &self,
        _service_name: &str,
        _function_name: &str,
        _args: &[Value],
    ) -> Result<Value, String> {
        Err("HTTP interface not available (compile with 'http-interface' feature)".to_string())
    }

    fn interface_type(&self) -> InterfaceType {
        InterfaceType::HTTP
    }

    fn is_available(&self) -> bool {
        false
    }
}

/// Rust FFI Interface implementation
struct RustFFIInterface;

impl RustFFIInterface {
    fn new() -> Self {
        Self
    }
}

impl ServiceInterface for RustFFIInterface {
    fn call_function(
        &self,
        _service_name: &str,
        _function_name: &str,
        _args: &[Value],
    ) -> Result<Value, String> {
        // Direct function call - zero overhead
        // This would call the actual runtime directly
        // Note: This is a simplified implementation
        // In a real implementation, you'd maintain a runtime instance
        // For now, return an error indicating FFI needs runtime integration
        Err(
            "FFI interface requires runtime integration - use execute_source or execute_program"
                .to_string(),
        )
    }

    fn interface_type(&self) -> InterfaceType {
        InterfaceType::FFI
    }

    fn is_available(&self) -> bool {
        true // Native FFI is always available
    }
}

// Helper functions for JSON conversion
pub fn value_to_json(value: &Value) -> serde_json::Value {
    match value {
        Value::Int(i) => serde_json::Value::Number((*i).into()),
        Value::Float(f) => serde_json::Value::Number(
            serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0)),
        ),
        Value::String(s) => serde_json::Value::String(s.clone()),
        Value::Bool(b) => serde_json::Value::Bool(*b),
        Value::Null => serde_json::Value::Null,
        Value::List(arr) => serde_json::Value::Array(arr.iter().map(value_to_json).collect()),
        Value::Map(map) => {
            let mut json_map = serde_json::Map::new();
            for (k, v) in map {
                json_map.insert(k.clone(), value_to_json(v));
            }
            serde_json::Value::Object(json_map)
        }
        Value::Result(ok_val, err_val) => {
            // Serialize Result as object
            let mut json_map = serde_json::Map::new();
            json_map.insert("ok".to_string(), value_to_json(ok_val));
            json_map.insert("err".to_string(), value_to_json(err_val));
            serde_json::Value::Object(json_map)
        }
        Value::Option(opt) => match opt {
            Some(v) => value_to_json(v),
            None => serde_json::Value::Null,
        },
        Value::Set(set) => serde_json::Value::Array(
            set.iter()
                .map(|s| serde_json::Value::String(s.clone()))
                .collect(),
        ),
        Value::Struct(name, fields) => {
            let mut json_map = serde_json::Map::new();
            json_map.insert("_type".to_string(), serde_json::Value::String(name.clone()));
            for (k, v) in fields {
                json_map.insert(k.clone(), value_to_json(v));
            }
            serde_json::Value::Object(json_map)
        }
        Value::Array(arr) => serde_json::Value::Array(arr.iter().map(value_to_json).collect()),
        Value::Closure(id) => serde_json::Value::String(format!("<closure {}>", id)),
    }
}

/// Convert serde_json::Value to DAL Value. Used by json::parse.
pub fn json_to_value(json: &serde_json::Value) -> Result<Value, String> {
    match json {
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(Value::Int(i))
            } else if let Some(f) = n.as_f64() {
                Ok(Value::Float(f))
            } else {
                Err("Invalid number".to_string())
            }
        }
        serde_json::Value::String(s) => Ok(Value::String(s.clone())),
        serde_json::Value::Bool(b) => Ok(Value::Bool(*b)),
        serde_json::Value::Null => Ok(Value::Null),
        serde_json::Value::Array(arr) => {
            let values: Result<Vec<Value>, String> = arr.iter().map(json_to_value).collect();
            Ok(Value::List(values?))
        }
        serde_json::Value::Object(map) => {
            // Check if it's a Result or Struct
            if let Some(type_val) = map.get("_type") {
                if let Some(type_str) = type_val.as_str() {
                    let mut fields = HashMap::new();
                    for (k, v) in map {
                        if k != "_type" {
                            fields.insert(k.clone(), json_to_value(v)?);
                        }
                    }
                    return Ok(Value::Struct(type_str.to_string(), fields));
                }
            }

            // Regular map
            let mut value_map = HashMap::new();
            for (k, v) in map {
                value_map.insert(k.clone(), json_to_value(v)?);
            }
            Ok(Value::Map(value_map))
        }
    }
}