cpa-server 0.4.1

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
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
//! The plugin host in the server (Go `sdk/cliproxy/service_plugins.go`,
//! `internal/api/server_management.go`): one [`cpa_plugin::Host`] per runtime, synced
//! with every published config by a single worker so the latest config always wins.

use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock, Weak};

use axum::body::{Body, Bytes};
use axum::extract::Request;
use axum::http::HeaderMap;
use cpa_common::gostr::GoStr;
use cpa_core::config::Config;
use cpa_core::exec::Caller;
use tokio::sync::watch;

use crate::Runtime;

pub(crate) mod execution;
pub(crate) mod interceptors;
pub(crate) mod model_callbacks;
pub(crate) mod refresh;

/// The host plus the config it should converge on.
pub struct PluginRuntime {
    host: cpa_plugin::Host,
    /// The latest published config and its publish sequence number.
    latest: watch::Sender<Option<(u64, Arc<Config>)>>,
    /// The sequence number of the last config the worker applied.
    applied: watch::Sender<u64>,
    access: RwLock<Arc<AccessRegistry>>,
    /// Go's executor table entries owned by plugins: provider to the registered executor.
    executors: RwLock<HashMap<String, cpa_plugin::executor::Adapter>>,
}

impl Default for PluginRuntime {
    fn default() -> Self {
        Self::with_host(cpa_plugin::Host::new())
    }
}

impl PluginRuntime {
    /// Wraps a host that is already running (the binary's, which loaded plugins for
    /// their command-line flags before the config was read).
    pub(crate) fn with_host(host: cpa_plugin::Host) -> Self {
        Self {
            host,
            latest: watch::Sender::new(None),
            applied: watch::Sender::new(0),
            access: RwLock::default(),
            executors: RwLock::default(),
        }
    }

    pub fn host(&self) -> &cpa_plugin::Host {
        &self.host
    }

    /// The registered plugin executor serving `credential`, if any. Go binds a
    /// credential's executor as the credential arrives (`registerExecutorForAuth`): a
    /// credential [`binds_native`] replaces a plugin executor registered for its
    /// provider at once, while the table here changes only on a plugin sync. So the
    /// table is consulted only for credentials that would leave a plugin executor bound.
    pub(crate) fn executor(
        &self,
        credential: &cpa_core::credential::Credential,
        cfg: &Config,
    ) -> Option<cpa_plugin::executor::Adapter> {
        let adapter = {
            let executors = self.executors.read().unwrap_or_else(std::sync::PoisonError::into_inner);
            executors.get(&credential.provider.trim().go_lower()).cloned()?
        };
        let compat_names = cpa_core::config::credentials::openai_compat_names(cfg);
        (!binds_native(credential, &compat_names)).then_some(adapter)
    }

    /// Whether a plugin executor is registered for `provider`.
    pub(crate) fn has_executor(&self, provider: &str) -> bool {
        let executors = self.executors.read().unwrap_or_else(std::sync::PoisonError::into_inner);
        executors.contains_key(&provider.trim().go_lower())
    }

    /// Records a published config; the worker started by [`start`] applies it.
    pub(crate) fn config_published(&self, cfg: Arc<Config>) {
        self.latest.send_modify(|latest| {
            let seq = latest.as_ref().map_or(1, |(seq, _)| seq + 1);
            *latest = Some((seq, cfg));
        });
    }

    fn published_seq(&self) -> u64 {
        self.latest.borrow().as_ref().map_or(0, |(seq, _)| *seq)
    }
}

/// Waits until the plugin worker started by [`start`] has applied every config published
/// so far (Go applies plugin config synchronously while it applies a config).
pub async fn applied(rt: &Runtime) {
    let seq = rt.plugin_runtime().published_seq();
    let _ = rt
        .plugin_runtime()
        .applied
        .subscribe()
        .wait_for(|applied| *applied >= seq)
        .await;
}

/// Go's startup and reload sequence (`syncPluginRuntimeConfigForConfig` and
/// `RefreshPluginManagementRoutes`): apply the config, register the client-key and
/// plugin frontend auth providers, then rebuild the plugin management routes around the
/// built-in ones, then register plugin models and executors (`syncPluginModelRuntime`).
/// Go runs that last step only once its listener is up; here it completes before
/// serving.
pub async fn sync(rt: &Runtime, cfg: Arc<Config>) {
    let host = rt.plugins();
    host.apply_config(cfg.clone()).await;
    // Go `configaccess.Register` (reload: `ApplyAccessProviders`) runs before the plugin
    // providers register.
    let (providers, exclusive) = host.frontend_auth_providers().await;
    rt.plugin_runtime()
        .register_access(!cfg.api_keys.is_empty(), providers, exclusive);
    host.register_management_routes(&reserved_management_routes()).await;
    // Go `sdktranslator.SetPluginHooks(s.pluginHost)`: the hooks are skipped while no
    // plugin offers one.
    cpa_translate::hooks::set_plugin_hooks(Some(host.translator_hooks()));
    // Go `registerPluginAuthParser`: auth files go to plugin auth providers first; the
    // next auth-folder reload picks up what a newly loaded plugin parses.
    cpa_core::config::credentials::set_plugin_auth_parser(Some(host.auth_parser()));
    sync_models(rt).await;
}

