nemo-relay 0.6.0

Core Rust SDK for NeMo Relay observability, scope management, and runtime instrumentation.
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

use serde::de::{self, Deserializer};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};

use super::{
    DYNAMIC_PLUGIN_MANIFEST_FILENAME, DynamicPluginCapability, DynamicPluginCheckState,
    DynamicPluginCompatibility, DynamicPluginId, DynamicPluginKind, DynamicPluginLoadContract,
    DynamicPluginMetadata, DynamicPluginRecord, DynamicPluginRustCompatibility,
    DynamicPluginRustLoadContract, DynamicPluginSource, DynamicPluginSpec, DynamicPluginStatus,
    DynamicPluginValidationStatus, DynamicPluginWorkerCompatibility,
    DynamicPluginWorkerLoadContract, WorkerRuntime, current_timestamp,
};
use crate::plugin::{PluginError, Result};

const SUPPORTED_WORKER_PROTOCOL: &str = "grpc-v1";

/// Authored `relay-plugin.toml` manifest.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifest {
    /// Relay plugin manifest schema version.
    pub manifest_version: u32,
    /// Plugin identity and lane declaration.
    pub plugin: DynamicPluginManifestPlugin,
    /// Relay compatibility declarations.
    pub compat: DynamicPluginManifestCompat,
    /// Default desired-state settings.
    pub defaults: DynamicPluginManifestDefaults,
    /// Required capability declarations.
    pub capabilities: DynamicPluginManifestCapabilities,
    /// Optional static configuration schema reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_schema: Option<DynamicPluginManifestConfigSchema>,
    /// Runtime load contract.
    #[cfg_attr(feature = "schema", schemars(with = "DynamicPluginManifestLoadSchema"))]
    pub load: DynamicPluginManifestLoad,
    /// Optional source-oriented author metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<DynamicPluginManifestSource>,
    /// Optional integrity/authenticity evidence references.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub integrity: Option<DynamicPluginManifestIntegrity>,
    /// Optional human-oriented description.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// Plugin identity block for `relay-plugin.toml`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestPlugin {
    /// Stable plugin identifier.
    pub id: DynamicPluginId,
    /// Optional display name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Optional plugin version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Execution lane.
    pub kind: DynamicPluginKind,
}

/// Compatibility block for `relay-plugin.toml`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestCompat {
    /// Supported Relay version or version range.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relay: Option<String>,
    /// Native plugin contract version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub native_api: Option<String>,
    /// Worker protocol version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub worker_protocol: Option<String>,
}

/// Defaults block for authored manifests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestDefaults {
    /// Explicit default desired enabled state.
    #[serde(default)]
    pub enabled: bool,
}

/// Capability declarations for authored manifests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestCapabilities {
    /// Required capability set.
    pub items: Vec<DynamicPluginCapability>,
}

/// Static configuration schema block for authored manifests.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestConfigSchema {
    /// Local JSON Schema path, resolved relative to `relay-plugin.toml`.
    pub path: String,
}

/// Load block for authored manifests.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DynamicPluginManifestLoad {
    /// Worker registration target.
    Worker(DynamicPluginManifestWorkerLoad),
    /// Native shared-library registration target.
    RustDynamic(DynamicPluginManifestRustDynamicLoad),
}

/// Worker lane authored load block.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestWorkerLoad {
    /// Worker runtime when `kind = "worker"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime: Option<WorkerRuntime>,
    /// Worker entrypoint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<String>,
}

/// Native shared-library authored load block.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestRustDynamicLoad {
    /// Native library path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub library: Option<String>,
    /// Native registration symbol.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
}

#[cfg(feature = "schema")]
#[derive(schemars::JsonSchema)]
#[allow(
    dead_code,
    reason = "variants are consumed by schemars derive metadata"
)]
#[serde(untagged)]
enum DynamicPluginManifestLoadSchema {
    Worker(DynamicPluginManifestWorkerLoad),
    RustDynamic(DynamicPluginManifestRustDynamicLoad),
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
struct RawDynamicPluginManifestLoad {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    runtime: Option<WorkerRuntime>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    entrypoint: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    library: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    symbol: Option<String>,
}

impl<'de> Deserialize<'de> for DynamicPluginManifestLoad {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw = RawDynamicPluginManifestLoad::deserialize(deserializer)?;
        let has_worker_fields = raw.runtime.is_some() || raw.entrypoint.is_some();
        let has_native_fields = raw.library.is_some() || raw.symbol.is_some();

