clawft-plugin 0.6.3

Plugin trait definitions for clawft
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Plugin manifest types.
//!
//! Defines [`PluginManifest`], [`PluginCapability`], [`PluginPermissions`],
//! and [`PluginResourceConfig`] -- the schema for plugin metadata parsed
//! from `clawft.plugin.json` or `.yaml` files.

use serde::{Deserialize, Serialize};

use crate::PluginError;

/// Plugin manifest parsed from `clawft.plugin.json` or `.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginManifest {
    /// Unique plugin identifier (reverse-domain, e.g., `"com.example.my-plugin"`).
    pub id: String,

    /// Human-readable plugin name.
    pub name: String,

    /// Semantic version string (must be valid semver).
    pub version: String,

    /// Capabilities this plugin provides.
    pub capabilities: Vec<PluginCapability>,

    /// Permissions the plugin requests.
    #[serde(default)]
    pub permissions: PluginPermissions,

    /// Resource limits configuration.
    #[serde(default)]
    pub resources: PluginResourceConfig,

    /// Path to the WASM module (relative to plugin directory).
    #[serde(default)]
    pub wasm_module: Option<String>,

    /// Skills provided by this plugin.
    #[serde(default)]
    pub skills: Vec<String>,

    /// Tools provided by this plugin.
    #[serde(default)]
    pub tools: Vec<String>,
}

/// Plugin capability types.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginCapability {
    /// Tool execution capability.
    Tool,
    /// Channel adapter capability.
    Channel,
    /// Pipeline stage capability.
    PipelineStage,
    /// Skill definition capability.
    Skill,
    /// Memory backend capability.
    MemoryBackend,
    /// Reserved for Workstream G (voice/audio).
    Voice,
}

/// Permissions requested by a plugin.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PluginPermissions {
    /// Allowed network hosts. Empty = no network. `["*"]` = all hosts.
    #[serde(default)]
    pub network: Vec<String>,

    /// Allowed filesystem paths.
    #[serde(default)]
    pub filesystem: Vec<String>,

    /// Allowed environment variable names.
    #[serde(default)]
    pub env_vars: Vec<String>,

    /// Whether the plugin can execute shell commands.
    #[serde(default)]
    pub shell: bool,
}

/// Resource limits for plugin execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginResourceConfig {
    /// Maximum WASM fuel per invocation (default: 1,000,000,000).
    #[serde(default = "default_max_fuel")]
    pub max_fuel: u64,

    /// Maximum WASM memory in MB (default: 16).
    #[serde(default = "default_max_memory_mb")]
    pub max_memory_mb: usize,

    /// Maximum HTTP requests per minute (default: 10).
    #[serde(default = "default_max_http_rpm")]
    pub max_http_requests_per_minute: u64,

    /// Maximum log messages per minute (default: 100).
    #[serde(default = "default_max_log_rpm")]
    pub max_log_messages_per_minute: u64,

    /// Maximum execution wall-clock seconds (default: 30).
    #[serde(default = "default_max_exec_seconds")]
    pub max_execution_seconds: u64,

    /// Maximum WASM table elements (default: 10,000).
    #[serde(default = "default_max_table_elements")]
    pub max_table_elements: u32,
}

fn default_max_fuel() -> u64 {
    1_000_000_000
}
fn default_max_memory_mb() -> usize {
    16
}
fn default_max_http_rpm() -> u64 {
    10
}
fn default_max_log_rpm() -> u64 {
    100
}
fn default_max_exec_seconds() -> u64 {
    30
}
fn default_max_table_elements() -> u32 {
    10_000
}

impl Default for PluginResourceConfig {
    fn default() -> Self {
        Self {
            max_fuel: default_max_fuel(),
            max_memory_mb: default_max_memory_mb(),
            max_http_requests_per_minute: default_max_http_rpm(),
            max_log_messages_per_minute: default_max_log_rpm(),
            max_execution_seconds: default_max_exec_seconds(),
            max_table_elements: default_max_table_elements(),
        }
    }
}

