ironclaw 0.22.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
//! Lifecycle management for extensions: discovery, installation, authentication,
//! and activation of channels, tools, and MCP servers.
//!
//! Extensions are the user-facing abstraction that unifies three runtime kinds:
//! - **Channels** (Telegram, Slack, Discord) — messaging integrations (WASM)
//! - **Tools** — sandboxed capabilities (WASM)
//! - **MCP servers** — external API integrations via Model Context Protocol
//!
//! The agent can search a built-in registry (or discover online), install,
//! authenticate, and activate extensions at runtime without CLI commands.
//!
//! ```text
//!  User: "add telegram"
//!    -> tool_search("telegram")    -> finds channel in registry
//!    -> tool_install("telegram")   -> copies bundled WASM to channels dir
//!    -> tool_activate("telegram")  -> configures credentials, starts channel
//! ```

pub mod discovery;
pub mod manager;
pub mod registry;

pub use discovery::OnlineDiscovery;
pub use manager::ExtensionManager;
pub use registry::ExtensionRegistry;

use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};

/// The kind of extension, determining how it's installed, authenticated, and activated.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ExtensionKind {
    /// Hosted MCP server, HTTP transport, OAuth 2.1 auth.
    McpServer,
    /// Sandboxed WASM module, file-based, capabilities auth.
    WasmTool,
    /// WASM channel module with hot-activation support.
    WasmChannel,
    /// External channel via channel-relay service (Slack, etc.).
    ChannelRelay,
}

impl std::fmt::Display for ExtensionKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExtensionKind::McpServer => write!(f, "mcp_server"),
            ExtensionKind::WasmTool => write!(f, "wasm_tool"),
            ExtensionKind::WasmChannel => write!(f, "wasm_channel"),
            ExtensionKind::ChannelRelay => write!(f, "channel_relay"),
        }
    }
}

/// A registry entry describing a known or discovered extension.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegistryEntry {
    /// Unique identifier (e.g., "notion", "weather", "telegram").
    pub name: String,
    /// Human-readable name (e.g., "Notion", "Weather Tool").
    pub display_name: String,
    /// What kind of extension this is.
    pub kind: ExtensionKind,
    /// Short description of what this extension does.
    pub description: String,
    /// Search keywords beyond the name.
    #[serde(default)]
    pub keywords: Vec<String>,
    /// Where to get this extension.
    pub source: ExtensionSource,
    /// Fallback source when the primary source fails (e.g., download 404 → build from source).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback_source: Option<Box<ExtensionSource>>,
    /// How authentication works.
    pub auth_hint: AuthHint,
    /// Extension version (semver), if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

/// Where the extension binary or server lives.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ExtensionSource {
    /// URL to a hosted MCP server.
    McpUrl { url: String },
    /// Downloadable WASM binary.
    WasmDownload {
        wasm_url: String,
        #[serde(default)]
        capabilities_url: Option<String>,
    },
    /// Build from local source directory.
    WasmBuildable {
        #[serde(alias = "repo_url")]
        source_dir: String,
        #[serde(default)]
        build_dir: Option<String>,
        /// Crate name used to locate the build artifact binary.
        #[serde(default)]
        crate_name: Option<String>,
    },
    /// Discovered online (not yet validated for a specific source type).
    Discovered { url: String },
    /// External channel via channel-relay service.
    ChannelRelay { relay_url: String },
}

/// Hint about what authentication method is needed.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthHint {
    /// MCP server supports Dynamic Client Registration (zero-config OAuth).
    Dcr,
    /// MCP server needs a pre-configured OAuth client_id.
    OAuthPreConfigured {
        /// URL where the user can create an OAuth app.
        setup_url: String,
    },
    /// WASM tool has auth defined in its capabilities.json file.
    CapabilitiesAuth,
    /// No authentication needed.
    None,
    /// OAuth via channel-relay service.
    ChannelRelayOAuth,
}

/// Where a search result came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResultSource {
    /// From the built-in curated registry.
    Registry,
    /// From online discovery (validated).
    Discovered,
}

/// Result of searching for extensions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// The registry entry.
    #[serde(flatten)]
    pub entry: RegistryEntry,
    /// Where this result came from.
    pub source: ResultSource,
    /// Whether the endpoint was validated (for discovered entries).
    #[serde(default)]
    pub validated: bool,
}

/// Result of installing an extension.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstallResult {
    pub name: String,
    pub kind: ExtensionKind,
    pub message: String,
}

