iron-shell 14.0.0

The world's first multi-agent shell with typed functional pipelines and multi-modal AI
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
//! Agent Marketplace Registry
//!
//! This module provides a registry for sharing and discovering IronShell agents.
//! Agents can be published, searched, installed, and versioned.
//!
//! Trust: an installed agent is a file, and nothing here runs it. The package
//! digest is SHA-256 and comes from the same registry as the package, so it
//! detects corruption and truncation in transit. It does not detect a
//! compromised registry, and nothing signs packages or checks a publisher key.
//! Only a digest the registry publishes is checked; there is no signing scheme.
//!
//! Names: an agent name and version become directory names in the cache, so
//! both are checked by `validate_package_name` at every entry point and again
//! on what the registry sends back.

use crate::packages::{is_sha256_hex, sha256_matches};
use anyhow::Result;

/// What a refused digest is, for the message: MD5 is named, since it is the
/// one shape an older registry sends.
fn describe_digest(digest: &str) -> String {
    match digest.len() {
        0 => "no digest".to_string(),
        32 => "a 32-character digest, which is MD5 (MD5 is not accepted)".to_string(),
        n => format!("a {n}-character digest"),
    }
}

/// Longest agent name or version accepted.
const MAX_NAME_LEN: usize = 128;

/// Refuse an agent name or version that is not one safe path segment
/// (`E_BAD_ARG`). Allowed: ASCII letters, digits, `-`, `_` and `.`, not
/// starting with `.` or `-`, and not a Windows device name. A `/` is refused,
/// so scoped (`scope/name`) names are not accepted: the client has never
/// routed them.
pub fn validate_package_name(name: &str, what: &str) -> Result<()> {
    let ok = !name.is_empty()
        && name.len() <= MAX_NAME_LEN
        && !name.starts_with(['.', '-'])
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
    let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
    let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
        || (stem.len() == 4
            && (stem.starts_with("COM") || stem.starts_with("LPT"))
            && stem.as_bytes()[3].is_ascii_digit());
    if ok && !device {
        return Ok(());
    }
    Err(registry_coded(
        crate::safety::ErrorCode::BadArg,
        format!(
            "marketplace: {what} {name:?} is not one safe name: use ASCII letters, digits, '-', '_' and '.', not starting with '.' or '-', at most {MAX_NAME_LEN} characters, and not a device name"
        ),
        "pass the agent's name or version as the registry lists it; a '/', '\\' or ':' is refused",
    ))
}

/// A coded error for the registry client (`builtin` = "marketplace"), so a caller
/// of `marketplace install` through the agent API can tell a missing agent from
/// a failed download.
fn registry_coded(code: crate::safety::ErrorCode, message: String, hint: &str) -> anyhow::Error {
    anyhow::Error::new(crate::safety::SafetyError {
        code,
        message,
        builtin: "marketplace".to_string(),
        hint: hint.to_string(),
        approval: None,
        did_you_mean: Vec::new(),
        expected: String::new(),
        got: String::new(),
    })
}

/// A registry client that cannot hang: 10 s to connect, and `total_secs` for
/// the whole request, the body included. It does not follow redirects itself:
/// `registry_get` follows them and judges each hop.
fn registry_client(total_secs: u64) -> Result<reqwest::Client> {
    crate::tls::install_provider();
    reqwest::Client::builder()
        .connect_timeout(std::time::Duration::from_secs(10))
        .timeout(std::time::Duration::from_secs(total_secs))
        .redirect(reqwest::redirect::Policy::none())
        .build()
        .map_err(|e| {
            registry_coded(
                crate::safety::ErrorCode::Io,
                format!("registry HTTP client could not be built: {}", e),
                "the local HTTP stack could not start; a TLS or network configuration problem on this host",
            )
        })
}