/// Go loads plugins while it builds the service, so its first auth-folder load already
/// asks plugin auth providers (sdk/cliproxy/builder.go `ApplyConfig`, then
/// `coreManager.Load` in `Service.Run`). Credentials load before plugins start here, so
/// the binary calls this once they have: while a plugin offers an auth provider, the
/// auth folder and config credentials load again, before serving. Not in Home mode,
/// whose credentials come from Home. Published as the watcher publishes a scan: a file
/// changed after the scan read it (a token refresh committed meanwhile) keeps its
/// current credential, and so does a file the scan read half-written. Plugins parse on
/// a blocking thread, holding no lock: a parse can make host callbacks that need the
/// async runtime, even with one worker thread. This load registers the credentials as
/// Go's first one does, so it replaces the startup load's refresh schedules
/// ([`crate::runtime::CredentialStore::end_bootstrap`]).
pub async fn reload_plugin_auth_files(rt: &Arc<Runtime>) {
    use cpa_core::config::credentials;
    /// Ends the startup window however the load ends, a failed one included, so the
    /// refresh loop never waits on provisional schedules. Owned by the load itself: a
    /// dropped caller leaves the window open until the parse it started is published.
    struct EndBootstrap(Arc<Runtime>);
    impl Drop for EndBootstrap {
        fn drop(&mut self) {
            self.0.store().end_bootstrap();
        }
    }
    let end = EndBootstrap(rt.clone());
    if !credentials::plugin_auth_parser_active() {
        return;
    }
    let rt = rt.clone();
    let reload = tokio::task::spawn_blocking(move || {
        let _end = end;
        let cfg = rt.config();
        credentials::preparse_auth_dir(&cfg);
        let scan = credentials::scan_auth_dir(&cfg);
        let mut all = scan.credentials;
        for existing in rt.store().snapshot() {
            if let cpa_core::credential::Source::File(path) = &existing.source
                && scan.incomplete.contains(path)
                && !all.iter().any(|c| c.id == existing.id)
            {
                all.push(cpa_core::credential::Credential::clone(&existing));
            }
        }
        all.extend(credentials::from_config(&cfg));
        rt.store().reconcile_scanned_with(all, &scan.read, |current, all| {
            keep_deferred(current, all, &scan.deferred)
        });
    });
    if let Err(e) = reload.await {
        tracing::error!(error = %e, "reloading auth files for plugin auth providers failed");
    }
}

/// Keeps the store's `current` credentials of the files a scan deferred (no plugin auth
/// provider has answered for their current bytes yet) and publishes nothing new for
/// them, as Go's watcher asks the plugin first; the watcher's next reload parses them.
/// Run under the store's reconciliation gate
/// ([`crate::runtime::CredentialStore::reconcile_scanned_with`]), so a refresh committed
/// after the scan is what is kept.
pub(crate) fn keep_deferred(
    current: &[Arc<cpa_core::credential::Credential>],
    all: &mut Vec<cpa_core::credential::Credential>,
    deferred: &std::collections::HashSet<std::path::PathBuf>,
) {
    use cpa_core::credential::{Credential, Source};
    if deferred.is_empty() {
        return;
    }
    // Saves and uploads record absolute paths; a relative auth-dir scans relative ones.
    let absolute = |p: &std::path::Path| std::path::absolute(p).unwrap_or_else(|_| p.to_owned());
    let deferred: std::collections::HashSet<_> = deferred.iter().map(|p| absolute(p)).collect();
    for existing in current {
        if let Source::File(p) = &existing.source
            && deferred.contains(&absolute(p))
            && !all.iter().any(|c| c.id == existing.id)
        {
            all.push(Credential::clone(existing));
        }
    }
}

/// Go `syncPluginModelRuntime`: collects plugin catalogs, lets plugin executors claim
/// the providers and models no built-in executor serves, then publishes the catalogs
/// for credential-bound registration and the claimed executor models.
async fn sync_models(rt: &Runtime) {
    let host = rt.plugins();
    host.register_models().await;
    let native = native_executor_providers(rt).await;
    // Ownership is decided against the registry, whose credentials carry the published
    // plugin catalog. Republishing changes that registry (a removed built-in catalog
    // frees its models), so repeat until the catalog is stable; Go decides once against
    // the previous catalog and catches up on the next sync.
    for _ in 0..3 {
        let registry = rt.registry();
        let Some(changes) = host
            .register_executors(&|p| native.contains(p), &|m| registry.model_providers(m))
            .await
        else {
            // The plugin set changed meanwhile; its own sync follows.
            return;
        };
        *rt.plugin_runtime()
            .executors
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = changes
            .register
            .into_iter()
            .map(|adapter| (adapter.provider.clone(), adapter))
            .collect();
        let specs = |models: &[cpa_plugin::api::ModelInfo]| models.iter().map(model_spec).collect::<Vec<_>>();
        let changed = cpa_core::registry::dynamic::set_plugin_catalog(cpa_core::registry::dynamic::PluginCatalog {
            providers: host
                .provider_models()
                .iter()
                .map(|(provider, models)| (provider.clone(), specs(models)))
                .collect(),
            clients: changes
                .clients
                .register
                .iter()
                .map(|(client, provider, models)| (client.clone(), provider.clone(), specs(models)))
                .collect(),
        });
        if !changed {
            return;
        }
    }
}

/// Go `registerExecutorForAuth`'s built-in providers.
const BUILTIN: [&str; 14] = [
    "codex",
    "claude",
    "gemini",
    "gemini-interactions",
    "vertex",
    "aistudio",
    "antigravity",
    "kimi",
    "kimi-ai",
    "kimi.ai",
    "kimi.com",
    "xai",
    "devin",
    "meta",
];