/// Result of upgrading one or more extensions.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UpgradeResult {
    /// Per-extension upgrade outcomes.
    pub results: Vec<UpgradeOutcome>,
    /// Summary message.
    pub message: String,
}

/// Outcome for a single extension upgrade.
#[derive(Debug, Clone, serde::Serialize)]
pub struct UpgradeOutcome {
    pub name: String,
    pub kind: ExtensionKind,
    /// What happened: "upgraded", "already_up_to_date", "failed", "not_in_registry".
    pub status: String,
    /// Human-readable detail.
    pub detail: String,
}

/// Auth readiness state for the extensions list UI.
///
/// Used by `check_tool_auth_status` and `check_channel_auth_status` to
/// communicate a tool's credential state to the list handler without
/// ambiguous `(bool, bool)` tuples.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolAuthState {
    /// Token/credentials are present — ready to use.
    Ready,
    /// Auth section exists but the access token is missing (OAuth not completed).
    NeedsAuth,
    /// Setup credentials (client_id/secret) must be configured before OAuth can start.
    NeedsSetup,
    /// No auth configuration at all (no capabilities or auth section).
    NoAuth,
}

/// The typed auth status, carrying only the data relevant to each state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthStatus {
    /// Authentication is complete; no further action needed.
    Authenticated,
    /// No authentication is required for this extension.
    NoAuthRequired,
    /// OAuth flow started — user must open `auth_url` in their browser.
    AwaitingAuthorization {
        auth_url: String,
        callback_type: String,
    },
    /// Waiting for user to provide a token/key manually.
    AwaitingToken {
        instructions: String,
        setup_url: Option<String>,
    },
    /// OAuth client credentials need to be configured before auth can proceed.
    NeedsSetup {
        instructions: String,
        setup_url: Option<String>,
    },
}

impl AuthStatus {
    /// The wire-format status string (backward-compatible with JS consumers).
    pub fn as_str(&self) -> &'static str {
        match self {
            AuthStatus::Authenticated => "authenticated",
            AuthStatus::NoAuthRequired => "no_auth_required",
            AuthStatus::AwaitingAuthorization { .. } => "awaiting_authorization",
            AuthStatus::AwaitingToken { .. } => "awaiting_token",
            AuthStatus::NeedsSetup { .. } => "needs_setup",
        }
    }
}

/// Result of authenticating an extension.
#[derive(Debug, Clone)]
pub struct AuthResult {
    pub name: String,
    pub kind: ExtensionKind,
    pub status: AuthStatus,
}

impl AuthResult {
    // ── Constructors ──────────────────────────────────────────────────

    pub fn authenticated(name: impl Into<String>, kind: ExtensionKind) -> Self {
        Self {
            name: name.into(),
            kind,
            status: AuthStatus::Authenticated,
        }
    }

    pub fn no_auth_required(name: impl Into<String>, kind: ExtensionKind) -> Self {
        Self {
            name: name.into(),
            kind,
            status: AuthStatus::NoAuthRequired,
        }
    }

    pub fn awaiting_authorization(
        name: impl Into<String>,
        kind: ExtensionKind,
        auth_url: String,
        callback_type: String,
    ) -> Self {
        Self {
            name: name.into(),
            kind,
            status: AuthStatus::AwaitingAuthorization {
                auth_url,
                callback_type,
            },
        }
    }

    pub fn awaiting_token(
        name: impl Into<String>,
        kind: ExtensionKind,
        instructions: String,
        setup_url: Option<String>,
    ) -> Self {
        Self {
            name: name.into(),
            kind,
            status: AuthStatus::AwaitingToken {
                instructions,
                setup_url,
            },
        }
    }

    pub fn needs_setup(
        name: impl Into<String>,
        kind: ExtensionKind,
        instructions: String,
        setup_url: Option<String>,
    ) -> Self {
        Self {
            name: name.into(),
            kind,
            status: AuthStatus::NeedsSetup {
                instructions,
                setup_url,
            },
        }
    }

    // ── Accessors ─────────────────────────────────────────────────────

    pub fn is_authenticated(&self) -> bool {
        matches!(self.status, AuthStatus::Authenticated)
    }

    pub fn auth_url(&self) -> Option<&str> {
        match &self.status {
            AuthStatus::AwaitingAuthorization { auth_url, .. } => Some(auth_url),
            _ => None,
        }
    }

