ag-agent 0.20.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! Host configuration, provider credentials, and per-turn harness assembly.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fmt::Display;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use std::{env, io};

use ag_contracts::{PermissionMode, ProviderCallBudget, ReasoningLevel};
use ag_harness::bash::{BashConfig, UnsandboxedExecutor};
use ag_harness::catalog::{Capabilities, ModelCatalog, ModelId, ModelSelector, ModelSpec};
use ag_harness::lifecycle::{LifecycleObserver, LifecycleObserverSet, LifecycleTraceObserver};
use ag_harness::model::{
    ModelClient, ModelCompletion, ModelMetadata, ModelProfile, ModelRegistry, ModelRequest,
    ReasoningEffort,
};
use ag_harness::provider::{
    ChatGptConfig, CostTier, LocalServerKind, ModelConfiguration, ModelProvider,
    chatgpt_auth_file_in,
};
use ag_harness::{
    Harness, Model, ModelError, OutputSchema, Repository, RepositoryError, RunRequest, ToolSet,
    TurnInput,
};
use ag_protocol::{ProtocolRequestProfile, SchemaRequiredPolicy, protocol_output_schema};
use ag_session::{
    AgentKind, AgentModel, HarnessModelOption, HarnessModelStatus, MINIMUM_RUNNING_CONTEXT_WINDOW,
    ModelCost, ServedModel,
};
use ag_telemetry::{Context, TraceContextExt as _};
use async_trait::async_trait;

use crate::agent::model_profile;

/// Revision of Agentty's harness model registrations. Durable sessions record
/// it and require the same value on resume.
///
/// Image input joined the declared capabilities without a new revision: the
/// harness weighs that capability only for image-bearing input, which
/// Agentty rejects before a harness turn, so recorded sessions and text
/// retries are unaffected while older sessions keep resuming.
const REGISTRATION_REVISION: &str = "agentty-native-2";
/// Conservative profile for a harness model without a declared profile. Its
/// default estimator runs up to 46% under dense content and further under
/// small requests whose fixed provider cost it never weighs.
const FALLBACK_MODEL_PROFILE: ModelProfile =
    ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
/// Placeholder endpoint for resume-only registrations, which never send
/// requests.
const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
/// SQLite file holding one session's durable harness history.
const SESSION_DATABASE_FILE: &str = "harness.db";
/// Trusted Bash executable used by edit-mode `bash` calls.
const BASH_EXECUTABLE: &str = "/bin/bash";
/// Nonsecret identity of the unsandboxed Bash policy.
const BASH_POLICY_REVISION: &str = "agentty-unsandboxed-1";
/// Deadline for one `bash` call.
const BASH_TIMEOUT: Duration = Duration::from_secs(600);
/// Environment variable naming the model the OpenAI-compatible server serves
/// for [`AgentModel::OpenAiCompatible`], such as Ollama's `qwen3:latest`.
const OPENAI_COMPATIBLE_MODEL_ENV: &str = "OPENAI_COMPATIBLE_MODEL";
/// Command that stores the sign-in [`ModelProvider::ChatGpt`] needs.
const CHATGPT_SIGN_IN_COMMAND: &str = "ag-harness login chatgpt";
/// Environment variable naming Agentty's data directory, `~/.agentty` by
/// default.
const AGENTTY_ROOT_ENV: &str = "AGENTTY_ROOT";
/// Environment prefixes that carry provider keys, credential files, and
/// endpoints, withheld from `bash`. `OPENAI_` covers both `OpenAI` and
/// OpenAI-compatible variables.
const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 6] = [
    "ANTHROPIC_",
    "CHATGPT_",
    "DASHSCOPE_",
    "KIMI_",
    "MODEL_",
    "OPENAI_",
];
/// Variables granted to `bash` first, so the harness environment limit never
/// drops them.
const PRIORITY_ENVIRONMENT: [&str; 17] = [
    "PATH",
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "LANG",
    "LC_ALL",
    "TERM",
    "TMPDIR",
    "SSH_AUTH_SOCK",
    "GIT_SSH_COMMAND",
    "CARGO_HOME",
    "RUSTUP_HOME",
    "RUSTUP_TOOLCHAIN",
    "VIRTUAL_ENV",
    "XDG_CONFIG_HOME",
    "XDG_CACHE_HOME",
];
/// Session-scoped instructions stored with every harness session.
const SYSTEM_PROMPT: &str = concat!(
    "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
    "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
    "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
    "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
    "the tool reports it."
);

