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