    pub fn callback_type(&self) -> Option<&str> {
        match &self.status {
            AuthStatus::AwaitingAuthorization { callback_type, .. } => Some(callback_type),
            _ => None,
        }
    }

    pub fn instructions(&self) -> Option<&str> {
        match &self.status {
            AuthStatus::AwaitingToken { instructions, .. }
            | AuthStatus::NeedsSetup { instructions, .. } => Some(instructions),
            _ => None,
        }
    }

    pub fn setup_url(&self) -> Option<&str> {
        match &self.status {
            AuthStatus::AwaitingToken { setup_url, .. }
            | AuthStatus::NeedsSetup { setup_url, .. } => setup_url.as_deref(),
            _ => None,
        }
    }

    pub fn is_awaiting_token(&self) -> bool {
        matches!(self.status, AuthStatus::AwaitingToken { .. })
    }

    pub fn status_str(&self) -> &'static str {
        self.status.as_str()
    }
}

/// Serialize `AuthResult` to the same flat JSON shape the JS frontend expects.
impl Serialize for AuthResult {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // Count fields: name + kind + status + optional fields
        let optional_count = self.auth_url().is_some() as usize
            + self.callback_type().is_some() as usize
            + self.instructions().is_some() as usize
            + self.setup_url().is_some() as usize;
        let mut map = serializer.serialize_map(Some(4 + optional_count))?;

        map.serialize_entry("name", &self.name)?;
        map.serialize_entry("kind", &self.kind)?;
        if let Some(url) = self.auth_url() {
            map.serialize_entry("auth_url", url)?;
        }
        if let Some(cb) = self.callback_type() {
            map.serialize_entry("callback_type", cb)?;
        }
        if let Some(inst) = self.instructions() {
            map.serialize_entry("instructions", inst)?;
        }
        if let Some(url) = self.setup_url() {
            map.serialize_entry("setup_url", url)?;
        }
        map.serialize_entry("awaiting_token", &self.is_awaiting_token())?;
        map.serialize_entry("status", self.status_str())?;
        map.end()
    }
}

/// Deserialize from the flat JSON shape back into the typed enum.
impl<'de> Deserialize<'de> for AuthResult {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// Flat helper matching the old JSON shape.
        #[derive(Deserialize)]
        #[allow(dead_code)]
        struct Raw {
            name: String,
            kind: ExtensionKind,
            #[serde(default)]
            auth_url: Option<String>,
            #[serde(default)]
            callback_type: Option<String>,
            #[serde(default)]
            instructions: Option<String>,
            #[serde(default)]
            setup_url: Option<String>,
            #[serde(default)]
            awaiting_token: bool,
            status: String,
        }

        let raw = Raw::deserialize(deserializer)?;
        let status = match raw.status.as_str() {
            "authenticated" => AuthStatus::Authenticated,
            "no_auth_required" => AuthStatus::NoAuthRequired,
            "awaiting_authorization" => AuthStatus::AwaitingAuthorization {
                auth_url: raw.auth_url.unwrap_or_default(),
                callback_type: raw.callback_type.unwrap_or_default(),
            },
            "awaiting_token" => AuthStatus::AwaitingToken {
                instructions: raw.instructions.unwrap_or_default(),
                setup_url: raw.setup_url,
            },
            "needs_setup" => AuthStatus::NeedsSetup {
                instructions: raw.instructions.unwrap_or_default(),
                setup_url: raw.setup_url,
            },
            other => {
                return Err(serde::de::Error::unknown_variant(
                    other,
                    &[
                        "authenticated",
                        "no_auth_required",
                        "awaiting_authorization",
                        "awaiting_token",
                        "needs_setup",
                    ],
                ));
            }
        };
        Ok(AuthResult {
            name: raw.name,
            kind: raw.kind,
            status,
        })
    }
}

/// Result of activating an extension.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActivateResult {
    pub name: String,
    pub kind: ExtensionKind,
    /// Names of tools that were loaded/registered.
    pub tools_loaded: Vec<String>,
    pub message: String,
}

/// Result of configuring secrets for an extension.
///
/// Returned by `ExtensionManager::configure()`, the single entrypoint
/// for providing secrets to any extension (chat auth, gateway setup, etc.).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerificationChallenge {
    /// One-time code the user must send back to the integration.
    pub code: String,
    /// Human-readable instructions for completing verification.
    pub instructions: String,
    /// Deep-link or shortcut URL that prefills the verification payload when supported.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deep_link: Option<String>,
}

