harn-vm 0.10.162

Async bytecode virtual machine for the Harn programming language
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
use serde::{Deserialize, Serialize};

use crate::llm_config::{self, ProviderDef};
use crate::value::{VmError, VmValue};

/// Credential resolution state reported by Harn's dispatch authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderCredentialStatus {
    Ok,
    Missing,
    NotRequired,
    Deferred,
    /// The credential is in a store that would only answer through a system
    /// dialog (a locked macOS Keychain) that this process does not show.
    NeedsUserApproval,
    /// A platform-managed provider needs a region and none resolves without
    /// the network.
    RegionUnconfigured,
    /// A platform-managed provider has no credential source discoverable
    /// without the network.
    CredentialsUnconfigured,
}

impl ProviderCredentialStatus {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Missing => "missing",
            Self::NotRequired => "not_required",
            Self::Deferred => "deferred",
            Self::NeedsUserApproval => "needs_user_approval",
            Self::RegionUnconfigured => "region_unconfigured",
            Self::CredentialsUnconfigured => "credentials_unconfigured",
        }
    }
}

impl From<super::providers::PlatformPrerequisiteGap> for ProviderCredentialStatus {
    fn from(gap: super::providers::PlatformPrerequisiteGap) -> Self {
        match gap {
            super::providers::PlatformPrerequisiteGap::Region => Self::RegionUnconfigured,
            super::providers::PlatformPrerequisiteGap::Credentials => Self::CredentialsUnconfigured,
        }
    }
}

/// Secret-free provider usability status for native hosts and VM projections.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProviderAuthStatus {
    pub name: String,
    pub available: bool,
    pub credential_status: ProviderCredentialStatus,
}

/// The authority that selected a provider for a single-route dispatch.
///
/// This is deliberately separate from credential state: selection explains
/// why Harn is asking for a particular credential, while credential probing
/// decides whether that route can run. Keeping the two concepts separate
/// prevents a missing key from rewriting an explicit selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProviderSelectionSource {
    CallOption,
    Environment,
    DefaultEnvironment,
    ConfiguredDefault,
    ModelSelection,
    RoutingPolicy,
    Automatic,
}

#[derive(Debug)]
pub(crate) struct ResolvedProviderAuth {
    pub status: ProviderAuthStatus,
    credential: ResolvedProviderCredential,
}

impl ResolvedProviderAuth {
    pub(crate) fn into_api_key(self) -> Option<String> {
        match self.credential {
            ResolvedProviderCredential::Key(api_key) => Some(api_key),
            _ => None,
        }
    }
}

#[derive(Debug)]
enum ResolvedProviderCredential {
    Key(String),
    /// Known to exist, value deliberately not read.
    Present,
    NeedsUserApproval,
    Missing,
    NotRequired,
    Deferred,
    /// Platform-managed, and its client's offline prerequisites do not resolve.
    PlatformUnconfigured(super::providers::PlatformPrerequisiteGap),
    ResolutionError(VmError),
}

/// Resolve one provider's usability through the exact credential path used by
/// dispatch. The returned status never contains secret material.
///
/// A status is a presence question, so it is answered without reading any
/// stored secret: a `secret_store` grant or a secret reference is checked for
/// existence only. On macOS reading a value can raise a Keychain dialog, and a
/// status walk visits every provider.
pub fn provider_auth_status(provider: &str) -> ProviderAuthStatus {
    let definition = llm_config::provider_config(provider);
    resolve_provider_auth_with_definition(provider, definition.as_ref(), CredentialRead::Presence)
        .status
}

/// Resolve all configured and runtime-registered providers in stable name order.
pub fn provider_auth_statuses() -> Vec<ProviderAuthStatus> {
    super::provider::register_default_providers();
    let mut names: std::collections::BTreeSet<String> =
        llm_config::provider_names().into_iter().collect();
    names.extend(super::provider::registered_provider_names());
    names
        .into_iter()
        .map(|name| provider_auth_status(&name))
        .collect()
}

pub fn available_provider_names() -> Vec<String> {
    llm_config::provider_names()
        .into_iter()
        .filter(|provider| provider_auth_status(provider).available)
        .collect()
}

pub(crate) fn provider_auth_status_with_definition(
    provider: &str,
    definition: &ProviderDef,
) -> ProviderAuthStatus {
    resolve_provider_auth_with_definition(provider, Some(definition), CredentialRead::Presence)
        .status
}

pub(crate) fn resolve_provider_auth(provider: &str) -> ResolvedProviderAuth {
    let definition = llm_config::provider_config(provider);
    resolve_provider_auth_with_definition(provider, definition.as_ref(), CredentialRead::Value)
}

/// Whether a resolution needs the credential itself or only whether it exists.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CredentialRead {
    Value,
    Presence,
}