/// Whether Go binds `c` to a built-in executor even over a registered plugin executor
/// (`registerExecutorForAuth`): an OpenAI-compatible credential
/// (`openAICompatInfoFromAuth`; `registerOpenAICompatProviderExecutor` keeps only a bare
/// compat executor), a built-in provider, or any other provider with a native
/// compatibility config (`hasNativeOpenAICompatExecutorConfig`: a `base_url` attribute
/// or an enabled `openai-compatibility` entry named after it; `OwnsExecutor` is true
/// for this host's plugin adapter, so `shouldKeepExistingOpenAICompatExecutor` returns
/// false and Go replaces it even with `respectNonOwned`). Otherwise a plugin executor
/// candidate keeps the provider.
fn binds_native(c: &cpa_core::credential::Credential, compat_names: &[String]) -> bool {
    let attr = |k: &str| c.attributes.get(k).map(|v| v.trim()).unwrap_or_default();
    let provider = c.provider.trim().go_lower();
    if !attr("compat_name").is_empty() || provider == "openai-compatibility" || BUILTIN.contains(&provider.as_str()) {
        return true;
    }
    let key = if provider.is_empty() {
        "openai-compatibility"
    } else {
        provider.as_str()
    };
    !attr("base_url").is_empty()
        || [key, &attr("provider_key").go_lower(), &provider]
            .iter()
            .any(|candidate| !candidate.is_empty() && compat_names.iter().any(|n| n == candidate))
}

/// Go `providerHasNativeExecutor`: providers a built-in executor is actually bound to.
/// Go binds one per enabled credential (`registerExecutorForAuth`), plus a fixed
/// baseline in Home mode. An OpenAI-compatible credential or a built-in provider always
/// binds; any other provider binds the OpenAI-compatible executor unless a plugin
/// executor is a candidate for it and no native compatibility config names it.
/// ponytail: Go keeps a binding after its last credential goes away; here bindings are
/// recomputed from the current credentials.
async fn native_executor_providers(rt: &Runtime) -> HashSet<String> {
    let cfg = rt.config();
    let compat_names = cpa_core::config::credentials::openai_compat_names(&cfg);
    let host = rt.plugins();
    let mut native = HashSet::new();
    for c in rt.store().snapshot().iter().filter(|c| !c.disabled) {
        let provider = c.provider.trim().go_lower();
        let key = if !c.attributes.get("compat_name").is_none_or(|v| v.trim().is_empty())
            || provider == "openai-compatibility"
        {
            cpa_core::registry::dynamic::provider_key(c)
        } else if provider.is_empty() {
            "openai-compatibility".to_owned()
        } else {
            provider
        };
        if !binds_native(c, &compat_names) && host.has_executor_candidate_provider(&key).await {
            continue;
        }
        native.insert(key);
    }
    if rt.remote_dispatch().is_some() {
        // Go `baselineExecutorAuths`: the built-in providers but `kimi.com`, plus the
        // OpenAI-compatible executor.
        native.extend(
            BUILTIN
                .iter()
                .filter(|p| **p != "kimi.com")
                .chain(&["openai-compatibility"])
                .map(|p| (*p).to_owned()),
        );
    }
    native
}

/// The request facts a plugin scheduler receives (Go `SchedulerPickRequest.Stream` and
/// `Options`: the client headers and the execution metadata, JSON values only).
#[derive(Debug, Default)]
pub struct SchedulerContext {
    pub stream: bool,
    pub options: cpa_plugin::api::SchedulerOptions,
}

/// Go `pickNextLegacy`'s scheduler options for a single-provider selection (Codex
/// realtime and Alpha Search): the selection headers, the route's own metadata
/// (`metadata`, such as a realtime call's pinned credential and execution session), the
/// provider as the session affinity provider and `affinity_model` (Go
/// `selectionArgForSelector`: the route model under session affinity, else empty).
/// These routes do not run `session.Enrich`. `None` without an active plugin scheduler.
pub(crate) fn provider_scheduler_context(
    rt: &Runtime,
    provider: &str,
    headers: &HeaderMap,
    affinity_model: &str,
    metadata: &[(&str, &str)],
) -> Option<Arc<SchedulerContext>> {
    if !rt.plugins().has_scheduler() {
        return None;
    }
    let string = |s: &str| serde_json::Value::String(s.to_owned());
    let mut out: cpa_plugin::gojson::Metadata = metadata.iter().map(|(k, v)| ((*k).to_owned(), string(v))).collect();
    out.insert("session_affinity_provider".into(), string(provider));
    out.insert("session_affinity_model".into(), string(affinity_model));
    Some(Arc::new(SchedulerContext {
        stream: false,
        options: cpa_plugin::api::SchedulerOptions {
            headers: go_request_header(headers),
            metadata: out,
        },
    }))
}

