systemprompt_cli/commands/admin/config/
catalog.rs1use std::collections::HashMap;
11
12use anyhow::Result;
13use clap::{Args, Subcommand};
14use systemprompt_config::{ModelSpec, ProfileBootstrap, ProviderCatalogService, ProviderSpec};
15use systemprompt_identifiers::{ModelId, ProviderId, SecretName};
16use systemprompt_models::profile::{ApiSurface, WireProtocol};
17
18use super::profile_io::{load_profile, save_profile};
19use super::types::ConfigMutationOutput;
20use crate::CliConfig;
21use crate::shared::{CommandOutput, render_result};
22use systemprompt_models::artifacts::ListItem;
23
24#[derive(Debug, Subcommand)]
25pub enum CatalogCommands {
26 #[command(subcommand, about = "Manage registry providers")]
27 Provider(ProviderCommands),
28
29 #[command(subcommand, about = "Manage the models a provider serves")]
30 Model(ModelCommands),
31}
32
33#[derive(Debug, Subcommand)]
34pub enum ProviderCommands {
35 #[command(about = "List declared providers")]
36 List,
37 #[command(about = "Add or replace a provider")]
38 Add(ProviderAddArgs),
39 #[command(about = "Remove a provider by name")]
40 Remove {
41 #[arg(long)]
42 name: String,
43 },
44}
45
46#[derive(Debug, Subcommand)]
47pub enum ModelCommands {
48 #[command(about = "Add or replace a model under a provider")]
49 Add(ModelAddArgs),
50 #[command(about = "Remove a model by id from a provider")]
51 Remove {
52 #[arg(long, help = "Provider that serves the model")]
53 provider: String,
54 #[arg(long)]
55 id: String,
56 },
57}
58
59#[derive(Debug, Clone, Args)]
60pub struct ProviderAddArgs {
61 #[arg(long)]
62 pub name: String,
63 #[arg(
64 long,
65 help = "Wire codec: anthropic | openai-chat | openai-responses | gemini"
66 )]
67 pub wire: String,
68 #[arg(
69 long,
70 help = "Client API surface: anthropic | openai | gemini | backend"
71 )]
72 pub surface: String,
73 #[arg(long)]
74 pub endpoint: String,
75 #[arg(long)]
76 pub api_key_secret: String,
77 #[arg(long = "header", help = "Extra header as KEY=VALUE (repeatable)")]
78 pub headers: Vec<String>,
79}
80
81#[derive(Debug, Clone, Args)]
82pub struct ModelAddArgs {
83 #[arg(long, help = "Provider that serves this model")]
84 pub provider: String,
85 #[arg(long)]
86 pub id: String,
87 #[arg(long = "alias", help = "Model alias (repeatable)")]
88 pub aliases: Vec<String>,
89 #[arg(
90 long,
91 help = "Vendor-side model name to forward upstream (defaults to id)"
92 )]
93 pub upstream_model: Option<String>,
94}
95
96pub async fn execute(command: &CatalogCommands, config: &CliConfig) -> Result<()> {
97 if matches!(command, CatalogCommands::Provider(ProviderCommands::List)) {
98 return list_providers(config);
99 }
100
101 let profile_path = ProfileBootstrap::get_path()?;
102 let mut profile = load_profile(profile_path)?;
103
104 let message = match command {
105 CatalogCommands::Provider(ProviderCommands::List) => unreachable!("handled above"),
106 CatalogCommands::Provider(ProviderCommands::Add(args)) => {
107 ProviderCatalogService::upsert_provider(&mut profile.providers, provider_spec(args)?);
108 format!(
109 "Provider {} (wire {}, surface {}) added",
110 args.name, args.wire, args.surface
111 )
112 },
113 CatalogCommands::Provider(ProviderCommands::Remove { name }) => {
114 ProviderCatalogService::remove_provider(
115 &mut profile.providers,
116 &ProviderId::new(name),
117 )?;
118 format!("Provider {} removed", name)
119 },
120 CatalogCommands::Model(ModelCommands::Add(args)) => {
121 ProviderCatalogService::upsert_model(&mut profile.providers, model_spec(args))?;
122 format!("Model {} added to {}", args.id, args.provider)
123 },
124 CatalogCommands::Model(ModelCommands::Remove { provider, id }) => {
125 ProviderCatalogService::remove_model(
126 &mut profile.providers,
127 &ProviderId::new(provider),
128 &ModelId::new(id),
129 )?;
130 format!("Model {} removed from {}", id, provider)
131 },
132 };
133
134 save_profile(&profile, profile_path)?;
135 let outcome = super::reconcile::reconcile_authz(&profile, profile_path).await;
136
137 render_result(
138 &CommandOutput::card_value(
139 "Provider Registry Updated",
140 &ConfigMutationOutput {
141 field: "providers".to_owned(),
142 message: super::reconcile::append_reconcile_notice(message, &outcome),
143 },
144 ),
145 config,
146 );
147 Ok(())
148}
149
150fn parse_wire(raw: &str) -> Result<WireProtocol> {
151 WireProtocol::from_tag(raw).ok_or_else(|| {
152 anyhow::anyhow!(
153 "invalid --wire '{raw}'; expected one of: anthropic, openai-chat, \
154 openai-responses, gemini"
155 )
156 })
157}
158
159fn parse_surface(raw: &str) -> Result<ApiSurface> {
160 ApiSurface::from_tag(raw).ok_or_else(|| {
161 anyhow::anyhow!(
162 "invalid --surface '{raw}'; expected one of: anthropic, openai, gemini, backend"
163 )
164 })
165}
166
167fn parse_headers(raw: &[String]) -> Result<HashMap<String, String>> {
168 raw.iter()
169 .map(|h| {
170 h.split_once('=')
171 .map(|(k, v)| (k.to_owned(), v.to_owned()))
172 .ok_or_else(|| anyhow::anyhow!("invalid --header '{h}'; expected KEY=VALUE"))
173 })
174 .collect()
175}
176
177fn provider_spec(args: &ProviderAddArgs) -> Result<ProviderSpec> {
178 Ok(ProviderSpec {
179 name: ProviderId::new(&args.name),
180 wire: parse_wire(&args.wire)?,
181 surface: parse_surface(&args.surface)?,
182 endpoint: args.endpoint.clone(),
183 api_key_secret: SecretName::new(&args.api_key_secret),
184 extra_headers: parse_headers(&args.headers)?,
185 })
186}
187
188fn model_spec(args: &ModelAddArgs) -> ModelSpec {
189 ModelSpec {
190 provider: ProviderId::new(&args.provider),
191 id: ModelId::new(&args.id),
192 aliases: args.aliases.iter().map(ModelId::new).collect(),
193 upstream_model: args.upstream_model.clone(),
194 }
195}
196
197fn list_providers(config: &CliConfig) -> Result<()> {
198 let profile_path = ProfileBootstrap::get_path()?;
199 let profile = load_profile(profile_path)?;
200 let items: Vec<ListItem> = profile
201 .providers
202 .providers
203 .iter()
204 .map(|p| {
205 let models: Vec<&str> = p.models.iter().map(|m| m.id.as_str()).collect();
206 let row = format!(
207 "{} [wire {} / surface {}] {} ({} models: {})",
208 p.name.as_str(),
209 p.wire,
210 p.surface,
211 p.endpoint,
212 models.len(),
213 models.join(", ")
214 );
215 ListItem::new(row, String::new(), String::new())
216 })
217 .collect();
218 render_result(
219 &CommandOutput::list(items).with_title("Provider Registry"),
220 config,
221 );
222 Ok(())
223}