/// Environment snapshot provider used for credentials and `bash` grants.
type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;

/// Host configuration that enables in-process [`AgentKind::Harness`] turns.
///
/// Each session keeps its durable harness history in
/// `<data_root>/<session id>/`, outside the session worktree; hosts remove that
/// directory when they delete the session.
#[derive(Clone)]
pub struct NativeHarnessConfig {
    data_root: PathBuf,
    environment: EnvironmentSource,
}

impl NativeHarnessConfig {
    /// Configures harness storage under `data_root`, reading provider
    /// credentials from the process environment.
    pub fn new(data_root: PathBuf) -> Self {
        Self::with_environment(data_root, process_environment)
    }

    /// Configures harness storage under `data_root` with an explicit
    /// environment source for provider credentials and `bash` grants.
    pub fn with_environment(
        data_root: PathBuf,
        environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
    ) -> Self {
        Self {
            data_root,
            environment: Arc::new(environment),
        }
    }

    /// Returns a fresh environment snapshot.
    pub(crate) fn environment(&self) -> BTreeMap<String, String> {
        (self.environment)()
    }

    /// Creates and returns the session database path.
    ///
    /// # Errors
    /// Returns an error for an identifier that is not one path component or
    /// when the session directory cannot be created.
    pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
        let is_single_component = !session_id.is_empty()
            && session_id != "."
            && session_id != ".."
            && !session_id.contains(['/', '\\', '\0']);
        if !is_single_component {
            return Err(format!("Invalid harness session id `{session_id}`."));
        }
        let directory = self.data_root.join(session_id);
        tokio::fs::create_dir_all(&directory)
            .await
            .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;

        Ok(directory.join(SESSION_DATABASE_FILE))
    }
}

/// Returns the process environment, skipping variables that are not valid
/// Unicode.
pub(crate) fn process_environment() -> BTreeMap<String, String> {
    unicode_environment(env::vars_os())
}

/// Returns the harness models a user can choose: the models the local
/// OpenAI-compatible server serves, plus `OPENAI_COMPATIBLE_MODEL` when the
/// server does not list it, then the paid hosted catalog models with the
/// variable or sign-in each still needs. `is_signed_in` reports whether
/// a sign-in provider's credential file holds a usable sign-in.
///
/// Listing the local server is bounded by short request timeouts; an
/// unreachable server contributes no discovered models.
pub(crate) async fn harness_models(
    environment: &BTreeMap<String, String>,
    is_signed_in: impl Fn(&Path) -> bool,
) -> Vec<HarnessModelOption> {
    let mut options = local_models(environment).await;
    options.extend(
        AgentKind::Harness
            .models()
            .iter()
            .filter_map(|model| hosted_model(*model, environment, &is_signed_in)),
    );

    options
}

/// Returns the served local models, with the configured model first when the
/// server does not list it.
async fn local_models(environment: &BTreeMap<String, String>) -> Vec<HarnessModelOption> {
    let server = ModelProvider::OpenAiCompatible
        .local_server(lookup(environment))
        .ok()
        .flatten();
    let inventory = async { server?.inventory().await.ok() }.await;
    let provider = inventory
        .as_ref()
        .map_or(LocalServerKind::OpenAiCompatible, |inventory| {
            inventory.kind
        })
        .display_name();
    let local_option = |model: AgentModel, status: HarnessModelStatus| HarnessModelOption {
        context_window: None,
        cost: ModelCost::Local,
        loaded_context_window: None,
        model,
        provider: provider.to_string(),
        status,
        trains_on_prompts: false,
    };
    let mut options = inventory
        .map_or_else(Vec::new, |inventory| inventory.models)
        .into_iter()
        .filter_map(|served| {
            let status = if served.supports_tools == Some(false) {
                HarnessModelStatus::NoToolSupport
            } else {
                HarnessModelStatus::Ready
            };

            Some(HarnessModelOption {
                context_window: served.context_window,
                loaded_context_window: served.loaded_context_window,
                ..local_option(
                    AgentModel::OpenAiCompatible(ServedModel::new(&served.id)?),
                    status,
                )
            })
        })
        .collect::<Vec<_>>();
    let configured = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV)
        .and_then(ServedModel::new)
        .map(AgentModel::OpenAiCompatible);
    if let Some(configured) = configured
        && !options.iter().any(|option| option.model == configured)
    {
        options.insert(0, local_option(configured, HarnessModelStatus::Ready));
    }

    options
}