/// The plugin scheduler's request for a selection, or `None` when no plugin scheduler
/// takes part (none active, or Home mode). Errors are the availability errors Go
/// reports before asking the scheduler.
pub(crate) fn scheduler_request(
    rt: &Runtime,
    selection: &crate::runtime::Selection,
    policy: &crate::scheduler::Policy,
    admit: &crate::runtime::Admit<'_>,
) -> Result<Option<cpa_plugin::api::SchedulerPickRequest>, crate::runtime::AcquireError> {
    let host = rt.plugins();
    if rt.remote_dispatch().is_some() || !host.has_scheduler() {
        return Ok(None);
    }
    let across = host.scheduler_wants_across_priorities();
    let candidates = rt.store().scheduler_candidates(selection, policy, admit, across)?;
    let mut providers: Vec<String> = Vec::new();
    for p in selection.provider_keys() {
        let p = p.trim().go_lower();
        if !p.is_empty() && p != "mixed" && !providers.contains(&p) {
            providers.push(p);
        }
    }
    let context = selection.scheduler.as_deref();
    Ok(Some(cpa_plugin::api::SchedulerPickRequest {
        // Handlers select across providers (Go `pickNextMixed`, "mixed"), which leaves
        // Provider empty; Codex realtime and Alpha Search select one provider (Go
        // `pickNextLegacy`), which names it.
        provider: if selection.providers.is_empty() {
            selection.provider.trim().go_lower()
        } else {
            String::new()
        },
        providers,
        model: selection.model.clone(),
        stream: context.is_some_and(|c| c.stream),
        options: context.map(|c| c.options.clone()).unwrap_or_default(),
        candidates: candidates
            .iter()
            .map(|c| cpa_plugin::api::SchedulerAuthCandidate {
                id: c.id.clone(),
                provider: c.provider.trim().go_lower(),
                priority: crate::scheduler::priority(c),
                // ponytail: candidates are ready, which Go reports as `active` unless an
                // earlier failure left the credential in `error`; that status is not
                // tracked apart from cooldowns here.
                status: "active".into(),
                attributes: c
                    .attributes
                    .iter()
                    .filter(|(k, _)| !scheduler_attribute_sensitive(k))
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect(),
                ..Default::default()
            })
            .collect(),
        ..Default::default()
    }))
}

/// Go `pickViaPluginScheduler` before native selection (`pickNextMixedLegacy`): the
/// highest-priority active plugin scheduler chooses among the ready candidates, rejects
/// the selection, or delegates to a built-in strategy; without an answer the configured
/// selector chooses. Go's Home mode selects remotely and consults no plugin scheduler.
pub(crate) async fn scheduler_pick(
    rt: &Runtime,
    request: Option<cpa_plugin::api::SchedulerPickRequest>,
) -> Result<crate::runtime::Pick, crate::runtime::AcquireError> {
    use crate::runtime::{AcquireError, Pick};
    let Some(request) = request else {
        return Ok(Pick::Configured);
    };
    let resp = match rt.plugins().pick_auth(request).await {
        Ok(Some(resp)) => resp,
        Ok(None) => return Ok(Pick::Configured),
        // Go returns the plugin's error; its status, if any, decides the response.
        Err(e) => {
            return Err(AcquireError::Scheduler(cpa_core::exec::ExecError::local(
                e.status(),
                cpa_core::exec::FailureScope::Model,
                e.to_string(),
            )));
        }
    };
    if resp.reject {
        return Err(AcquireError::Rejected {
            code: resp.reject_code,
            message: resp.reject_reason,
        });
    }
    if !resp.auth_id.is_empty() {
        return Ok(Pick::Auth(resp.auth_id));
    }
    Ok(match resp.delegate_builtin.as_str() {
        cpa_plugin::api::SCHEDULER_BUILTIN_ROUND_ROBIN => Pick::Builtin(crate::scheduler::Strategy::RoundRobin),
        cpa_plugin::api::SCHEDULER_BUILTIN_FILL_FIRST => Pick::Builtin(crate::scheduler::Strategy::FillFirst),
        _ => Pick::Configured,
    })
}

/// Go `schedulerAttributeSensitive`: credential attributes a scheduler never sees.
fn scheduler_attribute_sensitive(key: &str) -> bool {
    let key = key.trim().go_lower();
    let normalized: String = key
        .chars()
        .map(|c| if matches!(c, '-' | '.' | ' ') { '_' } else { c })
        .collect();
    let compact: String = key.chars().filter(|c| !matches!(c, '_' | '-' | '.' | ' ')).collect();
    [
        "api_key",
        "apikey",
        "token",
        "secret",
        "cookie",
        "credential",
        "password",
        "storage",
        "authorization",
        "auth_header",
        "proxy_url",
    ]
    .iter()
    .any(|fragment| key.contains(fragment) || normalized.contains(fragment) || compact.contains(fragment))
}

/// Go `pluginModelInfoToRegistryModelInfo`.
fn model_spec(m: &cpa_plugin::api::ModelInfo) -> cpa_core::registry::dynamic::Spec {
    cpa_core::registry::dynamic::Spec {
        id: m.id.trim().to_owned(),
        object: m.object.clone(),
        created: m.created,
        owned_by: m.owned_by.clone(),
        kind: m.model_type.clone(),
        display_name: m.display_name.clone(),
        name: m.name.clone(),
        version: m.version.clone(),
        description: m.description.clone(),
        input_token_limit: m.input_token_limit,
        output_token_limit: m.output_token_limit,
        supported_generation_methods: m.supported_generation_methods.clone(),
        context_length: m.context_length,
        max_completion_tokens: m.max_completion_tokens,
        supported_parameters: m.supported_parameters.clone(),
        supported_input_modalities: m.supported_input_modalities.clone(),
        supported_output_modalities: m.supported_output_modalities.clone(),
        thinking: m.thinking.as_ref().map(|t| cpa_core::registry::ThinkingSupport {
            min: t.min,
            max: t.max,
            zero_allowed: t.zero_allowed,
            dynamic_allowed: t.dynamic_allowed,
            disable_type: t.disable_type.clone(),
            levels: t.levels.clone(),
        }),
        user_defined: m.user_defined,
        ..Default::default()
    }
}

// ---- Frontend auth (Go `sdk/access`) -------------------------------------------------