        match (has_worker_fields, has_native_fields) {
            (true, false) => Ok(Self::Worker(DynamicPluginManifestWorkerLoad {
                runtime: raw.runtime,
                entrypoint: raw.entrypoint,
            })),
            (false, true) => Ok(Self::RustDynamic(DynamicPluginManifestRustDynamicLoad {
                library: raw.library,
                symbol: raw.symbol,
            })),
            (true, true) => Err(de::Error::custom(
                "load must declare either worker fields (runtime, entrypoint) or rust_dynamic fields (library, symbol), not both",
            )),
            (false, false) => Err(de::Error::custom(
                "load must declare either worker fields (runtime, entrypoint) or rust_dynamic fields (library, symbol)",
            )),
        }
    }
}

impl Serialize for DynamicPluginManifestLoad {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let raw = match self {
            Self::Worker(load) => RawDynamicPluginManifestLoad {
                runtime: load.runtime,
                entrypoint: load.entrypoint.clone(),
                library: None,
                symbol: None,
            },
            Self::RustDynamic(load) => RawDynamicPluginManifestLoad {
                runtime: None,
                entrypoint: None,
                library: load.library.clone(),
                symbol: load.symbol.clone(),
            },
        };
        raw.serialize(serializer)
    }
}

/// Source block for authored manifests.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestSource {
    /// Author-facing manifest root or package root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manifest_root: Option<String>,
    /// Author-facing artifact hint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact: Option<String>,
}

/// Integrity/authenticity evidence block for authored manifests.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicPluginManifestIntegrity {
    /// Expected artifact digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sha256: Option<String>,
    /// Optional signature reference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

impl DynamicPluginManifest {
    /// Parses a `relay-plugin.toml` manifest from TOML text.
    pub fn parse_toml(toml_source: &str) -> Result<Self> {
        let manifest = toml::from_str::<Self>(toml_source).map_err(|err| {
            PluginError::InvalidConfig(format!("invalid relay-plugin.toml: {err}"))
        })?;
        manifest.validate()?;
        Ok(manifest)
    }

    /// Loads and validates a `relay-plugin.toml` manifest from a file path or directory.
    pub fn load_from_path(path: impl AsRef<Path>) -> Result<(Self, String)> {
        let path = path.as_ref();
        let manifest_path = if path.is_dir() {
            path.join(DYNAMIC_PLUGIN_MANIFEST_FILENAME)
        } else {
            path.to_path_buf()
        };

        let display_ref = manifest_path.to_string_lossy().into_owned();
        let exists = manifest_path.try_exists().map_err(|err| {
            PluginError::Internal(format!("failed to inspect '{}': {err}", display_ref))
        })?;
        if !exists {
            return Err(PluginError::NotFound(format!(
                "dynamic plugin manifest '{}' does not exist",
                display_ref
            )));
        }

        let normalized_manifest_path = fs::canonicalize(&manifest_path).map_err(|err| {
            PluginError::Internal(format!(
                "failed to normalize dynamic plugin manifest '{}': {err}",
                display_ref
            ))
        })?;
        let manifest_ref = normalized_manifest_path.to_string_lossy().into_owned();

        let contents = fs::read_to_string(&normalized_manifest_path).map_err(|err| {
            PluginError::Internal(format!(
                "failed to read dynamic plugin manifest '{}': {err}",
                manifest_ref
            ))
        })?;
        let manifest = Self::parse_toml(&contents)?;
        Ok((manifest, manifest_ref))
    }