/// Returns one paid catalog model with the variable or sign-in its provider
/// still needs, or `None` for a model no built-in provider serves.
fn hosted_model(
    model: AgentModel,
    environment: &BTreeMap<String, String>,
    is_signed_in: impl Fn(&Path) -> bool,
) -> Option<HarnessModelOption> {
    let selection = ModelSelection::resolve_known(model.as_str()).ok()?;
    let provider = selection.provider;
    let cost = model_cost(provider.cost_tier(&selection.model)?);
    let status = configuration_status(provider, environment, is_signed_in);

    Some(HarnessModelOption {
        context_window: selection
            .profile(environment, None)
            .ok()
            .map(ModelProfile::context_window_tokens),
        cost,
        loaded_context_window: None,
        model,
        provider: provider_display_name(provider).to_string(),
        status,
        trains_on_prompts: provider.trains_on_prompts(&selection.model),
    })
}

/// Returns the cost Agentty shows for a model of the harness catalog's
/// price class `tier`.
fn model_cost(tier: CostTier) -> ModelCost {
    match tier {
        CostTier::Local => ModelCost::Local,
        CostTier::Plan => ModelCost::Plan,
        CostTier::Cheap => ModelCost::Cheap,
        CostTier::Standard => ModelCost::Standard,
        CostTier::Premium => ModelCost::Premium,
    }
}

/// Returns the name users know a hosted provider by.
fn provider_display_name(provider: ModelProvider) -> &'static str {
    match provider {
        ModelProvider::Anthropic => "Anthropic",
        ModelProvider::ChatGpt => "ChatGPT plan",
        ModelProvider::Kimi => "Kimi",
        ModelProvider::Muse => "Muse",
        ModelProvider::OpenAi => "OpenAI",
        ModelProvider::OpenAiCompatible => LocalServerKind::OpenAiCompatible.display_name(),
        ModelProvider::Qwen => "Qwen",
    }
}

/// Returns the context window `selection`'s server runs its model with, or
/// `None` for hosted providers and servers that do not report it.
///
/// Ollama loads the model first when needed, as the turn's first request
/// would. A server that cannot be queried reports nothing, leaving the
/// declared profile and the turn's own request to surface the failure.
///
/// # Errors
/// Returns an actionable error when the server runs the model with a window
/// too small for harness turns, which Ollama would otherwise fill by
/// silently dropping the start of the conversation.
pub(crate) async fn running_context_window(
    selection: &ModelSelection,
    environment: &BTreeMap<String, String>,
) -> Result<Option<u64>, String> {
    let Ok(Some(server)) = selection.provider.local_server(lookup(environment)) else {
        return Ok(None);
    };
    let Ok(Some(window)) = server.running_context_window(&selection.model).await else {
        return Ok(None);
    };
    if window < MINIMUM_RUNNING_CONTEXT_WINDOW {
        return Err(format!(
            "The local server runs `{}` with a {window}-token context window, below the \
             {MINIMUM_RUNNING_CONTEXT_WINDOW} tokens harness turns need, so it would drop the \
             start of the conversation. Restart Ollama with `OLLAMA_CONTEXT_LENGTH=32768` (or \
             raise the context length in the Ollama app's settings), or pick another model with \
             `/model`.",
            selection.model
        ));
    }

    Ok(Some(window))
}