/// Go `sdkaccess.AccessProviderTypeConfigAPIKey`: the client-key provider's registry key.
const CONFIG_PROVIDER_KEY: &str = "config-api-key";
/// Go `sdkaccess.DefaultAccessProviderName`: the client-key provider's identifier.
pub(crate) const CONFIG_PROVIDER: &str = "config-inline";

/// Go's global access provider registry as the syncs leave it: keys in first-registration
/// order (a re-registered key keeps its place; an unregistered one loses it), the plugin
/// behind each plugin key, and the exclusive key.
#[derive(Default)]
struct AccessRegistry {
    order: Vec<String>,
    plugins: HashMap<String, String>,
    exclusive: Option<String>,
}

enum Provider<'a> {
    ClientKeys,
    Plugin(&'a str),
}

impl AccessRegistry {
    /// Go `RegisteredProviders`. The client-key provider is present exactly when keys are
    /// configured now; before the first sync it sits first, as Go registers it before any
    /// plugin.
    fn providers(&self, client_keys: bool) -> Vec<Provider<'_>> {
        if let Some(id) = self.exclusive.as_ref().and_then(|key| self.plugins.get(key)) {
            return vec![Provider::Plugin(id)];
        }
        let mut out = Vec::with_capacity(self.order.len() + 1);
        if client_keys && !self.order.iter().any(|k| k == CONFIG_PROVIDER_KEY) {
            out.push(Provider::ClientKeys);
        }
        for key in &self.order {
            if key == CONFIG_PROVIDER_KEY {
                if client_keys {
                    out.push(Provider::ClientKeys);
                }
            } else if let Some(id) = self.plugins.get(key) {
                out.push(Provider::Plugin(id));
            }
        }
        out
    }
}

impl PluginRuntime {
    fn access(&self) -> Arc<AccessRegistry> {
        self.access.read().unwrap_or_else(|e| e.into_inner()).clone()
    }

    /// Go `configaccess.Register` then `RegisterFrontendAuthProviders`: register or
    /// unregister the client-key provider, register each plugin provider, set the
    /// exclusive key, and drop plugin keys no longer offered.
    pub(crate) fn register_access(
        &self,
        client_keys: bool,
        providers: Vec<(String, String)>,
        exclusive: Option<String>,
    ) {
        let mut slot = self.access.write().unwrap_or_else(|e| e.into_inner());
        let mut next = AccessRegistry {
            order: slot.order.clone(),
            plugins: HashMap::new(),
            exclusive,
        };
        let register = |order: &mut Vec<String>, key: &str| {
            if !order.iter().any(|k| k == key) {
                order.push(key.to_owned());
            }
        };
        if client_keys {
            register(&mut next.order, CONFIG_PROVIDER_KEY);
        } else {
            next.order.retain(|k| k != CONFIG_PROVIDER_KEY);
        }
        for (key, id) in providers {
            register(&mut next.order, &key);
            next.plugins.insert(key, id);
        }
        next.order
            .retain(|k| k == CONFIG_PROVIDER_KEY || next.plugins.contains_key(k));
        *slot = Arc::new(next);
    }
}

/// A request the access providers let through.
pub(crate) enum Access {
    /// No provider registered: Go's manager returns no result and sets nothing.
    Open,
    /// Go `sdkaccess.Result`: the caller, with the provider identifier that accepted it.
    /// ponytail: a plugin's result metadata is not kept (`Caller` has no field for it;
    /// only Go's Home mode reads it).
    Granted(Caller),
}

/// Go `sdkaccess.AuthError` as the middlewares answer it.
pub(crate) struct Denied {
    pub status: u16,
    pub message: &'static str,
}

const MISSING_API_KEY: &str = "Missing API key";

/// Go `sdkaccess.Manager.Authenticate` over the registered providers: client keys, then
/// plugin frontend auth providers in registration order (or only the exclusive one).
/// The first acceptance wins; afterwards "Invalid API key" if any provider saw an
/// invalid key, else "Missing API key". The request comes back with its body intact.
pub(crate) async fn authenticate(rt: &Runtime, req: Request) -> (Request, Result<Access, Denied>) {
    let config = rt.config();
    let registry = rt.plugin_runtime().access();
    let providers = registry.providers(!config.api_keys.is_empty());
    if providers.is_empty() {
        return (req, Ok(Access::Open));
    }
    let (parts, mut body) = req.into_parts();
    let mut read: Option<Bytes> = None;
    let mut invalid = false;
    let mut outcome = None;
    for provider in providers {
        match provider {
            Provider::ClientKeys => {
                match crate::access::authenticate(
                    &config.api_keys,
                    &parts.headers,
                    parts.uri.query().unwrap_or_default(),
                ) {
                    Ok(caller) => {
                        outcome = Some(Ok(Access::Granted(Caller {
                            provider: CONFIG_PROVIDER.to_owned(),
                            ..caller
                        })));
                        break;
                    }
                    Err(message) => invalid |= message != MISSING_API_KEY,
                }
            }
            Provider::Plugin(id) => {
                // Go `readAndRestoreRequestBody`: the whole body, once. Go reads it
                // without a bound; here it stops at MAX_REQUEST_BYTES, as the routes do.
                let bytes = match &read {
                    Some(bytes) => bytes.clone(),
                    None => match read_limited(std::mem::take(&mut body)).await {
                        Ok(Some(bytes)) => read.insert(bytes).clone(),
                        Ok(None) => {
                            outcome = Some(Err(Denied {
                                status: 413,
                                message: "request body too large",
                            }));
                            break;
                        }
                        // Go `NewRequestEntityTooLargeError` (dd7b4334).
                        Err(error) if crate::body_limit::is_too_large(&error) => {
                            outcome = Some(Err(Denied {
                                status: 413,
                                message: crate::body_limit::MESSAGE,
                            }));
                            break;
                        }
                        Err(error) => {
                            tracing::error!(
                                "authentication middleware error: failed to read plugin auth request body: {error}"
                            );
                            outcome = Some(Err(Denied {
                                status: 500,
                                message: "failed to read plugin auth request body",
                            }));
                            break;
                        }
                    },
                };
                let request = cpa_plugin::api::FrontendAuthRequest {
                    method: parts.method.as_str().to_owned(),
                    path: crate::management::percent_decode(parts.uri.path()),
                    headers: go_request_header(&parts.headers),
                    query: go_values(parts.uri.query().unwrap_or_default()),
                    body: cpa_plugin::gojson::NonNilBytes(bytes),
                };
                if let Some(accepted) = rt.plugins().frontend_authenticate(id, &request).await {
                    outcome = Some(Ok(Access::Granted(Caller {
                        principal: accepted.principal,
                        source: "",
                        provider: accepted.provider,
                    })));
                    break;
                }
            }
        }
    }
    let body = match read {
        Some(bytes) => Body::from(bytes),
        None => body,
    };
    let outcome = outcome.unwrap_or(Err(Denied {
        status: 401,
        message: if invalid { "Invalid API key" } else { MISSING_API_KEY },
    }));
    (Request::from_parts(parts, body), outcome)
}