fn resolve_provider_auth_with_definition(
    provider: &str,
    definition: Option<&ProviderDef>,
    read: CredentialRead,
) -> ResolvedProviderAuth {
    let name = provider.to_string();
    let credential = if provider == "mock"
        || provider == "fake"
        || super::mock::cli_llm_mock_replay_active()
        || super::mock::builtin_llm_mock_active()
    {
        ResolvedProviderCredential::NotRequired
    } else if let Some(definition) = definition {
        if definition.is_credential_resolution_platform_managed() {
            match super::providers::platform_offline_prerequisites(provider) {
                Ok(()) => ResolvedProviderCredential::Deferred,
                Err(gap) => ResolvedProviderCredential::PlatformUnconfigured(gap),
            }
        } else if definition.auth_style == "none"
            || matches!(definition.auth_env, llm_config::AuthEnv::None)
        {
            ResolvedProviderCredential::NotRequired
        } else {
            probe_credential(Some(definition), read)
        }
    } else {
        probe_credential(None, read)
    };
    let (available, credential_status) = match &credential {
        ResolvedProviderCredential::Key(_) | ResolvedProviderCredential::Present => {
            (true, ProviderCredentialStatus::Ok)
        }
        ResolvedProviderCredential::NeedsUserApproval => {
            (false, ProviderCredentialStatus::NeedsUserApproval)
        }
        ResolvedProviderCredential::Missing | ResolvedProviderCredential::ResolutionError(_) => {
            (false, ProviderCredentialStatus::Missing)
        }
        ResolvedProviderCredential::NotRequired => (true, ProviderCredentialStatus::NotRequired),
        ResolvedProviderCredential::Deferred => (true, ProviderCredentialStatus::Deferred),
        ResolvedProviderCredential::PlatformUnconfigured(gap) => (false, (*gap).into()),
    };
    ResolvedProviderAuth {
        status: ProviderAuthStatus {
            name,
            available,
            credential_status,
        },
        credential,
    }
}

fn probe_credential(
    definition: Option<&ProviderDef>,
    read: CredentialRead,
) -> ResolvedProviderCredential {
    match read {
        CredentialRead::Value => resolved_credential_from_probe(probe_api_key(definition)),
        CredentialRead::Presence => probe_credential_presence(definition),
    }
}

/// [`probe_api_key`] without reading a stored secret.
fn probe_credential_presence(definition: Option<&ProviderDef>) -> ResolvedProviderCredential {
    let envs: Vec<&str> = match definition.map(|definition| &definition.auth_env) {
        None => vec!["ANTHROPIC_API_KEY"],
        Some(llm_config::AuthEnv::None) => return ResolvedProviderCredential::NotRequired,
        Some(llm_config::AuthEnv::Single(env)) => vec![env.as_str()],
        Some(llm_config::AuthEnv::Multiple(envs)) => envs.iter().map(String::as_str).collect(),
    };
    let mut needs_approval = false;
    for env in envs {
        let raw = match crate::stdlib::process::session_env_presence(env) {
            Ok(Some(raw)) if !raw.is_empty() => raw,
            // A policy error reads as unset, exactly as `session_auth_env`
            // treats it on the value path.
            Ok(_) | Err(crate::stdlib::process::SessionEnvPresenceError::Policy) => continue,
            Err(crate::stdlib::process::SessionEnvPresenceError::NeedsUserApproval) => {
                needs_approval = true;
                continue;
            }
        };
        // Matches `probe_api_key`: the first variable that is set decides.
        return match crate::secrets::secret_ref_is_present(&raw) {
            Ok(None) | Ok(Some(true)) => ResolvedProviderCredential::Present,
            Ok(Some(false)) => ResolvedProviderCredential::Missing,
            Err(error) if error.needs_user_approval() => {
                ResolvedProviderCredential::NeedsUserApproval
            }
            Err(error) => ResolvedProviderCredential::ResolutionError(missing_key_error(format!(
                "Failed to check API key secret reference from {env}: {error}"
            ))),
        };
    }
    if needs_approval {
        ResolvedProviderCredential::NeedsUserApproval
    } else {
        ResolvedProviderCredential::Missing
    }
}

fn resolved_credential_from_probe(
    result: Result<Option<String>, ProviderCredentialError>,
) -> ResolvedProviderCredential {
    match result {
        Ok(Some(api_key)) => ResolvedProviderCredential::Key(api_key),
        Ok(None) => ResolvedProviderCredential::NotRequired,
        Err(ProviderCredentialError::Missing) => ResolvedProviderCredential::Missing,
        Err(ProviderCredentialError::Resolution(error)) => {
            ResolvedProviderCredential::ResolutionError(error)
        }
    }
}

/// Resolve the provider credential used by dispatch.
pub fn resolve_api_key(provider: &str) -> Result<String, VmError> {
    resolve_api_key_for_selection(provider, inferred_provider_selection_source(provider))
}

pub(crate) fn resolve_api_key_for_selection(
    provider: &str,
    source: ProviderSelectionSource,
) -> Result<String, VmError> {
    let definition = llm_config::provider_config(provider);
    resolve_api_key_with_definition(provider, definition.as_ref(), source)
}

