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