    /// Validates the authored manifest against the v1 contract.
    pub fn validate(&self) -> Result<()> {
        if self.manifest_version != 1 {
            return Err(PluginError::InvalidConfig(format!(
                "unsupported relay-plugin.toml manifest_version {}; expected 1",
                self.manifest_version
            )));
        }
        if self.plugin.id.trim().is_empty() {
            return Err(PluginError::InvalidConfig(
                "plugin.id must not be empty".into(),
            ));
        }
        ensure_optional_string_non_empty(self.plugin.name.as_deref(), "plugin.name")?;
        ensure_optional_string_non_empty(self.plugin.version.as_deref(), "plugin.version")?;
        ensure_optional_string_non_empty(self.description.as_deref(), "description")?;
        ensure_optional_string_non_empty(
            self.source
                .as_ref()
                .and_then(|source| source.manifest_root.as_deref()),
            "source.manifest_root",
        )?;
        ensure_optional_string_non_empty(
            self.source
                .as_ref()
                .and_then(|source| source.artifact.as_deref()),
            "source.artifact",
        )?;
        ensure_optional_string_non_empty(
            self.integrity
                .as_ref()
                .and_then(|integrity| integrity.sha256.as_deref()),
            "integrity.sha256",
        )?;
        ensure_optional_string_non_empty(
            self.integrity
                .as_ref()
                .and_then(|integrity| integrity.signature.as_deref()),
            "integrity.signature",
        )?;

        required_trimmed_string(self.compat.relay.as_deref(), "compat.relay")?;
        if self.capabilities.items.is_empty() {
            return Err(PluginError::InvalidConfig(
                "capabilities.items must declare at least one capability".into(),
            ));
        }
        reject_duplicate_capabilities(&self.capabilities.items)?;
        validate_config_schema_contract(&self.capabilities.items, self.config_schema.as_ref())?;

        if self.defaults.enabled {
            return Err(PluginError::InvalidConfig(
                "defaults.enabled=true is not supported for dynamic plugins; plugins are added disabled and require explicit enablement".into(),
            ));
        }

        validate_capability_shape(self.plugin.kind, &self.capabilities.items)?;
        validate_load_shape(self.plugin.kind, &self.load)?;
        validate_compat_shape(self.plugin.kind, &self.compat)?;
        Ok(())
    }

    /// Resolves the declared configuration schema path without accessing it.
    ///
    /// Relative schema paths are resolved from the parent directory of the
    /// canonical `relay-plugin.toml` path. Absolute local paths are returned
    /// unchanged.
    pub fn resolve_config_schema_path(
        &self,
        canonical_manifest_path: impl AsRef<Path>,
    ) -> Result<Option<PathBuf>> {
        let Some(config_schema) = &self.config_schema else {
            return Ok(None);
        };

        let schema_path = Path::new(validate_config_schema_path(config_schema)?);
        if schema_path.is_absolute() {
            return Ok(Some(schema_path.to_path_buf()));
        }

        let manifest_path = canonical_manifest_path.as_ref();
        let manifest_parent = manifest_path.parent().ok_or_else(|| {
            PluginError::InvalidConfig(format!(
                "dynamic plugin manifest path '{}' has no parent directory",
                manifest_path.display()
            ))
        })?;
        Ok(Some(manifest_parent.join(schema_path)))
    }

    /// Converts the authored manifest into a durable control-plane record.
    pub fn into_record(self, manifest_ref: Option<String>) -> Result<DynamicPluginRecord> {
        self.validate()?;
        let validation = self.validation_status();
        let plugin = self.plugin;
        let compat = self.compat;
        let load = self.load;

        Ok(DynamicPluginRecord {
            metadata: DynamicPluginMetadata {
                id: plugin.id.trim().to_owned(),
                name: plugin.name,
                version: plugin.version,
                kind: plugin.kind,
                generation: 0,
                created_at: None,
                updated_at: None,
            },
            source: DynamicPluginSource {
                manifest_ref,
                artifact_ref: self
                    .source
                    .as_ref()
                    .and_then(|source| source.artifact.clone()),
                environment_ref: None,
                artifact_digest: self
                    .integrity
                    .as_ref()
                    .and_then(|integrity| integrity.sha256.clone()),
            },
            spec: DynamicPluginSpec {
                present: true,
                enabled: false,
                config_ref: None,
            },
            compatibility: match plugin.kind {
                DynamicPluginKind::RustDynamic => {
                    DynamicPluginCompatibility::RustDynamic(DynamicPluginRustCompatibility {
                        relay: compat
                            .relay
                            .expect("validated manifest must carry compat.relay")
                            .trim()
                            .to_owned(),
                        native_api: compat
                            .native_api
                            .expect("validated rust_dynamic manifest must carry compat.native_api")
                            .trim()
                            .to_owned(),
                    })
                }
                DynamicPluginKind::Worker => {
                    DynamicPluginCompatibility::Worker(DynamicPluginWorkerCompatibility {
                        relay: compat
                            .relay
                            .expect("validated manifest must carry compat.relay")
                            .trim()
                            .to_owned(),
                        worker_protocol: compat
                            .worker_protocol
                            .expect("validated worker manifest must carry compat.worker_protocol")
                            .trim()
                            .to_owned(),
                    })
                }
            },
            load: load.into_record_load_contract(),
            status: DynamicPluginStatus {
                validation,
                ..DynamicPluginStatus::default()
            },
        })
    }

