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