/// Reads `environment` as the lookup the harness provider catalog expects.
pub(super) fn lookup(
    environment: &BTreeMap<String, String>,
) -> impl FnMut(&str) -> Result<String, env::VarError> + '_ {
    |name| {
        environment
            .get(name)
            .cloned()
            .ok_or(env::VarError::NotPresent)
    }
}

/// Returns the `ChatGPT` credential file Agentty signs in to and reads,
/// shared with `ag-harness login chatgpt` through [`chatgpt_auth_file_in`]:
/// `CHATGPT_AUTH_FILE`, else `auth/chatgpt.json` under `AGENTTY_ROOT` or
/// `~/.agentty`, or `None` when none of them is set. A data-directory
/// variable is used as given unless it is empty, as `agentty`'s data
/// directory reads it.
pub(super) fn chatgpt_auth_file(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
    let set = |name: &str| {
        environment
            .get(name)
            .filter(|value| !value.is_empty())
            .map(PathBuf::from)
    };
    let data_dir = set(AGENTTY_ROOT_ENV).or_else(|| set("HOME").map(|home| home.join(".agentty")));

    chatgpt_auth_file_in(lookup(environment), data_dir.as_deref())
}

/// Keeps the variables whose name and value are both valid Unicode.
fn unicode_environment(
    variables: impl IntoIterator<Item = (OsString, OsString)>,
) -> BTreeMap<String, String> {
    variables
        .into_iter()
        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
        .collect()
}

/// Returns whether a provider can serve requests now: a sign-in provider
/// needs a usable sign-in, as `is_signed_in` reports; another needs
/// its API key unless optional, then a base URL unless it has a default.
fn configuration_status(
    provider: ModelProvider,
    environment: &BTreeMap<String, String>,
    is_signed_in: impl Fn(&Path) -> bool,
) -> HarnessModelStatus {
    if provider.requires_sign_in() {
        let signed_in =
            chatgpt_auth_file(environment).is_some_and(|auth_file| is_signed_in(&auth_file));

        return if signed_in {
            HarnessModelStatus::Ready
        } else {
            HarnessModelStatus::SignInRequired(CHATGPT_SIGN_IN_COMMAND)
        };
    }
    if provider.requires_api_key() && !has_value(environment, provider.api_key_environment()) {
        return HarnessModelStatus::MissingConfiguration(provider.api_key_environment());
    }
    if provider.default_base_url().is_none()
        && !has_value(environment, provider.base_url_environment())
    {
        return HarnessModelStatus::MissingConfiguration(provider.base_url_environment());
    }

    HarnessModelStatus::Ready
}

/// Returns the trimmed value of `name`, or `None` when it is unset or blank.
fn nonblank<'a>(environment: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
    environment
        .get(name)
        .map(|value| value.trim())
        .filter(|value| !value.is_empty())
}

/// Returns whether `name` holds a nonblank value.
fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
    nonblank(environment, name).is_some()
}

/// One harness model resolved to its built-in provider and the model id
/// sent to it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ModelSelection {
    model: String,
    provider: ModelProvider,
}

impl ModelSelection {
    /// Resolves an Agentty harness model id to its provider. A served
    /// `openai-compatible/<model>` id resolves to that model, and the bare
    /// `openai-compatible` id to the model `OPENAI_COMPATIBLE_MODEL` names.
    ///
    /// # Errors
    /// Returns an error when no built-in provider serves `model`, or when
    /// `OPENAI_COMPATIBLE_MODEL` is unset for `openai-compatible`.
    pub(crate) fn resolve(
        model: &str,
        environment: &BTreeMap<String, String>,
    ) -> Result<Self, String> {
        let Some(AgentModel::OpenAiCompatible(served)) = AgentKind::Harness.parse_model(model)
        else {
            return Self::resolve_known(model);
        };
        if let Some(name) = served.name() {
            return Ok(Self {
                model: name.to_string(),
                provider: ModelProvider::OpenAiCompatible,
            });
        }
        let served = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV).ok_or_else(|| {
            format!(
                "Cannot use harness model `{model}`: {OPENAI_COMPATIBLE_MODEL_ENV} is unset. Pick \
                 a local model with `/model`, or set it to the model your OpenAI-compatible \
                 server serves, such as `qwen3:latest`, before starting Agentty."
            )
        })?;