    /// Produces the initial validation status for a successfully validated manifest.
    pub fn validation_status(&self) -> DynamicPluginValidationStatus {
        DynamicPluginValidationStatus {
            manifest: DynamicPluginCheckState::Valid,
            compatibility: DynamicPluginCheckState::Unknown,
            integrity: DynamicPluginCheckState::Unknown,
            environment: DynamicPluginCheckState::Unknown,
            authenticity: DynamicPluginCheckState::Unknown,
            policy_satisfied: DynamicPluginCheckState::Unknown,
            checked_at: Some(current_timestamp()),
            message: Some("manifest validated".into()),
        }
    }
}

fn required_string<'a>(value: Option<&'a str>, field: &str) -> Result<&'a str> {
    value.ok_or_else(|| PluginError::InvalidConfig(format!("{field} is required")))
}

fn required_trimmed_string<'a>(value: Option<&'a str>, field: &str) -> Result<&'a str> {
    let value = required_string(value, field)?;
    if value.trim().is_empty() {
        return Err(PluginError::InvalidConfig(format!(
            "{field} must not be empty"
        )));
    }
    // Validate trimmed content while returning the original slice so each caller
    // can decide whether preserving or normalizing whitespace is correct.
    Ok(value)
}

fn ensure_optional_string_non_empty(value: Option<&str>, field: &str) -> Result<()> {
    if value.is_some_and(|value| value.trim().is_empty()) {
        return Err(PluginError::InvalidConfig(format!(
            "{field} must not be empty when provided"
        )));
    }
    Ok(())
}

fn reject_duplicate_capabilities(capabilities: &[DynamicPluginCapability]) -> Result<()> {
    let mut seen = HashSet::with_capacity(capabilities.len());
    for capability in capabilities {
        if !seen.insert(*capability) {
            return Err(PluginError::InvalidConfig(format!(
                "capabilities.items contains duplicate capability '{capability:?}'"
            )));
        }
    }
    Ok(())
}

fn validate_config_schema_contract(
    capabilities: &[DynamicPluginCapability],
    config_schema: Option<&DynamicPluginManifestConfigSchema>,
) -> Result<()> {
    let has_capability = capabilities.contains(&DynamicPluginCapability::ConfigSchema);
    match (has_capability, config_schema) {
        (true, None) => {
            return Err(PluginError::InvalidConfig(
                "capabilities.items containing config_schema requires a [config_schema] section"
                    .into(),
            ));
        }
        (false, Some(_)) => {
            return Err(PluginError::InvalidConfig(
                "[config_schema] requires capabilities.items containing config_schema".into(),
            ));
        }
        (false, None) => return Ok(()),
        (true, Some(config_schema)) => {
            validate_config_schema_path(config_schema)?;
        }
    }
    Ok(())
}

fn validate_config_schema_path(config_schema: &DynamicPluginManifestConfigSchema) -> Result<&str> {
    let path = required_trimmed_string(Some(&config_schema.path), "config_schema.path")?;
    if has_uri_scheme(path) || is_unc_path(path) {
        return Err(PluginError::InvalidConfig(
            "config_schema.path must be a local filesystem path, not a URI or network share".into(),
        ));
    }
    Ok(path)
}

fn is_unc_path(value: &str) -> bool {
    // A leading `//` can identify a local path on POSIX, but manifests are portable and the same
    // spelling is a UNC network share on Windows, so reject it consistently on every platform.
    value.starts_with(r"\\") || value.starts_with("//")
}

fn has_uri_scheme(value: &str) -> bool {
    if value
        .get(..5)
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("file:"))
    {
        return true;
    }
    let Some((scheme, _)) = value.split_once("://") else {
        return false;
    };
    let mut chars = scheme.chars();
    chars
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic())
        && chars.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.'))
}