/// Represents new permissions requested by a plugin version upgrade
/// that were not present in the previously approved permission set.
///
/// Used to determine which permissions need user re-approval when a
/// plugin updates its manifest.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PermissionDiff {
    /// Network hosts requested that were not previously approved.
    pub new_network: Vec<String>,
    /// Filesystem paths requested that were not previously approved.
    pub new_filesystem: Vec<String>,
    /// Environment variables requested that were not previously approved.
    pub new_env_vars: Vec<String>,
    /// Whether shell access is being escalated from `false` to `true`.
    pub shell_escalation: bool,
}

impl PermissionDiff {
    /// Returns `true` if no new permissions are being requested.
    pub fn is_empty(&self) -> bool {
        self.new_network.is_empty()
            && self.new_filesystem.is_empty()
            && self.new_env_vars.is_empty()
            && !self.shell_escalation
    }
}

impl PluginPermissions {
    /// Compute the diff between previously approved permissions and newly
    /// requested permissions.
    ///
    /// Returns a [`PermissionDiff`] containing only the items in `requested`
    /// that are not present in `approved`. For the `shell` field, only an
    /// escalation from `false` to `true` counts as a new permission.
    pub fn diff(approved: &PluginPermissions, requested: &PluginPermissions) -> PermissionDiff {
        let new_network = requested
            .network
            .iter()
            .filter(|item| !approved.network.contains(item))
            .cloned()
            .collect();

        let new_filesystem = requested
            .filesystem
            .iter()
            .filter(|item| !approved.filesystem.contains(item))
            .cloned()
            .collect();

        let new_env_vars = requested
            .env_vars
            .iter()
            .filter(|item| !approved.env_vars.contains(item))
            .cloned()
            .collect();

        let shell_escalation = !approved.shell && requested.shell;

        PermissionDiff {
            new_network,
            new_filesystem,
            new_env_vars,
            shell_escalation,
        }
    }
}

impl PluginManifest {
    /// Validate the manifest. Returns an error describing the first
    /// validation failure, or `Ok(())` if the manifest is valid.
    pub fn validate(&self) -> Result<(), PluginError> {
        if self.id.is_empty() {
            return Err(PluginError::LoadFailed(
                "manifest: id is required".into(),
            ));
        }
        if self.id.len() > 128 {
            return Err(PluginError::LoadFailed(
                "manifest: id must be 128 characters or fewer".into(),
            ));
        }
        if !self
            .id
            .chars()
            .all(|c| c.is_alphanumeric() || c == '.' || c == '-' || c == '_')
        {
            return Err(PluginError::LoadFailed(
                "manifest: id must contain only alphanumeric characters, dots, hyphens, and underscores".into(),
            ));
        }
        if self.name.is_empty() {
            return Err(PluginError::LoadFailed(
                "manifest: name is required".into(),
            ));
        }
        // Validate semver
        if semver::Version::parse(&self.version).is_err() {
            return Err(PluginError::LoadFailed(format!(
                "manifest: invalid semver version '{}'",
                self.version
            )));
        }
        if self.capabilities.is_empty() {
            return Err(PluginError::LoadFailed(
                "manifest: at least one capability is required".into(),
            ));
        }
        Ok(())
    }

    /// Parse a manifest from a JSON string.
    pub fn from_json(json: &str) -> Result<Self, PluginError> {
        let manifest: Self = serde_json::from_str(json)?;
        manifest.validate()?;
        Ok(manifest)
    }