/// The whole body, or `None` once it passes [`crate::MAX_REQUEST_BYTES`].
async fn read_limited(body: Body) -> Result<Option<Bytes>, axum::Error> {
    use futures_util::StreamExt as _;
    let mut stream = body.into_data_stream();
    let mut out = bytes::BytesMut::new();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        if out.len() + chunk.len() > crate::MAX_REQUEST_BYTES {
            return Ok(None);
        }
        out.extend_from_slice(&chunk);
    }
    Ok(Some(out.freeze()))
}

/// A server request's `http.Header` as Go's handlers see it: canonical names, values in
/// order, and no `Host` (Go moves it to `Request.Host`). A chunked request also loses
/// `Transfer-Encoding`, `Content-Length` and `Trailer` (Go `readTransfer`).
pub(crate) fn go_request_header(headers: &HeaderMap) -> cpa_plugin::gojson::Header {
    let chunked = headers.contains_key(axum::http::header::TRANSFER_ENCODING);
    let mut out = cpa_plugin::gojson::Header::new();
    for (name, value) in headers {
        let dropped = name == axum::http::header::HOST
            || (chunked
                && (name == axum::http::header::TRANSFER_ENCODING
                    || name == axum::http::header::CONTENT_LENGTH
                    || name == axum::http::header::TRAILER));
        if dropped {
            continue;
        }
        out.entry(cpa_exec::proxy::canonical_header(name.as_str()))
            .or_default()
            .push(String::from_utf8_lossy(value.as_bytes()).into_owned());
    }
    out
}

/// `Request.URL.Query()` as `url.Values`.
pub(crate) fn go_values(raw_query: &str) -> cpa_plugin::gojson::Header {
    let mut out = cpa_plugin::gojson::Header::new();
    for (k, v) in crate::management::go_query(raw_query) {
        out.entry(k).or_default().push(v);
    }
    out
}

/// Syncs the current config now, then follows every later publish. Call once at
/// startup, before serving (Go applies plugins before the server starts).
pub async fn start(rt: &Arc<Runtime>) {
    model_callbacks::attach(rt);
    let mut rx = rt.plugin_runtime().latest.subscribe();
    rx.mark_unchanged();
    // At least this publish is in the current config.
    let seq = rt.plugin_runtime().published_seq();
    sync(rt, rt.config()).await;
    rt.plugin_runtime().applied.send_replace(seq);
    let weak: Weak<Runtime> = Arc::downgrade(rt);
    tokio::spawn(async move {
        while rx.changed().await.is_ok() {
            let Some((seq, cfg)) = rx.borrow_and_update().clone() else {
                continue;
            };
            let Some(rt) = weak.upgrade() else {
                return;
            };
            sync(&rt, cfg).await;
            rt.plugin_runtime().applied.send_replace(seq);
        }
    });
}

/// Go `registeredManagementRouteKeys`: every built-in `/v0/management` route as gin
/// lists it. Plugins cannot register these keys even where this server does not
/// implement the route, so a plugin keeps the same routes under both servers.
/// ponytail: Go registers these only once a management secret exists; until then it
/// lets plugins claim them. The full list is used unconditionally.
pub fn reserved_management_routes() -> HashSet<String> {
    GO_V0_MANAGEMENT_ROUTES.iter().map(|r| (*r).to_owned()).collect()
}