fn validate_capability_shape(
    kind: DynamicPluginKind,
    capabilities: &[DynamicPluginCapability],
) -> Result<()> {
    let has_native = capabilities.contains(&DynamicPluginCapability::PluginNative);
    let has_worker = capabilities.contains(&DynamicPluginCapability::PluginWorker);
    match kind {
        DynamicPluginKind::RustDynamic => {
            if !has_native {
                return Err(PluginError::InvalidConfig(
                    "rust_dynamic plugins must declare capabilities.items containing plugin_native"
                        .into(),
                ));
            }
            if has_worker {
                return Err(PluginError::InvalidConfig(
                    "rust_dynamic plugins must not declare plugin_worker".into(),
                ));
            }
        }
        DynamicPluginKind::Worker => {
            if !has_worker {
                return Err(PluginError::InvalidConfig(
                    "worker plugins must declare capabilities.items containing plugin_worker"
                        .into(),
                ));
            }
            if has_native {
                return Err(PluginError::InvalidConfig(
                    "worker plugins must not declare plugin_native".into(),
                ));
            }
        }
    }
    Ok(())
}

fn validate_load_shape(kind: DynamicPluginKind, load: &DynamicPluginManifestLoad) -> Result<()> {
    match (kind, load) {
        (DynamicPluginKind::RustDynamic, DynamicPluginManifestLoad::Worker(_)) => {
            return Err(PluginError::InvalidConfig(
                "rust_dynamic plugins must not declare load.runtime or load.entrypoint".into(),
            ));
        }
        (DynamicPluginKind::Worker, DynamicPluginManifestLoad::RustDynamic(_)) => {
            return Err(PluginError::InvalidConfig(
                "worker plugins must not declare load.library or load.symbol".into(),
            ));
        }
        (DynamicPluginKind::RustDynamic, DynamicPluginManifestLoad::RustDynamic(load)) => {
            required_trimmed_string(load.library.as_deref(), "load.library")?;
            required_trimmed_string(load.symbol.as_deref(), "load.symbol")?;
        }
        (DynamicPluginKind::Worker, DynamicPluginManifestLoad::Worker(load)) => {
            required_trimmed_string(load.entrypoint.as_deref(), "load.entrypoint")?;
            match load.runtime {
                Some(WorkerRuntime::Python | WorkerRuntime::Rust | WorkerRuntime::Command) => {}
                None => {
                    return Err(PluginError::InvalidConfig(
                        "worker plugins must declare load.runtime".into(),
                    ));
                }
            }
        }
    }
    Ok(())
}

impl DynamicPluginManifestLoad {
    fn into_record_load_contract(self) -> DynamicPluginLoadContract {
        match self {
            Self::Worker(load) => {
                DynamicPluginLoadContract::Worker(DynamicPluginWorkerLoadContract {
                    runtime: load
                        .runtime
                        .expect("validated worker manifest must carry load.runtime"),
                    entrypoint: load
                        .entrypoint
                        .expect("validated worker manifest must carry load.entrypoint")
                        .trim()
                        .to_owned(),
                })
            }
            Self::RustDynamic(load) => {
                DynamicPluginLoadContract::RustDynamic(DynamicPluginRustLoadContract {
                    library: load
                        .library
                        .expect("validated rust_dynamic manifest must carry load.library")
                        .trim()
                        .to_owned(),
                    symbol: load
                        .symbol
                        .expect("validated rust_dynamic manifest must carry load.symbol")
                        .trim()
                        .to_owned(),
                })
            }
        }
    }
}

fn validate_compat_shape(
    kind: DynamicPluginKind,
    compat: &DynamicPluginManifestCompat,
) -> Result<()> {
    match kind {
        DynamicPluginKind::RustDynamic => {
            required_trimmed_string(compat.native_api.as_deref(), "compat.native_api")?;
            if compat.worker_protocol.is_some() {
                return Err(PluginError::InvalidConfig(
                    "rust_dynamic plugins must not declare compat.worker_protocol".into(),
                ));
            }
        }
        DynamicPluginKind::Worker => {
            let worker_protocol = required_trimmed_string(
                compat.worker_protocol.as_deref(),
                "compat.worker_protocol",
            )?;
            if worker_protocol.trim() != SUPPORTED_WORKER_PROTOCOL {
                return Err(PluginError::InvalidConfig(format!(
                    "worker plugins must declare compat.worker_protocol = \"{SUPPORTED_WORKER_PROTOCOL}\""
                )));
            }
            if compat.native_api.is_some() {
                return Err(PluginError::InvalidConfig(
                    "worker plugins must not declare compat.native_api".into(),
                ));
            }
        }
    }
    Ok(())
}