#[derive(Debug, Clone)]
pub struct ConfigureResult {
    /// Human-readable status message.
    pub message: String,
    /// Whether the extension was successfully activated after configuration.
    pub activated: bool,
    /// Whether a restart is required for the new configuration to take effect.
    pub restart_required: bool,
    /// OAuth authorization URL (if OAuth flow was started).
    pub auth_url: Option<String>,
    /// Pending manual verification challenge (for Telegram owner binding, etc.).
    pub verification: Option<VerificationChallenge>,
}

fn default_true() -> bool {
    true
}

/// An installed extension with its current status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledExtension {
    pub name: String,
    pub kind: ExtensionKind,
    /// Human-readable display name (e.g. "Telegram Channel" vs "Telegram Tool").
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Server or source URL (e.g. MCP server endpoint).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    pub authenticated: bool,
    pub active: bool,
    /// Tool names if active.
    #[serde(default)]
    pub tools: Vec<String>,
    /// Whether this extension has a setup schema (required_secrets/required_fields) that can be configured.
    #[serde(default)]
    pub needs_setup: bool,
    /// Whether this extension has an auth configuration (OAuth or manual token).
    #[serde(default)]
    pub has_auth: bool,
    /// Whether this extension is installed locally (false = available in registry but not installed).
    #[serde(default = "default_true")]
    pub installed: bool,
    /// Last activation error for WASM channels.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub activation_error: Option<String>,
    /// Extension version from capabilities file (semver).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

/// Error type for extension operations.
#[derive(Debug, thiserror::Error)]
pub enum ExtensionError {
    #[error("Extension not found: {0}")]
    NotFound(String),

    #[error("Extension already installed: {0}")]
    AlreadyInstalled(String),

    #[error("Extension not installed: {0}")]
    NotInstalled(String),

    #[error("Authentication failed: {0}")]
    AuthFailed(String),

    #[error("Server does not support OAuth: {0}")]
    AuthNotSupported(String),

    #[error("Activation failed: {0}")]
    ActivationFailed(String),

    #[error("Authentication required")]
    AuthRequired,

    #[error("Installation failed: {0}")]
    InstallFailed(String),

    #[error("Discovery failed: {0}")]
    DiscoveryFailed(String),

    #[error("Invalid URL: {0}")]
    InvalidUrl(String),

    #[error("Download failed: {0}")]
    DownloadFailed(String),

    #[error("Config error: {0}")]
    Config(String),

    #[error("Primary install failed: {primary}; fallback install also failed: {fallback}")]
    FallbackFailed {
        primary: Box<ExtensionError>,
        fallback: Box<ExtensionError>,
    },

    #[error("Token validation failed: {0}")]
    ValidationFailed(String),