/// `internal/api/server_management.go` at 6fecc6e.
const GO_V0_MANAGEMENT_ROUTES: [&str; 144] = [
    "DELETE /v0/management/api-keys",
    "DELETE /v0/management/auth-files",
    "DELETE /v0/management/claude-api-key",
    "DELETE /v0/management/codex-api-key",
    "DELETE /v0/management/gemini-api-key",
    "DELETE /v0/management/interactions-api-key",
    "DELETE /v0/management/logs",
    "DELETE /v0/management/meta-api-key",
    "DELETE /v0/management/oauth-excluded-models",
    "DELETE /v0/management/oauth-model-alias",
    "DELETE /v0/management/oauth-request-scoped-errors",
    "DELETE /v0/management/oauth-session",
    "DELETE /v0/management/openai-compatibility",
    "DELETE /v0/management/plugins/:id",
    "DELETE /v0/management/plugins/:id/quota",
    "DELETE /v0/management/proxy-url",
    "DELETE /v0/management/vertex-api-key",
    "DELETE /v0/management/xai-api-key",
    "GET /v0/management/anthropic-auth-url",
    "GET /v0/management/antigravity-auth-url",
    "GET /v0/management/api-key-usage",
    "GET /v0/management/api-keys",
    "GET /v0/management/auth-files",
    "GET /v0/management/auth-files/download",
    "GET /v0/management/auth-files/models",
    "GET /v0/management/claude-api-key",
    "GET /v0/management/codex-api-key",
    "GET /v0/management/codex-auth-url",
    "GET /v0/management/config",
    "GET /v0/management/config.yaml",
    "GET /v0/management/debug",
    "GET /v0/management/devin-auth-url",
    "GET /v0/management/error-logs-max-files",
    "GET /v0/management/force-model-prefix",
    "GET /v0/management/gemini-api-key",
    "GET /v0/management/get-auth-status",
    "GET /v0/management/interactions-api-key",
    "GET /v0/management/kimi-ai-auth-url",
    "GET /v0/management/kimi-auth-url",
    "GET /v0/management/latest-version",
    "GET /v0/management/logging-to-file",
    "GET /v0/management/logs",
    "GET /v0/management/logs-max-total-size-mb",
    "GET /v0/management/max-retry-credentials",
    "GET /v0/management/max-retry-interval",
    "GET /v0/management/meta-api-key",
    "GET /v0/management/meta-auth-url",
    "GET /v0/management/model-definitions/:channel",
    "GET /v0/management/oauth-callback",
    "GET /v0/management/oauth-excluded-models",
    "GET /v0/management/oauth-model-alias",
    "GET /v0/management/oauth-request-scoped-errors",
    "GET /v0/management/openai-compatibility",
    "GET /v0/management/plugin-store",
    "GET /v0/management/plugins",
    "GET /v0/management/plugins/:id/config",
    "GET /v0/management/plugins/:id/quota",
    "GET /v0/management/proxy-url",
    "GET /v0/management/quota-exceeded/switch-preview-model",
    "GET /v0/management/quota-exceeded/switch-project",
    "GET /v0/management/quota/providers",
    "GET /v0/management/request-error-logs",
    "GET /v0/management/request-error-logs/:name",
    "GET /v0/management/request-log",
    "GET /v0/management/request-log-by-id/:id",
    "GET /v0/management/request-retry",
    "GET /v0/management/routing/strategy",
    "GET /v0/management/usage-queue",
    "GET /v0/management/usage-statistics-enabled",
    "GET /v0/management/vertex-api-key",
    "GET /v0/management/ws-auth",
    "GET /v0/management/xai-api-key",
    "GET /v0/management/xai-auth-url",
    "PATCH /v0/management/api-keys",
    "PATCH /v0/management/auth-files/fields",
    "PATCH /v0/management/auth-files/status",
    "PATCH /v0/management/claude-api-key",
    "PATCH /v0/management/codex-api-key",
    "PATCH /v0/management/debug",
    "PATCH /v0/management/error-logs-max-files",
    "PATCH /v0/management/force-model-prefix",
    "PATCH /v0/management/gemini-api-key",
    "PATCH /v0/management/interactions-api-key",
    "PATCH /v0/management/logging-to-file",
    "PATCH /v0/management/logs-max-total-size-mb",
    "PATCH /v0/management/max-retry-credentials",
    "PATCH /v0/management/max-retry-interval",
    "PATCH /v0/management/meta-api-key",
    "PATCH /v0/management/oauth-excluded-models",
    "PATCH /v0/management/oauth-model-alias",
    "PATCH /v0/management/oauth-request-scoped-errors",
    "PATCH /v0/management/openai-compatibility",
    "PATCH /v0/management/plugins/:id/config",
    "PATCH /v0/management/plugins/:id/enabled",
    "PATCH /v0/management/proxy-url",
    "PATCH /v0/management/quota-exceeded/switch-preview-model",
    "PATCH /v0/management/quota-exceeded/switch-project",
    "PATCH /v0/management/request-log",
    "PATCH /v0/management/request-retry",
    "PATCH /v0/management/routing/strategy",
    "PATCH /v0/management/usage-statistics-enabled",
    "PATCH /v0/management/vertex-api-key",
    "PATCH /v0/management/ws-auth",
    "PATCH /v0/management/xai-api-key",
    "POST /v0/management/api-call",
    "POST /v0/management/auth-files",
    "POST /v0/management/auth-files/refresh",
    "POST /v0/management/oauth-callback",
    "POST /v0/management/plugin-store/:id/install",
    "POST /v0/management/plugins/:id/quota",
    "POST /v0/management/plugins/:id/quota/reset",
    "POST /v0/management/quota/fetch",
    "POST /v0/management/quota/reset",
    "POST /v0/management/reset-quota",
    "POST /v0/management/vertex/import",
    "PUT /v0/management/api-keys",
    "PUT /v0/management/claude-api-key",
    "PUT /v0/management/codex-api-key",
    "PUT /v0/management/config.yaml",
    "PUT /v0/management/debug",
    "PUT /v0/management/error-logs-max-files",
    "PUT /v0/management/force-model-prefix",
    "PUT /v0/management/gemini-api-key",
    "PUT /v0/management/interactions-api-key",
    "PUT /v0/management/logging-to-file",
    "PUT /v0/management/logs-max-total-size-mb",
    "PUT /v0/management/max-retry-credentials",
    "PUT /v0/management/max-retry-interval",
    "PUT /v0/management/meta-api-key",
    "PUT /v0/management/oauth-excluded-models",
    "PUT /v0/management/oauth-model-alias",
    "PUT /v0/management/oauth-request-scoped-errors",
    "PUT /v0/management/openai-compatibility",
    "PUT /v0/management/plugins/:id/config",
    "PUT /v0/management/proxy-url",
    "PUT /v0/management/quota-exceeded/switch-preview-model",
    "PUT /v0/management/quota-exceeded/switch-project",
    "PUT /v0/management/request-log",
    "PUT /v0/management/request-retry",
    "PUT /v0/management/routing/strategy",
    "PUT /v0/management/usage-statistics-enabled",
    "PUT /v0/management/vertex-api-key",
    "PUT /v0/management/ws-auth",
    "PUT /v0/management/xai-api-key",
];

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

    fn outcome(result: &Result<Access, Denied>) -> (u16, &'static str) {
        match result {
            Ok(_) => (200, ""),
            Err(denied) => (denied.status, denied.message),
        }
    }

    /// A plugin frontend auth provider reads the body even after the client keys
    /// rejected the request, so the read stops at MAX_REQUEST_BYTES.
    #[tokio::test]
    async fn plugin_auth_reads_a_bounded_body() {
        let dir = cpa_plugin::testing::scratch(&std::env::temp_dir(), "plugin-auth-body");
        let cfg = Config::parse(&format!(
            "config-version: 8\nauth-dir: {}\naccess:\n  api-keys: [client-key]\n",
            dir.display()
        ))
        .unwrap();
        let rt = crate::testing::runtime(
            cfg,
            Vec::new(),
            cpa_exec::Executors {
                claude: cpa_exec::claude::ClaudeExecutor::new("http://127.0.0.1:1").unwrap(),
                codex: Default::default(),
                devices: Default::default(),
                openai: Default::default(),
                google: Default::default(),
            },
        );
        // A provider for a plugin that is not loaded: it never accepts.
        rt.plugin_runtime()
            .register_access(true, vec![("plugin-auth".into(), "p".into())], None);
        let request = |key: Option<&str>, body: Body| {
            let mut builder = Request::builder().method("POST").uri("/v1/chat/completions");
            if let Some(key) = key {
                builder = builder.header("authorization", format!("Bearer {key}"));
            }
            builder.body(body).unwrap()
        };
        for key in [None, Some("wrong")] {
            let big = Body::from(vec![b'x'; crate::MAX_REQUEST_BYTES + 1]);
            let (_, result) = authenticate(&rt, request(key, big)).await;
            assert_eq!(outcome(&result), (413, "request body too large"), "{key:?}");
        }
        // At the limit the body is read, offered and handed back whole.
        let (req, result) = authenticate(
            &rt,
            request(Some("wrong"), Body::from(vec![b'y'; crate::MAX_REQUEST_BYTES])),
        )
        .await;
        assert_eq!(outcome(&result), (401, "Invalid API key"));
        let body = axum::body::to_bytes(req.into_body(), usize::MAX).await.unwrap();
        assert_eq!(body.len(), crate::MAX_REQUEST_BYTES);
        let (_, result) = authenticate(&rt, request(None, Body::from("{}"))).await;
        assert_eq!(outcome(&result), (401, MISSING_API_KEY));
        let (_, result) = authenticate(&rt, request(Some("client-key"), Body::from("{}"))).await;
        assert_eq!(outcome(&result), (200, ""));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Go `TestPluginRegisteredSonnet55TurnsThinkingOffWithBetweenTools`: a plugin model's
    /// `DisableType` reaches the Claude applier through the registry conversion. An older
    /// plugin's payload without it turns thinking off with `disabled`, even on a model the
    /// proxy knows refuses it: plugin capabilities are authoritative, as in Go.
    #[test]
    fn plugin_registered_sonnet_5_5_turns_thinking_off_with_between_tools() {
        let thinking_off = |model: &str, thinking: &[u8]| {
            let info = model_spec(&cpa_plugin::api::ModelInfo {
                id: model.into(),
                model_type: "claude".into(),
                thinking: Some(cpa_plugin::gojson::from_slice(thinking).unwrap()),
                ..Default::default()
            })
            .to_info();
            let body = format!(
                r#"{{"model":"{model}","messages":[{{"role":"user","content":"hi"}}],"thinking":{{"type":"disabled"}}}}"#
            );
            let caps = cpa_common::thinking::ModelCaps::from(&info);
            let out = cpa_common::thinking::apply_thinking_with_model_info(
                body.as_bytes(),
                &[],
                model,
                "claude",
                "claude",
                "claude",
                Some(&caps),
            )
            .unwrap();
            serde_json::from_slice::<serde_json::Value>(&out).unwrap()["thinking"].clone()
        };
        let current = br#"{"ZeroAllowed":true,"Levels":["low","medium","high"],"DisableType":"between_tools"}"#;
        assert_eq!(
            thinking_off("claude-sonnet-5-5", current),
            serde_json::json!({"type": "between_tools"})
        );
        let older = br#"{"ZeroAllowed":true,"Levels":["low","medium","high"]}"#;
        assert_eq!(
            thinking_off("claude-opus-5-5", older),
            serde_json::json!({"type": "disabled"})
        );
    }
}