        Ok(Self {
            model: served.to_string(),
            provider: ModelProvider::OpenAiCompatible,
        })
    }

    /// Resolves a recorded registration key such as `kimi/kimi-k3`,
    /// `chatgpt/gpt-6.1-sol`, or `openai-compatible/qwen3:latest`, or `None`
    /// for a key without a known provider and model.
    pub(crate) fn from_key(key: &str) -> Option<Self> {
        let (provider, model) = key.split_once('/')?;
        if provider == ModelProvider::OpenAiCompatible.as_str() {
            return (!model.trim().is_empty()).then(|| Self {
                model: model.to_string(),
                provider: ModelProvider::OpenAiCompatible,
            });
        }
        // A ChatGPT-plan model id is its key, `chatgpt/<model>`.
        let id = if provider == ModelProvider::ChatGpt.as_str() {
            key
        } else {
            model
        };

        Self::resolve_known(id)
            .ok()
            .filter(|selection| selection.key() == key)
    }

    /// Resolves a catalog model id to the built-in provider listing it. A
    /// `chatgpt/<model>` id resolves only to [`ModelProvider::ChatGpt`], and
    /// a bare id never does, so the `ChatGPT` plan and API-billed `OpenAI`
    /// never stand in for each other.
    fn resolve_known(model: &str) -> Result<Self, String> {
        let unknown = || format!("The harness does not serve model `{model}`.");
        if let Some(plan_model) = model
            .strip_prefix(ModelProvider::ChatGpt.as_str())
            .and_then(|rest| rest.strip_prefix('/'))
        {
            return ModelProvider::ChatGpt
                .known_models()
                .contains(&plan_model)
                .then(|| Self {
                    model: plan_model.to_string(),
                    provider: ModelProvider::ChatGpt,
                })
                .ok_or_else(unknown);
        }

        ModelProvider::all()
            .iter()
            .copied()
            .filter(|provider| !provider.requires_sign_in())
            .find(|provider| provider.known_models().contains(&model))
            .map(|provider| Self {
                model: model.to_string(),
                provider,
            })
            .ok_or_else(unknown)
    }

    /// Returns the stable registry key.
    pub(crate) fn key(&self) -> String {
        format!("{}/{}", self.provider, self.model)
    }

    /// Registers this model's provider client under its key.
    ///
    /// # Errors
    /// Returns an actionable error when credentials or the endpoint are
    /// missing, or the registration is invalid.
    pub(crate) fn registry(
        &self,
        environment: &BTreeMap<String, String>,
        provider_call_budget: Option<&ProviderCallBudget>,
        running_context_window: Option<u64>,
    ) -> Result<ModelRegistry, String> {
        let mut configuration = ModelConfiguration::new(self.provider, &self.model);
        // Only the `ChatGPT` provider reads a sign-in, and the harness keeps
        // no default location for it.
        if self.provider.requires_sign_in()
            && let Some(auth_file) = chatgpt_auth_file(environment)
        {
            configuration = configuration.auth_file(auth_file);
        }
        let client = configuration
            .client_from_environment(lookup(environment))
            .map_err(|error| {
                let remedy = if self.provider.requires_sign_in() {
                    format!("Run `{CHATGPT_SIGN_IN_COMMAND}`, then retry.")
                } else if self.provider.requires_api_key() {
                    format!(
                        "Set {} before starting Agentty.",
                        self.provider.api_key_environment()
                    )
                } else {
                    format!(
                        "Check {OPENAI_COMPATIBLE_MODEL_ENV} and {} before starting Agentty.",
                        self.provider.base_url_environment()
                    )
                };

                format!(
                    "Cannot use harness model `{}`: {error}. {remedy}",
                    self.model
                )
            })?;

        let model: Arc<dyn Model> = match provider_call_budget {
            Some(budget) => Arc::new(BudgetedModel {
                budget: budget.clone(),
                inner: client,
            }),
            None => Arc::new(client),
        };

        self.register(model, self.profile(environment, running_context_window)?)
    }

    /// Builds a harness for this model with Agentty's defaults.
    ///
    /// # Errors
    /// Returns the registration failure.
    pub(crate) fn harness(
        &self,
        context: &HarnessContext<'_>,
        observer: impl LifecycleObserver + 'static,
    ) -> Result<Harness, String> {
        let registry = self.registry(
            context.environment,
            context.provider_call_budget,
            context.running_context_window,
        )?;

        self.harness_from(&registry, context, observer)
    }

    /// Builds a harness that resumes a session recorded on this model without
    /// its provider credentials. Switch the session to another model before
    /// running a turn; this registration never sends a request.
    ///
    /// # Errors
    /// Returns the registration failure.
    pub(crate) fn resume_only_harness(
        &self,
        context: &HarnessContext<'_>,
        observer: impl LifecycleObserver + 'static,
    ) -> Result<Harness, String> {
        // A sign-in provider's client reads no credential until a request,
        // so it needs no stored sign-in here.
        let client = if self.provider.requires_sign_in() {
            ModelClient::chatgpt(ChatGptConfig {
                auth_file: PathBuf::new(),
                base_url: RESUME_ONLY_BASE_URL.to_string(),
                model: self.model.clone(),
            })
            .map_err(failure("Invalid resume-only harness model"))?
        } else {
            ModelConfiguration::new(self.provider, &self.model)
                .base_url(RESUME_ONLY_BASE_URL)
                .client_from_environment(|_| Ok(String::new()))
                .map_err(failure("Invalid resume-only harness model"))?
        };
        let metadata = client.metadata().clone();
        let profile = self.profile(context.environment, None)?;
        let registry = self.register(Arc::new(ResumeOnlyModel { metadata }), profile)?;

        self.harness_from(&registry, context, observer)
    }

    /// Registers `model` as the catalog entry of this selection's key, with
    /// `profile` and the capabilities the harness provider catalog declares
    /// for the model, under [`REGISTRATION_REVISION`]. A selection only holds
    /// a cataloged model or one an OpenAI-compatible server serves, both of
    /// which the catalog describes.
    ///
    /// The entry carries no prices or output limit, so runs stay unpriced
    /// and unmetered as before, and the harness derives the same key,
    /// revision, and capabilities recorded sessions hold.
    fn register(
        &self,
        model: Arc<dyn Model>,
        profile: ModelProfile,
    ) -> Result<ModelRegistry, String> {
        let id = ModelId::cataloged(self.provider, &self.model);
        let declared = self
            .provider
            .capabilities(&self.model)
            .unwrap_or(Capabilities::NONE);
        let spec = ModelSpec::new(id.clone())
            .with_provider(self.provider)
            .with_capabilities(declared)
            .with_profile(profile);
        let handle = ModelCatalog::builder()
            .model(spec, model)
            .build()
            .and_then(|catalog| catalog.resolve(&ModelSelector::Id(id)))
            .map_err(failure("Invalid harness model registration"))?;
        let mut registry = ModelRegistry::new();
        registry
            .register_catalog_entry(&handle, REGISTRATION_REVISION)
            .map_err(failure("Invalid harness model registration"))?;

        Ok(registry)
    }

    /// Builds a harness over this selection's registration in `registry`.
    ///
    /// A turn built inside a recording trace also exports the harness's
    /// `invoke_agent`, `chat`, and `execute_tool` spans beneath the current
    /// span; an untraced turn skips that projection.
    fn harness_from(
        &self,
        registry: &ModelRegistry,
        context: &HarnessContext<'_>,
        observer: impl LifecycleObserver + 'static,
    ) -> Result<Harness, String> {
        Ok(Harness::from_registry(registry, &self.key())
            .map_err(failure("Invalid harness model registration"))?
            .repository(context.repository.clone())
            .model_reasoning_effort(reasoning_effort(context.reasoning_level))
            .with_lifecycle_observer(traced(observer)))
    }

    /// Returns the context profile sized to the window a local server runs
    /// the model with, else the one the harness provider catalog or the
    /// environment declares for this model, else the Agentty catalog model's
    /// declared profile, else the conservative fallback. Codex models served
    /// by the harness take the provider catalog's profile, not the one
    /// Agentty declares for Codex app-server compaction.
    ///
    /// # Errors
    /// Returns an error for an invalid environment-declared profile.
    fn profile(
        &self,
        environment: &BTreeMap<String, String>,
        running_context_window: Option<u64>,
    ) -> Result<ModelProfile, String> {
        let declared = match running_context_window {
            Some(window) => self.provider.running_profile(lookup(environment), window),
            None => self
                .provider
                .declared_profile(&self.model, lookup(environment)),
        }
        .map_err(failure("Invalid harness model profile"))?;

        Ok(declared
            .or_else(|| {
                AgentKind::Harness
                    .parse_model(&self.model)
                    .and_then(model_profile::declared)
            })
            .unwrap_or(FALLBACK_MODEL_PROFILE))
    }
}