    #[error("{0}")]
    Other(String),
}

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

    #[test]
    fn auth_result_authenticated_round_trip() {
        let result = AuthResult::authenticated("gmail", ExtensionKind::WasmTool);
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(json["status"], "authenticated");
        assert_eq!(json["name"], "gmail");
        assert_eq!(json["kind"], "wasm_tool");
        assert_eq!(json["awaiting_token"], false);
        assert!(json.get("auth_url").is_none());
        assert!(json.get("instructions").is_none());

        let back: AuthResult = serde_json::from_value(json).unwrap();
        assert!(back.is_authenticated());
        assert!(back.auth_url().is_none());
    }

    #[test]
    fn auth_result_awaiting_authorization_round_trip() {
        let result = AuthResult::awaiting_authorization(
            "google-drive",
            ExtensionKind::WasmTool,
            "https://accounts.google.com/o/oauth2/v2/auth?state=abc".to_string(),
            "local".to_string(),
        );
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(json["status"], "awaiting_authorization");
        assert_eq!(
            json["auth_url"],
            "https://accounts.google.com/o/oauth2/v2/auth?state=abc"
        );
        assert_eq!(json["callback_type"], "local");
        assert_eq!(json["awaiting_token"], false);

        let back: AuthResult = serde_json::from_value(json).unwrap();
        assert_eq!(
            back.auth_url(),
            Some("https://accounts.google.com/o/oauth2/v2/auth?state=abc")
        );
        assert_eq!(back.callback_type(), Some("local"));
        assert!(!back.is_authenticated());
    }

    #[test]
    fn auth_result_awaiting_token_round_trip() {
        let result = AuthResult::awaiting_token(
            "telegram",
            ExtensionKind::WasmChannel,
            "Enter your bot token".to_string(),
            None,
        );
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(json["status"], "awaiting_token");
        assert_eq!(json["instructions"], "Enter your bot token");
        assert_eq!(json["awaiting_token"], true);
        assert!(json.get("auth_url").is_none());

        let back: AuthResult = serde_json::from_value(json).unwrap();
        assert!(back.is_awaiting_token());
        assert_eq!(back.instructions(), Some("Enter your bot token"));
    }

    #[test]
    fn auth_result_needs_setup_round_trip() {
        let result = AuthResult::needs_setup(
            "custom-tool",
            ExtensionKind::WasmTool,
            "Configure OAuth credentials in the Setup tab.".to_string(),
            Some("https://console.cloud.google.com".to_string()),
        );
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(json["status"], "needs_setup");
        assert_eq!(json["setup_url"], "https://console.cloud.google.com");
        assert_eq!(json["awaiting_token"], false);

        let back: AuthResult = serde_json::from_value(json).unwrap();
        assert!(!back.is_authenticated());
        assert!(!back.is_awaiting_token());
        assert_eq!(back.setup_url(), Some("https://console.cloud.google.com"));
    }

    #[test]
    fn auth_result_no_auth_required_round_trip() {
        let result = AuthResult::no_auth_required("echo", ExtensionKind::WasmTool);
        let json = serde_json::to_value(&result).unwrap();

        assert_eq!(json["status"], "no_auth_required");
        assert_eq!(json["awaiting_token"], false);

        let back: AuthResult = serde_json::from_value(json).unwrap();
        assert!(!back.is_authenticated());
        assert_eq!(back.status, AuthStatus::NoAuthRequired);
    }

    #[test]
    fn auth_status_type_safety() {
        // AwaitingAuthorization always has auth_url
        let result = AuthResult::awaiting_authorization(
            "test",
            ExtensionKind::WasmTool,
            "https://example.com".to_string(),
            "local".to_string(),
        );
        assert!(result.auth_url().is_some());
        assert!(!result.is_awaiting_token());

        // Authenticated never has auth_url
        let result = AuthResult::authenticated("test", ExtensionKind::WasmTool);
        assert!(result.auth_url().is_none());
        assert!(result.instructions().is_none());
        assert!(result.setup_url().is_none());
    }

    // ── ExtensionKind ────────────────────────────────────────────────

    #[test]
    fn extension_kind_display() {
        assert_eq!(ExtensionKind::McpServer.to_string(), "mcp_server");
        assert_eq!(ExtensionKind::WasmTool.to_string(), "wasm_tool");
        assert_eq!(ExtensionKind::WasmChannel.to_string(), "wasm_channel");
    }

    #[test]
    fn extension_kind_serde_roundtrip() {
        for kind in [
            ExtensionKind::McpServer,
            ExtensionKind::WasmTool,
            ExtensionKind::WasmChannel,
        ] {
            let json = serde_json::to_value(kind).unwrap();
            let back: ExtensionKind = serde_json::from_value(json).unwrap();
            assert_eq!(back, kind);
        }
        // Verify the serialized strings match rename_all = "snake_case"
        assert_eq!(
            serde_json::to_value(ExtensionKind::McpServer).unwrap(),
            "mcp_server"
        );
        assert_eq!(
            serde_json::to_value(ExtensionKind::WasmTool).unwrap(),
            "wasm_tool"
        );
        assert_eq!(
            serde_json::to_value(ExtensionKind::WasmChannel).unwrap(),
            "wasm_channel"
        );
    }

    // ── ExtensionSource ──────────────────────────────────────────────

    #[test]
    fn extension_source_serde_mcp_url() {
        let src = ExtensionSource::McpUrl {
            url: "https://mcp.example.com".to_string(),
        };
        let json = serde_json::to_value(&src).unwrap();
        assert_eq!(json["type"], "mcp_url");
        assert_eq!(json["url"], "https://mcp.example.com");
        let back: ExtensionSource = serde_json::from_value(json).unwrap();
        assert!(
            matches!(back, ExtensionSource::McpUrl { url } if url == "https://mcp.example.com")
        );
    }

    #[test]
    fn extension_source_serde_wasm_download() {
        let src = ExtensionSource::WasmDownload {
            wasm_url: "https://cdn.example.com/tool.wasm".to_string(),
            capabilities_url: Some("https://cdn.example.com/caps.json".to_string()),
        };
        let json = serde_json::to_value(&src).unwrap();
        assert_eq!(json["type"], "wasm_download");
        assert_eq!(json["wasm_url"], "https://cdn.example.com/tool.wasm");
        assert_eq!(
            json["capabilities_url"],
            "https://cdn.example.com/caps.json"
        );
        let back: ExtensionSource = serde_json::from_value(json).unwrap();
        assert!(
            matches!(back, ExtensionSource::WasmDownload { capabilities_url: Some(c), .. } if c.contains("caps.json"))
        );
    }

    #[test]
    fn extension_source_serde_wasm_buildable() {
        let src = ExtensionSource::WasmBuildable {
            source_dir: "/home/user/tools/my-tool".to_string(),
            build_dir: Some("target/wasm32-wasip2/release".to_string()),
            crate_name: Some("my_tool".to_string()),
        };
        let json = serde_json::to_value(&src).unwrap();
        assert_eq!(json["type"], "wasm_buildable");
        assert_eq!(json["source_dir"], "/home/user/tools/my-tool");
        let back: ExtensionSource = serde_json::from_value(json).unwrap();
        assert!(
            matches!(back, ExtensionSource::WasmBuildable { source_dir, .. } if source_dir.contains("my-tool"))
        );
    }

    #[test]
    fn extension_source_serde_discovered() {
        let src = ExtensionSource::Discovered {
            url: "https://discovered.example.com".to_string(),
        };
        let json = serde_json::to_value(&src).unwrap();
        assert_eq!(json["type"], "discovered");
        let back: ExtensionSource = serde_json::from_value(json).unwrap();
        assert!(matches!(back, ExtensionSource::Discovered { url } if url.contains("discovered")));
    }

    // ── AuthHint ─────────────────────────────────────────────────────

    #[test]
    fn auth_hint_serde_all_variants() {
        // Dcr
        let json = serde_json::to_value(&AuthHint::Dcr).unwrap();
        assert_eq!(json["type"], "dcr");
        let back: AuthHint = serde_json::from_value(json).unwrap();
        assert!(matches!(back, AuthHint::Dcr));

        // OAuthPreConfigured
        let hint = AuthHint::OAuthPreConfigured {
            setup_url: "https://dev.example.com/apps".to_string(),
        };
        let json = serde_json::to_value(&hint).unwrap();
        assert_eq!(json["type"], "o_auth_pre_configured");
        assert_eq!(json["setup_url"], "https://dev.example.com/apps");
        let back: AuthHint = serde_json::from_value(json).unwrap();
        assert!(
            matches!(back, AuthHint::OAuthPreConfigured { setup_url } if setup_url.contains("dev.example"))
        );

        // CapabilitiesAuth
        let json = serde_json::to_value(&AuthHint::CapabilitiesAuth).unwrap();
        assert_eq!(json["type"], "capabilities_auth");
        let back: AuthHint = serde_json::from_value(json).unwrap();
        assert!(matches!(back, AuthHint::CapabilitiesAuth));

        // None
        let json = serde_json::to_value(&AuthHint::None).unwrap();
        assert_eq!(json["type"], "none");
        let back: AuthHint = serde_json::from_value(json).unwrap();
        assert!(matches!(back, AuthHint::None));
    }

    // ── SearchResult ─────────────────────────────────────────────────

    #[test]
    fn search_result_serde_registry_source() {
        // SearchResult uses #[serde(flatten)] on entry, which means
        // RegistryEntry.source (ExtensionSource) and SearchResult.source
        // (ResultSource) collide on the "source" key. The last writer wins
        // during serialization, so we test serialize-only (no roundtrip).
        let entry = RegistryEntry {
            name: "notion".to_string(),
            display_name: "Notion".to_string(),
            kind: ExtensionKind::McpServer,
            description: "Notion integration".to_string(),
            keywords: vec!["notes".to_string(), "wiki".to_string()],
            source: ExtensionSource::McpUrl {
                url: "https://mcp.notion.so".to_string(),
            },
            fallback_source: None,
            auth_hint: AuthHint::Dcr,
            version: None,
        };
        let sr = SearchResult {
            entry,
            source: ResultSource::Registry,
            validated: false,
        };
        let json = serde_json::to_value(&sr).unwrap();
        assert_eq!(json["name"], "notion");
        assert_eq!(json["kind"], "mcp_server");
        assert_eq!(json["description"], "Notion integration");
        assert_eq!(json["validated"], false);
        // The flattened entry fields are present at the top level
        assert!(json.get("auth_hint").is_some());
        assert_eq!(json["keywords"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn search_result_serde_discovered_source() {
        let entry = RegistryEntry {
            name: "custom-api".to_string(),
            display_name: "Custom API".to_string(),
            kind: ExtensionKind::McpServer,
            description: "Discovered MCP server".to_string(),
            keywords: vec![],
            source: ExtensionSource::Discovered {
                url: "https://custom.example.com/.well-known/mcp".to_string(),
            },
            fallback_source: None,
            auth_hint: AuthHint::None,
            version: None,
        };
        let sr = SearchResult {
            entry,
            source: ResultSource::Discovered,
            validated: true,
        };
        let json = serde_json::to_value(&sr).unwrap();
        assert_eq!(json["name"], "custom-api");
        assert_eq!(json["display_name"], "Custom API");
        assert_eq!(json["validated"], true);
        assert!(json.get("keywords").is_some());
    }

    // ── InstallResult ────────────────────────────────────────────────

    #[test]
    fn install_result_serde_roundtrip() {
        let ir = InstallResult {
            name: "weather".to_string(),
            kind: ExtensionKind::WasmTool,
            message: "Installed successfully".to_string(),
        };
        let json = serde_json::to_value(&ir).unwrap();
        assert_eq!(json["name"], "weather");
        assert_eq!(json["kind"], "wasm_tool");
        assert_eq!(json["message"], "Installed successfully");
        let back: InstallResult = serde_json::from_value(json).unwrap();
        assert_eq!(back.name, "weather");
        assert_eq!(back.kind, ExtensionKind::WasmTool);
    }

    // ── ActivateResult ───────────────────────────────────────────────

    #[test]
    fn activate_result_serde_roundtrip() {
        let ar = ActivateResult {
            name: "slack".to_string(),
            kind: ExtensionKind::WasmChannel,
            tools_loaded: vec!["send_message".to_string(), "read_channel".to_string()],
            message: "Activated with 2 tools".to_string(),
        };
        let json = serde_json::to_value(&ar).unwrap();
        assert_eq!(json["name"], "slack");
        assert_eq!(json["kind"], "wasm_channel");
        assert_eq!(json["tools_loaded"].as_array().unwrap().len(), 2);
        let back: ActivateResult = serde_json::from_value(json).unwrap();
        assert_eq!(back.tools_loaded, vec!["send_message", "read_channel"]);
    }

    // ── InstalledExtension ───────────────────────────────────────────

    #[test]
    fn installed_extension_serde_defaults() {
        // Minimal JSON: optional fields absent, defaults kick in
        let json = serde_json::json!({
            "name": "echo",
            "kind": "wasm_tool",
            "authenticated": false,
            "active": false,
        });
        let ext: InstalledExtension = serde_json::from_value(json).unwrap();
        assert_eq!(ext.name, "echo");
        assert!(ext.installed, "installed should default to true");
        assert!(!ext.needs_setup, "needs_setup should default to false");
        assert!(!ext.has_auth);
        assert!(ext.tools.is_empty());
        assert!(ext.display_name.is_none());
        assert!(ext.description.is_none());
        assert!(ext.url.is_none());
        assert!(ext.activation_error.is_none());
    }

    #[test]
    fn installed_extension_serde_all_fields() {
        let ext = InstalledExtension {
            name: "gmail".to_string(),
            kind: ExtensionKind::WasmTool,
            display_name: Some("Gmail Tool".to_string()),
            description: Some("Read and send emails".to_string()),
            url: Some("https://gmail.example.com".to_string()),
            authenticated: true,
            active: true,
            tools: vec!["send_email".to_string(), "read_inbox".to_string()],
            needs_setup: true,
            has_auth: true,
            installed: false,
            activation_error: Some("token expired".to_string()),
            version: None,
        };
        let json = serde_json::to_value(&ext).unwrap();
        assert_eq!(json["display_name"], "Gmail Tool");
        assert_eq!(json["description"], "Read and send emails");
        assert_eq!(json["url"], "https://gmail.example.com");
        assert_eq!(json["needs_setup"], true);
        assert_eq!(json["installed"], false);
        assert_eq!(json["activation_error"], "token expired");

        let back: InstalledExtension = serde_json::from_value(json).unwrap();
        assert_eq!(back.name, "gmail");
        assert_eq!(back.tools.len(), 2);
        assert!(back.needs_setup);
        assert!(!back.installed);
        assert_eq!(back.activation_error.as_deref(), Some("token expired"));
    }

    // ── ExtensionError Display ───────────────────────────────────────

    #[test]
    fn extension_error_display_all_variants() {
        let cases: Vec<(ExtensionError, &str)> = vec![
            (
                ExtensionError::NotFound("foo".into()),
                "Extension not found: foo",
            ),
            (
                ExtensionError::AlreadyInstalled("bar".into()),
                "Extension already installed: bar",
            ),
            (
                ExtensionError::NotInstalled("baz".into()),
                "Extension not installed: baz",
            ),
            (
                ExtensionError::AuthFailed("bad token".into()),
                "Authentication failed: bad token",
            ),
            (
                ExtensionError::ActivationFailed("crash".into()),
                "Activation failed: crash",
            ),
            (
                ExtensionError::InstallFailed("disk full".into()),
                "Installation failed: disk full",
            ),
            (
                ExtensionError::DiscoveryFailed("timeout".into()),
                "Discovery failed: timeout",
            ),
            (
                ExtensionError::InvalidUrl("not a url".into()),
                "Invalid URL: not a url",
            ),
            (
                ExtensionError::DownloadFailed("404".into()),
                "Download failed: 404",
            ),
            (
                ExtensionError::Config("missing key".into()),
                "Config error: missing key",
            ),
            (ExtensionError::AuthRequired, "Authentication required"),
            (
                ExtensionError::Other("something broke".into()),
                "something broke",
            ),
            (
                ExtensionError::FallbackFailed {
                    primary: Box::new(ExtensionError::DownloadFailed("404".into())),
                    fallback: Box::new(ExtensionError::InstallFailed("no cargo".into())),
                },
                "Primary install failed: Download failed: 404; fallback install also failed: Installation failed: no cargo",
            ),
        ];
        for (err, expected) in cases {
            assert_eq!(err.to_string(), expected);
        }
    }

    // ── ToolAuthState ────────────────────────────────────────────────

    #[test]
    fn tool_auth_state_equality() {
        assert_eq!(ToolAuthState::Ready, ToolAuthState::Ready);
        assert_eq!(ToolAuthState::NeedsAuth, ToolAuthState::NeedsAuth);
        assert_eq!(ToolAuthState::NeedsSetup, ToolAuthState::NeedsSetup);
        assert_eq!(ToolAuthState::NoAuth, ToolAuthState::NoAuth);

        assert_ne!(ToolAuthState::Ready, ToolAuthState::NeedsAuth);
        assert_ne!(ToolAuthState::NeedsSetup, ToolAuthState::NoAuth);
        assert_ne!(ToolAuthState::Ready, ToolAuthState::NoAuth);
    }

    // ── ResultSource ─────────────────────────────────────────────────

    #[test]
    fn result_source_serde() {
        let json = serde_json::to_value(ResultSource::Registry).unwrap();
        assert_eq!(json, "registry");
        let back: ResultSource = serde_json::from_value(json).unwrap();
        assert_eq!(back, ResultSource::Registry);

        let json = serde_json::to_value(ResultSource::Discovered).unwrap();
        assert_eq!(json, "discovered");
        let back: ResultSource = serde_json::from_value(json).unwrap();
        assert_eq!(back, ResultSource::Discovered);
    }

    // ── AuthResult::status_str ───────────────────────────────────────

    #[test]
    fn auth_result_status_str_all_variants() {
        assert_eq!(
            AuthResult::authenticated("a", ExtensionKind::McpServer).status_str(),
            "authenticated"
        );
        assert_eq!(
            AuthResult::no_auth_required("b", ExtensionKind::WasmTool).status_str(),
            "no_auth_required"
        );
        assert_eq!(
            AuthResult::awaiting_authorization(
                "c",
                ExtensionKind::WasmChannel,
                "https://x.com".into(),
                "local".into(),
            )
            .status_str(),
            "awaiting_authorization"
        );
        assert_eq!(
            AuthResult::awaiting_token("d", ExtensionKind::WasmTool, "paste token".into(), None)
                .status_str(),
            "awaiting_token"
        );
        assert_eq!(
            AuthResult::needs_setup(
                "e",
                ExtensionKind::McpServer,
                "configure oauth".into(),
                Some("https://setup.example.com".into()),
            )
            .status_str(),
            "needs_setup"
        );
    }
}