Skip to main content

ai6_account_api_key/
lib.rs

1//! AI6's account provider for the API-key kinds: Anthropic API keys, gateway bearer tokens and OpenAI API keys.
2
3#![doc = include_str!("../README.md")]
4#![forbid(unsafe_code)]
5
6ai6::guatiao::providers!(ApiKeyAccounts);
7
8use std::collections::BTreeMap;
9use std::ffi::OsString;
10use std::sync::{Arc, Mutex, PoisonError};
11use std::time::Duration;
12
13use ai6::guatiao::library::{Object, ProviderError};
14use ai6::guatiao::{FromValue, Provider, Schema, Status, ToValue};
15use coqui_acp_api::{
16    AccountGrant, AccountKeeper, AccountKindInfo, AccountModelsQuery, AccountOffer,
17    AccountProvider, AccountProviderInfo, AccountRef, AccountUsage, AccountUsageQuery,
18    AccountWatch, LoginOutcome, LoginPrompter, LoginRequest, ModelInfo, ModelListing,
19    ProcessSpawner, RenewReport, RenewRequest, SignedInCheck, SignedInQuery, UnknownKind,
20    WatchRequest,
21};
22use coqui_acp_claude::account_usage as claude_usage;
23use coqui_acp_claude::accounts as claude;
24use coqui_acp_codex::account_usage as codex_usage;
25use coqui_acp_codex::accounts as codex;
26use coqui_acp_harness::ThroughSpawner;
27use coqui_acp_harness::account::{Files, bad};
28use coqui_acp_harness::provider::provides_of;
29
30/// The id the provider is registered under.
31pub const PROVIDER_ID: &str = "api_key_accounts";
32
33/// The kinds this provider serves, with the ids Claude Code's and Codex's account providers gave them.
34pub const KINDS: [&str; 3] = [claude::API_KEY, claude::AUTH_TOKEN, codex::API_KEY];
35
36/// What the provider runs and reads for the Claude Code kinds (`anthropic-api-key`, `anthropic-auth-token`).
37#[derive(ToValue, FromValue, Schema, Debug, Clone)]
38#[map(crate = ::ai6::guatiao)]
39pub struct ClaudeSide {
40    /// The Claude Code program that lists an account's models: a path, or a name looked up on the `PATH` where the
41    /// spawner runs it. Default `claude`.
42    #[map(default = "claude".to_owned())]
43    pub executable: String,
44    /// The address a key's rate limits are read from when the account names no `base_url`, in place of
45    /// `https://api.anthropic.com`. Absent, Anthropic's.
46    pub usage_endpoint: Option<String>,
47    /// How the session that lists models reads Claude Code's output, waits for it and ends it.
48    #[map(flatten)]
49    pub session: coqui_acp_claude::SessionSettings,
50}
51
52impl Default for ClaudeSide {
53    fn default() -> Self {
54        Self {
55            executable: "claude".to_owned(),
56            usage_endpoint: None,
57            session: coqui_acp_claude::SessionSettings::default(),
58        }
59    }
60}
61
62/// What the provider runs and reads for the Codex kind (`codex-api-key`).
63#[derive(ToValue, FromValue, Schema, Debug, Clone)]
64#[map(crate = ::ai6::guatiao)]
65pub struct CodexSide {
66    /// The Codex program that saves the key and lists the account's models: a path, or a name looked up on the
67    /// `PATH` where the spawner runs it. Default `codex`.
68    #[map(default = "codex".to_owned())]
69    pub executable: String,
70    /// The address a key's rate limits are read from when the account names no `openai_base_url`, in place of
71    /// `https://api.openai.com/v1`. Absent, OpenAI's.
72    pub usage_endpoint: Option<String>,
73    /// How the sessions that list models read the app server's output, wait for it and end it.
74    #[map(flatten)]
75    pub session: coqui_acp_codex::SessionSettings,
76}
77
78impl Default for CodexSide {
79    fn default() -> Self {
80        Self {
81            executable: "codex".to_owned(),
82            usage_endpoint: None,
83            session: coqui_acp_codex::SessionSettings::default(),
84        }
85    }
86}
87
88/// One instance's settings; every one has a default.
89#[derive(ToValue, FromValue, Schema, Debug, Clone)]
90#[map(crate = ::ai6::guatiao, deny_unknown_fields)]
91pub struct ApiKeySettings {
92    /// The Claude Code kinds.
93    #[map(default = ClaudeSide::default())]
94    pub claude: ClaudeSide,
95    /// The Codex kind.
96    #[map(default = CodexSide::default())]
97    pub codex: CodexSide,
98    /// The longest, in milliseconds, the command that saves a Codex key (`codex login`) may take; 0 ends it at once.
99    /// Default 60000.
100    #[map(default = 60_000)]
101    pub command_timeout_ms: u64,
102    /// The longest, in milliseconds, a rate-limits read may take in all. Default 10000.
103    #[map(default = 10_000)]
104    pub usage_timeout_ms: u64,
105}
106
107impl Default for ApiKeySettings {
108    fn default() -> Self {
109        Self {
110            claude: ClaudeSide::default(),
111            codex: CodexSide::default(),
112            command_timeout_ms: 60_000,
113            usage_timeout_ms: 10_000,
114        }
115    }
116}
117
118/// The harness a kind belongs to.
119#[derive(Clone, Copy, PartialEq, Eq)]
120enum Family {
121    Claude,
122    Codex,
123}
124
125fn family(kind: &str) -> Option<Family> {
126    match kind {
127        claude::API_KEY | claude::AUTH_TOKEN => Some(Family::Claude),
128        codex::API_KEY => Some(Family::Codex),
129        _ => None,
130    }
131}
132
133/// The kinds, as the harnesses' own catalogs describe them: the same entries (settings schema, endpoints, standards
134/// provided) their account providers listed before they dropped the keys.
135fn kinds() -> Vec<AccountKindInfo> {
136    let anthropic = claude::catalog();
137    let openai = codex::catalog();
138    [
139        (&anthropic, claude::API_KEY),
140        (&anthropic, claude::AUTH_TOKEN),
141        (&openai, codex::API_KEY),
142    ]
143    .into_iter()
144    .filter_map(|(catalog, id)| catalog.kind(id).cloned())
145    .collect()
146}
147
148/// What the provider offers: its three kinds, no way to sign in, usage for each, and no automatic `local` account.
149#[must_use]
150pub fn offer() -> AccountOffer {
151    let mut offer = AccountOffer::new();
152    offer.kinds = kinds();
153    offer.usage = KINDS.iter().map(|id| (*id).to_owned()).collect();
154    offer
155}
156
157/// The harness a grant's kind belongs to: `BAD_VALUE` for an id that is not one and for any kind this provider does
158/// not serve, the automatic `local` account included.
159fn own(grant: &AccountGrant) -> Result<Family, ProviderError> {
160    grant.check_id()?;
161    family(&grant.kind).ok_or_else(|| bad("this provider keeps no account of that kind"))
162}
163
164fn unsupported(why: &str) -> ProviderError {
165    ProviderError::new(Status::GUATIAO_ERR_UNSUPPORTED, why)
166}
167
168/// API-key accounts as a provider of `account_provider`, under the id `api_key_accounts`.
169///
170/// A key is handed over in the grant's sealed credentials for each call and goes nowhere but to the account's own
171/// endpoint (a rate-limits read) or to the harness's environment or `login` standard input (a models listing).
172#[derive(Provider, Debug)]
173#[provider(
174    AccountProvider,
175    id = "api_key_accounts",
176    name = "API key accounts",
177    config = ApiKeySettings,
178    new = ApiKeyAccounts::unconfigured,
179    crate = ::ai6::guatiao
180)]
181pub struct ApiKeyAccounts {
182    settings: ApiKeySettings,
183    /// What each account's usage last read as, and the revision it was told at.
184    reports: Mutex<BTreeMap<String, (AccountUsage, u64)>>,
185}
186
187impl From<ApiKeySettings> for ApiKeyAccounts {
188    fn from(settings: ApiKeySettings) -> Self {
189        Self::new(settings)
190    }
191}
192
193impl ApiKeyAccounts {
194    /// A provider configured as `settings` say.
195    #[must_use]
196    pub fn new(settings: ApiKeySettings) -> Self {
197        Self {
198            settings,
199            reports: Mutex::new(BTreeMap::new()),
200        }
201    }
202
203    fn unconfigured() -> Self {
204        Self::new(ApiKeySettings::default())
205    }
206
207    fn timeout(&self) -> Duration {
208        Duration::from_millis(self.settings.usage_timeout_ms)
209    }
210
211    /// `usage` with the revision it is told at: one more than the last, when what it reads has changed.
212    fn revised(&self, mut usage: AccountUsage) -> AccountUsage {
213        let Some(id) = usage.account.clone() else {
214            return usage;
215        };
216        usage.revision = 0;
217        let mut reports = self.reports.lock().unwrap_or_else(PoisonError::into_inner);
218        let revision = match reports.get(&id) {
219            Some((last, revision)) if *last == usage => *revision,
220            Some((_, revision)) => revision + 1,
221            None => 1,
222        };
223        reports.insert(id, (usage.clone(), revision));
224        usage.revision = revision;
225        usage
226    }
227
228    fn models_of_claude(
229        &self,
230        query: &AccountModelsQuery,
231        spawner: Arc<Object<dyn ProcessSpawner>>,
232    ) -> Result<ModelListing, ProviderError> {
233        let mut launch = coqui_acp_claude::ClaudeLaunch::new(".");
234        launch.executable = OsString::from(&self.settings.claude.executable);
235        for (name, value) in query.environment.expose().iter() {
236            launch.env.insert(name.into(), value.into());
237        }
238        let files = Files::new(Arc::clone(&spawner));
239        // A key sets one variable: no file is placed, so there is nothing to hold or to tell a keeper.
240        drop(claude::apply(&query.account, &mut launch, &files)?);
241        drop(files);
242        Ok(claude_listing(
243            &launch,
244            &ThroughSpawner::shared(spawner),
245            self.settings.claude.session.settings(),
246        ))
247    }
248
249    fn models_of_codex(
250        &self,
251        query: &AccountModelsQuery,
252        spawner: Arc<Object<dyn ProcessSpawner>>,
253    ) -> Result<ModelListing, ProviderError> {
254        let mut launch = coqui_acp_codex::CodexLaunch::new(".");
255        launch.executable = OsString::from(&self.settings.codex.executable);
256        for (name, value) in query.environment.expose().iter() {
257            launch.env.insert(name.into(), value.into());
258        }
259        let files = Files::new(Arc::clone(&spawner));
260        // The key is saved in the account's home by `codex login --with-api-key`, on its standard input.
261        let options = codex::ApplyOptions::new()
262            .timeout(Duration::from_millis(self.settings.command_timeout_ms));
263        drop(codex::apply_with(
264            &query.account,
265            &mut launch,
266            &files,
267            &options,
268        )?);
269        drop(files);
270        Ok(codex_listing(
271            &launch,
272            &ThroughSpawner::shared(spawner),
273            self.settings.codex.session.settings(),
274        ))
275    }
276}
277
278impl AccountProvider for ApiKeyAccounts {
279    fn describe(&self) -> Result<AccountProviderInfo, ProviderError> {
280        let mut info = AccountProviderInfo::new("API key accounts");
281        info.description = "Keeps Anthropic API keys, gateway bearer tokens and OpenAI API keys: reads each key's rate limits and lists the models it may use.".into();
282        Ok(info)
283    }
284
285    fn offers(&self) -> Result<AccountOffer, ProviderError> {
286        Ok(offer())
287    }
288
289    fn provides(&self, account: AccountRef) -> Result<Vec<String>, ProviderError> {
290        provides_of(&offer(), &account, &[])
291    }
292
293    fn login(
294        &self,
295        request: LoginRequest,
296        spawner: Object<dyn ProcessSpawner>,
297        prompter: Object<dyn LoginPrompter>,
298    ) -> Result<LoginOutcome, ProviderError> {
299        drop((request, spawner, prompter));
300        Err(unsupported(
301            "this provider signs no one in: a key is stored as a secret and handed over with the account",
302        ))
303    }
304
305    fn renew(
306        &self,
307        request: RenewRequest,
308        spawner: Object<dyn ProcessSpawner>,
309    ) -> Result<RenewReport, ProviderError> {
310        drop(spawner);
311        own(&request.account)?;
312        Err(unsupported(
313            "a key or token does not expire in a way that can be renewed, so there is nothing to do",
314        ))
315    }
316
317    fn watch(
318        &self,
319        request: WatchRequest,
320        spawner: Object<dyn ProcessSpawner>,
321        keeper: Object<dyn AccountKeeper>,
322    ) -> Result<Object<dyn AccountWatch>, ProviderError> {
323        drop((spawner, keeper));
324        own(&request.account)?;
325        Err(unsupported(
326            "this kind of account keeps its credential in no file that a program renews, so there is nothing to watch",
327        ))
328    }
329
330    fn signed_in(&self, query: SignedInQuery) -> Result<SignedInCheck, ProviderError> {
331        drop(query);
332        Err(unsupported(
333            "this provider offers no account of the program's own login",
334        ))
335    }
336
337    fn usage(
338        &self,
339        query: AccountUsageQuery,
340        spawner: Object<dyn ProcessSpawner>,
341        keeper: Object<dyn AccountKeeper>,
342    ) -> Result<AccountUsage, ProviderError> {
343        // The rate limits are read over the network with the key: no program is started and no file read.
344        drop((spawner, keeper));
345        let report = match own(&query.account)? {
346            Family::Claude => {
347                let mut options = claude_usage::ReadOptions::new().timeout(self.timeout());
348                if let Some(endpoint) = &self.settings.claude.usage_endpoint {
349                    options = options.endpoint(endpoint.clone());
350                }
351                claude_usage::read_limits(&query.account, &options)?
352            }
353            Family::Codex => {
354                let mut options = codex_usage::ReadOptions::new().timeout(self.timeout());
355                if let Some(endpoint) = &self.settings.codex.usage_endpoint {
356                    options = options.endpoint(endpoint.clone());
357                }
358                codex_usage::read_limits(&query.account, &options)?
359            }
360        };
361        Ok(self.revised(AccountUsage::from_report(report)))
362    }
363
364    fn models(
365        &self,
366        query: AccountModelsQuery,
367        spawner: Object<dyn ProcessSpawner>,
368        keeper: Object<dyn AccountKeeper>,
369    ) -> Result<ModelListing, ProviderError> {
370        // A key keeps no file a program renews, so no keeper is ever told anything.
371        drop(keeper);
372        let family = own(&query.account)?;
373        let spawner = Arc::new(spawner);
374        match family {
375            Family::Claude => self.models_of_claude(&query, spawner),
376            Family::Codex => self.models_of_codex(&query, spawner),
377        }
378    }
379}
380
381/// The models Claude Code lists once started on `launch`, with no turn.
382fn claude_listing(
383    launch: &coqui_acp_claude::ClaudeLaunch,
384    spawn: &ThroughSpawner,
385    settings: coqui_acp_claude::ClaudeSettings,
386) -> ModelListing {
387    match coqui_acp_claude::ClaudeSession::start(launch, spawn, settings, |_| true) {
388        Ok(session) => {
389            let signed_out = session.signed_out();
390            let listing = session.models().map_or_else(
391                || {
392                    if signed_out {
393                        ModelListing::unknown(
394                            "nobody is signed in to Claude Code, which lists its models once someone is",
395                        )
396                        .signed_out()
397                    } else {
398                        ModelListing::unavailable(UnknownKind::Failed, "Claude Code listed no model")
399                    }
400                },
401                |models| {
402                    ModelListing::of(
403                        models
404                            .into_iter()
405                            .map(|model| {
406                                let mut info = ModelInfo::new(model.id.clone());
407                                info.name = Some(model.label());
408                                info.description = model.description;
409                                info.resolved = model.resolved;
410                                info.version = model.version;
411                                info.efforts = model.efforts;
412                                info.is_default = model.id == "default";
413                                info
414                            })
415                            .collect(),
416                    )
417                },
418            );
419            session.close();
420            if signed_out && listing.known {
421                listing.signed_out()
422            } else {
423                listing
424            }
425        }
426        Err(error) => ModelListing::unavailable(
427            match &error {
428                coqui_acp_claude::Error::Spawn(why)
429                    if why.kind() == std::io::ErrorKind::NotFound =>
430                {
431                    UnknownKind::NotInstalled
432                }
433                _ => UnknownKind::Failed,
434            },
435            format!("Claude Code could not be asked: {error}"),
436        ),
437    }
438}
439
440/// The models Codex lists once started on `launch`, with no thread.
441fn codex_listing(
442    launch: &coqui_acp_codex::CodexLaunch,
443    spawn: &ThroughSpawner,
444    settings: coqui_acp_codex::CodexSettings,
445) -> ModelListing {
446    match coqui_acp_codex::CodexSession::read_models(launch, spawn, settings) {
447        Ok(coqui_acp_codex::ModelRead {
448            models: Some(models),
449            signed_out,
450            ..
451        }) => {
452            let listing = ModelListing::of(
453                models
454                    .into_iter()
455                    .map(|model| {
456                        let mut info = ModelInfo::new(model.id);
457                        info.name = Some(model.name);
458                        info.description = model.description;
459                        info.efforts = model.efforts;
460                        info.default_effort = model.default_effort;
461                        info.is_default = model.is_default;
462                        info
463                    })
464                    .collect(),
465            );
466            if signed_out {
467                listing.signed_out()
468            } else {
469                listing
470            }
471        }
472        Ok(_) => ModelListing::unknown("Codex listed no model"),
473        Err(error) => ModelListing::unavailable(
474            match &error {
475                coqui_acp_codex::Error::Spawn(why)
476                    if why.kind() == std::io::ErrorKind::NotFound =>
477                {
478                    UnknownKind::NotInstalled
479                }
480                _ => UnknownKind::Failed,
481            },
482            format!("Codex could not be asked: {error}"),
483        ),
484    }
485}