/// Inputs shared by every harness built for one turn.
pub(crate) struct HarnessContext<'a> {
    /// Environment snapshot used for credentials.
    pub(crate) environment: &'a BTreeMap<String, String>,
    /// Optional limit charged for every model request.
    pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
    /// Requested reasoning depth.
    pub(crate) reasoning_level: ReasoningLevel,
    /// Validated worktree available to tools.
    pub(crate) repository: &'a Repository,
    /// Context window the local server runs the model with, when known.
    pub(crate) running_context_window: Option<u64>,
}

/// Returns the instructions stored with new harness sessions.
pub(crate) fn system_prompt() -> &'static str {
    SYSTEM_PROMPT
}

/// Returns the protocol output schema for one request profile.
///
/// # Errors
/// Returns an error when the harness rejects the protocol schema.
pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
    OutputSchema::new(protocol_output_schema(
        profile,
        SchemaRequiredPolicy::MinimumProtocolKeys,
    ))
    .map_err(failure("The harness rejected the protocol schema"))
}

/// Explicit output schema and tools of one harness turn or run.
pub(crate) struct RunOptions {
    bash: Option<BashConfig>,
    output: OutputSchema,
    tools: ToolSet,
}

impl RunOptions {
    /// Builds the options for one turn: `read` always, plus `write` and
    /// unsandboxed `bash` outside read-only mode.
    ///
    /// # Errors
    /// Returns an error when the schema or `bash` policy is rejected.
    pub(crate) fn new(
        profile: ProtocolRequestProfile,
        permission_mode: PermissionMode,
        environment: &BTreeMap<String, String>,
    ) -> Result<Self, String> {
        let output = output_schema(profile)?;
        if permission_mode == PermissionMode::ReadOnly {
            return Ok(Self {
                bash: None,
                output,
                tools: ToolSet::empty().with_read(),
            });
        }

        Ok(Self {
            bash: Some(bash_config(environment)?),
            output,
            tools: ToolSet::builtins(),
        })
    }

