Skip to main content

act_types/
types.rs

1use std::collections::{BTreeMap, HashMap};
2
3use crate::cbor;
4
5// ── LocalizedString ──
6
7/// A localizable text value, matching the WIT `localized-string` variant.
8///
9/// - `Plain` — a single string in the component's `default-language`.
10/// - `Localized` — a map of BCP 47 language tags to text.
11#[derive(Debug, Clone)]
12pub enum LocalizedString {
13    /// A single string assumed to be in the component's `default-language`.
14    Plain(String),
15    /// Language tag → text map. MUST include the component's `default-language`.
16    Localized(HashMap<String, String>),
17}
18
19impl Default for LocalizedString {
20    fn default() -> Self {
21        Self::Plain(String::new())
22    }
23}
24
25impl LocalizedString {
26    /// Create a plain (non-localized) string.
27    pub fn plain(text: impl Into<String>) -> Self {
28        Self::Plain(text.into())
29    }
30
31    /// Create a localized string with a single language entry.
32    pub fn new(lang: impl Into<String>, text: impl Into<String>) -> Self {
33        let mut map = HashMap::new();
34        map.insert(lang.into(), text.into());
35        Self::Localized(map)
36    }
37
38    /// Look up text for a specific language tag.
39    ///
40    /// For `Plain`, always returns the text (it is assumed to match any language).
41    /// For `Localized`, performs exact key lookup.
42    pub fn get(&self, lang: &str) -> Option<&str> {
43        match self {
44            Self::Plain(text) => Some(text.as_str()),
45            Self::Localized(map) => map.get(lang).map(|s| s.as_str()),
46        }
47    }
48
49    /// Resolve to text for the given language, with fallback chain.
50    ///
51    /// - `Plain` → returns the plain string (assumed to be in `default_language`).
52    /// - `Localized` → exact match → prefix match → any entry.
53    pub fn resolve(&self, lang: &str) -> &str {
54        match self {
55            Self::Plain(text) => text.as_str(),
56            Self::Localized(map) => {
57                // 1. Exact match
58                if let Some(text) = map.get(lang) {
59                    return text.as_str();
60                }
61                // 2. Prefix match (e.g. "zh" matches "zh-Hans")
62                if let Some(text) = map
63                    .iter()
64                    .find(|(tag, _)| tag.starts_with(lang) || lang.starts_with(tag.as_str()))
65                    .map(|(_, text)| text.as_str())
66                {
67                    return text;
68                }
69                // 3. Any entry
70                map.values().next().map(|s| s.as_str()).unwrap_or("")
71            }
72        }
73    }
74
75    /// Get some text, regardless of language.
76    /// Useful when you don't have the default language available.
77    pub fn any_text(&self) -> &str {
78        match self {
79            Self::Plain(text) => text.as_str(),
80            Self::Localized(map) => map.values().next().map(|s| s.as_str()).unwrap_or(""),
81        }
82    }
83}
84
85impl From<String> for LocalizedString {
86    fn from(s: String) -> Self {
87        Self::Plain(s)
88    }
89}
90
91impl From<&str> for LocalizedString {
92    fn from(s: &str) -> Self {
93        Self::Plain(s.to_string())
94    }
95}
96
97impl From<Vec<(String, String)>> for LocalizedString {
98    fn from(v: Vec<(String, String)>) -> Self {
99        Self::Localized(v.into_iter().collect())
100    }
101}
102
103impl From<HashMap<String, String>> for LocalizedString {
104    fn from(map: HashMap<String, String>) -> Self {
105        Self::Localized(map)
106    }
107}
108
109// ── Metadata ──
110
111/// Key → value metadata, stored as JSON values internally.
112///
113/// Converts to/from WIT `list<tuple<string, list<u8>>>` (CBOR) at the boundary.
114#[derive(Debug, Clone, Default)]
115pub struct Metadata(HashMap<String, serde_json::Value>);
116
117impl Metadata {
118    pub fn new() -> Self {
119        Self(HashMap::new())
120    }
121
122    /// Insert a value. Overwrites any existing entry for the key.
123    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
124        self.0.insert(key.into(), value.into());
125    }
126
127    /// Get a value by key.
128    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
129        self.0.get(key)
130    }
131
132    /// Get a value by key, deserializing into a typed value.
133    pub fn get_as<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
134        self.0
135            .get(key)
136            .and_then(|v| serde_json::from_value(v.clone()).ok())
137    }
138
139    /// Check if a key exists.
140    pub fn contains_key(&self, key: &str) -> bool {
141        self.0.contains_key(key)
142    }
143
144    /// Returns true if there are no entries.
145    pub fn is_empty(&self) -> bool {
146        self.0.is_empty()
147    }
148
149    /// Iterate over key-value pairs.
150    pub fn iter(&self) -> impl Iterator<Item = (&String, &serde_json::Value)> {
151        self.0.iter()
152    }
153
154    /// Number of entries.
155    pub fn len(&self) -> usize {
156        self.0.len()
157    }
158
159    /// Merge all entries from `other` into `self`. Entries in `other` overwrite existing keys.
160    pub fn extend(&mut self, other: Metadata) {
161        self.0.extend(other.0);
162    }
163}
164
165/// Convert from a JSON object value. Non-object values produce empty metadata.
166impl From<serde_json::Value> for Metadata {
167    fn from(value: serde_json::Value) -> Self {
168        match value {
169            serde_json::Value::Object(map) => Self(map.into_iter().collect()),
170            _ => Self::new(),
171        }
172    }
173}
174
175/// Convert to a JSON object value (consuming).
176impl From<Metadata> for serde_json::Value {
177    fn from(m: Metadata) -> Self {
178        serde_json::Value::Object(m.0.into_iter().collect())
179    }
180}
181
182/// Convert from WIT metadata (CBOR-encoded values).
183impl From<Vec<(String, Vec<u8>)>> for Metadata {
184    fn from(v: Vec<(String, Vec<u8>)>) -> Self {
185        Self(
186            v.into_iter()
187                .filter_map(|(k, cbor_bytes)| {
188                    let val = cbor::cbor_to_json(&cbor_bytes).ok()?;
189                    Some((k, val))
190                })
191                .collect(),
192        )
193    }
194}
195
196/// Convert to WIT metadata (CBOR-encoded values).
197impl From<Metadata> for Vec<(String, Vec<u8>)> {
198    fn from(m: Metadata) -> Self {
199        m.0.into_iter()
200            .map(|(k, v)| (k, cbor::to_cbor(&v)))
201            .collect()
202    }
203}
204
205use crate::constants::*;
206
207// ── Component info (act:component custom section) ──
208
209/// Parameters for the `wasi:filesystem` capability.
210#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
211pub struct FilesystemCap {
212    /// Internal WASM root path for all host mounts (default: `/`).
213    #[serde(
214        rename = "mount-root",
215        default,
216        skip_serializing_if = "Option::is_none"
217    )]
218    pub mount_root: Option<String>,
219
220    /// Paths the component needs access to, each with a required mode.
221    /// Empty = zero filesystem access. To declare broad access, use
222    /// `allow = [{ path = "**", mode = "rw" }]`.
223    #[serde(default, skip_serializing_if = "Vec::is_empty")]
224    pub allow: Vec<FilesystemAllow>,
225}
226
227/// One path × mode entry in a `[std.capabilities."wasi:filesystem"].allow` array.
228/// Both fields are required.
229#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
230pub struct FilesystemAllow {
231    /// Glob pattern (matches the user-policy `allow` / `deny` shape).
232    pub path: String,
233    /// Access mode the component requests.
234    pub mode: FsMode,
235}
236
237/// Filesystem access mode a component declares for a path.
238#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
239#[serde(rename_all = "lowercase")]
240pub enum FsMode {
241    /// Read-only.
242    Ro,
243    /// Read-write.
244    Rw,
245}
246
247/// Parameters for the `wasi:http` capability.
248#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
249pub struct HttpCap {
250    /// Hosts / schemes / methods / ports the component needs to reach.
251    /// Empty = zero HTTP access. To declare broad access, use
252    /// `allow = [{ host = "*" }]`.
253    #[serde(default, skip_serializing_if = "Vec::is_empty")]
254    pub allow: Vec<HttpAllow>,
255}
256
257/// One entry in a `[std.capabilities."wasi:http"].allow` array.
258///
259/// `host` is required (exact match, `*.suffix` wildcard, or `*` for any).
260/// Other fields are optional narrowers. Declarations never carry `cidr`,
261/// `except_ports`, or `deny` — those are user-policy concerns.
262#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
263pub struct HttpAllow {
264    pub host: String,
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub scheme: Option<String>,
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub methods: Option<Vec<String>>,
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub ports: Option<Vec<u16>>,
271}
272
273/// Parameters for the `wasi:sockets` capability.
274#[derive(Debug, Clone, Copy, Default, serde::Serialize, serde::Deserialize)]
275pub struct SocketsCap {}
276
277/// Capability declarations from the `std:capabilities` map in `act:component`.
278///
279/// Well-known capabilities have typed fields. Unknown third-party capabilities
280/// are collected in `other`. Serializes as a CBOR/JSON map keyed by capability ID.
281#[serde_with::skip_serializing_none]
282#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
283#[serde(default)]
284pub struct Capabilities {
285    /// `wasi:filesystem` — filesystem access.
286    #[serde(rename = "wasi:filesystem")]
287    pub filesystem: Option<FilesystemCap>,
288    /// `wasi:http` — outbound HTTP requests.
289    #[serde(rename = "wasi:http")]
290    pub http: Option<HttpCap>,
291    /// `wasi:sockets` — outbound TCP/UDP connections.
292    #[serde(rename = "wasi:sockets")]
293    pub sockets: Option<SocketsCap>,
294    /// Third-party capabilities keyed by identifier.
295    #[serde(flatten)]
296    pub other: BTreeMap<String, serde_json::Value>,
297}
298
299impl Capabilities {
300    /// True if no capabilities are declared.
301    pub fn is_empty(&self) -> bool {
302        self.http.is_none()
303            && self.filesystem.is_none()
304            && self.sockets.is_none()
305            && self.other.is_empty()
306    }
307
308    /// Check if a capability is declared by its string identifier.
309    pub fn has(&self, id: &str) -> bool {
310        match id {
311            CAP_HTTP => self.http.is_some(),
312            CAP_FILESYSTEM => self.filesystem.is_some(),
313            CAP_SOCKETS => self.sockets.is_some(),
314            other => self.other.contains_key(other),
315        }
316    }
317
318    /// Get the `mount-root` parameter from the `wasi:filesystem` capability.
319    pub fn fs_mount_root(&self) -> Option<&str> {
320        self.filesystem.as_ref()?.mount_root.as_deref()
321    }
322}
323
324/// Component metadata stored in the `act:component` WASM custom section (CBOR-encoded).
325///
326/// Used by SDK macros (serialization) and host (deserialization).
327/// Also deserializable from `act.toml` manifest via `alias` attributes.
328///
329/// Extra namespaces (not `std`) are collected into `extra`.
330#[non_exhaustive]
331#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
332pub struct ComponentInfo {
333    /// Well-known component metadata.
334    #[serde(default)]
335    pub std: StdComponentInfo,
336    /// Extra namespaces (third-party extensions).
337    #[serde(flatten, default, skip_serializing_if = "HashMap::is_empty")]
338    pub extra: HashMap<String, serde_json::Value>,
339}
340
341/// Well-known component metadata under the `std` namespace.
342#[non_exhaustive]
343#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
344pub struct StdComponentInfo {
345    #[serde(default)]
346    pub name: String,
347    #[serde(default)]
348    pub version: String,
349    #[serde(default)]
350    pub description: String,
351    #[serde(
352        rename = "default-language",
353        default,
354        skip_serializing_if = "Option::is_none"
355    )]
356    pub default_language: Option<String>,
357    #[serde(default, skip_serializing_if = "Capabilities::is_empty")]
358    pub capabilities: Capabilities,
359}
360
361impl ComponentInfo {
362    pub fn new(
363        name: impl Into<String>,
364        version: impl Into<String>,
365        description: impl Into<String>,
366    ) -> Self {
367        Self {
368            std: StdComponentInfo {
369                name: name.into(),
370                version: version.into(),
371                description: description.into(),
372                ..Default::default()
373            },
374            ..Default::default()
375        }
376    }
377
378    // Convenience accessors for backward compatibility.
379    pub fn name(&self) -> &str {
380        &self.std.name
381    }
382    pub fn version(&self) -> &str {
383        &self.std.version
384    }
385    pub fn description(&self) -> &str {
386        &self.std.description
387    }
388}
389
390// ── Error type ──
391
392/// Error type mapping to ACT `tool-error`.
393#[derive(Debug, Clone)]
394pub struct ActError {
395    pub kind: String,
396    pub message: String,
397}
398
399impl ActError {
400    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
401        Self {
402            kind: kind.into(),
403            message: message.into(),
404        }
405    }
406
407    pub fn not_found(message: impl Into<String>) -> Self {
408        Self::new(ERR_NOT_FOUND, message)
409    }
410
411    pub fn invalid_args(message: impl Into<String>) -> Self {
412        Self::new(ERR_INVALID_ARGS, message)
413    }
414
415    pub fn internal(message: impl Into<String>) -> Self {
416        Self::new(ERR_INTERNAL, message)
417    }
418
419    pub fn timeout(message: impl Into<String>) -> Self {
420        Self::new(ERR_TIMEOUT, message)
421    }
422
423    pub fn capability_denied(message: impl Into<String>) -> Self {
424        Self::new(ERR_CAPABILITY_DENIED, message)
425    }
426
427    pub fn session_not_found(message: impl Into<String>) -> Self {
428        Self::new(ERR_SESSION_NOT_FOUND, message)
429    }
430}
431
432impl std::fmt::Display for ActError {
433    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434        write!(f, "{}: {}", self.kind, self.message)
435    }
436}
437
438impl std::error::Error for ActError {}
439
440/// Result type for ACT operations.
441pub type ActResult<T> = Result<T, ActError>;
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use serde_json::json;
447
448    #[test]
449    fn localized_string_plain() {
450        let ls = LocalizedString::plain("hello");
451        assert_eq!(ls.resolve("en"), "hello");
452        assert_eq!(ls.any_text(), "hello");
453    }
454
455    #[test]
456    fn localized_string_from_str() {
457        let ls = LocalizedString::from("hello");
458        assert_eq!(ls.any_text(), "hello");
459    }
460
461    #[test]
462    fn localized_string_default() {
463        let ls = LocalizedString::default();
464        assert_eq!(ls.any_text(), "");
465    }
466
467    #[test]
468    fn localized_string_resolve_by_lang() {
469        let mut map = std::collections::HashMap::new();
470        map.insert("en".to_string(), "hello".to_string());
471        map.insert("ru".to_string(), "привет".to_string());
472        let ls = LocalizedString::Localized(map);
473        assert_eq!(ls.resolve("ru"), "привет");
474        assert_eq!(ls.resolve("en"), "hello");
475        // Unknown lang falls back to some entry
476        assert!(!ls.resolve("fr").is_empty());
477    }
478
479    #[test]
480    fn localized_string_resolve_prefix() {
481        let mut map = HashMap::new();
482        map.insert("zh-Hans".to_string(), "你好".to_string());
483        map.insert("en".to_string(), "hello".to_string());
484        let ls = LocalizedString::Localized(map);
485        assert_eq!(ls.resolve("zh"), "你好");
486    }
487
488    #[test]
489    fn localized_string_get() {
490        let ls = LocalizedString::new("en", "hello");
491        assert_eq!(ls.get("en"), Some("hello"));
492        assert_eq!(ls.get("ru"), None);
493    }
494
495    #[test]
496    fn localized_string_from_vec() {
497        let v = vec![("en".to_string(), "hi".to_string())];
498        let ls = LocalizedString::from(v);
499        assert_eq!(ls.resolve("en"), "hi");
500    }
501
502    #[test]
503    fn metadata_insert_and_get() {
504        let mut m = Metadata::new();
505        m.insert("std:read-only", true);
506        assert_eq!(m.get("std:read-only"), Some(&json!(true)));
507        assert_eq!(m.get_as::<bool>("std:read-only"), Some(true));
508    }
509
510    #[test]
511    fn metadata_to_json_empty() {
512        let json: serde_json::Value = Metadata::new().into();
513        assert_eq!(json, json!({}));
514    }
515
516    #[test]
517    fn metadata_to_json_with_values() {
518        let mut m = Metadata::new();
519        m.insert("std:read-only", true);
520        let json: serde_json::Value = m.into();
521        assert_eq!(json["std:read-only"], json!(true));
522    }
523
524    #[test]
525    fn metadata_from_vec() {
526        let v = vec![("key".to_string(), cbor::to_cbor(&42u32))];
527        let m = Metadata::from(v);
528        assert_eq!(m.get("key"), Some(&json!(42)));
529        assert_eq!(m.get_as::<u32>("key"), Some(42));
530    }
531
532    #[test]
533    fn capabilities_cbor_roundtrip() {
534        let mut info = ComponentInfo::new("test", "0.1.0", "test component");
535        info.std.capabilities.http = Some(HttpCap::default());
536        info.std.capabilities.filesystem = Some(FilesystemCap {
537            mount_root: Some("/data".to_string()),
538            ..Default::default()
539        });
540
541        let mut buf = Vec::new();
542        ciborium::into_writer(&info, &mut buf).unwrap();
543
544        let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
545        assert!(decoded.std.capabilities.http.is_some());
546        assert!(decoded.std.capabilities.filesystem.is_some());
547        assert!(decoded.std.capabilities.sockets.is_none());
548        assert_eq!(decoded.std.capabilities.fs_mount_root(), Some("/data"));
549    }
550
551    #[test]
552    fn capabilities_empty_roundtrip() {
553        let info = ComponentInfo::new("test", "0.1.0", "test");
554
555        let mut buf = Vec::new();
556        ciborium::into_writer(&info, &mut buf).unwrap();
557
558        let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
559        assert!(decoded.std.capabilities.is_empty());
560    }
561
562    #[test]
563    fn capabilities_fs_no_params_roundtrip() {
564        let mut info = ComponentInfo::new("test", "0.1.0", "test");
565        info.std.capabilities.filesystem = Some(FilesystemCap::default());
566
567        let mut buf = Vec::new();
568        ciborium::into_writer(&info, &mut buf).unwrap();
569
570        let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
571        assert!(decoded.std.capabilities.filesystem.is_some());
572        assert_eq!(decoded.std.capabilities.fs_mount_root(), None);
573    }
574
575    #[test]
576    fn capabilities_unknown_preserved() {
577        let mut info = ComponentInfo::new("test", "0.1.0", "test");
578        info.std
579            .capabilities
580            .other
581            .insert("acme:gpu".to_string(), json!({"cores": 8}));
582
583        let mut buf = Vec::new();
584        ciborium::into_writer(&info, &mut buf).unwrap();
585
586        let decoded: ComponentInfo = ciborium::from_reader(&buf[..]).unwrap();
587        assert!(decoded.std.capabilities.has("acme:gpu"));
588        assert_eq!(decoded.std.capabilities.other["acme:gpu"]["cores"], 8);
589    }
590
591    #[test]
592    fn filesystem_cap_with_allow_roundtrips() {
593        let toml_input = r#"
594[std.capabilities."wasi:filesystem"]
595description = "test"
596
597[[std.capabilities."wasi:filesystem".allow]]
598path = "/etc/**"
599mode = "ro"
600
601[[std.capabilities."wasi:filesystem".allow]]
602path = "/tmp/**"
603mode = "rw"
604"#;
605        #[derive(serde::Deserialize)]
606        struct Wrap {
607            std: Std,
608        }
609        #[derive(serde::Deserialize)]
610        struct Std {
611            capabilities: Capabilities,
612        }
613        let w: Wrap = toml::from_str(toml_input).expect("parses");
614        let fs = w.std.capabilities.filesystem.expect("fs declared");
615        assert_eq!(fs.allow.len(), 2);
616        assert_eq!(fs.allow[0].path, "/etc/**");
617        assert!(matches!(fs.allow[0].mode, FsMode::Ro));
618        assert_eq!(fs.allow[1].path, "/tmp/**");
619        assert!(matches!(fs.allow[1].mode, FsMode::Rw));
620    }
621
622    #[test]
623    fn filesystem_cap_requires_path_and_mode_on_each_entry() {
624        // Missing `mode` → parse error.
625        let bad = r#"
626[[std.capabilities."wasi:filesystem".allow]]
627path = "/tmp/**"
628"#;
629        #[derive(serde::Deserialize)]
630        struct Wrap {
631            std: Std,
632        }
633        #[derive(serde::Deserialize)]
634        struct Std {
635            capabilities: Capabilities,
636        }
637        assert!(
638            toml::from_str::<Wrap>(bad).is_err(),
639            "missing mode must fail"
640        );
641    }
642
643    #[test]
644    fn http_cap_with_allow_roundtrips() {
645        let toml_input = r#"
646[std.capabilities."wasi:http"]
647description = "Calls OpenAI + GitHub"
648
649[[std.capabilities."wasi:http".allow]]
650host = "api.openai.com"
651scheme = "https"
652methods = ["GET", "POST"]
653
654[[std.capabilities."wasi:http".allow]]
655host = "*.github.com"
656scheme = "https"
657"#;
658        #[derive(serde::Deserialize)]
659        struct Wrap {
660            std: Std,
661        }
662        #[derive(serde::Deserialize)]
663        struct Std {
664            capabilities: Capabilities,
665        }
666        let w: Wrap = toml::from_str(toml_input).expect("parses");
667        let http = w.std.capabilities.http.expect("http declared");
668        assert_eq!(http.allow.len(), 2);
669        assert_eq!(http.allow[0].host, "api.openai.com");
670        assert_eq!(http.allow[0].scheme.as_deref(), Some("https"));
671        assert_eq!(
672            http.allow[0].methods.as_deref(),
673            Some(&["GET".to_string(), "POST".to_string()][..])
674        );
675        assert_eq!(http.allow[1].host, "*.github.com");
676    }
677
678    #[test]
679    fn http_cap_requires_host_on_each_entry() {
680        // Missing `host` → parse error.
681        let bad = r#"
682[[std.capabilities."wasi:http".allow]]
683scheme = "https"
684"#;
685        #[derive(serde::Deserialize)]
686        struct Wrap {
687            std: Std,
688        }
689        #[derive(serde::Deserialize)]
690        struct Std {
691            capabilities: Capabilities,
692        }
693        assert!(
694            toml::from_str::<Wrap>(bad).is_err(),
695            "missing host must fail"
696        );
697    }
698
699    #[test]
700    fn http_cap_wildcard_host() {
701        // "*" is the explicit any-host wildcard.
702        let toml_input = r#"
703[[std.capabilities."wasi:http".allow]]
704host = "*"
705"#;
706        #[derive(serde::Deserialize)]
707        struct Wrap {
708            std: Std,
709        }
710        #[derive(serde::Deserialize)]
711        struct Std {
712            capabilities: Capabilities,
713        }
714        let w: Wrap = toml::from_str(toml_input).expect("parses");
715        assert_eq!(w.std.capabilities.http.unwrap().allow[0].host, "*");
716    }
717}