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