Skip to main content

ag_agent/agent/native/
config.rs

1//! Host configuration, provider credentials, and per-turn harness assembly.
2
3use std::collections::BTreeMap;
4use std::ffi::OsString;
5use std::fmt::Display;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::time::Duration;
9use std::{env, io};
10
11use ag_contracts::{PermissionMode, ProviderCallBudget, ReasoningLevel};
12use ag_harness::bash::{BashConfig, UnsandboxedExecutor};
13use ag_harness::catalog::Capabilities;
14use ag_harness::lifecycle::{LifecycleObserver, LifecycleObserverSet, LifecycleTraceObserver};
15use ag_harness::model::{
16    ModelCapabilities, ModelClient, ModelCompletion, ModelMetadata, ModelProfile, ModelRegistry,
17    ModelRequest, ReasoningEffort,
18};
19use ag_harness::provider::{
20    ChatGptConfig, CostTier, LocalServerKind, ModelConfiguration, ModelProvider,
21    chatgpt_auth_file_in,
22};
23use ag_harness::recovery::ExecutionIdentity;
24use ag_harness::{
25    Harness, Model, ModelError, OutputSchema, Repository, RepositoryError, ToolSet, TurnInput,
26    TurnOptions,
27};
28use ag_protocol::{ProtocolRequestProfile, SchemaRequiredPolicy, protocol_output_schema};
29use ag_session::{
30    AgentKind, AgentModel, HarnessModelOption, HarnessModelStatus, MINIMUM_RUNNING_CONTEXT_WINDOW,
31    ModelCost, ServedModel,
32};
33use ag_telemetry::{Context, TraceContextExt as _};
34use async_trait::async_trait;
35
36use crate::agent::model_profile;
37
38/// Revision of Agentty's harness model registrations. Durable sessions record
39/// it and require the same value on resume.
40///
41/// Image input joined the declared capabilities without a new revision: the
42/// harness weighs that capability only for image-bearing input, which
43/// Agentty rejects before a harness turn, so recorded sessions and text
44/// retries are unaffected while older sessions keep resuming.
45const REGISTRATION_REVISION: &str = "agentty-native-2";
46/// Conservative profile for a harness model without a declared profile. Its
47/// default estimator runs up to 46% under dense content and further under
48/// small requests whose fixed provider cost it never weighs.
49const FALLBACK_MODEL_PROFILE: ModelProfile =
50    ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
51/// Placeholder endpoint for resume-only registrations, which never send
52/// requests.
53const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
54/// SQLite file holding one session's durable harness history.
55const SESSION_DATABASE_FILE: &str = "harness.db";
56/// Trusted Bash executable used by edit-mode `bash` calls.
57const BASH_EXECUTABLE: &str = "/bin/bash";
58/// Nonsecret identity of the unsandboxed Bash policy.
59const BASH_POLICY_REVISION: &str = "agentty-unsandboxed-1";
60/// Deadline for one `bash` call.
61const BASH_TIMEOUT: Duration = Duration::from_secs(600);
62/// Environment variable naming the model the OpenAI-compatible server serves
63/// for [`AgentModel::OpenAiCompatible`], such as Ollama's `qwen3:latest`.
64const OPENAI_COMPATIBLE_MODEL_ENV: &str = "OPENAI_COMPATIBLE_MODEL";
65/// Command that stores the sign-in [`ModelProvider::ChatGpt`] needs.
66const CHATGPT_SIGN_IN_COMMAND: &str = "ag-harness login chatgpt";
67/// Environment variable naming Agentty's data directory, `~/.agentty` by
68/// default.
69const AGENTTY_ROOT_ENV: &str = "AGENTTY_ROOT";
70/// Environment prefixes that carry provider keys, credential files, and
71/// endpoints, withheld from `bash`. `OPENAI_` covers both `OpenAI` and
72/// OpenAI-compatible variables.
73const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 5] =
74    ["CHATGPT_", "DASHSCOPE_", "KIMI_", "MODEL_", "OPENAI_"];
75/// Variables granted to `bash` first, so the harness environment limit never
76/// drops them.
77const PRIORITY_ENVIRONMENT: [&str; 17] = [
78    "PATH",
79    "HOME",
80    "USER",
81    "LOGNAME",
82    "SHELL",
83    "LANG",
84    "LC_ALL",
85    "TERM",
86    "TMPDIR",
87    "SSH_AUTH_SOCK",
88    "GIT_SSH_COMMAND",
89    "CARGO_HOME",
90    "RUSTUP_HOME",
91    "RUSTUP_TOOLCHAIN",
92    "VIRTUAL_ENV",
93    "XDG_CONFIG_HOME",
94    "XDG_CACHE_HOME",
95];
96/// Session-scoped instructions stored with every harness session.
97const SYSTEM_PROMPT: &str = concat!(
98    "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
99    "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
100    "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
101    "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
102    "the tool reports it."
103);
104
105/// Environment snapshot provider used for credentials and `bash` grants.
106type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
107
108/// Host configuration that enables in-process [`AgentKind::Harness`] turns.
109///
110/// Each session keeps its durable harness history in
111/// `<data_root>/<session id>/`, outside the session worktree; hosts remove that
112/// directory when they delete the session.
113#[derive(Clone)]
114pub struct NativeHarnessConfig {
115    data_root: PathBuf,
116    environment: EnvironmentSource,
117}
118
119impl NativeHarnessConfig {
120    /// Configures harness storage under `data_root`, reading provider
121    /// credentials from the process environment.
122    pub fn new(data_root: PathBuf) -> Self {
123        Self::with_environment(data_root, process_environment)
124    }
125
126    /// Configures harness storage under `data_root` with an explicit
127    /// environment source for provider credentials and `bash` grants.
128    pub fn with_environment(
129        data_root: PathBuf,
130        environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
131    ) -> Self {
132        Self {
133            data_root,
134            environment: Arc::new(environment),
135        }
136    }
137
138    /// Returns a fresh environment snapshot.
139    pub(crate) fn environment(&self) -> BTreeMap<String, String> {
140        (self.environment)()
141    }
142
143    /// Creates and returns the session database path.
144    ///
145    /// # Errors
146    /// Returns an error for an identifier that is not one path component or
147    /// when the session directory cannot be created.
148    pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
149        let is_single_component = !session_id.is_empty()
150            && session_id != "."
151            && session_id != ".."
152            && !session_id.contains(['/', '\\', '\0']);
153        if !is_single_component {
154            return Err(format!("Invalid harness session id `{session_id}`."));
155        }
156        let directory = self.data_root.join(session_id);
157        tokio::fs::create_dir_all(&directory)
158            .await
159            .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;
160
161        Ok(directory.join(SESSION_DATABASE_FILE))
162    }
163}
164
165/// Returns the process environment, skipping variables that are not valid
166/// Unicode.
167pub(crate) fn process_environment() -> BTreeMap<String, String> {
168    unicode_environment(env::vars_os())
169}
170
171/// Returns the harness models a user can choose: the models the local
172/// OpenAI-compatible server serves, plus `OPENAI_COMPATIBLE_MODEL` when the
173/// server does not list it, then the paid hosted catalog models with the
174/// variable or sign-in each still needs. `is_signed_in` reports whether
175/// a sign-in provider's credential file holds a usable sign-in.
176///
177/// Listing the local server is bounded by short request timeouts; an
178/// unreachable server contributes no discovered models.
179pub(crate) async fn harness_models(
180    environment: &BTreeMap<String, String>,
181    is_signed_in: impl Fn(&Path) -> bool,
182) -> Vec<HarnessModelOption> {
183    let mut options = local_models(environment).await;
184    options.extend(
185        AgentKind::Harness
186            .models()
187            .iter()
188            .filter_map(|model| hosted_model(*model, environment, &is_signed_in)),
189    );
190
191    options
192}
193
194/// Returns the served local models, with the configured model first when the
195/// server does not list it.
196async fn local_models(environment: &BTreeMap<String, String>) -> Vec<HarnessModelOption> {
197    let server = ModelProvider::OpenAiCompatible
198        .local_server(lookup(environment))
199        .ok()
200        .flatten();
201    let inventory = async { server?.inventory().await.ok() }.await;
202    let provider = inventory
203        .as_ref()
204        .map_or(LocalServerKind::OpenAiCompatible, |inventory| {
205            inventory.kind
206        })
207        .display_name();
208    let local_option = |model: AgentModel, status: HarnessModelStatus| HarnessModelOption {
209        context_window: None,
210        cost: ModelCost::Local,
211        loaded_context_window: None,
212        model,
213        provider: provider.to_string(),
214        status,
215        trains_on_prompts: false,
216    };
217    let mut options = inventory
218        .map_or_else(Vec::new, |inventory| inventory.models)
219        .into_iter()
220        .filter_map(|served| {
221            let status = if served.supports_tools == Some(false) {
222                HarnessModelStatus::NoToolSupport
223            } else {
224                HarnessModelStatus::Ready
225            };
226
227            Some(HarnessModelOption {
228                context_window: served.context_window,
229                loaded_context_window: served.loaded_context_window,
230                ..local_option(
231                    AgentModel::OpenAiCompatible(ServedModel::new(&served.id)?),
232                    status,
233                )
234            })
235        })
236        .collect::<Vec<_>>();
237    let configured = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV)
238        .and_then(ServedModel::new)
239        .map(AgentModel::OpenAiCompatible);
240    if let Some(configured) = configured
241        && !options.iter().any(|option| option.model == configured)
242    {
243        options.insert(0, local_option(configured, HarnessModelStatus::Ready));
244    }
245
246    options
247}
248
249/// Returns one paid catalog model with the variable or sign-in its provider
250/// still needs, or `None` for a model no built-in provider serves.
251fn hosted_model(
252    model: AgentModel,
253    environment: &BTreeMap<String, String>,
254    is_signed_in: impl Fn(&Path) -> bool,
255) -> Option<HarnessModelOption> {
256    let selection = ModelSelection::resolve_known(model.as_str()).ok()?;
257    let provider = selection.provider;
258    let cost = model_cost(provider.cost_tier(&selection.model)?);
259    let status = configuration_status(provider, environment, is_signed_in);
260
261    Some(HarnessModelOption {
262        context_window: selection
263            .profile(environment, None)
264            .ok()
265            .map(ModelProfile::context_window_tokens),
266        cost,
267        loaded_context_window: None,
268        model,
269        provider: provider_display_name(provider).to_string(),
270        status,
271        trains_on_prompts: provider.trains_on_prompts(&selection.model),
272    })
273}
274
275/// Returns the cost Agentty shows for a model of the harness catalog's
276/// price class `tier`.
277fn model_cost(tier: CostTier) -> ModelCost {
278    match tier {
279        CostTier::Local => ModelCost::Local,
280        CostTier::Plan => ModelCost::Plan,
281        CostTier::Cheap => ModelCost::Cheap,
282        CostTier::Standard => ModelCost::Standard,
283        CostTier::Premium => ModelCost::Premium,
284    }
285}
286
287/// Returns the name users know a hosted provider by.
288fn provider_display_name(provider: ModelProvider) -> &'static str {
289    match provider {
290        ModelProvider::ChatGpt => "ChatGPT plan",
291        ModelProvider::Kimi => "Kimi",
292        ModelProvider::Muse => "Muse",
293        ModelProvider::OpenAi => "OpenAI",
294        ModelProvider::OpenAiCompatible => LocalServerKind::OpenAiCompatible.display_name(),
295        ModelProvider::Qwen => "Qwen",
296    }
297}
298
299/// Returns the context window `selection`'s server runs its model with, or
300/// `None` for hosted providers and servers that do not report it.
301///
302/// Ollama loads the model first when needed, as the turn's first request
303/// would. A server that cannot be queried reports nothing, leaving the
304/// declared profile and the turn's own request to surface the failure.
305///
306/// # Errors
307/// Returns an actionable error when the server runs the model with a window
308/// too small for harness turns, which Ollama would otherwise fill by
309/// silently dropping the start of the conversation.
310pub(crate) async fn running_context_window(
311    selection: &ModelSelection,
312    environment: &BTreeMap<String, String>,
313) -> Result<Option<u64>, String> {
314    let Ok(Some(server)) = selection.provider.local_server(lookup(environment)) else {
315        return Ok(None);
316    };
317    let Ok(Some(window)) = server.running_context_window(&selection.model).await else {
318        return Ok(None);
319    };
320    if window < MINIMUM_RUNNING_CONTEXT_WINDOW {
321        return Err(format!(
322            "The local server runs `{}` with a {window}-token context window, below the \
323             {MINIMUM_RUNNING_CONTEXT_WINDOW} tokens harness turns need, so it would drop the \
324             start of the conversation. Restart Ollama with `OLLAMA_CONTEXT_LENGTH=32768` (or \
325             raise the context length in the Ollama app's settings), or pick another model with \
326             `/model`.",
327            selection.model
328        ));
329    }
330
331    Ok(Some(window))
332}
333
334/// Reads `environment` as the lookup the harness provider catalog expects.
335pub(super) fn lookup(
336    environment: &BTreeMap<String, String>,
337) -> impl FnMut(&str) -> Result<String, env::VarError> + '_ {
338    |name| {
339        environment
340            .get(name)
341            .cloned()
342            .ok_or(env::VarError::NotPresent)
343    }
344}
345
346/// Returns the `ChatGPT` credential file Agentty signs in to and reads,
347/// shared with `ag-harness login chatgpt` through [`chatgpt_auth_file_in`]:
348/// `CHATGPT_AUTH_FILE`, else `auth/chatgpt.json` under `AGENTTY_ROOT` or
349/// `~/.agentty`, or `None` when none of them is set. A data-directory
350/// variable is used as given unless it is empty, as `agentty`'s data
351/// directory reads it.
352pub(super) fn chatgpt_auth_file(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
353    let set = |name: &str| {
354        environment
355            .get(name)
356            .filter(|value| !value.is_empty())
357            .map(PathBuf::from)
358    };
359    let data_dir = set(AGENTTY_ROOT_ENV).or_else(|| set("HOME").map(|home| home.join(".agentty")));
360
361    chatgpt_auth_file_in(lookup(environment), data_dir.as_deref())
362}
363
364/// Keeps the variables whose name and value are both valid Unicode.
365fn unicode_environment(
366    variables: impl IntoIterator<Item = (OsString, OsString)>,
367) -> BTreeMap<String, String> {
368    variables
369        .into_iter()
370        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
371        .collect()
372}
373
374/// Returns whether a provider can serve requests now: a sign-in provider
375/// needs a usable sign-in, as `is_signed_in` reports; another needs
376/// its API key unless optional, then a base URL unless it has a default.
377fn configuration_status(
378    provider: ModelProvider,
379    environment: &BTreeMap<String, String>,
380    is_signed_in: impl Fn(&Path) -> bool,
381) -> HarnessModelStatus {
382    if provider.requires_sign_in() {
383        let signed_in =
384            chatgpt_auth_file(environment).is_some_and(|auth_file| is_signed_in(&auth_file));
385
386        return if signed_in {
387            HarnessModelStatus::Ready
388        } else {
389            HarnessModelStatus::SignInRequired(CHATGPT_SIGN_IN_COMMAND)
390        };
391    }
392    if provider.requires_api_key() && !has_value(environment, provider.api_key_environment()) {
393        return HarnessModelStatus::MissingConfiguration(provider.api_key_environment());
394    }
395    if provider.default_base_url().is_none()
396        && !has_value(environment, provider.base_url_environment())
397    {
398        return HarnessModelStatus::MissingConfiguration(provider.base_url_environment());
399    }
400
401    HarnessModelStatus::Ready
402}
403
404/// Returns the trimmed value of `name`, or `None` when it is unset or blank.
405fn nonblank<'a>(environment: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
406    environment
407        .get(name)
408        .map(|value| value.trim())
409        .filter(|value| !value.is_empty())
410}
411
412/// Returns whether `name` holds a nonblank value.
413fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
414    nonblank(environment, name).is_some()
415}
416
417/// One harness model resolved to its built-in provider and the model id
418/// sent to it.
419#[derive(Clone, Debug, Eq, PartialEq)]
420pub(crate) struct ModelSelection {
421    model: String,
422    provider: ModelProvider,
423}
424
425impl ModelSelection {
426    /// Resolves an Agentty harness model id to its provider. A served
427    /// `openai-compatible/<model>` id resolves to that model, and the bare
428    /// `openai-compatible` id to the model `OPENAI_COMPATIBLE_MODEL` names.
429    ///
430    /// # Errors
431    /// Returns an error when no built-in provider serves `model`, or when
432    /// `OPENAI_COMPATIBLE_MODEL` is unset for `openai-compatible`.
433    pub(crate) fn resolve(
434        model: &str,
435        environment: &BTreeMap<String, String>,
436    ) -> Result<Self, String> {
437        let Some(AgentModel::OpenAiCompatible(served)) = AgentKind::Harness.parse_model(model)
438        else {
439            return Self::resolve_known(model);
440        };
441        if let Some(name) = served.name() {
442            return Ok(Self {
443                model: name.to_string(),
444                provider: ModelProvider::OpenAiCompatible,
445            });
446        }
447        let served = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV).ok_or_else(|| {
448            format!(
449                "Cannot use harness model `{model}`: {OPENAI_COMPATIBLE_MODEL_ENV} is unset. Pick \
450                 a local model with `/model`, or set it to the model your OpenAI-compatible \
451                 server serves, such as `qwen3:latest`, before starting Agentty."
452            )
453        })?;
454
455        Ok(Self {
456            model: served.to_string(),
457            provider: ModelProvider::OpenAiCompatible,
458        })
459    }
460
461    /// Resolves a recorded registration key such as `kimi/kimi-k3`,
462    /// `chatgpt/gpt-6.1-sol`, or `openai-compatible/qwen3:latest`, or `None`
463    /// for a key without a known provider and model.
464    pub(crate) fn from_key(key: &str) -> Option<Self> {
465        let (provider, model) = key.split_once('/')?;
466        if provider == ModelProvider::OpenAiCompatible.as_str() {
467            return (!model.trim().is_empty()).then(|| Self {
468                model: model.to_string(),
469                provider: ModelProvider::OpenAiCompatible,
470            });
471        }
472        // A ChatGPT-plan model id is its key, `chatgpt/<model>`.
473        let id = if provider == ModelProvider::ChatGpt.as_str() {
474            key
475        } else {
476            model
477        };
478
479        Self::resolve_known(id)
480            .ok()
481            .filter(|selection| selection.key() == key)
482    }
483
484    /// Resolves a catalog model id to the built-in provider listing it. A
485    /// `chatgpt/<model>` id resolves only to [`ModelProvider::ChatGpt`], and
486    /// a bare id never does, so the `ChatGPT` plan and API-billed `OpenAI`
487    /// never stand in for each other.
488    fn resolve_known(model: &str) -> Result<Self, String> {
489        let unknown = || format!("The harness does not serve model `{model}`.");
490        if let Some(plan_model) = model
491            .strip_prefix(ModelProvider::ChatGpt.as_str())
492            .and_then(|rest| rest.strip_prefix('/'))
493        {
494            return ModelProvider::ChatGpt
495                .known_models()
496                .contains(&plan_model)
497                .then(|| Self {
498                    model: plan_model.to_string(),
499                    provider: ModelProvider::ChatGpt,
500                })
501                .ok_or_else(unknown);
502        }
503
504        ModelProvider::all()
505            .iter()
506            .copied()
507            .filter(|provider| !provider.requires_sign_in())
508            .find(|provider| provider.known_models().contains(&model))
509            .map(|provider| Self {
510                model: model.to_string(),
511                provider,
512            })
513            .ok_or_else(unknown)
514    }
515
516    /// Returns the stable registry key.
517    pub(crate) fn key(&self) -> String {
518        format!("{}/{}", self.provider, self.model)
519    }
520
521    /// Registers this model's provider client under its key.
522    ///
523    /// # Errors
524    /// Returns an actionable error when credentials or the endpoint are
525    /// missing, or the registration is invalid.
526    pub(crate) fn registry(
527        &self,
528        environment: &BTreeMap<String, String>,
529        provider_call_budget: Option<&ProviderCallBudget>,
530        running_context_window: Option<u64>,
531    ) -> Result<ModelRegistry, String> {
532        let mut configuration = ModelConfiguration::new(self.provider, &self.model);
533        // Only the `ChatGPT` provider reads a sign-in, and the harness keeps
534        // no default location for it.
535        if self.provider.requires_sign_in()
536            && let Some(auth_file) = chatgpt_auth_file(environment)
537        {
538            configuration = configuration.auth_file(auth_file);
539        }
540        let client = configuration
541            .client_from_environment(lookup(environment))
542            .map_err(|error| {
543                let remedy = if self.provider.requires_sign_in() {
544                    format!("Run `{CHATGPT_SIGN_IN_COMMAND}`, then retry.")
545                } else if self.provider.requires_api_key() {
546                    format!(
547                        "Set {} before starting Agentty.",
548                        self.provider.api_key_environment()
549                    )
550                } else {
551                    format!(
552                        "Check {OPENAI_COMPATIBLE_MODEL_ENV} and {} before starting Agentty.",
553                        self.provider.base_url_environment()
554                    )
555                };
556
557                format!(
558                    "Cannot use harness model `{}`: {error}. {remedy}",
559                    self.model
560                )
561            })?;
562
563        let model: Arc<dyn Model> = match provider_call_budget {
564            Some(budget) => Arc::new(BudgetedModel {
565                budget: budget.clone(),
566                inner: client,
567            }),
568            None => Arc::new(client),
569        };
570
571        self.register(model, self.profile(environment, running_context_window)?)
572    }
573
574    /// Builds a harness for this model with Agentty's defaults.
575    ///
576    /// # Errors
577    /// Returns the registration failure.
578    pub(crate) fn harness(
579        &self,
580        context: &HarnessContext<'_>,
581        observer: impl LifecycleObserver + 'static,
582    ) -> Result<Harness, String> {
583        let registry = self.registry(
584            context.environment,
585            context.provider_call_budget,
586            context.running_context_window,
587        )?;
588
589        self.harness_from(&registry, context, observer)
590    }
591
592    /// Builds a harness that resumes a session recorded on this model without
593    /// its provider credentials. Switch the session to another model before
594    /// running a turn; this registration never sends a request.
595    ///
596    /// # Errors
597    /// Returns the registration failure.
598    pub(crate) fn resume_only_harness(
599        &self,
600        context: &HarnessContext<'_>,
601        observer: impl LifecycleObserver + 'static,
602    ) -> Result<Harness, String> {
603        // A sign-in provider's client reads no credential until a request,
604        // so it needs no stored sign-in here.
605        let client = if self.provider.requires_sign_in() {
606            ModelClient::chatgpt(ChatGptConfig {
607                auth_file: PathBuf::new(),
608                base_url: RESUME_ONLY_BASE_URL.to_string(),
609                model: self.model.clone(),
610            })
611            .map_err(failure("Invalid resume-only harness model"))?
612        } else {
613            ModelConfiguration::new(self.provider, &self.model)
614                .base_url(RESUME_ONLY_BASE_URL)
615                .client_from_environment(|_| Ok(String::new()))
616                .map_err(failure("Invalid resume-only harness model"))?
617        };
618        let metadata = client.metadata().clone();
619        let profile = self.profile(context.environment, None)?;
620        let registry = self.register(Arc::new(ResumeOnlyModel { metadata }), profile)?;
621
622        self.harness_from(&registry, context, observer)
623    }
624
625    /// Registers `model` under this selection's key with `profile` and the
626    /// tool calls and image input the harness provider catalog declares for
627    /// the model. A selection only holds a cataloged model or one an
628    /// OpenAI-compatible server serves, both of which the catalog describes.
629    fn register(
630        &self,
631        model: Arc<dyn Model>,
632        profile: ModelProfile,
633    ) -> Result<ModelRegistry, String> {
634        let identity = ExecutionIdentity::new(self.key(), REGISTRATION_REVISION)
635            .map_err(failure("Invalid harness model registration"))?;
636        let declared = self
637            .provider
638            .capabilities(&self.model)
639            .unwrap_or(Capabilities::NONE);
640        let capabilities = ModelCapabilities {
641            image_input: declared.image_input(),
642            tool_calls: declared.tool_calls(),
643            ..ModelCapabilities::new(profile)
644        };
645        let mut registry = ModelRegistry::new();
646        registry
647            .register_shared(identity, model, capabilities)
648            .map_err(failure("Invalid harness model registration"))?;
649
650        Ok(registry)
651    }
652
653    /// Builds a harness over this selection's registration in `registry`.
654    ///
655    /// A turn built inside a recording trace also exports the harness's
656    /// `invoke_agent`, `chat`, and `execute_tool` spans beneath the current
657    /// span; an untraced turn skips that projection.
658    fn harness_from(
659        &self,
660        registry: &ModelRegistry,
661        context: &HarnessContext<'_>,
662        observer: impl LifecycleObserver + 'static,
663    ) -> Result<Harness, String> {
664        Ok(Harness::from_registry(registry, &self.key())
665            .map_err(failure("Invalid harness model registration"))?
666            .repository(context.repository.clone())
667            .model_reasoning_effort(reasoning_effort(context.reasoning_level))
668            .with_lifecycle_observer(traced(observer)))
669    }
670
671    /// Returns the context profile sized to the window a local server runs
672    /// the model with, else the one the harness provider catalog or the
673    /// environment declares for this model, else the Agentty catalog model's
674    /// declared profile, else the conservative fallback. Codex models served
675    /// by the harness take the provider catalog's profile, not the one
676    /// Agentty declares for Codex app-server compaction.
677    ///
678    /// # Errors
679    /// Returns an error for an invalid environment-declared profile.
680    fn profile(
681        &self,
682        environment: &BTreeMap<String, String>,
683        running_context_window: Option<u64>,
684    ) -> Result<ModelProfile, String> {
685        let declared = match running_context_window {
686            Some(window) => self.provider.running_profile(lookup(environment), window),
687            None => self
688                .provider
689                .declared_profile(&self.model, lookup(environment)),
690        }
691        .map_err(failure("Invalid harness model profile"))?;
692
693        Ok(declared
694            .or_else(|| {
695                AgentKind::Harness
696                    .parse_model(&self.model)
697                    .and_then(model_profile::declared)
698            })
699            .unwrap_or(FALLBACK_MODEL_PROFILE))
700    }
701}
702
703/// Inputs shared by every harness built for one turn.
704pub(crate) struct HarnessContext<'a> {
705    /// Environment snapshot used for credentials.
706    pub(crate) environment: &'a BTreeMap<String, String>,
707    /// Optional limit charged for every model request.
708    pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
709    /// Requested reasoning depth.
710    pub(crate) reasoning_level: ReasoningLevel,
711    /// Validated worktree available to tools.
712    pub(crate) repository: &'a Repository,
713    /// Context window the local server runs the model with, when known.
714    pub(crate) running_context_window: Option<u64>,
715}
716
717/// Returns the instructions stored with new harness sessions.
718pub(crate) fn system_prompt() -> &'static str {
719    SYSTEM_PROMPT
720}
721
722/// Returns the protocol output schema for one request profile.
723///
724/// # Errors
725/// Returns an error when the harness rejects the protocol schema.
726pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
727    OutputSchema::new(protocol_output_schema(
728        profile,
729        SchemaRequiredPolicy::MinimumProtocolKeys,
730    ))
731    .map_err(failure("The harness rejected the protocol schema"))
732}
733
734/// Builds explicit options for one turn: `read` always, plus `write` and
735/// unsandboxed `bash` outside read-only mode.
736///
737/// # Errors
738/// Returns an error when the schema or `bash` policy is rejected.
739pub(crate) fn turn_options(
740    profile: ProtocolRequestProfile,
741    permission_mode: PermissionMode,
742    environment: &BTreeMap<String, String>,
743) -> Result<TurnOptions, String> {
744    let options = TurnOptions::from_output(output_schema(profile)?);
745    if permission_mode == PermissionMode::ReadOnly {
746        return Ok(options.with_tools(ToolSet::empty().with_read()));
747    }
748
749    Ok(options
750        .with_tools(ToolSet::builtins())
751        .with_bash(bash_config(environment)?))
752}
753
754/// Configures unsandboxed `bash` with the host environment minus provider
755/// variables, keeping essentials first within the harness grant limits.
756fn bash_config(environment: &BTreeMap<String, String>) -> Result<BashConfig, String> {
757    let mut config = BashConfig::for_executor(
758        Arc::new(UnsandboxedExecutor::without_isolation()),
759        PathBuf::from(BASH_EXECUTABLE),
760        BASH_POLICY_REVISION.to_string(),
761        BASH_TIMEOUT,
762        BashConfig::DEFAULT_CAPTURE_BYTES,
763    )
764    .map_err(failure("Invalid harness bash policy"))?
765    .with_host_information();
766    for (name, value) in bash_environment(environment) {
767        if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
768            config = granted;
769        }
770    }
771
772    Ok(config)
773}
774
775/// Orders granted variables: essentials first, then the rest by name.
776fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
777    let is_granted = |name: &str| {
778        !PROVIDER_ENVIRONMENT_PREFIXES
779            .iter()
780            .any(|prefix| name.starts_with(prefix))
781    };
782    let priority = PRIORITY_ENVIRONMENT
783        .iter()
784        .filter_map(|name| environment.get_key_value(*name));
785    let remaining = environment
786        .iter()
787        .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));
788
789    priority
790        .chain(remaining)
791        .filter(|(name, _)| is_granted(name))
792        .collect()
793}
794
795/// Validates the worktree with the first absolute `git` on `PATH`.
796///
797/// # Errors
798/// Returns an error for an invalid worktree or when no usable Git exists.
799pub(crate) fn repository(
800    folder: &Path,
801    environment: &BTreeMap<String, String>,
802) -> Result<Repository, String> {
803    let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
804    let candidates = environment
805        .get("PATH")
806        .into_iter()
807        .flat_map(env::split_paths)
808        .filter(|directory| directory.is_absolute())
809        .map(|directory| directory.join(&executable_name));
810    for candidate in candidates {
811        match Repository::new(folder, candidate) {
812            Ok(repository) => return Ok(repository),
813            Err(
814                error @ (RepositoryError::Root { .. }
815                | RepositoryError::RootIsGitAdministrative { .. }),
816            ) => return Err(format!("Invalid harness worktree: {error}")),
817            Err(_) => {}
818        }
819    }
820
821    Err("The harness needs a Git executable on PATH.".to_string())
822}
823
824/// Returns an error mapper that prefixes a harness failure with `context`.
825pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
826    move |error| format!("{context}: {error}")
827}
828
829/// Maps Agentty's reasoning level to the harness reasoning effort.
830fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
831    match reasoning_level {
832        ReasoningLevel::Low => ReasoningEffort::Low,
833        ReasoningLevel::Medium => ReasoningEffort::Medium,
834        ReasoningLevel::High => ReasoningEffort::High,
835        ReasoningLevel::XHigh => ReasoningEffort::XHigh,
836        ReasoningLevel::Max => ReasoningEffort::Max,
837    }
838}
839
840/// Adds the harness's OpenTelemetry span projection after `observer` when
841/// the current execution span is recording. Its `execute_tool` spans repeat
842/// the run identity the turn inherits, like other harnesses' tool spans.
843fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
844    let observers = LifecycleObserverSet::new(observer);
845    if !Context::current().span().is_recording() {
846        return observers;
847    }
848
849    observers.with_observer(
850        LifecycleTraceObserver::new().with_tool_attributes(ag_telemetry::run_identity),
851    )
852}
853
854/// Model wrapper that charges one provider call before every request.
855struct BudgetedModel {
856    budget: ProviderCallBudget,
857    inner: ModelClient,
858}
859
860#[async_trait]
861impl Model for BudgetedModel {
862    fn metadata(&self) -> Option<ModelMetadata> {
863        Model::metadata(&self.inner)
864    }
865
866    fn validate_schema(&self, schema: &OutputSchema) -> Result<(), ModelError> {
867        Model::validate_schema(&self.inner, schema)
868    }
869
870    fn validate_input(&self, input: &TurnInput) -> Result<(), ModelError> {
871        Model::validate_input(&self.inner, input)
872    }
873
874    fn keeps_prefix_across_schemas(&self) -> bool {
875        Model::keeps_prefix_across_schemas(&self.inner)
876    }
877
878    fn replays_reasoning_text(&self) -> bool {
879        Model::replays_reasoning_text(&self.inner)
880    }
881
882    async fn complete(&self, request: ModelRequest) -> Result<ModelCompletion, ModelError> {
883        self.budget.consume().map_err(ModelError::request)?;
884
885        Model::complete(&self.inner, request).await
886    }
887}
888
889/// Stand-in for a recorded model that only lets its session resume and switch
890/// away.
891struct ResumeOnlyModel {
892    metadata: ModelMetadata,
893}
894
895#[async_trait]
896impl Model for ResumeOnlyModel {
897    fn metadata(&self) -> Option<ModelMetadata> {
898        Some(self.metadata.clone())
899    }
900
901    async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
902        Err(ModelError::request(io::Error::other(
903            "the recorded harness model can only resume its session",
904        )))
905    }
906}
907
908#[cfg(test)]
909#[path = "config_test.rs"]
910mod tests;