omegon-extension 0.20.0

Omegon extension SDK — safe, versioned interface for third-party extensions
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Manifest validation — caught at extension installation time.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Manifest validation error.
#[derive(Debug, Clone)]
pub struct ManifestError {
    pub reason: String,
    pub is_fatal: bool,
}

impl ManifestError {
    pub fn fatal(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            is_fatal: true,
        }
    }

    pub fn recoverable(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            is_fatal: false,
        }
    }
}

/// Extension metadata from manifest.toml.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionManifest {
    pub extension: ExtensionMetadata,
    pub runtime: RuntimeConfig,
    #[serde(default)]
    pub startup: StartupConfig,
    #[serde(default)]
    pub widgets: HashMap<String, WidgetConfig>,
    #[serde(default)]
    pub mind: MindConfig,
    #[serde(default)]
    pub config: HashMap<String, ConfigField>,
}

/// A declared configuration field in the extension manifest.
///
/// Extensions declare their config requirements in `[config.<field_name>]`
/// tables. The host resolves values from per-extension config files and
/// delivers them via `bootstrap_config` RPC after initialization.
///
/// Example manifest:
/// ```toml
/// [config.signal_phone]
/// type = "string"
/// label = "Signal phone number"
/// description = "E.164 format, e.g. +14155551234"
/// required = true
///
/// [config.webhook_enabled]
/// type = "boolean"
/// label = "Enable webhook"
/// default = "false"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigField {
    /// Field type — determines validation and UI widget.
    #[serde(rename = "type")]
    pub field_type: ConfigFieldType,

    /// Human-readable label for settings UI.
    pub label: String,

    /// Longer description / help text.
    #[serde(default)]
    pub description: String,

    /// Whether the field must have a value before the extension can start.
    #[serde(default)]
    pub required: bool,

    /// Default value (as string — parsed according to `field_type`).
    #[serde(default)]
    pub default: Option<String>,

    /// For `string` fields: regex pattern the value must match.
    #[serde(default)]
    pub pattern: Option<String>,

    /// For `string` fields: hint shown as input placeholder.
    #[serde(default)]
    pub placeholder: Option<String>,

    /// For `enum` fields: allowed values.
    #[serde(default)]
    pub values: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ConfigFieldType {
    String,
    Number,
    Boolean,
    Enum,
    /// Multi-line text (rendered as textarea).
    Text,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionMetadata {
    pub name: String,
    pub version: String,
    #[serde(default)]
    pub description: String,
    /// SDK version constraint (e.g., "0.15.6-*" or "0.15.*" or "0.15").
    /// This is validated against the omegon-extension crate version at install time.
    /// Wildcard matching: "0.15.6" matches "0.15.6-rc.1", "0.15.6-rc.2", "0.15.6".
    #[serde(default)]
    pub sdk_version: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum RuntimeConfig {
    Native { binary: String },
    Oci { image: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StartupConfig {
    /// RPC method to call for health check on startup.
    #[serde(default = "default_ping_method")]
    pub ping_method: String,
    /// Timeout in milliseconds for health check.
    #[serde(default = "default_timeout_ms")]
    pub timeout_ms: u64,
}

fn default_ping_method() -> String {
    "get_tools".to_string()
}

fn default_timeout_ms() -> u64 {
    5000
}

impl Default for StartupConfig {
    fn default() -> Self {
        Self {
            ping_method: default_ping_method(),
            timeout_ms: default_timeout_ms(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetConfig {
    pub label: String,
    pub kind: String, // "stateful" or "ephemeral"
    pub renderer: String,
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MindConfig {
    /// Whether this extension has a persistent mind
    #[serde(default)]
    pub enabled: bool,

    /// Description of the mind for UI/documentation
    #[serde(default)]
    pub description: String,

    /// Maximum facts to keep (optional, default: unlimited)
    #[serde(default)]
    pub max_facts: Option<usize>,

    /// Retention policy: delete facts older than this many days
    #[serde(default)]
    pub retention_days: Option<u32>,
}

impl ExtensionManifest {
    /// Load and validate manifest from TOML file.
    pub fn from_file(path: &Path) -> Result<Self, ManifestError> {
        let content = std::fs::read_to_string(path)
            .map_err(|e| ManifestError::fatal(format!("failed to read manifest: {}", e)))?;

        let manifest: ExtensionManifest = toml::from_str(&content)
            .map_err(|e| ManifestError::fatal(format!("failed to parse manifest: {}", e)))?;

        // Validate
        manifest.validate()?;

        Ok(manifest)
    }

    /// Validate manifest schema.
    fn validate(&self) -> Result<(), ManifestError> {
        // Name must not be empty
        if self.extension.name.is_empty() {
            return Err(ManifestError::fatal("extension.name must not be empty"));
        }

        // Name must be lowercase alphanumeric + hyphens
        if !self
            .extension
            .name
            .chars()
            .all(|c| (c.is_ascii_lowercase() || c.is_ascii_digit()) || c == '-')
        {
            return Err(ManifestError::fatal(
                "extension.name must contain only lowercase alphanumeric and hyphens",
            ));
        }

        // Version must be a valid semver
        if self.extension.version.is_empty() {
            return Err(ManifestError::fatal("extension.version must not be empty"));
        }

        // Validate runtime config
        match &self.runtime {
            RuntimeConfig::Native { binary } => {
                if binary.is_empty() {
                    return Err(ManifestError::fatal("runtime.binary must not be empty"));
                }
                // Don't validate file existence here — that's done at spawn time
            }
            RuntimeConfig::Oci { image } => {
                if image.is_empty() {
                    return Err(ManifestError::fatal("runtime.image must not be empty"));
                }
            }
        }

        // Validate widgets
        for (id, widget) in &self.widgets {
            if id.is_empty() {
                return Err(ManifestError::fatal("widget id must not be empty"));
            }
            if widget.label.is_empty() {
                return Err(ManifestError::fatal("widget.label must not be empty"));
            }
            if widget.renderer.is_empty() {
                return Err(ManifestError::fatal("widget.renderer must not be empty"));
            }
            // Validate kind
            match widget.kind.as_str() {
                "stateful" | "ephemeral" => {}
                _ => {
                    return Err(ManifestError::fatal(format!(
                        "widget.kind must be 'stateful' or 'ephemeral', got '{}'",
                        widget.kind
                    )));
                }
            }
        }

        // Validate startup config
        if self.startup.timeout_ms == 0 {
            return Err(ManifestError::fatal("startup.timeout_ms must be > 0"));
        }
        if self.startup.timeout_ms > 60000 {
            return Err(ManifestError::recoverable(
                "startup.timeout_ms > 60s is unusual; extensions should start faster",
            ));
        }

        // Validate config fields
        for (name, field) in &self.config {
            if name.is_empty() {
                return Err(ManifestError::fatal("config field name must not be empty"));
            }
            if field.label.is_empty() {
                return Err(ManifestError::fatal(format!(
                    "config.{name}.label must not be empty"
                )));
            }
            if field.field_type == ConfigFieldType::Enum && field.values.is_empty() {
                return Err(ManifestError::fatal(format!(
                    "config.{name} is type 'enum' but declares no values"
                )));
            }
            if let Some(ref pattern) = field.pattern {
                if pattern.is_empty() {
                    return Err(ManifestError::fatal(format!(
                        "config.{name}.pattern must not be empty if specified"
                    )));
                }
            }
        }

        Ok(())
    }

    /// Check SDK version compatibility.
    ///
    /// # Constraints
    ///
    /// - Extension declares `sdk_version` in manifest.toml
    /// - Omegon validates at install time: extension's sdk_version must match omegon's SDK crate version
    /// - Wildcard matching: "0.15" matches "0.15.0", "0.15.6", "0.15.6-rc.1"
    /// - Exact match preferred: "0.15.6" prevents forward compatibility risks
    pub fn check_sdk_version(&self, omegon_sdk_version: &str) -> Result<(), ManifestError> {
        if self.extension.sdk_version.is_empty() {
            // Not specified — allow for now, but warn
            return Err(ManifestError::recoverable(
                "extension.sdk_version not specified; recommend adding for safety",
            ));
        }

        // Simple semver prefix matching
        // "0.15" matches "0.15.6", "0.15.6-rc.1"
        // "0.15.6" matches "0.15.6", "0.15.6-rc.1"
        if !omegon_sdk_version.starts_with(&self.extension.sdk_version) {
            return Err(ManifestError::fatal(format!(
                "SDK version mismatch: extension requires {}, but omegon has {}",
                self.extension.sdk_version, omegon_sdk_version
            )));
        }

        Ok(())
    }
}

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

    #[test]
    fn test_validate_native_manifest() {
        let manifest = ExtensionManifest {
            extension: ExtensionMetadata {
                name: "my-ext".to_string(),
                version: "0.1.0".to_string(),
                description: "Test".to_string(),
                sdk_version: "0.15".to_string(),
            },
            runtime: RuntimeConfig::Native {
                binary: "target/release/my-ext".to_string(),
            },
            startup: StartupConfig::default(),
            widgets: HashMap::new(),
            mind: MindConfig::default(),
            config: HashMap::new(),
        };

        assert!(manifest.validate().is_ok());
    }

    #[test]
    fn test_validate_invalid_name() {
        let manifest = ExtensionManifest {
            extension: ExtensionMetadata {
                name: "MY_EXT".to_string(),
                version: "0.1.0".to_string(),
                description: "".to_string(),
                sdk_version: "".to_string(),
            },
            runtime: RuntimeConfig::Native {
                binary: "binary".to_string(),
            },
            startup: StartupConfig::default(),
            widgets: HashMap::new(),
            mind: MindConfig::default(),
            config: HashMap::new(),
        };

        assert!(manifest.validate().is_err());
    }

    #[test]
    fn test_sdk_version_check() {
        let manifest = ExtensionManifest {
            extension: ExtensionMetadata {
                name: "test".to_string(),
                version: "0.1.0".to_string(),
                description: "".to_string(),
                sdk_version: "0.15".to_string(),
            },
            runtime: RuntimeConfig::Native {
                binary: "binary".to_string(),
            },
            startup: StartupConfig::default(),
            widgets: HashMap::new(),
            mind: MindConfig::default(),
            config: HashMap::new(),
        };

        // Exact match
        assert!(manifest.check_sdk_version("0.15.6").is_ok());
        // Prefix match
        assert!(manifest.check_sdk_version("0.15.6-rc.1").is_ok());
        // Mismatch
        assert!(manifest.check_sdk_version("0.16.0").is_err());
    }

    #[test]
    fn test_config_fields_parse_from_toml() {
        let toml_str = r#"
[extension]
name = "vox"
version = "0.1.0"

[runtime]
type = "native"
binary = "target/release/vox"

[config.signal_phone]
type = "string"
label = "Signal phone number"
description = "E.164 format"
required = true
pattern = '^\+[1-9]\d{1,14}$'
placeholder = "+14155551234"

[config.webhook_enabled]
type = "boolean"
label = "Enable webhook"
default = "false"

[config.imap_provider]
type = "enum"
label = "IMAP provider"
values = ["gmail", "fastmail", "custom"]
default = "gmail"
"#;

        let manifest: ExtensionManifest = toml::from_str(toml_str).unwrap();
        assert_eq!(manifest.config.len(), 3);

        let phone = &manifest.config["signal_phone"];
        assert_eq!(phone.field_type, ConfigFieldType::String);
        assert!(phone.required);
        assert_eq!(phone.pattern.as_deref(), Some(r"^\+[1-9]\d{1,14}$"));

        let webhook = &manifest.config["webhook_enabled"];
        assert_eq!(webhook.field_type, ConfigFieldType::Boolean);
        assert!(!webhook.required);
        assert_eq!(webhook.default.as_deref(), Some("false"));

        let imap = &manifest.config["imap_provider"];
        assert_eq!(imap.field_type, ConfigFieldType::Enum);
        assert_eq!(imap.values, vec!["gmail", "fastmail", "custom"]);

        assert!(manifest.validate().is_ok());
    }

    #[test]
    fn test_config_enum_requires_values() {
        let manifest = ExtensionManifest {
            extension: ExtensionMetadata {
                name: "test".into(),
                version: "0.1.0".into(),
                description: "".into(),
                sdk_version: "".into(),
            },
            runtime: RuntimeConfig::Native { binary: "bin".into() },
            startup: StartupConfig::default(),
            widgets: HashMap::new(),
            mind: MindConfig::default(),
            config: HashMap::from([(
                "my_enum".into(),
                ConfigField {
                    field_type: ConfigFieldType::Enum,
                    label: "Pick one".into(),
                    description: "".into(),
                    required: false,
                    default: None,
                    pattern: None,
                    placeholder: None,
                    values: vec![],
                },
            )]),
        };

        let err = manifest.validate().unwrap_err();
        assert!(err.reason.contains("no values"));
    }

    #[test]
    fn test_config_backwards_compat_no_config_section() {
        let toml_str = r#"
[extension]
name = "old-ext"
version = "0.1.0"

[runtime]
type = "native"
binary = "target/release/old"
"#;
        let manifest: ExtensionManifest = toml::from_str(toml_str).unwrap();
        assert!(manifest.config.is_empty());
        assert!(manifest.validate().is_ok());
    }
}