返回 CodeWhale
provider_setup.rs
根目录 / crates / tui / src / tui / ui / provider_setup.rs
1 //! Provider-configuration support: runtime-preset file snapshots with
2 //! rollback, and the provider key verification seam
3 //! (docs/architecture/TUI_MODULARIZATION.md slice 8).
4
5 use super::*;
6
7 pub(crate) trait ProviderKeyVerifier {
8 fn verify<'a>(
9 &'a self,
10 provider: ProviderKind,
11 api_key: &'a str,
12 base_url: &'a str,
13 ) -> ProviderKeyVerification<'a>;
14 }
15
16 pub(crate) struct LiveProviderKeyVerifier;
17
18 impl ProviderKeyVerifier for LiveProviderKeyVerifier {
19 fn verify<'a>(
20 &'a self,
21 provider: ProviderKind,
22 api_key: &'a str,
23 base_url: &'a str,
24 ) -> ProviderKeyVerification<'a> {
25 Box::pin(codewhale_engine::client::verify_provider_api_key(
26 provider, api_key, base_url,
27 ))
28 }
29 }
30
31 /// Publish the `/models` roster a successful key probe already downloaded as
32 /// this exact route's live catalog (the #3385 cache and its provider-lake
33 /// partition). A route roster is authoritative for the ids it lists and for
34 /// its omissions, so the model pick that follows — and `/provider` and
35 /// `/model` — offer what this key can call today instead of bundled or
36 /// Models.dev rows the provider has retired. The probe scopes rows to the
37 /// provider kind; ownership here is the exact route identity, so a named or
38 /// regional table keeps its own partition.
39 ///
40 /// The endpoint decides availability; the catalog still decides which listed
41 /// ids are chat models. Ollama publishes only through its capability-aware
42 /// native refresh. A first roster for another route keeps only the ids the
43 /// catalog already offers there (case-insensitively, in the provider's own
44 /// spelling), so an OpenAI-style `/models` that also lists embedding, speech
45 /// and image models does not flood setup. When the catalog knows none of the
46 /// ids, or the route already has a roster, the probe's roster is kept whole.
47 ///
48 /// Does not: list a served chat model the catalog does not know yet (until
49 /// the catalog or `codewhale models --update` lists it — the same as before
50 /// this probe was read), refresh on its own schedule, or remove the roster if
51 /// the user abandons setup. The rows are secret-free facts about this
52 /// endpoint; account-scoped endpoints are re-fenced by
53 /// `begin_scoped_refresh`.
54 pub(crate) fn publish_verified_roster(
55 config: &Config,
56 identity: &codewhale_runtime::config::ProviderIdentity,
57 base_url: &str,
58 roster: Option<codewhale_config::catalog::ProviderCatalogDelta>,
59 ) {
60 if identity.provider == ProviderKind::Ollama {
61 return;
62 }
63 let Some(mut roster) = roster else {
64 return;
65 };
66 let Ok(ticket) =
67 codewhale_engine::provider_catalog_live::begin_scoped_refresh(config, identity, base_url)
68 else {
69 return;
70 };
71 let key = identity.key.as_str();
72 let has_route_roster = codewhale_engine::provider_catalog_live::cached_entry_for_route(
73 identity.provider,
74 key,
75 base_url,
76 )
77 .ok()
78 .flatten()
79 .is_some_and(|entry| entry.fetched_at > 0);
80 if !has_route_roster {
81 // Without a route roster this is the catalog view: bundled, Models.dev
82 // and signed rows for this provider.
83 let offered = codewhale_engine::provider_lake::catalog_models_for_route(
84 identity.provider,
85 key,
86 base_url,
87 );
88 let chat: Vec<_> = roster
89 .offerings
90 .iter()
91 .filter(|row| {
92 offered
93 .iter()
94 .any(|id| id.eq_ignore_ascii_case(&row.wire_model_id))
95 })
96 .cloned()
97 .collect();
98 if !chat.is_empty() {
99 roster.offerings = chat;
100 }
101 }
102 let owner = identity.key.to_string();
103 for row in &mut roster.offerings {
104 row.provider.clone_from(&owner);
105 }
106 roster.provider = owner;
107 // `None` means a newer refresh for this route superseded the probe; its
108 // rows win, which is the failure-preserving outcome we want.
109 let _ = codewhale_engine::provider_catalog_live::record_success_if_current(&ticket, roster);
110 }
111
112 pub(crate) struct RuntimePresetFileSnapshot {
113 pub(crate) path: PathBuf,
114 pub(crate) contents: Option<Vec<u8>>,
115 }
116
117 impl RuntimePresetFileSnapshot {
118 pub(crate) fn capture(path: PathBuf) -> Result<Self> {
119 let contents = match std::fs::read(&path) {
120 Ok(contents) => Some(contents),
121 Err(error) if error.kind() == io::ErrorKind::NotFound => None,
122 Err(error) => {
123 return Err(error)
124 .with_context(|| format!("failed to snapshot {}", path.display()));
125 }
126 };
127 Ok(Self { path, contents })
128 }
129
130 fn restore(&self) -> Result<()> {
131 match &self.contents {
132 Some(contents) => codewhale_util::utils::write_atomic(&self.path, contents)
133 .with_context(|| format!("failed to restore {}", self.path.display())),
134 None => match std::fs::remove_file(&self.path) {
135 Ok(()) => Ok(()),
136 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
137 Err(error) => {
138 Err(error).with_context(|| format!("failed to remove {}", self.path.display()))
139 }
140 },
141 }
142 }
143 }
144
145 pub(crate) fn runtime_preset_error_with_rollback(
146 error: anyhow::Error,
147 snapshots: &[&RuntimePresetFileSnapshot],
148 ) -> anyhow::Error {
149 let rollback_errors = snapshots
150 .iter()
151 .filter_map(|snapshot| snapshot.restore().err())
152 .map(|error| format!("{error:#}"))
153 .collect::<Vec<_>>();
154 if rollback_errors.is_empty() {
155 error
156 } else {
157 anyhow::anyhow!(
158 "{error:#}; runtime preset rollback also failed: {}",
159 rollback_errors.join("; ")
160 )
161 }
162 }
163
163 lines RUST