/// GET a registry URL, following redirects by hand. Each hop is judged by the
/// guard before it is requested, and the hop count has the same ceiling as
/// `web_curl`. A connection that fails is a coded network error, not an I/O
/// fault on this machine and not a missing agent.
async fn registry_get(client: &reqwest::Client, url: &str) -> Result<reqwest::Response> {
    let mut hop = url.to_string();
    for _ in 0..=crate::builtins::WEB_MAX_REDIRS {
        let response = client.get(&hop).send().await.map_err(|e| {
            registry_coded(
                crate::safety::ErrorCode::Network,
                format!("could not reach the registry at {hop}: {e}"),
                "the registry is down or the network is unavailable; nothing was changed, so retry later",
            )
        })?;
        let location = response
            .headers()
            .get(reqwest::header::LOCATION)
            .and_then(|v| v.to_str().ok());
        match crate::security::judged_redirect(
            "marketplace",
            &hop,
            response.status().as_u16(),
            location,
        )? {
            // The registry's own requests are not pinned (see the report): each
            // hop is judged, and the next request goes to the URL that was judged.
            Some(next) => hop = next.url,
            None => return Ok(response),
        }
    }
    Err(crate::safety::budget_exceeded(
        "marketplace",
        format!("more than {} redirects", crate::builtins::WEB_MAX_REDIRS),
        "request the final URL directly",
    ))
}