    /// Returns a run request for `input` with these options.
    pub(crate) fn request(self, input: String) -> RunRequest {
        let request = RunRequest::new(input).output(self.output).tools(self.tools);

        match self.bash {
            Some(bash) => request.bash(bash),
            None => request,
        }
    }
}

/// Configures unsandboxed `bash` with the host environment minus provider
/// variables, keeping essentials first within the harness grant limits.
fn bash_config(environment: &BTreeMap<String, String>) -> Result<BashConfig, String> {
    let mut config = BashConfig::for_executor(
        Arc::new(UnsandboxedExecutor::without_isolation()),
        PathBuf::from(BASH_EXECUTABLE),
        BASH_POLICY_REVISION.to_string(),
        BASH_TIMEOUT,
        BashConfig::DEFAULT_CAPTURE_BYTES,
    )
    .map_err(failure("Invalid harness bash policy"))?
    .with_host_information();
    for (name, value) in bash_environment(environment) {
        if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
            config = granted;
        }
    }

    Ok(config)
}

/// Orders granted variables: essentials first, then the rest by name.
fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
    let is_granted = |name: &str| {
        !PROVIDER_ENVIRONMENT_PREFIXES
            .iter()
            .any(|prefix| name.starts_with(prefix))
    };
    let priority = PRIORITY_ENVIRONMENT
        .iter()
        .filter_map(|name| environment.get_key_value(*name));
    let remaining = environment
        .iter()
        .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));

    priority
        .chain(remaining)
        .filter(|(name, _)| is_granted(name))
        .collect()
}