    /// Parse a manifest from a YAML string.
    ///
    /// Note: `serde_yaml` is NOT a dependency of `clawft-plugin` to keep the
    /// crate lightweight. YAML manifest parsing is handled in the loader
    /// layer (C3) which calls `serde_yaml::from_str()` and then constructs a
    /// `PluginManifest`. This method is a convenience stub.
    pub fn from_yaml(_yaml: &str) -> Result<Self, PluginError> {
        Err(PluginError::NotImplemented(
            "YAML manifest parsing deferred to C3 skill loader".into(),
        ))
    }
}

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

    fn valid_manifest_json() -> String {
        serde_json::json!({
            "id": "com.example.test-plugin",
            "name": "Test Plugin",
            "version": "1.0.0",
            "capabilities": ["tool", "skill"],
            "permissions": {
                "network": ["api.example.com"],
                "filesystem": ["/tmp/plugin"],
                "env_vars": ["MY_API_KEY"],
                "shell": false
            },
            "resources": {
                "max_fuel": 500_000_000u64,
                "max_memory_mb": 8,
                "max_http_requests_per_minute": 5,
                "max_log_messages_per_minute": 50,
                "max_execution_seconds": 15,
                "max_table_elements": 5000
            },
            "wasm_module": "plugin.wasm",
            "skills": ["code-review"],
            "tools": ["lint_code"]
        })
        .to_string()
    }

    #[test]
    fn test_manifest_parse_json() {
        let json = valid_manifest_json();
        let manifest = PluginManifest::from_json(&json).unwrap();
        assert_eq!(manifest.id, "com.example.test-plugin");
        assert_eq!(manifest.name, "Test Plugin");
        assert_eq!(manifest.version, "1.0.0");
        assert_eq!(manifest.capabilities.len(), 2);
        assert_eq!(manifest.capabilities[0], PluginCapability::Tool);
        assert_eq!(manifest.capabilities[1], PluginCapability::Skill);
        assert_eq!(manifest.permissions.network, vec!["api.example.com"]);
        assert_eq!(manifest.permissions.filesystem, vec!["/tmp/plugin"]);
        assert_eq!(manifest.permissions.env_vars, vec!["MY_API_KEY"]);
        assert!(!manifest.permissions.shell);
        assert_eq!(manifest.resources.max_fuel, 500_000_000);
        assert_eq!(manifest.resources.max_memory_mb, 8);
        assert_eq!(manifest.resources.max_http_requests_per_minute, 5);
        assert_eq!(manifest.resources.max_log_messages_per_minute, 50);
        assert_eq!(manifest.resources.max_execution_seconds, 15);
        assert_eq!(manifest.resources.max_table_elements, 5000);
        assert_eq!(manifest.wasm_module, Some("plugin.wasm".into()));
        assert_eq!(manifest.skills, vec!["code-review"]);
        assert_eq!(manifest.tools, vec!["lint_code"]);
    }

    #[test]
    fn test_manifest_parse_yaml_returns_not_implemented() {
        let result = PluginManifest::from_yaml("name: test");
        assert!(result.is_err());
        match result.unwrap_err() {
            PluginError::NotImplemented(msg) => {
                assert!(msg.contains("YAML manifest parsing deferred"));
            }
            other => panic!("expected NotImplemented, got: {other}"),
        }
    }

    #[test]
    fn test_manifest_missing_id_fails() {
        let json = serde_json::json!({
            "id": "",
            "name": "Test",
            "version": "1.0.0",
            "capabilities": ["tool"]
        })
        .to_string();
        let err = PluginManifest::from_json(&json).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("id is required"), "got: {msg}");
    }

    #[test]
    fn test_manifest_invalid_version_fails() {
        let json = serde_json::json!({
            "id": "com.test",
            "name": "Test",
            "version": "not-semver",
            "capabilities": ["tool"]
        })
        .to_string();
        let err = PluginManifest::from_json(&json).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("invalid semver"), "got: {msg}");
    }

    #[test]
    fn test_manifest_empty_capabilities_fails() {
        let json = serde_json::json!({
            "id": "com.test",
            "name": "Test",
            "version": "1.0.0",
            "capabilities": []
        })
        .to_string();
        let err = PluginManifest::from_json(&json).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("at least one capability"),
            "got: {msg}"
        );
    }

    #[test]
    fn test_manifest_missing_name_fails() {
        let json = serde_json::json!({
            "id": "com.test",
            "name": "",
            "version": "1.0.0",
            "capabilities": ["tool"]
        })
        .to_string();
        let err = PluginManifest::from_json(&json).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("name is required"), "got: {msg}");
    }

    #[test]
    fn test_plugin_capability_serde_roundtrip() {
        let capabilities = vec![
            PluginCapability::Tool,
            PluginCapability::Channel,
            PluginCapability::PipelineStage,
            PluginCapability::Skill,
            PluginCapability::MemoryBackend,
            PluginCapability::Voice,
        ];
        for cap in &capabilities {
            let json = serde_json::to_string(cap).unwrap();
            let restored: PluginCapability = serde_json::from_str(&json).unwrap();
            assert_eq!(&restored, cap);
        }
    }

    #[test]
    fn test_plugin_capability_json_values() {
        assert_eq!(
            serde_json::to_string(&PluginCapability::Tool).unwrap(),
            "\"tool\""
        );
        assert_eq!(
            serde_json::to_string(&PluginCapability::Channel).unwrap(),
            "\"channel\""
        );
        assert_eq!(
            serde_json::to_string(&PluginCapability::PipelineStage).unwrap(),
            "\"pipeline_stage\""
        );
        assert_eq!(
            serde_json::to_string(&PluginCapability::Skill).unwrap(),
            "\"skill\""
        );
        assert_eq!(
            serde_json::to_string(&PluginCapability::MemoryBackend).unwrap(),
            "\"memory_backend\""
        );
        assert_eq!(
            serde_json::to_string(&PluginCapability::Voice).unwrap(),
            "\"voice\""
        );
    }

    #[test]
    fn test_permissions_default_is_empty() {
        let perms = PluginPermissions::default();
        assert!(perms.network.is_empty());
        assert!(perms.filesystem.is_empty());
        assert!(perms.env_vars.is_empty());
        assert!(!perms.shell);
    }

    #[test]
    fn test_resource_config_defaults() {
        let config = PluginResourceConfig::default();
        assert_eq!(config.max_fuel, 1_000_000_000);
        assert_eq!(config.max_memory_mb, 16);
        assert_eq!(config.max_http_requests_per_minute, 10);
        assert_eq!(config.max_log_messages_per_minute, 100);
        assert_eq!(config.max_execution_seconds, 30);
        assert_eq!(config.max_table_elements, 10_000);
    }

    #[test]
    fn test_manifest_with_defaults() {
        let json = serde_json::json!({
            "id": "com.test.minimal",
            "name": "Minimal",
            "version": "0.1.0",
            "capabilities": ["tool"]
        })
        .to_string();
        let manifest = PluginManifest::from_json(&json).unwrap();
        // Permissions default to empty
        assert!(manifest.permissions.network.is_empty());
        assert!(!manifest.permissions.shell);
        // Resources default to standard values
        assert_eq!(manifest.resources.max_fuel, 1_000_000_000);
        assert_eq!(manifest.resources.max_memory_mb, 16);
        // Optional fields default to None/empty
        assert!(manifest.wasm_module.is_none());
        assert!(manifest.skills.is_empty());
        assert!(manifest.tools.is_empty());
    }

    #[test]
    fn test_manifest_serde_roundtrip() {
        let json = valid_manifest_json();
        let manifest = PluginManifest::from_json(&json).unwrap();
        let serialized = serde_json::to_string(&manifest).unwrap();
        let restored = PluginManifest::from_json(&serialized).unwrap();
        assert_eq!(manifest.id, restored.id);
        assert_eq!(manifest.name, restored.name);
        assert_eq!(manifest.version, restored.version);
        assert_eq!(manifest.capabilities, restored.capabilities);
    }

    #[test]
    fn test_permissions_serde_roundtrip() {
        let perms = PluginPermissions {
            network: vec!["*.example.com".into(), "api.test.com".into()],
            filesystem: vec!["/tmp".into(), "/data".into()],
            env_vars: vec!["MY_KEY".into()],
            shell: true,
        };
        let json = serde_json::to_string(&perms).unwrap();
        let restored: PluginPermissions = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.network, perms.network);
        assert_eq!(restored.filesystem, perms.filesystem);
        assert_eq!(restored.env_vars, perms.env_vars);
        assert_eq!(restored.shell, perms.shell);
    }

    // -- PermissionDiff tests --

    #[test]
    fn diff_identical_permissions_is_empty() {
        let perms = PluginPermissions {
            network: vec!["api.example.com".into()],
            filesystem: vec!["/tmp".into()],
            env_vars: vec!["HOME".into()],
            shell: true,
        };
        let diff = PluginPermissions::diff(&perms, &perms);
        assert!(diff.is_empty());
        assert_eq!(diff, PermissionDiff::default());
    }

    #[test]
    fn diff_detects_new_network_hosts() {
        let approved = PluginPermissions {
            network: vec!["api.example.com".into()],
            ..Default::default()
        };
        let requested = PluginPermissions {
            network: vec!["api.example.com".into(), "cdn.example.com".into()],
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert_eq!(diff.new_network, vec!["cdn.example.com"]);
        assert!(diff.new_filesystem.is_empty());
        assert!(diff.new_env_vars.is_empty());
        assert!(!diff.shell_escalation);
        assert!(!diff.is_empty());
    }

    #[test]
    fn diff_detects_new_filesystem_paths() {
        let approved = PluginPermissions {
            filesystem: vec!["/tmp".into()],
            ..Default::default()
        };
        let requested = PluginPermissions {
            filesystem: vec!["/tmp".into(), "/data".into()],
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert_eq!(diff.new_filesystem, vec!["/data"]);
    }

    #[test]
    fn diff_detects_new_env_vars() {
        let approved = PluginPermissions {
            env_vars: vec!["HOME".into()],
            ..Default::default()
        };
        let requested = PluginPermissions {
            env_vars: vec!["HOME".into(), "API_KEY".into()],
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert_eq!(diff.new_env_vars, vec!["API_KEY"]);
    }

    #[test]
    fn diff_detects_shell_escalation() {
        let approved = PluginPermissions {
            shell: false,
            ..Default::default()
        };
        let requested = PluginPermissions {
            shell: true,
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert!(diff.shell_escalation);
        assert!(!diff.is_empty());
    }

    #[test]
    fn diff_no_shell_escalation_when_already_approved() {
        let approved = PluginPermissions {
            shell: true,
            ..Default::default()
        };
        let requested = PluginPermissions {
            shell: true,
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert!(!diff.shell_escalation);
    }

    #[test]
    fn diff_no_shell_escalation_on_downgrade() {
        let approved = PluginPermissions {
            shell: true,
            ..Default::default()
        };
        let requested = PluginPermissions {
            shell: false,
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert!(!diff.shell_escalation);
    }

    #[test]
    fn diff_empty_approved_all_requested_are_new() {
        let approved = PluginPermissions::default();
        let requested = PluginPermissions {
            network: vec!["a.com".into(), "b.com".into()],
            filesystem: vec!["/data".into()],
            env_vars: vec!["KEY".into()],
            shell: true,
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert_eq!(diff.new_network, vec!["a.com", "b.com"]);
        assert_eq!(diff.new_filesystem, vec!["/data"]);
        assert_eq!(diff.new_env_vars, vec!["KEY"]);
        assert!(diff.shell_escalation);
    }

    #[test]
    fn diff_removed_permissions_not_reported() {
        // If requested drops a permission that was approved, it should NOT
        // appear as a new permission (only additions are reported).
        let approved = PluginPermissions {
            network: vec!["old.example.com".into(), "keep.example.com".into()],
            ..Default::default()
        };
        let requested = PluginPermissions {
            network: vec!["keep.example.com".into()],
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert!(diff.is_empty());
    }

    #[test]
    fn diff_wildcard_network_is_treated_as_new_entry() {
        // Wildcard "*" is compared as a literal string entry.
        // If the approved set has specific domains but the requested set
        // adds a wildcard, the wildcard is detected as a new entry.
        let approved = PluginPermissions {
            network: vec!["api.example.com".into()],
            ..Default::default()
        };
        let requested = PluginPermissions {
            network: vec!["api.example.com".into(), "*".into()],
            ..Default::default()
        };
        let diff = PluginPermissions::diff(&approved, &requested);
        assert_eq!(diff.new_network, vec!["*"]);
    }

    #[test]
    fn permission_diff_is_empty_default() {
        let diff = PermissionDiff::default();
        assert!(diff.is_empty());
    }
}