fn resolve_api_key_with_definition(
    provider: &str,
    definition: Option<&ProviderDef>,
    source: ProviderSelectionSource,
) -> Result<String, VmError> {
    let selection_hint = provider_selection_hint(provider, source);

    match resolve_provider_auth_with_definition(provider, definition, CredentialRead::Value)
        .credential
    {
        ResolvedProviderCredential::Key(api_key) => Ok(api_key),
        // A platform-managed client still owns the live answer: its chain also
        // reaches sources only the network can (instance metadata), and it
        // raises its own typed error when nothing resolves. Availability is
        // what reads the offline gap; an explicit dispatch is not refused here.
        ResolvedProviderCredential::NotRequired
        | ResolvedProviderCredential::Deferred
        | ResolvedProviderCredential::PlatformUnconfigured(_) => Ok(String::new()),
        ResolvedProviderCredential::ResolutionError(error) => Err(error),
        // Presence reads only; a value read never produces either.
        ResolvedProviderCredential::Present | ResolvedProviderCredential::NeedsUserApproval => {
            Err(missing_key_error(format!(
                "{provider} credential was checked for presence where its value was needed"
            )))
        }
        ResolvedProviderCredential::Missing => {
            if let Some(definition) = definition {
                let aggregate_hint = no_credentials_message();
                let requirement = match &definition.auth_env {
                    llm_config::AuthEnv::Single(env) => {
                        format!("set {env} environment variable")
                    }
                    llm_config::AuthEnv::Multiple(envs) => {
                        format!("set one of {} environment variables", envs.join(", "))
                    }
                    llm_config::AuthEnv::None => return Ok(String::new()),
                };
                Err(missing_key_error(format!(
                    "Missing API key: {requirement}{selection_hint}\n{aggregate_hint}"
                )))
            } else {
                let aggregate_hint = no_credentials_message();
                Err(missing_key_error(format!(
                    "Missing API key: set ANTHROPIC_API_KEY environment variable{selection_hint}\n{aggregate_hint}"
                )))
            }
        }
    }
}

pub(crate) fn inferred_provider_selection_source(provider: &str) -> ProviderSelectionSource {
    if crate::stdlib::process::session_env_value("HARN_LLM_PROVIDER")
        .is_some_and(|selected| selected == provider)
    {
        ProviderSelectionSource::Environment
    } else if crate::stdlib::process::session_env_value("HARN_DEFAULT_PROVIDER")
        .is_some_and(|selected| selected.trim() == provider)
    {
        ProviderSelectionSource::DefaultEnvironment
    } else if llm_config::load_config()
        .default_provider
        .as_deref()
        .is_some_and(|selected| selected.trim() == provider)
    {
        ProviderSelectionSource::ConfiguredDefault
    } else {
        ProviderSelectionSource::Automatic
    }
}