/// Validates the worktree with the first absolute `git` on `PATH`.
///
/// # Errors
/// Returns an error for an invalid worktree or when no usable Git exists.
pub(crate) fn repository(
    folder: &Path,
    environment: &BTreeMap<String, String>,
) -> Result<Repository, String> {
    let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
    let candidates = environment
        .get("PATH")
        .into_iter()
        .flat_map(env::split_paths)
        .filter(|directory| directory.is_absolute())
        .map(|directory| directory.join(&executable_name));
    for candidate in candidates {
        match Repository::new(folder, candidate) {
            Ok(repository) => return Ok(repository),
            Err(
                error @ (RepositoryError::Root { .. }
                | RepositoryError::RootIsGitAdministrative { .. }),
            ) => return Err(format!("Invalid harness worktree: {error}")),
            Err(_) => {}
        }
    }

    Err("The harness needs a Git executable on PATH.".to_string())
}

/// Returns an error mapper that prefixes a harness failure with `context`.
pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
    move |error| format!("{context}: {error}")
}

/// Maps Agentty's reasoning level to the harness reasoning effort.
fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
    match reasoning_level {
        ReasoningLevel::Low => ReasoningEffort::Low,
        ReasoningLevel::Medium => ReasoningEffort::Medium,
        ReasoningLevel::High => ReasoningEffort::High,
        ReasoningLevel::XHigh => ReasoningEffort::XHigh,
        ReasoningLevel::Max => ReasoningEffort::Max,
    }
}

/// Adds the harness's OpenTelemetry span projection after `observer` when
/// the current execution span is recording. Its `execute_tool` spans repeat
/// the run identity the turn inherits, like other harnesses' tool spans.
fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
    let observers = LifecycleObserverSet::new(observer);
    if !Context::current().span().is_recording() {
        return observers;
    }

    observers.with_observer(
        LifecycleTraceObserver::new().with_tool_attributes(ag_telemetry::run_identity),
    )
}

/// Model wrapper that charges one provider call before every request.
struct BudgetedModel {
    budget: ProviderCallBudget,
    inner: ModelClient,
}

#[async_trait]
impl Model for BudgetedModel {
    fn metadata(&self) -> Option<ModelMetadata> {
        Model::metadata(&self.inner)
    }

    fn validate_schema(&self, schema: &OutputSchema) -> Result<(), ModelError> {
        Model::validate_schema(&self.inner, schema)
    }

    fn validate_input(&self, input: &TurnInput) -> Result<(), ModelError> {
        Model::validate_input(&self.inner, input)
    }

    fn keeps_prefix_across_schemas(&self) -> bool {
        Model::keeps_prefix_across_schemas(&self.inner)
    }

    fn replays_reasoning_text(&self) -> bool {
        Model::replays_reasoning_text(&self.inner)
    }

    fn replays_turn_instructions(&self) -> bool {
        Model::replays_turn_instructions(&self.inner)
    }

    async fn complete(&self, request: ModelRequest) -> Result<ModelCompletion, ModelError> {
        self.budget.consume().map_err(ModelError::request)?;

        Model::complete(&self.inner, request).await
    }
}

/// Stand-in for a recorded model that only lets its session resume and switch
/// away.
struct ResumeOnlyModel {
    metadata: ModelMetadata,
}

#[async_trait]
impl Model for ResumeOnlyModel {
    fn metadata(&self) -> Option<ModelMetadata> {
        Some(self.metadata.clone())
    }

    async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
        Err(ModelError::request(io::Error::other(
            "the recorded harness model can only resume its session",
        )))
    }
}

#[cfg(test)]
#[path = "config_test.rs"]
mod tests;