/// The error for a registry answer that is not a success: a 404 is a missing
/// agent, and any other status means the registry could not answer.
fn registry_status_error(
    status: reqwest::StatusCode,
    missing: String,
    hint: &str,
) -> anyhow::Error {
    if status == reqwest::StatusCode::NOT_FOUND {
        return registry_coded(crate::safety::ErrorCode::NotFound, missing, hint);
    }
    registry_coded(
        crate::safety::ErrorCode::Network,
        format!("the registry answered HTTP {}", status.as_u16()),
        "the registry is unavailable right now; nothing was changed, so retry later",
    )
}
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Agent metadata for the marketplace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentManifest {
    /// Unique agent identifier (namespace/name format)
    pub name: String,
    /// Human-readable display name
    pub display_name: String,
    /// Agent description
    pub description: String,
    /// Semantic version
    pub version: String,
    /// Author information
    pub author: AuthorInfo,
    /// License (SPDX identifier)
    pub license: String,
    /// Repository URL
    pub repository: Option<String>,
    /// Homepage URL
    pub homepage: Option<String>,
    /// Keywords for search
    pub keywords: Vec<String>,
    /// Categories
    pub categories: Vec<String>,
    /// Agent capabilities
    pub capabilities: Vec<String>,
    /// Required IronShell version
    pub ironshell_version: String,
    /// Dependencies on other agents
    pub dependencies: Vec<AgentDependency>,
    /// Agent definition
    pub agent: AgentDefinition,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorInfo {
    pub name: String,
    pub email: Option<String>,
    pub url: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentDependency {
    pub name: String,
    pub version: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentDefinition {
    /// System prompt for the agent
    pub system_prompt: String,
    /// Model to use (optional, uses default if not specified)
    pub model: Option<String>,
    /// Available tools/builtins
    pub tools: Vec<String>,
    /// Tool calling mode
    pub tool_choice: Option<String>,
    /// Temperature for generation
    pub temperature: Option<f32>,
    /// Max tokens
    pub max_tokens: Option<u32>,
}

/// Published agent in the registry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublishedAgent {
    pub manifest: AgentManifest,
    /// Download count
    pub downloads: u64,
    /// Star count
    pub stars: u64,
    /// Fork count
    pub forks: u64,
    /// Verification status
    pub verified: bool,
    /// Published timestamp
    pub published_at: u64,
    /// Last updated timestamp
    pub updated_at: u64,
    /// SHA-256 hash of the agent bundle
    pub checksum: String,
    /// Bundle size in bytes
    pub size: u64,
}

/// Search query for the marketplace
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchQuery {
    pub query: Option<String>,
    pub category: Option<String>,
    pub keyword: Option<String>,
    pub author: Option<String>,
    pub sort_by: Option<SortBy>,
    pub page: Option<u32>,
    pub per_page: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SortBy {
    Downloads,
    Stars,
    Recent,
    Name,
}

/// Search results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResults {
    pub total: u64,
    pub page: u32,
    pub per_page: u32,
    pub results: Vec<PublishedAgent>,
}

/// Local registry client
pub struct RegistryClient {
    /// Registry URL
    registry_url: String,
    /// Local cache directory
    cache_dir: PathBuf,
    /// Installed agents
    installed: HashMap<String, InstalledAgent>,
}

impl std::fmt::Debug for RegistryClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RegistryClient")
            .field("registry_url", &self.registry_url)
            .field("cache_dir", &self.cache_dir)
            .field("installed_count", &self.installed.len())
            .finish()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledAgent {
    pub manifest: AgentManifest,
    pub installed_at: u64,
    pub path: PathBuf,
}

impl RegistryClient {
    /// Create a new registry client over the user's agent cache
    pub fn new(registry_url: Option<String>) -> Result<Self> {
        let cache_dir = dirs::cache_dir()
            .ok_or_else(|| {
                registry_coded(
                    crate::safety::ErrorCode::Io,
                    "Could not determine cache directory".to_string(),
                    "this host reports no cache directory; set HOME (or XDG_CACHE_HOME on Linux) and retry",
                )
            })?
            .join("ironshell")
            .join("agents");
        Self::with_cache_dir(registry_url, cache_dir)
    }

    /// Create a registry client over `cache_dir`, which is created if absent.
    /// `new` uses the user's cache; tests and hosts that keep the cache
    /// elsewhere use this.
    pub fn with_cache_dir(registry_url: Option<String>, cache_dir: PathBuf) -> Result<Self> {
        let registry_url =
            registry_url.unwrap_or_else(|| "https://registry.ironshell.dev".to_string());

        std::fs::create_dir_all(&cache_dir)?;

        let installed = Self::load_installed(&cache_dir)?;

        Ok(Self {
            registry_url,
            cache_dir,
            installed,
        })
    }

    /// Search for agents in the registry
    pub async fn search(&self, query: SearchQuery) -> Result<SearchResults> {
        let client = registry_client(30)?;

        let mut url = format!("{}/api/v1/agents/search", self.registry_url);
        let mut params = vec![];

        if let Some(q) = &query.query {
            params.push(format!("q={}", urlencoding::encode(q)));
        }
        if let Some(cat) = &query.category {
            params.push(format!("category={}", urlencoding::encode(cat)));
        }
        if let Some(kw) = &query.keyword {
            params.push(format!("keyword={}", urlencoding::encode(kw)));
        }
        if let Some(author) = &query.author {
            params.push(format!("author={}", urlencoding::encode(author)));
        }
        if let Some(sort) = &query.sort_by {
            params.push(format!("sort={}", serde_json::to_string(sort)?));
        }
        if let Some(page) = query.page {
            params.push(format!("page={}", page));
        }
        if let Some(per_page) = query.per_page {
            params.push(format!("per_page={}", per_page));
        }

        if !params.is_empty() {
            url = format!("{}?{}", url, params.join("&"));
        }

        let response = registry_get(&client, &url).await?;
        let results: SearchResults =
            crate::http_body::body_json_capped(response, crate::http_body::AI_BODY_MAX).await?;
        Ok(results)
    }

    /// Get agent details
    pub async fn get(&self, name: &str, version: Option<&str>) -> Result<PublishedAgent> {
        validate_package_name(name, "agent name")?;
        if let Some(v) = version {
            validate_package_name(v, "agent version")?;
        }
        let client = registry_client(30)?;

        let version_suffix = version
            .map(|v| format!("/{}", urlencoding::encode(v)))
            .unwrap_or_default();
        let url = format!(
            "{}/api/v1/agents/{}{}",
            self.registry_url,
            urlencoding::encode(name),
            version_suffix
        );

        let response = registry_get(&client, &url).await?;
        if !response.status().is_success() {
            return Err(registry_status_error(
                response.status(),
                format!("Agent not found: {}", name),
                "list the registry's agents with marketplace search, then use one of their names",
            ));
        }

        let agent: PublishedAgent =
            crate::http_body::body_json_capped(response, crate::http_body::AI_BODY_MAX).await?;
        Ok(agent)
    }

    /// Install an agent
    pub fn install<'a>(
        &'a mut self,
        name: &'a str,
        version: Option<&'a str>,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<InstalledAgent>> + Send + 'a>>
    {
        Box::pin(async move {
            // The name selects a cache directory, so it is checked before the
            // installed list, the registry, or the disk is touched.
            validate_package_name(name, "agent name")?;
            if let Some(v) = version {
                validate_package_name(v, "agent version")?;
            }

            // Check if already installed
            if let Some(installed) = self.installed.get(name) {
                if version.is_none() || version == Some(&installed.manifest.version) {
                    return Ok(installed.clone());
                }
            }

            // Fetch agent from registry
            let agent = self.get(name, version).await?;

            // The version in the registry's reply names a directory too.
            validate_package_name(&agent.manifest.version, "agent version from the registry")?;

            // Install dependencies first
            for dep in &agent.manifest.dependencies {
                self.install(&dep.name, Some(&dep.version)).await?;
            }

            // Download and install
            let client = registry_client(120)?;
            let url = format!(
                "{}/api/v1/agents/{}/{}/download",
                self.registry_url,
                urlencoding::encode(name),
                urlencoding::encode(&agent.manifest.version)
            );

            let response = registry_get(&client, &url).await?;
            if !response.status().is_success() {
                return Err(registry_status_error(
                    response.status(),
                    format!("Agent not found: {}", name),
                    "list the registry's agents with marketplace search, then use one of their names",
                ));
            }
            // A package is held whole to check its digest, so it is held to the
            // file limit every whole-file read uses.
            let max =
                usize::try_from(crate::security::max_file_size_bytes()?).unwrap_or(usize::MAX);
            let bytes = crate::http_body::body_bytes_capped(response, max).await?;

            // Verify the download against the registry's SHA-256 digest before
            // anything is written. Only a 64-hex SHA-256 passes: MD5 is
            // collision-broken, and a missing or other-shaped digest is refused.
            if !is_sha256_hex(&agent.checksum) {
                return Err(registry_coded(
                    crate::safety::ErrorCode::Io,
                    format!(
                        "Agent {} has {}; only a SHA-256 digest (64 hex digits) is accepted, so it was not installed",
                        name,
                        describe_digest(&agent.checksum)
                    ),
                    "the registry must publish a SHA-256 digest for this agent; nothing was written, so retry after the registry fixes it",
                ));
            }
            if !sha256_matches(&bytes, &agent.checksum)? {
                return Err(registry_coded(
                    crate::safety::ErrorCode::Io,
                    format!("Checksum mismatch for agent {}", name),
                    "the downloaded package does not match its published digest; retry the install, and report the agent if it keeps failing",
                ));
            }

            // Save to local cache
            let agent_dir = self.cache_dir.join(name).join(&agent.manifest.version);
            std::fs::create_dir_all(&agent_dir)?;

            let manifest_path = agent_dir.join("manifest.json");
            std::fs::write(
                &manifest_path,
                serde_json::to_string_pretty(&agent.manifest)?,
            )?;

            let agent_path = agent_dir.join("agent.ish");
            std::fs::write(&agent_path, &bytes)?;

            let installed = InstalledAgent {
                manifest: agent.manifest.clone(),
                installed_at: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)?
                    .as_secs(),
                path: agent_dir.clone(),
            };

            self.installed.insert(name.to_string(), installed.clone());
            self.save_installed()?;

            Ok(installed)
        })
    }

    /// Uninstall an agent
    pub fn uninstall(&mut self, name: &str) -> Result<()> {
        validate_package_name(name, "agent name")?;
        let Some(installed) = self.installed.get(name) else {
            return Err(registry_coded(
                crate::safety::ErrorCode::NotFound,
                format!("Agent not installed: {}", name),
                "list installed agents with marketplace list; nothing was removed",
            ));
        };
        // The record's path comes from installed.json, a file on disk, so it is
        // resolved and must lie inside the cache before anything is deleted.
        if let Some(dir) = self.cache_contained(&installed.path)? {
            std::fs::remove_dir_all(dir)?;
        }
        self.installed.remove(name);
        self.save_installed()?;
        Ok(())
    }

    /// Resolve an installed path and confirm it lies strictly inside the cache.
    /// `Ok(None)` when the path does not exist, so there is nothing to remove.
    /// A path that resolves outside the cache (through `..`, or a link) is
    /// refused with `E_BAD_STATE`, and nothing is touched.
    fn cache_contained(&self, path: &std::path::Path) -> Result<Option<PathBuf>> {
        let cache = std::fs::canonicalize(&self.cache_dir)?;
        let target = match std::fs::canonicalize(path) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        if target != cache && target.starts_with(&cache) {
            return Ok(Some(target));
        }
        Err(registry_coded(
            crate::safety::ErrorCode::BadState,
            format!(
                "installed path {} is outside the agent cache {}; refusing to touch it",
                path.display(),
                cache.display()
            ),
            "the installed list (installed.json in the agent cache) names a path outside the cache; nothing was removed, so correct or delete that entry by hand",
        ))
    }

    /// List installed agents
    pub fn list_installed(&self) -> Vec<&InstalledAgent> {
        self.installed.values().collect()
    }

    /// Publish an agent to the registry
    pub async fn publish(
        &self,
        manifest: &AgentManifest,
        agent_code: &str,
        api_key: &str,
    ) -> Result<PublishedAgent> {
        validate_package_name(&manifest.name, "agent name")?;
        validate_package_name(&manifest.version, "agent version")?;
        let client = registry_client(30)?;

        let url = format!("{}/api/v1/agents/publish", self.registry_url);

        let response = client
            .post(&url)
            .header("Authorization", format!("Bearer {}", api_key))
            .json(&serde_json::json!({
                "manifest": manifest,
                "code": agent_code,
            }))
            .send()
            .await?;

        if !response.status().is_success() {
            let error: serde_json::Value =
                crate::http_body::body_json_capped(response, crate::http_body::AI_BODY_MAX).await?;
            return Err(registry_coded(
                crate::safety::ErrorCode::Io,
                format!("Failed to publish: {}", error),
                "the registry rejected the publish; the message it sent says why",
            ));
        }

        let published: PublishedAgent =
            crate::http_body::body_json_capped(response, crate::http_body::AI_BODY_MAX).await?;
        Ok(published)
    }

    /// Load installed agents from disk
    fn load_installed(cache_dir: &PathBuf) -> Result<HashMap<String, InstalledAgent>> {
        let index_path = cache_dir.join("installed.json");
        if index_path.exists() {
            let content = std::fs::read_to_string(&index_path)?;
            Ok(serde_json::from_str(&content)?)
        } else {
            Ok(HashMap::new())
        }
    }

    /// Save installed agents index
    fn save_installed(&self) -> Result<()> {
        let index_path = self.cache_dir.join("installed.json");
        let content = serde_json::to_string_pretty(&self.installed)?;
        std::fs::write(&index_path, content)?;
        Ok(())
    }

    /// Get agent by name (from installed or fetch)
    pub fn get_installed(&self, name: &str) -> Option<&InstalledAgent> {
        self.installed.get(name)
    }

    /// Load agent code
    pub fn load_agent_code(&self, name: &str) -> Result<String> {
        let installed = self.get_installed(name).ok_or_else(|| {
            registry_coded(
                crate::safety::ErrorCode::NotFound,
                format!("Agent not installed: {}", name),
                "list installed agents with marketplace list, then use one of their names",
            )
        })?;

        let dir = self.cache_contained(&installed.path)?.ok_or_else(|| {
            registry_coded(
                crate::safety::ErrorCode::NotFound,
                format!("Agent {} has no files on disk", name),
                "reinstall it with marketplace install",
            )
        })?;
        Ok(std::fs::read_to_string(dir.join("agent.ish"))?)
    }
}

/// CLI commands for the marketplace
#[derive(Debug, Clone)]
pub enum MarketplaceCommand {
    Search {
        query: String,
    },
    Install {
        name: String,
        version: Option<String>,
    },
    Uninstall {
        name: String,
    },
    List,
    Info {
        name: String,
    },
    Publish {
        path: PathBuf,
    },
    Update {
        name: Option<String>,
    },
}

/// Process marketplace CLI commands
pub async fn process_command(command: MarketplaceCommand) -> Result<String> {
    let mut client = RegistryClient::new(None)?;

    match command {
        MarketplaceCommand::Search { query } => {
            let results = client
                .search(SearchQuery {
                    query: Some(query),
                    ..Default::default()
                })
                .await?;

            let mut output = format!("Found {} agents:\n\n", results.total);
            for agent in results.results {
                output.push_str(&format!(
                    "  {} v{} - {}\n    by {} | ⬇ {} | ⭐ {}\n\n",
                    agent.manifest.name,
                    agent.manifest.version,
                    agent.manifest.description,
                    agent.manifest.author.name,
                    agent.downloads,
                    agent.stars
                ));
            }
            Ok(output)
        }

        MarketplaceCommand::Install { name, version } => {
            let installed = client.install(&name, version.as_deref()).await?;
            Ok(format!(
                "✓ Installed {} v{}\n  Location: {}",
                installed.manifest.name,
                installed.manifest.version,
                installed.path.display()
            ))
        }

        MarketplaceCommand::Uninstall { name } => {
            client.uninstall(&name)?;
            Ok(format!("✓ Uninstalled {}", name))
        }

        MarketplaceCommand::List => {
            let installed = client.list_installed();
            if installed.is_empty() {
                return Ok("No agents installed.".to_string());
            }

            let mut output = format!("Installed agents ({}):\n\n", installed.len());
            for agent in installed {
                output.push_str(&format!(
                    "  {} v{}\n    {}\n\n",
                    agent.manifest.name, agent.manifest.version, agent.manifest.description
                ));
            }
            Ok(output)
        }

        MarketplaceCommand::Info { name } => {
            let agent = client.get(&name, None).await?;
            Ok(format!(
                "{}\n{}\n\nVersion: {}\nAuthor: {} <{}>\nLicense: {}\n\nCapabilities: {}\nKeywords: {}\n\nDownloads: {}\nStars: {}\nVerified: {}",
                agent.manifest.display_name,
                agent.manifest.description,
                agent.manifest.version,
                agent.manifest.author.name,
                agent.manifest.author.email.unwrap_or_default(),
                agent.manifest.license,
                agent.manifest.capabilities.join(", "),
                agent.manifest.keywords.join(", "),
                agent.downloads,
                agent.stars,
                if agent.verified { "✓" } else { "✗" }
            ))
        }

        MarketplaceCommand::Publish { path } => {
            let manifest_path = path.join("manifest.json");
            let code_path = path.join("agent.ish");

            if !manifest_path.exists() {
                return Err(registry_coded(
                    crate::safety::ErrorCode::NotFound,
                    format!("manifest.json not found in {}", path.display()),
                    "point the publish at a directory that holds manifest.json and agent.ish",
                ));
            }
            if !code_path.exists() {
                return Err(registry_coded(
                    crate::safety::ErrorCode::NotFound,
                    format!("agent.ish not found in {}", path.display()),
                    "point the publish at a directory that holds manifest.json and agent.ish",
                ));
            }

            let manifest: AgentManifest =
                serde_json::from_str(&std::fs::read_to_string(&manifest_path)?)?;
            let code = std::fs::read_to_string(&code_path)?;

            let api_key = std::env::var("IRONSHELL_API_KEY").map_err(|_| {
                registry_coded(
                    crate::safety::ErrorCode::BadState,
                    "IRONSHELL_API_KEY environment variable not set".to_string(),
                    "set IRONSHELL_API_KEY to your registry API key, then retry",
                )
            })?;

            let published = client.publish(&manifest, &code, &api_key).await?;
            Ok(format!(
                "✓ Published {} v{}\n  Registry: {}",
                published.manifest.name, published.manifest.version, client.registry_url
            ))
        }

        MarketplaceCommand::Update { name } => {
            let agents_to_update: Vec<_> = if let Some(name) = name {
                vec![name]
            } else {
                client.installed.keys().cloned().collect()
            };

            let mut output = String::new();
            for agent_name in agents_to_update {
                let latest = client.get(&agent_name, None).await?;
                let needs_update = client
                    .get_installed(&agent_name)
                    .map(|installed| latest.manifest.version != installed.manifest.version)
                    .unwrap_or(false);
                let old_version = client
                    .get_installed(&agent_name)
                    .map(|i| i.manifest.version.clone());

                if needs_update {
                    client.install(&agent_name, None).await?;
                    if let Some(old_ver) = old_version {
                        output.push_str(&format!(
                            "✓ Updated {} {} → {}\n",
                            agent_name, old_ver, latest.manifest.version
                        ));
                    }
                } else if client.get_installed(&agent_name).is_some() {
                    output.push_str(&format!("  {} is up to date\n", agent_name));
                }
            }

            if output.is_empty() {
                output = "All agents are up to date.".to_string();
            }
            Ok(output)
        }
    }
}

impl Default for SearchQuery {
    fn default() -> Self {
        Self {
            query: None,
            category: None,
            keyword: None,
            author: None,
            sort_by: Some(SortBy::Downloads),
            page: Some(1),
            per_page: Some(20),
        }
    }
}

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

    #[test]
    fn uninstalling_a_missing_agent_carries_not_found() {
        let mut client = RegistryClient {
            registry_url: String::new(),
            cache_dir: std::env::temp_dir(),
            installed: HashMap::new(),
        };
        let err = client
            .uninstall("no-such-agent")
            .expect_err("nothing is installed, so uninstall must refuse");
        let coded = err
            .downcast_ref::<crate::safety::SafetyError>()
            .expect("the refusal carries a SafetyError");
        assert!(matches!(coded.code, crate::safety::ErrorCode::NotFound));
        assert!(err.to_string().contains("no-such-agent"));
    }

    #[test]
    fn test_agent_manifest_serialization() {
        let manifest = AgentManifest {
            name: "nervosys/code-reviewer".to_string(),
            display_name: "Code Reviewer".to_string(),
            description: "Automated code review agent".to_string(),
            version: "1.0.0".to_string(),
            author: AuthorInfo {
                name: "Nervosys".to_string(),
                email: Some("contact@nervosys.ai".to_string()),
                url: Some("https://nervosys.ai".to_string()),
            },
            license: "MIT".to_string(),
            repository: Some("https://github.com/nervosys/code-reviewer".to_string()),
            homepage: None,
            keywords: vec!["code".to_string(), "review".to_string()],
            categories: vec!["development".to_string()],
            capabilities: vec!["code_analysis".to_string(), "suggestions".to_string()],
            ironshell_version: ">=0.2.0".to_string(),
            dependencies: vec![],
            agent: AgentDefinition {
                system_prompt: "You are a code reviewer...".to_string(),
                model: Some("gpt-4o-mini".to_string()),
                tools: vec!["read_file".to_string(), "grep".to_string()],
                tool_choice: None,
                temperature: Some(0.3),
                max_tokens: Some(4096),
            },
        };

        let json = serde_json::to_string(&manifest).unwrap();
        let parsed: AgentManifest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.name, manifest.name);
    }

    #[test]
    fn test_search_query_default() {
        let query = SearchQuery::default();
        assert!(query.query.is_none());
        assert_eq!(query.page, Some(1));
        assert_eq!(query.per_page, Some(20));
    }
}