fn provider_selection_hint(provider: &str, source: ProviderSelectionSource) -> String {
    let selected_via = match source {
        ProviderSelectionSource::CallOption => "the llm_call `provider` option".to_string(),
        ProviderSelectionSource::Environment => "HARN_LLM_PROVIDER".to_string(),
        ProviderSelectionSource::DefaultEnvironment => "HARN_DEFAULT_PROVIDER".to_string(),
        ProviderSelectionSource::ConfiguredDefault => {
            let paths = llm_config::loaded_config_paths();
            if paths.is_empty() {
                "the built-in configured default".to_string()
            } else {
                format!(
                    "the configured default (provider config loaded from {})",
                    paths
                        .iter()
                        .map(|path| path.display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
        }
        ProviderSelectionSource::ModelSelection => "the selected model".to_string(),
        ProviderSelectionSource::RoutingPolicy => "the routing policy".to_string(),
        ProviderSelectionSource::Automatic => "the automatic provider preference order".to_string(),
    };
    format!(
        " (provider '{provider}' selected via {selected_via}; set HARN_LLM_PROVIDER=mock to run \
         without a provider)"
    )
}

#[derive(Debug)]
enum ProviderCredentialError {
    Missing,
    Resolution(VmError),
}

/// Read one credential-bearing variable through the session environment rather
/// than the raw process environment.
///
/// Under an isolated policy no credential resolves — that is what makes an eval
/// run reproducible instead of quietly picking up the launcher's key. Under a
/// granted policy, a declared variable resolves to the granted value, so harn's
/// own `llm_call` can use it.
///
/// A grant-resolution failure (an unresolvable `secret_store` pointer) is a
/// missing credential from this path's point of view; `resolve_api_key` renders
/// the same loud "Missing API key" guidance it renders for an unset variable,
/// and the spawn boundary still reports the underlying `MissingSecret`.
fn session_auth_env(name: &str) -> Option<String> {
    crate::stdlib::process::session_env_var(name)
        .ok()
        .flatten()
        .filter(|value| !value.is_empty())
}

fn probe_api_key(
    definition: Option<&ProviderDef>,
) -> Result<Option<String>, ProviderCredentialError> {
    let Some(definition) = definition else {
        return session_auth_env("ANTHROPIC_API_KEY")
            .map(Some)
            .ok_or(ProviderCredentialError::Missing);
    };
    match &definition.auth_env {
        llm_config::AuthEnv::None => Ok(None),
        llm_config::AuthEnv::Single(env) => {
            let raw = session_auth_env(env).ok_or(ProviderCredentialError::Missing)?;
            resolve_auth_env_value(env, &raw)
                .map_err(ProviderCredentialError::Resolution)
                .map(Some)
        }
        llm_config::AuthEnv::Multiple(envs) => {
            for env in envs {
                let Some(raw) = session_auth_env(env) else {
                    continue;
                };
                return resolve_auth_env_value(env, &raw)
                    .map_err(ProviderCredentialError::Resolution)
                    .map(Some);
            }
            Err(ProviderCredentialError::Missing)
        }
    }
}

fn missing_key_error(message: String) -> VmError {
    VmError::Thrown(VmValue::String(arcstr::ArcStr::from(message)))
}

fn resolve_auth_env_value(env_name: &str, raw: &str) -> Result<String, VmError> {
    match crate::secrets::resolve_secret_ref_to_string(raw) {
        Ok(Some(secret)) => Ok(secret),
        Ok(None) => Ok(raw.to_string()),
        Err(error) => Err(missing_key_error(format!(
            "Failed to resolve API key secret reference from {env_name}: {error}"
        ))),
    }
}

/// Canonical documentation entry point for provider credential setup.
pub const PROVIDER_SETUP_DOCS_URL: &str = "https://harnlang.com/provider-setup.html";

/// Whether this provider needs a credential at all. Local servers such as
/// Ollama declare `auth_style = "none"` and are usable with no key.
fn requires_credential(provider: &str) -> bool {
    llm_config::provider_config(provider).is_some_and(|definition| definition.auth_style != "none")
}

/// Credential env vars accepted by the named providers, in their order, with
/// duplicates removed. Providers that need no key contribute nothing.
///
/// `primary_only` keeps just the first variable each provider accepts. A
/// provider that takes alternatives (Gemini reads `GEMINI_API_KEY` or
/// `GOOGLE_API_KEY`) would otherwise spend two slots in a short list to say
/// one thing; `harn doctor` and the docs still name every alternative.
fn credential_env_names(providers: &[String], primary_only: bool) -> Vec<String> {
    let mut envs: Vec<String> = Vec::new();
    for name in providers {
        let Some(definition) = llm_config::provider_config(name) else {
            continue;
        };
        if definition.auth_style == "none" {
            continue;
        }
        let accepted = llm_config::auth_env_names(&definition.auth_env);
        let accepted = if primary_only {
            accepted.into_iter().take(1).collect()
        } else {
            accepted
        };
        for env in accepted {
            if !envs.contains(&env) {
                envs.push(env);
            }
        }
    }
    envs
}

/// Build the canonical no-credentials guidance from the live catalog.
///
/// The catalog carries dozens of providers, and printing every accepted
/// variable buries the one thing a reader needs: a name they recognise and a
/// next step. So this names the catalog's curated short list, says how many
/// other providers exist, and points at the two places that hold the complete
/// answer — `harn doctor` locally and the setup guide online. The short list
/// is catalog data, not a literal here, so the curated set keeps one owner.
pub fn no_credentials_message() -> String {
    let all_providers = llm_config::provider_names();
    let featured = llm_config::featured_provider_names();

    // An overlay can suppress every featured provider. Falling back to the
    // full catalog keeps the message useful instead of empty.
    let shown_envs = match credential_env_names(&featured, true) {
        envs if envs.is_empty() => credential_env_names(&all_providers, false),
        envs => envs,
    };
    if shown_envs.is_empty() {
        return format!(
            "No LLM providers are declared in the loaded catalog. Add one, then read \
             {PROVIDER_SETUP_DOCS_URL}."
        );
    }

    let featured_keyed = featured
        .iter()
        .filter(|name| requires_credential(name))
        .count();
    let catalog_keyed = all_providers
        .iter()
        .filter(|name| requires_credential(name))
        .count();
    let remaining = catalog_keyed.saturating_sub(featured_keyed);
    let more_hint = if remaining == 0 {
        String::new()
    } else {
        format!(" Harn supports {remaining} more providers.")
    };

    let keyless: Vec<String> = featured
        .iter()
        .filter(|name| !requires_credential(name))
        .map(|name| format!("`{name}`"))
        .collect();
    let keyless_hint = if keyless.is_empty() {
        String::new()
    } else {
        format!(" {} runs locally and needs no key.", keyless.join(" and "))
    };

    format!(
        "No LLM provider credentials found. Set one of these environment variables to an API key \
         or a harn-secret://namespace/name reference: {envs}.{keyless_hint}{more_hint} \
         Run `harn doctor` to print every provider and the variable it reads, or read \
         {PROVIDER_SETUP_DOCS_URL}. `harn models recommend` suggests a setup for this machine.",
        envs = shown_envs.join(", "),
    )
}

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

    struct ScopedEnv {
        name: &'static str,
        previous: Option<String>,
    }

    impl ScopedEnv {
        fn set(name: &'static str, value: &str) -> Self {
            let previous = std::env::var(name).ok();
            unsafe { std::env::set_var(name, value) };
            Self { name, previous }
        }

        fn unset(name: &'static str) -> Self {
            let previous = std::env::var(name).ok();
            unsafe { std::env::remove_var(name) };
            Self { name, previous }
        }
    }

    impl Drop for ScopedEnv {
        fn drop(&mut self) {
            unsafe {
                match &self.previous {
                    Some(value) => std::env::set_var(self.name, value),
                    None => std::env::remove_var(self.name),
                }
            }
        }
    }

    #[test]
    fn typed_status_covers_each_credential_resolution_class() {
        let _guard = crate::llm::env_guard();
        let _anthropic = ScopedEnv::unset("ANTHROPIC_API_KEY");
        let _azure_key = ScopedEnv::unset("AZURE_OPENAI_API_KEY");
        let _azure_token = ScopedEnv::unset("AZURE_OPENAI_AD_TOKEN");
        let _azure_bearer = ScopedEnv::unset("AZURE_OPENAI_BEARER_TOKEN");
        let _aws_region = ScopedEnv::set("AWS_REGION", "us-east-1");
        let _aws_key = ScopedEnv::set("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE");
        let _aws_secret = ScopedEnv::set("AWS_SECRET_ACCESS_KEY", "example-secret");

        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Missing
        );
        assert_eq!(
            provider_auth_status("ollama").credential_status,
            ProviderCredentialStatus::NotRequired
        );
        assert_eq!(
            provider_auth_status("bedrock").credential_status,
            ProviderCredentialStatus::Deferred
        );
        assert_eq!(
            provider_auth_status("vertex").credential_status,
            ProviderCredentialStatus::Deferred
        );
        assert_eq!(resolve_api_key("bedrock").unwrap(), "");
        assert_eq!(resolve_api_key("vertex").unwrap(), "");
        assert!(resolve_api_key("azure_openai").is_err());
    }

    #[test]
    fn bedrock_is_unavailable_until_its_offline_prerequisites_resolve() {
        let _guard = crate::llm::env_guard();
        let mut env = crate::llm::test_env::UnconfiguredProviderEnv::new();

        let status = provider_auth_status("bedrock");
        assert!(!status.available, "{status:?}");
        assert_eq!(status.credential_status.as_str(), "region_unconfigured");

        env.set("AWS_REGION", "us-east-1");
        let status = provider_auth_status("bedrock");
        assert!(!status.available, "{status:?}");
        assert_eq!(
            status.credential_status.as_str(),
            "credentials_unconfigured"
        );

        // Negative control: a region and a key pair make it eligible again.
        env.set("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE");
        env.set("AWS_SECRET_ACCESS_KEY", "example-secret");
        let status = provider_auth_status("bedrock");
        assert!(status.available, "{status:?}");
        assert_eq!(status.credential_status.as_str(), "deferred");
    }

    #[test]
    fn bedrock_prerequisites_resolve_from_shared_files_and_container_env() {
        let _guard = crate::llm::env_guard();
        let mut env = crate::llm::test_env::UnconfiguredProviderEnv::new();
        let dir = env.aws_dir().to_path_buf();
        std::fs::write(
            dir.join("config"),
            "[profile work]\nregion = eu-west-1\n[default]\noutput = json\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("credentials"),
            "[work]\naws_access_key_id = AKIDEXAMPLE\naws_secret_access_key = example\n",
        )
        .unwrap();

        // The default profile has neither a region nor a credential.
        assert_eq!(
            provider_auth_status("bedrock").credential_status.as_str(),
            "region_unconfigured"
        );
        env.set("AWS_PROFILE", "work");
        assert!(provider_auth_status("bedrock").available);

        // A container credential endpoint is a credential source on its own.
        std::fs::write(dir.join("credentials"), "").unwrap();
        assert_eq!(
            provider_auth_status("bedrock").credential_status.as_str(),
            "credentials_unconfigured"
        );
        env.set(
            "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
            "/v2/credentials/id",
        );
        assert!(provider_auth_status("bedrock").available);
    }

    #[test]
    fn missing_credential_diagnostic_names_the_actual_selection_authority() {
        let _guard = crate::llm::env_guard();
        let env = crate::test_env::test_env_guard();
        env.set("HARN_LLM_PROVIDER", "anthropic");
        let _missing_key = ScopedEnv::unset("ANTHROPIC_API_KEY");

        let message = match resolve_api_key("anthropic").unwrap_err() {
            VmError::Thrown(VmValue::String(message)) => message.to_string(),
            other => format!("{other:?}"),
        };
        assert!(
            message.contains("provider 'anthropic' selected via HARN_LLM_PROVIDER"),
            "got: {message}"
        );
        assert!(!message.contains(" or the provider catalog"));
        assert!(!message.contains("<built-in defaults>"));
    }

    #[test]
    fn selection_hints_name_only_the_authority_that_fired() {
        let explicit = provider_selection_hint("openai", ProviderSelectionSource::CallOption);
        assert!(explicit.contains("selected via the llm_call `provider` option"));
        assert!(!explicit.contains("config loaded from"));

        let automatic = provider_selection_hint("openai", ProviderSelectionSource::Automatic);
        assert!(automatic.contains("selected via the automatic provider preference order"));
        assert!(!automatic.contains("config loaded from"));

        let configured =
            provider_selection_hint("anthropic", ProviderSelectionSource::ConfiguredDefault);
        if llm_config::loaded_config_paths().is_empty() {
            assert!(configured.contains("selected via the built-in configured default"));
            assert!(!configured.contains("config loaded from"));
        } else {
            assert!(configured.contains("configured default (provider config loaded from"));
        }
    }

    #[test]
    fn credential_authority_matrix_is_fail_closed_and_secret_free() {
        let _guard = crate::llm::env_guard();
        const SECRET: &str = "sk-authority-matrix-sentinel";

        let allowed_key = ScopedEnv::set("ANTHROPIC_API_KEY", SECRET);
        assert_eq!(resolve_api_key("anthropic").unwrap(), SECRET, "allowed");
        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Ok
        );

        {
            let _environment =
                ScopedEnvironment::install(crate::security::SessionEnvironment::isolated());
            let error = resolve_api_key("anthropic").unwrap_err().to_string();
            assert!(error.contains("Missing API key"), "denied: {error}");
            assert!(!error.contains(SECRET), "denied diagnostic leaked the key");
        }

        drop(allowed_key);
        let missing_key = ScopedEnv::unset("ANTHROPIC_API_KEY");
        let missing = resolve_api_key("anthropic").unwrap_err().to_string();
        assert!(missing.contains("Missing API key"), "missing: {missing}");
        assert!(!missing.contains(SECRET));

        drop(missing_key);
        let _malformed_key = ScopedEnv::set("ANTHROPIC_API_KEY", "harn-secret://malformed");
        let malformed = resolve_api_key("anthropic").unwrap_err().to_string();
        assert!(
            malformed.contains("Failed to resolve API key secret reference"),
            "malformed: {malformed}"
        );
        assert!(!malformed.contains(SECRET));
        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Missing
        );
    }

    #[test]
    fn status_and_dispatch_resolve_the_same_secret_reference_without_caching() {
        let _guard = crate::llm::env_guard();
        let _providers = ScopedEnv::set("HARN_SECRET_PROVIDERS", "env");
        let _reference = ScopedEnv::set(
            "ANTHROPIC_API_KEY",
            "harn-secret://provider/anthropic-api-key",
        );
        let secret = ScopedEnv::set("HARN_SECRET_PROVIDER_ANTHROPIC_API_KEY", "sk-from-ref");

        assert_eq!(resolve_api_key("anthropic").unwrap(), "sk-from-ref");
        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Ok
        );

        drop(secret);
        let _missing = ScopedEnv::unset("HARN_SECRET_PROVIDER_ANTHROPIC_API_KEY");
        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Missing
        );
        let error = resolve_api_key("anthropic").unwrap_err();
        let message = match error {
            VmError::Thrown(VmValue::String(message)) => message.to_string(),
            other => format!("{other:?}"),
        };
        assert!(
            message.contains("Failed to resolve API key secret reference from ANTHROPIC_API_KEY")
        );
        assert!(message.contains("provider/anthropic-api-key"));
        assert!(!message.contains("sk-from-ref"));
    }

    #[test]
    fn harness_session_provider_resolves_reference_without_global_secret_state() {
        let _guard = crate::llm::env_guard();
        let _reference = ScopedEnv::set(
            "ANTHROPIC_API_KEY",
            "harn-secret://burin.provider-auth/anthropic-api-key",
        );
        let _providers = ScopedEnv::set("HARN_SECRET_PROVIDERS", "env");
        let _global_secret = ScopedEnv::unset("HARN_SECRET_BURIN_PROVIDER_AUTH_ANTHROPIC_API_KEY");
        let provider = crate::secrets::MemorySecretProvider::new("burin-session").with_secret(
            crate::secrets::SecretId::new("burin.provider-auth", "anthropic-api-key"),
            "sk-process-local",
        );

        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime")
            .block_on(crate::secrets::with_active_secret_provider(
                Some(std::sync::Arc::new(provider)),
                async {
                    assert_eq!(resolve_api_key("anthropic").unwrap(), "sk-process-local");
                    assert_eq!(
                        provider_auth_status("anthropic").credential_status,
                        ProviderCredentialStatus::Ok
                    );
                },
            ));

        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Missing,
            "the process-local provider must not escape its task"
        );
    }

    /// Install a environment policy for the duration of a test and clear it on
    /// drop, so a panicking assertion cannot leak a profile into a sibling test
    /// sharing the thread.
    struct ScopedEnvironment;

    impl ScopedEnvironment {
        fn install(environment: crate::security::SessionEnvironment) -> Self {
            crate::stdlib::process::set_session_environment(Some(environment));
            Self
        }
    }

    impl Drop for ScopedEnvironment {
        fn drop(&mut self) {
            crate::stdlib::process::set_session_environment(None);
        }
    }

    #[test]
    fn isolated_policy_hides_the_launcher_key_from_dispatch() {
        // The launcher has a key; the session is isolated. Harn's own credential
        // path must not see it, or a "no credentials" eval silently runs against
        // whatever the operator happened to have exported.
        let _guard = crate::llm::env_guard();
        let _key = ScopedEnv::set("ANTHROPIC_API_KEY", "sk-launcher");

        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Ok,
            "outside a session, bootstrap reads still use the process env"
        );

        let _environment =
            ScopedEnvironment::install(crate::security::SessionEnvironment::isolated());
        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Missing,
            "isolated must close the in-process credential path, not just subprocess env"
        );
        let message = match resolve_api_key("anthropic").unwrap_err() {
            VmError::Thrown(VmValue::String(message)) => message.to_string(),
            other => format!("{other:?}"),
        };
        assert!(message.contains("Missing API key"));
        assert!(!message.contains("sk-launcher"), "error leaked the key");
    }

    #[test]
    fn lane_grant_reaches_harns_own_dispatch() {
        // A granted policy must make its provider key usable
        // for its own llm_call, not only hand it to subprocesses. The launcher
        // variable here is deliberately NOT the provider's auth env var, so the
        // key can only arrive through the grant's `expose_as_env`.
        use crate::security::{
            EnvironmentPolicyKind, GrantSourceSpec, GrantSpec, SessionEnvironment,
        };

        let _guard = crate::llm::env_guard();
        let _absent = ScopedEnv::unset("ANTHROPIC_API_KEY");
        let _source = ScopedEnv::set("LAUNCHER_ANTHROPIC_SECRET", "sk-granted");

        let granted = SessionEnvironment::launch(
            EnvironmentPolicyKind::Granted,
            vec![GrantSpec {
                name: "anthropic".to_string(),
                source: GrantSourceSpec::Env {
                    var: "LAUNCHER_ANTHROPIC_SECRET".to_string(),
                },
                expose_as_env: Some("ANTHROPIC_API_KEY".to_string()),
                for_command: None,
                expose_to: Default::default(),
            }],
            &|name| std::env::var(name).ok(),
        )
        .expect("granted policy launch");
        let _environment = ScopedEnvironment::install(granted);

        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Ok
        );
        assert_eq!(resolve_api_key("anthropic").unwrap(), "sk-granted");
    }

    /// A secret store that counts value reads and answers presence from a
    /// fixed verdict, standing in for a macOS Keychain where a value read is
    /// the dialog and an attribute search is not.
    struct ReadCountingStore {
        reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        presence: fn(&crate::secrets::SecretId) -> Result<bool, crate::secrets::SecretError>,
    }

    #[async_trait::async_trait]
    impl crate::secrets::SecretProvider for ReadCountingStore {
        async fn get(
            &self,
            _id: &crate::secrets::SecretId,
        ) -> Result<crate::secrets::SecretBytes, crate::secrets::SecretError> {
            self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(crate::secrets::SecretBytes::from("sk-stored"))
        }
        async fn contains(
            &self,
            id: &crate::secrets::SecretId,
        ) -> Result<bool, crate::secrets::SecretError> {
            (self.presence)(id)
        }
        async fn put(
            &self,
            _id: &crate::secrets::SecretId,
            _value: crate::secrets::SecretBytes,
        ) -> Result<(), crate::secrets::SecretError> {
            unreachable!("status never writes")
        }
        async fn rotate(
            &self,
            _id: &crate::secrets::SecretId,
        ) -> Result<crate::secrets::RotationHandle, crate::secrets::SecretError> {
            unreachable!("status never rotates")
        }
        async fn list(
            &self,
            _prefix: &crate::secrets::SecretId,
        ) -> Result<Vec<crate::secrets::SecretMeta>, crate::secrets::SecretError> {
            Ok(Vec::new())
        }
        fn namespace(&self) -> &'static str {
            "read-counting"
        }
        fn supports_versions(&self) -> bool {
            false
        }
    }

    fn secret_store_grant() -> crate::security::SessionEnvironment {
        use crate::security::{
            EnvironmentPolicyKind, GrantSourceSpec, GrantSpec, SessionEnvironment,
        };
        SessionEnvironment::launch(
            EnvironmentPolicyKind::Granted,
            vec![GrantSpec {
                name: "anthropic".to_string(),
                source: GrantSourceSpec::SecretStore {
                    account: "burin.provider_auth".to_string(),
                    key: "anthropic_api_key".to_string(),
                },
                expose_as_env: Some("ANTHROPIC_API_KEY".to_string()),
                for_command: None,
                expose_to: Default::default(),
            }],
            &|name| std::env::var(name).ok(),
        )
        .expect("granted policy launch")
    }

    fn with_store<T>(store: ReadCountingStore, check: impl FnOnce() -> T) -> T {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("test runtime")
            .block_on(crate::secrets::with_active_secret_provider(
                Some(std::sync::Arc::new(store)),
                async { check() },
            ))
    }

    /// Status is a presence question and must not read the stored value.
    ///
    /// A status walk visits every provider, and on macOS each value read of a
    /// Keychain item is an access dialog for any binary not on the item's
    /// ACL, which is every freshly built one. The negative control is the
    /// dispatch read in the same test: the store does count value reads, so a
    /// status path that read the value could not report zero.
    #[test]
    fn status_of_a_stored_grant_reads_no_secret_and_dispatch_does() {
        let _guard = crate::llm::env_guard();
        let _absent = ScopedEnv::unset("ANTHROPIC_API_KEY");
        let _environment = ScopedEnvironment::install(secret_store_grant());
        let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let store = ReadCountingStore {
            reads: std::sync::Arc::clone(&reads),
            presence: |_| Ok(true),
        };
        with_store(store, || {
            let status = provider_auth_status("anthropic");
            assert_eq!(status.credential_status, ProviderCredentialStatus::Ok);
            assert!(status.available);
            let statuses = provider_auth_statuses();
            assert!(statuses
                .iter()
                .any(|status| status.name == "anthropic" && status.available));
            assert_eq!(
                reads.load(std::sync::atomic::Ordering::SeqCst),
                0,
                "a status question read a stored secret"
            );

            assert_eq!(resolve_api_key("anthropic").unwrap(), "sk-stored");
            assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 1);
        });
    }

    /// A store that could only answer through a dialog this process will not
    /// show reports a typed state, not "missing" and not a prompt.
    #[test]
    fn a_store_that_needs_approval_is_reported_as_such() {
        let _guard = crate::llm::env_guard();
        let _absent = ScopedEnv::unset("ANTHROPIC_API_KEY");
        let _environment = ScopedEnvironment::install(secret_store_grant());
        let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let store = ReadCountingStore {
            reads: std::sync::Arc::clone(&reads),
            presence: |id| {
                Err(crate::secrets::SecretError::NeedsUserApproval {
                    provider: "keyring".to_string(),
                    id: id.clone(),
                })
            },
        };
        with_store(store, || {
            let status = provider_auth_status("anthropic");
            assert_eq!(
                status.credential_status,
                ProviderCredentialStatus::NeedsUserApproval
            );
            assert!(!status.available);
            assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0);
        });
    }

    #[test]
    fn an_empty_auth_variable_is_a_missing_credential() {
        // An exported-but-empty key is not a credential. The multi-var branch
        // always skipped empties; the single-var branch now agrees, so a blank
        // export fails loudly at resolution instead of reaching a provider as an
        // empty bearer token.
        let _guard = crate::llm::env_guard();
        let _blank = ScopedEnv::set("ANTHROPIC_API_KEY", "");
        assert_eq!(
            provider_auth_status("anthropic").credential_status,
            ProviderCredentialStatus::Missing
        );
        assert!(resolve_api_key("anthropic").is_err());
    }

    #[test]
    fn status_serialization_is_stable_and_secret_free() {
        let status = ProviderAuthStatus {
            name: "example".to_string(),
            available: true,
            credential_status: ProviderCredentialStatus::Deferred,
        };
        assert_eq!(
            serde_json::to_value(status).unwrap(),
            serde_json::json!({
                "name": "example",
                "available": true,
                "credential_status": "deferred",
            })
        );
    }

    #[test]
    fn available_provider_names_uses_dispatch_semantics() {
        let _guard = crate::llm::env_guard();
        let _vertex_token = ScopedEnv::unset("VERTEX_AI_ACCESS_TOKEN");
        let _google_token = ScopedEnv::unset("GOOGLE_OAUTH_ACCESS_TOKEN");
        let _google_credentials = ScopedEnv::unset("GOOGLE_APPLICATION_CREDENTIALS");
        let _aws_region = ScopedEnv::set("AWS_REGION", "us-east-1");
        let _aws_key = ScopedEnv::set("AWS_ACCESS_KEY_ID", "AKIDEXAMPLE");
        let _aws_secret = ScopedEnv::set("AWS_SECRET_ACCESS_KEY", "example-secret");

        let available = available_provider_names();
        assert!(available.iter().any(|name| name == "bedrock"));
        assert!(available.iter().any(|name| name == "vertex"));
    }
}