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::sync::atomic::{AtomicBool, Ordering};
9use std::time::Duration;
10use std::{env, io};
11
12use ag_contracts::{HostCacheSharing, PermissionMode, ReasoningLevel, TurnRequest};
13use ag_harness::bash::BashConfig;
14use ag_harness::catalog::{
15    Capabilities, ModelCatalog, ModelHandle, ModelId, ModelSelector, ModelSpec,
16};
17use ag_harness::lifecycle::{LifecycleObserver, LifecycleObserverSet, LifecycleTraceObserver};
18use ag_harness::model::{
19    ContextPolicy, ModelClient, ModelCompletion, ModelMetadata, ModelProfile, ModelRegistry,
20    ModelRequest, ReasoningEffort,
21};
22use ag_harness::provider::{
23    ChatGptConfig, CostTier, LocalServerKind, ModelConfiguration, ModelProvider,
24    chatgpt_auth_file_in,
25};
26use ag_harness::sandbox::Sandbox;
27use ag_harness::{
28    Harness, HarnessError, Model, ModelError, OutputSchema, Repository, RepositoryError,
29    RunRequest, ToolSet,
30};
31use ag_protocol::{ProtocolRequestProfile, SchemaRequiredPolicy, protocol_output_schema};
32use ag_session::{
33    AgentKind, AgentModel, HarnessModelOption, HarnessModelStatus, MINIMUM_RUNNING_CONTEXT_WINDOW,
34    ModelCost, ServedModel,
35};
36use ag_telemetry::{Context, TraceContextExt as _};
37use async_trait::async_trait;
38
39use super::cargo_cache::TrustedCargoCache;
40use super::sandbox::CommandSandbox;
41use crate::agent::model_profile;
42
43/// Revision of Agentty's harness model registrations. Durable sessions record
44/// it and require the same value on resume.
45///
46/// Image input joined the declared capabilities without a new revision: the
47/// harness weighs that capability only for image-bearing input, which
48/// Agentty rejects before a harness turn, so recorded sessions and text
49/// retries are unaffected while older sessions keep resuming.
50const REGISTRATION_REVISION: &str = "agentty-native-2";
51/// Conservative profile for a harness model without a declared profile. Its
52/// default estimator runs up to 46% under dense content and further under
53/// small requests whose fixed provider cost it never weighs.
54const FALLBACK_MODEL_PROFILE: ModelProfile =
55    ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
56/// Placeholder endpoint for resume-only registrations, which never send
57/// requests.
58const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
59/// Placeholder key for resume-only registrations, nonblank because a blank
60/// required key counts as missing.
61const RESUME_ONLY_API_KEY: &str = "resume-only";
62/// SQLite file holding one session's durable harness history.
63const SESSION_DATABASE_FILE: &str = "harness.db";
64/// Trusted Bash executable used by edit-mode `bash` calls.
65const BASH_EXECUTABLE: &str = "/bin/bash";
66/// Nonsecret identity of the native sandbox Bash policy. Change it when the
67/// grants, the Bash executable, or the `ag-harness` sandbox enforcement
68/// change.
69const BASH_POLICY_REVISION: &str = "agentty-native-sandbox-1";
70/// Policy revision of sessions sharing the host's dependency caches, whose
71/// cache variables name the host's caches instead of the temporary
72/// directory's.
73const HOST_CACHE_POLICY_REVISION: &str = "agentty-native-sandbox-1-host-caches";
74/// Directory beside a session's harness database that its commands use as
75/// `TMPDIR` and for tool caches.
76const SESSION_TEMPORARY_DIRECTORY: &str = "tmp";
77/// Directory under the data root holding one temporary directory per
78/// running utility prompt. Agentty session ids never start with a dot.
79const UTILITY_TEMPORARY_PARENT: &str = ".utility";
80/// Deadline for one `bash` call.
81const BASH_TIMEOUT: Duration = Duration::from_secs(600);
82/// Environment variable naming the model the OpenAI-compatible server serves
83/// for [`AgentModel::OpenAiCompatible`], such as Ollama's `qwen3:latest`.
84const OPENAI_COMPATIBLE_MODEL_ENV: &str = "OPENAI_COMPATIBLE_MODEL";
85/// Command that stores the sign-in [`ModelProvider::ChatGpt`] needs.
86const CHATGPT_SIGN_IN_COMMAND: &str = "ag-harness login chatgpt";
87/// Environment variable naming Agentty's data directory, `~/.agentty` by
88/// default.
89const AGENTTY_ROOT_ENV: &str = "AGENTTY_ROOT";
90/// Environment prefixes that carry provider keys, credential files, and
91/// endpoints, withheld from `bash`. `OPENAI_` covers both `OpenAI` and
92/// OpenAI-compatible variables, and `CLAUDE_CODE_OAUTH_TOKEN` the Claude
93/// subscription token Claude Code reads beside the `ANTHROPIC_` variables.
94const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 7] = [
95    "ANTHROPIC_",
96    "CHATGPT_",
97    "CLAUDE_CODE_OAUTH_TOKEN",
98    "DASHSCOPE_",
99    "KIMI_",
100    "MODEL_",
101    "OPENAI_",
102];
103/// Prefixes of variable names withheld from `bash` as credentials, matched
104/// case-insensitively.
105const CREDENTIAL_PREFIXES: [&str; 5] = ["AWS_", "GH_", "GITHUB_", "GITLAB_", "GLAB_"];
106/// Endings of variable names withheld from `bash` as credentials, matched
107/// case-insensitively: `*_KEY` (including `*_API_KEY`) and the connection
108/// strings that embed passwords.
109const CREDENTIAL_SUFFIXES: [&str; 3] = ["_KEY", "DATABASE_URL", "_DSN"];
110/// Words whose presence anywhere in a variable name withholds it from
111/// `bash` as a credential, matched case-insensitively, such as
112/// `NPM_TOKEN` or `CARGO_REGISTRY_TOKEN`.
113const CREDENTIAL_WORDS: [&str; 5] = ["TOKEN", "SECRET", "PASSWORD", "PASSWD", "CREDENTIAL"];
114/// Variables granted to `bash` first, so the harness environment limit never
115/// drops them.
116const PRIORITY_ENVIRONMENT: [&str; 17] = [
117    "PATH",
118    "HOME",
119    "USER",
120    "LOGNAME",
121    "SHELL",
122    "LANG",
123    "LC_ALL",
124    "TERM",
125    "TMPDIR",
126    "SSH_AUTH_SOCK",
127    "GIT_SSH_COMMAND",
128    "CARGO_HOME",
129    "RUSTUP_HOME",
130    "RUSTUP_TOOLCHAIN",
131    "VIRTUAL_ENV",
132    "XDG_CONFIG_HOME",
133    "XDG_CACHE_HOME",
134];
135/// Session-scoped instructions stored with every harness session.
136const SYSTEM_PROMPT: &str = concat!(
137    "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
138    "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
139    "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
140    "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
141    "the tool reports it."
142);
143
144/// Environment snapshot provider used for credentials and `bash` grants.
145type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
146
147/// Host configuration that enables in-process [`AgentKind::Harness`] turns.
148///
149/// Each session keeps its durable harness history in
150/// `<data_root>/<session id>/`, outside the session worktree; hosts remove
151/// that directory when they delete the session. Its `tmp` directory is the
152/// `TMPDIR` and tool cache of the session's commands, which cannot read the
153/// rest of the data root; utility prompts get a fresh one each.
154///
155/// `bash` runs inside the native sandbox, which needs the host to call
156/// [`super::dispatch_sandbox_helper`] first in `main`; where the sandbox
157/// cannot run, commands run without it and every turn reports why.
158#[derive(Clone)]
159pub struct NativeHarnessConfig {
160    /// Directory of the per-project Cargo caches session turns reuse, or
161    /// `None` when sessions download their own dependencies.
162    cargo_cache_root: Option<PathBuf>,
163    data_root: PathBuf,
164    environment: EnvironmentSource,
165    /// Whether this process already removed the utility temporary
166    /// directories earlier processes left behind.
167    swept_utility_directories: Arc<AtomicBool>,
168}
169
170impl NativeHarnessConfig {
171    /// Configures harness storage under `data_root`, reading provider
172    /// settings from the process environment.
173    pub fn new(data_root: PathBuf) -> Self {
174        Self::with_environment(data_root, process_environment)
175    }
176
177    /// Configures harness storage under `data_root` with an explicit
178    /// environment source for provider settings and `bash` grants. A
179    /// relative `data_root` is resolved against the current directory.
180    ///
181    /// Provider API keys come from the API key file the environment
182    /// locates, `auth/api_keys.json` in Agentty's data directory:
183    /// `AGENTTY_ROOT`, else `~/.agentty`. A key variable is only imported into
184    /// that file.
185    pub fn with_environment(
186        data_root: PathBuf,
187        environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
188    ) -> Self {
189        Self {
190            cargo_cache_root: None,
191            data_root: std::path::absolute(&data_root).unwrap_or(data_root),
192            environment: Arc::new(environment),
193            swept_utility_directories: Arc::default(),
194        }
195    }
196
197    /// Makes session turns reuse the per-project Cargo caches under
198    /// `cache_root`, which the host fills through
199    /// [`super::TrustedCargoCache::refresh`] with the same root. A relative
200    /// `cache_root` is resolved against the current directory.
201    #[must_use]
202    pub fn with_trusted_cargo_cache(mut self, cache_root: PathBuf) -> Self {
203        self.cargo_cache_root = Some(std::path::absolute(&cache_root).unwrap_or(cache_root));
204
205        self
206    }
207
208    /// Returns a fresh environment snapshot, before stored API keys replace
209    /// its key variables.
210    pub(crate) fn environment(&self) -> BTreeMap<String, String> {
211        (self.environment)()
212    }
213
214    /// Creates and returns the session database path.
215    ///
216    /// # Errors
217    /// Returns an error for an identifier that is not one path component or
218    /// when the session directory cannot be created.
219    pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
220        let is_single_component = !session_id.is_empty()
221            && session_id != "."
222            && session_id != ".."
223            && !session_id.contains(['/', '\\', '\0']);
224        if !is_single_component {
225            return Err(format!("Invalid harness session id `{session_id}`."));
226        }
227        let directory = self.data_root.join(session_id);
228        tokio::fs::create_dir_all(&directory)
229            .await
230            .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;
231
232        Ok(directory.join(SESSION_DATABASE_FILE))
233    }
234
235    /// Returns the sandbox of the session's commands run in the folder of
236    /// `request`, with the session's own temporary directory, which keeps one
237    /// path for the session's lifetime because the harness fingerprints it
238    /// into the policy, and goes with the session's harness directory. When
239    /// `request` shares the
240    /// host's caches, commands use the host's dependency caches, Cargo's
241    /// included; otherwise, or where the host's Cargo caches cannot be
242    /// shared, and when the host keeps Cargo caches and resolved the
243    /// project's main checkout, its `CARGO_HOME` receives copies from that
244    /// project's cache. Each turn prepares the directory anew, so the choice
245    /// can change between turns.
246    ///
247    /// # Errors
248    /// Returns an error for an invalid session id or when the directory
249    /// cannot be prepared.
250    pub(crate) async fn session_sandbox(
251        &self,
252        session_id: &str,
253        request: &TurnRequest,
254        environment: &BTreeMap<String, String>,
255    ) -> Result<CommandSandbox, String> {
256        let database = self.session_database(session_id).await?;
257        let temporary_directory = database.with_file_name(SESSION_TEMPORARY_DIRECTORY);
258        tokio::fs::create_dir_all(&temporary_directory)
259            .await
260            .map_err(|error| {
261                format!("Failed to create the harness temporary directory: {error}")
262            })?;
263        let cargo_cache = self
264            .cargo_cache_root
265            .as_deref()
266            .zip(request.main_checkout_root.as_deref())
267            .map(|(root, main_checkout)| TrustedCargoCache::for_project(root, main_checkout));
268
269        CommandSandbox::prepare(
270            &self.data_root,
271            temporary_directory,
272            &request.folder,
273            environment,
274            cargo_cache,
275            request.host_caches,
276        )
277        .await
278    }
279
280    /// Returns the sandbox of one utility prompt's commands run in
281    /// `workspace`, with a fresh temporary directory removed when the
282    /// returned guard drops; utility prompts never share the host's caches. The
283    /// first call of this process first removes the directories earlier
284    /// processes left behind, which only one process per data root can own.
285    ///
286    /// # Errors
287    /// Returns an error when the directory cannot be created or prepared.
288    pub(crate) async fn utility_sandbox(
289        &self,
290        workspace: &Path,
291        environment: &BTreeMap<String, String>,
292    ) -> Result<(CommandSandbox, tempfile::TempDir), String> {
293        let parent = self.data_root.join(UTILITY_TEMPORARY_PARENT);
294        if !self.swept_utility_directories.swap(true, Ordering::SeqCst) {
295            let _ = tokio::fs::remove_dir_all(&parent).await;
296        }
297        let directory = tokio::task::spawn_blocking(move || {
298            std::fs::create_dir_all(&parent)
299                .and_then(|()| tempfile::Builder::new().prefix("run-").tempdir_in(&parent))
300        })
301        .await
302        .map_err(io::Error::other)
303        .flatten()
304        .map_err(|error| format!("Failed to create the harness temporary directory: {error}"))?;
305        let sandbox = CommandSandbox::prepare(
306            &self.data_root,
307            directory.path().to_path_buf(),
308            workspace,
309            environment,
310            None,
311            HostCacheSharing::PerSession,
312        )
313        .await?;
314
315        Ok((sandbox, directory))
316    }
317}
318
319/// Returns the process environment, skipping variables that are not valid
320/// Unicode.
321pub(crate) fn process_environment() -> BTreeMap<String, String> {
322    unicode_environment(env::vars_os())
323}
324
325/// Returns the harness models a user can choose: the models the local
326/// OpenAI-compatible server serves, plus `OPENAI_COMPATIBLE_MODEL` when the
327/// server does not list it, then the paid hosted catalog models with the
328/// API key, variable, or sign-in each still needs. `is_signed_in` reports
329/// whether a sign-in provider's credential file holds a usable sign-in.
330///
331/// Listing the local server is bounded by short request timeouts; an
332/// unreachable server contributes no discovered models.
333pub(crate) async fn harness_models(
334    environment: &BTreeMap<String, String>,
335    is_signed_in: impl Fn(&Path) -> bool,
336) -> Vec<HarnessModelOption> {
337    let mut options = local_models(environment).await;
338    options.extend(
339        AgentKind::Harness
340            .models()
341            .iter()
342            .filter_map(|model| hosted_model(*model, environment, &is_signed_in)),
343    );
344
345    options
346}
347
348/// Returns the served local models, with the configured model first when the
349/// server does not list it.
350async fn local_models(environment: &BTreeMap<String, String>) -> Vec<HarnessModelOption> {
351    let server = ModelProvider::OpenAiCompatible
352        .local_server(lookup(environment))
353        .ok()
354        .flatten();
355    let inventory = async { server?.inventory().await.ok() }.await;
356    let provider = inventory
357        .as_ref()
358        .map_or(LocalServerKind::OpenAiCompatible, |inventory| {
359            inventory.kind
360        })
361        .display_name();
362    let local_option = |model: AgentModel, status: HarnessModelStatus| HarnessModelOption {
363        context_window: None,
364        cost: ModelCost::Local,
365        loaded_context_window: None,
366        model,
367        provider: provider.to_string(),
368        status,
369        trains_on_prompts: false,
370    };
371    let mut options = inventory
372        .map_or_else(Vec::new, |inventory| inventory.models)
373        .into_iter()
374        .filter_map(|served| {
375            let status = if served.supports_tools == Some(false) {
376                HarnessModelStatus::NoToolSupport
377            } else {
378                HarnessModelStatus::Ready
379            };
380
381            Some(HarnessModelOption {
382                context_window: served.context_window,
383                loaded_context_window: served.loaded_context_window,
384                ..local_option(
385                    AgentModel::OpenAiCompatible(ServedModel::new(&served.id)?),
386                    status,
387                )
388            })
389        })
390        .collect::<Vec<_>>();
391    let configured = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV)
392        .and_then(ServedModel::new)
393        .map(AgentModel::OpenAiCompatible);
394    if let Some(configured) = configured
395        && !options.iter().any(|option| option.model == configured)
396    {
397        options.insert(0, local_option(configured, HarnessModelStatus::Ready));
398    }
399
400    options
401}
402
403/// Returns one paid catalog model with the API key, variable, or sign-in its
404/// provider still needs, or `None` for a model no built-in provider serves.
405fn hosted_model(
406    model: AgentModel,
407    environment: &BTreeMap<String, String>,
408    is_signed_in: impl Fn(&Path) -> bool,
409) -> Option<HarnessModelOption> {
410    let selection = ModelSelection::resolve_known(model.as_str()).ok()?;
411    let provider = selection.provider;
412    let cost = model_cost(provider.cost_tier(&selection.model)?);
413    let status = configuration_status(provider, environment, is_signed_in);
414
415    Some(HarnessModelOption {
416        context_window: selection
417            .profile(environment, None)
418            .ok()
419            .map(ModelProfile::context_window_tokens),
420        cost,
421        loaded_context_window: None,
422        model,
423        provider: provider_display_name(provider).to_string(),
424        status,
425        trains_on_prompts: provider.trains_on_prompts(&selection.model),
426    })
427}
428
429/// Returns the cost Agentty shows for a model of the harness catalog's
430/// price class `tier`; a tier added to the catalog later shows as standard.
431fn model_cost(tier: CostTier) -> ModelCost {
432    match tier {
433        CostTier::Local => ModelCost::Local,
434        CostTier::Plan => ModelCost::Plan,
435        CostTier::Cheap => ModelCost::Cheap,
436        CostTier::Premium => ModelCost::Premium,
437        _ => ModelCost::Standard,
438    }
439}
440
441/// Returns the name users know a hosted provider by, or the provider
442/// identifier for a provider the harness adds later.
443fn provider_display_name(provider: ModelProvider) -> &'static str {
444    const DISPLAY_NAMES: [(ModelProvider, &str); 7] = [
445        (ModelProvider::Anthropic, "Anthropic"),
446        (ModelProvider::ChatGpt, "ChatGPT plan"),
447        (ModelProvider::Kimi, "Kimi"),
448        (ModelProvider::Muse, "Muse"),
449        (ModelProvider::OpenAi, "OpenAI"),
450        (
451            ModelProvider::OpenAiCompatible,
452            LocalServerKind::OpenAiCompatible.display_name(),
453        ),
454        (ModelProvider::Qwen, "Qwen"),
455    ];
456
457    DISPLAY_NAMES
458        .iter()
459        .find(|(known, _)| *known == provider)
460        .map_or(provider.as_str(), |(_, name)| name)
461}
462
463/// Returns the context window `selection`'s server runs its model with, or
464/// `None` for hosted providers and servers that do not report it.
465///
466/// Ollama loads the model first when needed, as the turn's first request
467/// would. A server that cannot be queried reports nothing, leaving the
468/// declared profile and the turn's own request to surface the failure.
469///
470/// # Errors
471/// Returns an actionable error when the server runs the model with a window
472/// too small for harness turns, which Ollama would otherwise fill by
473/// silently dropping the start of the conversation.
474pub(crate) async fn running_context_window(
475    selection: &ModelSelection,
476    environment: &BTreeMap<String, String>,
477) -> Result<Option<u64>, String> {
478    let Ok(Some(server)) = selection.provider.local_server(lookup(environment)) else {
479        return Ok(None);
480    };
481    let Ok(Some(window)) = server.running_context_window(&selection.model).await else {
482        return Ok(None);
483    };
484    if window < MINIMUM_RUNNING_CONTEXT_WINDOW {
485        return Err(format!(
486            "The local server runs `{}` with a {window}-token context window, below the \
487             {MINIMUM_RUNNING_CONTEXT_WINDOW} tokens harness turns need, so it would drop the \
488             start of the conversation. Restart Ollama with `OLLAMA_CONTEXT_LENGTH=32768` (or \
489             raise the context length in the Ollama app's settings), or pick another model with \
490             `/model`.",
491            selection.model
492        ));
493    }
494
495    Ok(Some(window))
496}
497
498/// Reads `environment` as the lookup the harness provider catalog expects.
499pub(super) fn lookup(
500    environment: &BTreeMap<String, String>,
501) -> impl FnMut(&str) -> Result<String, env::VarError> + '_ {
502    |name| {
503        environment
504            .get(name)
505            .cloned()
506            .ok_or(env::VarError::NotPresent)
507    }
508}
509
510/// Returns the `ChatGPT` credential file Agentty signs in to and reads,
511/// shared with `ag-harness login chatgpt` through [`chatgpt_auth_file_in`]:
512/// `CHATGPT_AUTH_FILE`, else `auth/chatgpt.json` under `AGENTTY_ROOT` or
513/// `~/.agentty`, or `None` when none of them is set. A data-directory
514/// variable is used as given unless it is empty, as `agentty`'s data
515/// directory reads it.
516pub(super) fn chatgpt_auth_file(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
517    chatgpt_auth_file_in(lookup(environment), agentty_home(environment).as_deref())
518}
519
520/// Returns Agentty's data directory as `agentty` reads it: `AGENTTY_ROOT`,
521/// else `~/.agentty`, each used as given unless empty, or `None` when
522/// neither variable is set.
523pub(super) fn agentty_home(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
524    let set = |name: &str| {
525        environment
526            .get(name)
527            .filter(|value| !value.is_empty())
528            .map(PathBuf::from)
529    };
530
531    set(AGENTTY_ROOT_ENV).or_else(|| set("HOME").map(|home| home.join(".agentty")))
532}
533
534/// Keeps the variables whose name and value are both valid Unicode.
535fn unicode_environment(
536    variables: impl IntoIterator<Item = (OsString, OsString)>,
537) -> BTreeMap<String, String> {
538    variables
539        .into_iter()
540        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
541        .collect()
542}
543
544/// Returns whether a provider can serve requests now: a sign-in provider
545/// needs a usable sign-in, as `is_signed_in` reports; another needs a base
546/// URL unless it has a default, then its stored API key unless optional.
547/// The base URL is checked first so that a provider asks for a key only
548/// when saving one makes it ready.
549fn configuration_status(
550    provider: ModelProvider,
551    environment: &BTreeMap<String, String>,
552    is_signed_in: impl Fn(&Path) -> bool,
553) -> HarnessModelStatus {
554    if provider.requires_sign_in() {
555        let signed_in =
556            chatgpt_auth_file(environment).is_some_and(|auth_file| is_signed_in(&auth_file));
557
558        return if signed_in {
559            HarnessModelStatus::Ready
560        } else {
561            HarnessModelStatus::SignInRequired(CHATGPT_SIGN_IN_COMMAND)
562        };
563    }
564    if provider.default_base_url().is_none()
565        && !has_value(environment, provider.base_url_environment())
566    {
567        return HarnessModelStatus::MissingConfiguration(provider.base_url_environment());
568    }
569    if provider.requires_api_key() && !has_value(environment, provider.api_key_environment()) {
570        return HarnessModelStatus::ApiKeyRequired(provider.as_str());
571    }
572
573    HarnessModelStatus::Ready
574}
575
576/// Returns the trimmed value of `name`, or `None` when it is unset or blank.
577fn nonblank<'a>(environment: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
578    environment
579        .get(name)
580        .map(|value| value.trim())
581        .filter(|value| !value.is_empty())
582}
583
584/// Returns whether `name` holds a nonblank value.
585fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
586    nonblank(environment, name).is_some()
587}
588
589/// One harness model resolved to its built-in provider and the model id
590/// sent to it.
591#[derive(Clone, Debug, Eq, PartialEq)]
592pub(crate) struct ModelSelection {
593    model: String,
594    provider: ModelProvider,
595}
596
597impl ModelSelection {
598    /// Resolves an Agentty harness model id to its provider. A served
599    /// `openai-compatible/<model>` id resolves to that model, and the bare
600    /// `openai-compatible` id to the model `OPENAI_COMPATIBLE_MODEL` names.
601    ///
602    /// # Errors
603    /// Returns an error when no built-in provider serves `model`, or when
604    /// `OPENAI_COMPATIBLE_MODEL` is unset for `openai-compatible`.
605    pub(crate) fn resolve(
606        model: &str,
607        environment: &BTreeMap<String, String>,
608    ) -> Result<Self, String> {
609        let Some(AgentModel::OpenAiCompatible(served)) = AgentKind::Harness.parse_model(model)
610        else {
611            return Self::resolve_known(model);
612        };
613        if let Some(name) = served.name() {
614            return Ok(Self {
615                model: name.to_string(),
616                provider: ModelProvider::OpenAiCompatible,
617            });
618        }
619        let served = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV).ok_or_else(|| {
620            format!(
621                "Cannot use harness model `{model}`: {OPENAI_COMPATIBLE_MODEL_ENV} is unset. Pick \
622                 a local model with `/model`, or set it to the model your OpenAI-compatible \
623                 server serves, such as `qwen3:latest`, before starting Agentty."
624            )
625        })?;
626
627        Ok(Self {
628            model: served.to_string(),
629            provider: ModelProvider::OpenAiCompatible,
630        })
631    }
632
633    /// Resolves a recorded registration key such as `kimi/kimi-k3`,
634    /// `chatgpt/gpt-6.1-sol`, or `openai-compatible/qwen3:latest`, or `None`
635    /// for a key without a known provider and model.
636    pub(crate) fn from_key(key: &str) -> Option<Self> {
637        let (provider, model) = key.split_once('/')?;
638        if provider == ModelProvider::OpenAiCompatible.as_str() {
639            return (!model.trim().is_empty()).then(|| Self {
640                model: model.to_string(),
641                provider: ModelProvider::OpenAiCompatible,
642            });
643        }
644        // A ChatGPT-plan model id is its key, `chatgpt/<model>`.
645        let id = if provider == ModelProvider::ChatGpt.as_str() {
646            key
647        } else {
648            model
649        };
650
651        Self::resolve_known(id)
652            .ok()
653            .filter(|selection| selection.key() == key)
654    }
655
656    /// Resolves a catalog model id to the built-in provider listing it. A
657    /// `chatgpt/<model>` id resolves only to [`ModelProvider::ChatGpt`], and
658    /// a bare id never does, so the `ChatGPT` plan and API-billed `OpenAI`
659    /// never stand in for each other.
660    fn resolve_known(model: &str) -> Result<Self, String> {
661        let unknown = || format!("The harness does not serve model `{model}`.");
662        if let Some(plan_model) = model
663            .strip_prefix(ModelProvider::ChatGpt.as_str())
664            .and_then(|rest| rest.strip_prefix('/'))
665        {
666            return ModelProvider::ChatGpt
667                .known_models()
668                .contains(&plan_model)
669                .then(|| Self {
670                    model: plan_model.to_string(),
671                    provider: ModelProvider::ChatGpt,
672                })
673                .ok_or_else(unknown);
674        }
675
676        ModelProvider::all()
677            .iter()
678            .copied()
679            .filter(|provider| !provider.requires_sign_in())
680            .find(|provider| provider.known_models().contains(&model))
681            .map(|provider| Self {
682                model: model.to_string(),
683                provider,
684            })
685            .ok_or_else(unknown)
686    }
687
688    /// Returns the stable registry key.
689    pub(crate) fn key(&self) -> String {
690        format!("{}/{}", self.provider, self.model)
691    }
692
693    /// Returns this model's entry in the harness provider catalog, with its
694    /// list prices and declared profile, or `None` for a model the catalog
695    /// does not describe, such as one a local server serves.
696    pub(crate) fn catalog_spec(&self) -> Option<ModelSpec> {
697        self.provider.model_spec(&self.model)
698    }
699
700    /// Returns the catalog entry of the API model a plan-billed model
701    /// mirrors: for a `ChatGPT` plan model, the same-named `OpenAI` API
702    /// model, whose list prices give the plan usage's API equivalent. Other
703    /// models, and plan models without an API twin, return `None`.
704    pub(crate) fn api_twin_spec(&self) -> Option<ModelSpec> {
705        (self.provider == ModelProvider::ChatGpt)
706            .then(|| ModelProvider::OpenAi.model_spec(&self.model))
707            .flatten()
708    }
709
710    /// Returns the context window turns on this model are fitted to, as
711    /// [`Self::profile`] resolves it, or `None` for an invalid
712    /// environment-declared profile.
713    pub(crate) fn context_window(
714        &self,
715        environment: &BTreeMap<String, String>,
716        running_context_window: Option<u64>,
717    ) -> Option<u64> {
718        self.profile(environment, running_context_window)
719            .ok()
720            .map(ModelProfile::context_window_tokens)
721    }
722
723    /// Returns the Agentty model id of the registration key `key`, as users
724    /// pick the model: `ChatGPT` plan and local server models keep their
725    /// provider, as in `chatgpt/gpt-6-luna`, and other cataloged models are
726    /// bare, as in `gpt-6-luna`. An unknown key is returned unchanged.
727    pub(crate) fn model_id_of(key: &str) -> String {
728        match Self::from_key(key) {
729            Some(selection)
730                if !matches!(
731                    selection.provider,
732                    ModelProvider::ChatGpt | ModelProvider::OpenAiCompatible
733                ) =>
734            {
735                selection.model
736            }
737            _ => key.to_string(),
738        }
739    }
740
741    /// Returns the model that writes compaction summaries for sessions
742    /// running on this selection in its place: `requested`, such as the
743    /// user's Default Fast Model, when it resolves to another harness model
744    /// whose provider can serve requests now, as `is_signed_in` reports for a
745    /// sign-in provider, and that declares structured output for the summary
746    /// schema. Otherwise returns `None`, so the session's own model
747    /// summarizes, and logs why a requested model was passed over.
748    pub(crate) fn summary_model(
749        &self,
750        requested: Option<&str>,
751        environment: &BTreeMap<String, String>,
752        is_signed_in: impl Fn(&Path) -> bool,
753    ) -> Option<Self> {
754        let requested = requested?;
755        let rejection = match Self::resolve(requested, environment) {
756            Err(error) => error,
757            Ok(candidate) if candidate == *self => return None,
758            Ok(candidate) => {
759                match configuration_status(candidate.provider, environment, is_signed_in) {
760                    HarnessModelStatus::Ready
761                        if candidate
762                            .provider
763                            .capabilities(&candidate.model)
764                            .is_some_and(Capabilities::structured_output) =>
765                    {
766                        return Some(candidate);
767                    }
768                    HarnessModelStatus::Ready => "it declares no structured output".to_string(),
769                    status => format!("it is not ready ({status:?})"),
770                }
771            }
772        };
773        tracing::warn!(summary_model = requested, %rejection, "summarizing on the session model");
774
775        None
776    }
777
778    /// Registers this model's provider client under its key.
779    ///
780    /// # Errors
781    /// Returns an actionable error when credentials or the endpoint are
782    /// missing, or the registration is invalid.
783    pub(crate) fn registry(
784        &self,
785        environment: &BTreeMap<String, String>,
786        running_context_window: Option<u64>,
787    ) -> Result<ModelRegistry, String> {
788        let model = self.client(environment)?;
789
790        self.register(model, self.profile(environment, running_context_window)?)
791    }
792
793    /// Returns this model's catalog entry as the harness provider catalog
794    /// declares it, with its prices, profile, and output limit, so the
795    /// requests it answers as a summary model are priced at its own prices.
796    ///
797    /// # Errors
798    /// Returns an actionable error when credentials or the endpoint are
799    /// missing, or the entry is invalid.
800    fn summary_entry(&self, environment: &BTreeMap<String, String>) -> Result<ModelHandle, String> {
801        let id = ModelId::cataloged(self.provider, &self.model);
802        let spec = self
803            .provider
804            .model_spec(&self.model)
805            .ok_or("The harness provider catalog does not list the summary model.")?;
806
807        ModelCatalog::builder()
808            .model(spec, self.client(environment)?)
809            .build()
810            .and_then(|catalog| catalog.resolve(&ModelSelector::Id(id)))
811            .map_err(failure("Invalid harness summary model"))
812    }
813
814    /// Returns this model's provider client. Provider-call budgets are
815    /// charged once per run by the turn, not per model request here.
816    ///
817    /// # Errors
818    /// Returns an actionable error when credentials or the endpoint are
819    /// missing.
820    fn client(&self, environment: &BTreeMap<String, String>) -> Result<Arc<dyn Model>, String> {
821        let mut configuration = ModelConfiguration::new(self.provider, &self.model);
822        // Only the `ChatGPT` provider reads a sign-in, and the harness keeps
823        // no default location for it.
824        if self.provider.requires_sign_in()
825            && let Some(auth_file) = chatgpt_auth_file(environment)
826        {
827            configuration = configuration.auth_file(auth_file);
828        }
829        let client = configuration
830            .client_from_environment(lookup(environment))
831            .map_err(|error| {
832                let remedy = if self.provider.requires_sign_in() {
833                    format!("Run `{CHATGPT_SIGN_IN_COMMAND}`, then retry.")
834                } else if self.provider.requires_api_key() {
835                    "Pick the model with `/model` to paste its API key, then retry.".to_string()
836                } else {
837                    format!(
838                        "Check {OPENAI_COMPATIBLE_MODEL_ENV} and {} before starting Agentty.",
839                        self.provider.base_url_environment()
840                    )
841                };
842
843                format!(
844                    "Cannot use harness model `{}`: {error}. {remedy}",
845                    self.model
846                )
847            })?;
848
849        Ok(Arc::new(client))
850    }
851
852    /// Builds a harness for this model with Agentty's defaults, summarizing
853    /// on `context.summary_model` when it is set and can serve summaries, as
854    /// [`HarnessContext::apply_summary_model`] decides.
855    ///
856    /// # Errors
857    /// Returns the registration failure.
858    pub(crate) fn harness(
859        &self,
860        context: &HarnessContext<'_>,
861        observer: impl LifecycleObserver + 'static,
862    ) -> Result<Harness, String> {
863        let registry = self.registry(context.environment, context.running_context_window)?;
864        let mut harness = self.harness_from(&registry, context, observer)?;
865        context.apply_summary_model(|summary| harness.set_summary_model(summary));
866
867        Ok(harness)
868    }
869
870    /// Builds a harness that resumes a session recorded on this model without
871    /// its provider credentials. Switch the session to another model before
872    /// running a turn; this registration never sends a request.
873    ///
874    /// # Errors
875    /// Returns the registration failure.
876    pub(crate) fn resume_only_harness(
877        &self,
878        context: &HarnessContext<'_>,
879        observer: impl LifecycleObserver + 'static,
880    ) -> Result<Harness, String> {
881        // A sign-in provider's client reads no credential until a request,
882        // so it needs no stored sign-in here.
883        let client = if self.provider.requires_sign_in() {
884            ModelClient::chatgpt(ChatGptConfig {
885                auth_file: PathBuf::new(),
886                base_url: RESUME_ONLY_BASE_URL.to_string(),
887                model: self.model.clone(),
888            })
889            .map_err(failure("Invalid resume-only harness model"))?
890        } else {
891            ModelConfiguration::new(self.provider, &self.model)
892                .base_url(RESUME_ONLY_BASE_URL)
893                .client_from_environment(|_| Ok(RESUME_ONLY_API_KEY.to_string()))
894                .map_err(failure("Invalid resume-only harness model"))?
895        };
896        let metadata = client.metadata().clone();
897        let profile = self.profile(context.environment, None)?;
898        let registry = self.register(Arc::new(ResumeOnlyModel { metadata }), profile)?;
899
900        self.harness_from(&registry, context, observer)
901    }
902
903    /// Registers `model` as the catalog entry of this selection's key, with
904    /// `profile` and the capabilities the harness provider catalog declares
905    /// for the model, under [`REGISTRATION_REVISION`]. A selection only holds
906    /// a cataloged model or one an OpenAI-compatible server serves, both of
907    /// which the catalog describes.
908    ///
909    /// The entry carries no prices or output limit, so runs stay unpriced
910    /// and unmetered as before, and the harness derives the same key,
911    /// revision, and capabilities recorded sessions hold.
912    fn register(
913        &self,
914        model: Arc<dyn Model>,
915        profile: ModelProfile,
916    ) -> Result<ModelRegistry, String> {
917        let id = ModelId::cataloged(self.provider, &self.model);
918        let declared = self
919            .provider
920            .capabilities(&self.model)
921            .unwrap_or(Capabilities::NONE);
922        let spec = ModelSpec::new(id.clone())
923            .with_provider(self.provider)
924            .with_capabilities(declared)
925            .with_profile(profile);
926        let handle = ModelCatalog::builder()
927            .model(spec, model)
928            .build()
929            .and_then(|catalog| catalog.resolve(&ModelSelector::Id(id)))
930            .map_err(failure("Invalid harness model registration"))?;
931        let mut registry = ModelRegistry::new();
932        registry
933            .register_catalog_entry(&handle, REGISTRATION_REVISION)
934            .map_err(failure("Invalid harness model registration"))?;
935
936        Ok(registry)
937    }
938
939    /// Builds a harness over this selection's registration in `registry`
940    /// whose durable sessions, when `context.compacts`, compact their earlier
941    /// turns automatically once replayed history nears the context budget,
942    /// and otherwise evict them.
943    ///
944    /// A turn built inside a recording trace also exports the harness's
945    /// `invoke_agent`, `chat`, and `execute_tool` spans beneath the current
946    /// span; an untraced turn skips that projection.
947    fn harness_from(
948        &self,
949        registry: &ModelRegistry,
950        context: &HarnessContext<'_>,
951        observer: impl LifecycleObserver + 'static,
952    ) -> Result<Harness, String> {
953        let context_policy = if context.compacts {
954            ContextPolicy::auto_compact()
955        } else {
956            ContextPolicy::Evict
957        };
958
959        Ok(Harness::from_registry(registry, &self.key())
960            .map_err(failure("Invalid harness model registration"))?
961            .context_policy(context_policy)
962            .repository(context.repository.clone())
963            .sandbox(context.sandbox)
964            .model_reasoning_effort(reasoning_effort(context.reasoning_level))
965            .with_lifecycle_observer(traced(observer)))
966    }
967
968    /// Returns the context profile sized to the window a local server runs
969    /// the model with, else the one the harness provider catalog or the
970    /// environment declares for this model, else the Agentty catalog model's
971    /// declared profile, else the conservative fallback. Codex models served
972    /// by the harness take the provider catalog's profile, not the one
973    /// Agentty declares for Codex app-server compaction.
974    ///
975    /// # Errors
976    /// Returns an error for an invalid environment-declared profile.
977    fn profile(
978        &self,
979        environment: &BTreeMap<String, String>,
980        running_context_window: Option<u64>,
981    ) -> Result<ModelProfile, String> {
982        let declared = match running_context_window {
983            Some(window) => self.provider.running_profile(lookup(environment), window),
984            None => self
985                .provider
986                .declared_profile(&self.model, lookup(environment)),
987        }
988        .map_err(failure("Invalid harness model profile"))?;
989
990        Ok(declared
991            .or_else(|| {
992                AgentKind::Harness
993                    .parse_model(&self.model)
994                    .and_then(model_profile::declared)
995            })
996            .unwrap_or(FALLBACK_MODEL_PROFILE))
997    }
998}
999
1000/// Inputs shared by every harness built for one turn.
1001pub(crate) struct HarnessContext<'a> {
1002    /// Whether durable sessions compact their earlier turns automatically.
1003    pub(crate) compacts: bool,
1004    /// Environment snapshot used for credentials.
1005    pub(crate) environment: &'a BTreeMap<String, String>,
1006    /// Requested reasoning depth.
1007    pub(crate) reasoning_level: ReasoningLevel,
1008    /// Validated worktree available to tools.
1009    pub(crate) repository: &'a Repository,
1010    /// Context window the local server runs the model with, when known.
1011    pub(crate) running_context_window: Option<u64>,
1012    /// How `bash` runs where the native sandbox cannot.
1013    pub(crate) sandbox: Sandbox,
1014    /// Model that writes compaction summaries in place of the turn's model,
1015    /// resolved by [`ModelSelection::summary_model`].
1016    pub(crate) summary_model: Option<&'a ModelSelection>,
1017}
1018
1019impl HarnessContext<'_> {
1020    /// Hands the catalog entry of [`Self::summary_model`] to `apply`, which
1021    /// sets it on a harness or session. When the entry cannot be built or
1022    /// `apply` refuses it, logs why and leaves the session's own model
1023    /// summarizing rather than failing the turn.
1024    pub(crate) fn apply_summary_model(
1025        &self,
1026        apply: impl FnOnce(&ModelHandle) -> Result<(), HarnessError>,
1027    ) {
1028        let Some(summary_model) = self.summary_model else {
1029            return;
1030        };
1031        let applied = summary_model
1032            .summary_entry(self.environment)
1033            .and_then(|entry| apply(&entry).map_err(|error| error.to_string()));
1034        if let Err(error) = applied {
1035            let summary_model = summary_model.key();
1036            tracing::warn!(%summary_model, %error, "summarizing on the session model");
1037        }
1038    }
1039}
1040
1041/// Returns the instructions stored with new harness sessions.
1042pub(crate) fn system_prompt() -> &'static str {
1043    SYSTEM_PROMPT
1044}
1045
1046/// Returns the protocol output schema for one request profile.
1047///
1048/// # Errors
1049/// Returns an error when the harness rejects the protocol schema.
1050pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
1051    OutputSchema::new(protocol_output_schema(
1052        profile,
1053        SchemaRequiredPolicy::MinimumProtocolKeys,
1054    ))
1055    .map_err(failure("The harness rejected the protocol schema"))
1056}
1057
1058/// Explicit output schema and tools of one harness turn or run.
1059pub(crate) struct RunOptions {
1060    bash: Option<BashConfig>,
1061    output: OutputSchema,
1062    tools: ToolSet,
1063}
1064
1065impl RunOptions {
1066    /// Builds the options for one turn: `read` always, plus `write` and
1067    /// `bash` in `sandbox` outside read-only mode.
1068    ///
1069    /// # Errors
1070    /// Returns an error when the schema or `bash` policy is rejected.
1071    pub(crate) fn new(
1072        profile: ProtocolRequestProfile,
1073        permission_mode: PermissionMode,
1074        environment: &BTreeMap<String, String>,
1075        sandbox: &CommandSandbox,
1076    ) -> Result<Self, String> {
1077        let output = output_schema(profile)?;
1078        if permission_mode == PermissionMode::ReadOnly {
1079            return Ok(Self {
1080                bash: None,
1081                output,
1082                tools: ToolSet::empty().with_read(),
1083            });
1084        }
1085
1086        Ok(Self {
1087            bash: Some(bash_config(environment, sandbox)?),
1088            output,
1089            tools: ToolSet::builtins(),
1090        })
1091    }
1092
1093    /// Returns whether the run offers `bash`, which the native sandbox runs.
1094    pub(crate) fn offers_bash(&self) -> bool {
1095        self.bash.is_some()
1096    }
1097
1098    /// Returns a run request for `input` with these options.
1099    pub(crate) fn request(self, input: String) -> RunRequest {
1100        let request = RunRequest::new(input).output(self.output).tools(self.tools);
1101
1102        match self.bash {
1103            Some(bash) => request.bash(bash),
1104            None => request,
1105        }
1106    }
1107}
1108
1109/// Configures `bash` in the native sandbox with `sandbox`'s grants and the
1110/// host environment minus provider variables, keeping essentials first
1111/// within the harness grant limits. Host values of the variables the
1112/// grants set, such as `TMPDIR` and the tool caches, are not granted.
1113fn bash_config(
1114    environment: &BTreeMap<String, String>,
1115    sandbox: &CommandSandbox,
1116) -> Result<BashConfig, String> {
1117    let revision = if sandbox.shares_host_caches() {
1118        HOST_CACHE_POLICY_REVISION
1119    } else {
1120        BASH_POLICY_REVISION
1121    };
1122    let mut config = BashConfig::native(
1123        PathBuf::from(BASH_EXECUTABLE),
1124        revision.to_string(),
1125        BASH_TIMEOUT,
1126        BashConfig::DEFAULT_CAPTURE_BYTES,
1127    )
1128    .and_then(|config| sandbox.grant(config.with_host_information()))
1129    .map_err(failure("Invalid harness bash policy"))?;
1130    for (name, value) in bash_environment(environment) {
1131        if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
1132            config = granted;
1133        }
1134    }
1135
1136    Ok(config)
1137}
1138
1139/// Orders granted variables: essentials first, then the rest by name,
1140/// without provider variables or credentials.
1141fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
1142    let is_granted = |name: &str| {
1143        !PROVIDER_ENVIRONMENT_PREFIXES
1144            .iter()
1145            .any(|prefix| name.starts_with(prefix))
1146            && !is_credential(name)
1147    };
1148    let priority = PRIORITY_ENVIRONMENT
1149        .iter()
1150        .filter_map(|name| environment.get_key_value(*name));
1151    let remaining = environment
1152        .iter()
1153        .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));
1154
1155    priority
1156        .chain(remaining)
1157        .filter(|(name, _)| is_granted(name))
1158        .collect()
1159}
1160
1161/// Returns whether the variable `name` likely carries a credential, which
1162/// commands with network access could send anywhere: tokens, secrets, keys,
1163/// passwords, credentials, and connection strings, plus every AWS, GitHub,
1164/// and `GitLab` variable, whatever their case.
1165fn is_credential(name: &str) -> bool {
1166    let name = name.to_ascii_uppercase();
1167
1168    CREDENTIAL_PREFIXES
1169        .iter()
1170        .any(|prefix| name.starts_with(prefix))
1171        || CREDENTIAL_SUFFIXES
1172            .iter()
1173            .any(|suffix| name.ends_with(suffix))
1174        || CREDENTIAL_WORDS.iter().any(|word| name.contains(word))
1175}
1176
1177/// Validates the worktree with the first absolute `git` on `PATH`.
1178///
1179/// # Errors
1180/// Returns an error for an invalid worktree or when no usable Git exists.
1181pub(crate) fn repository(
1182    folder: &Path,
1183    environment: &BTreeMap<String, String>,
1184) -> Result<Repository, String> {
1185    let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
1186    let candidates = environment
1187        .get("PATH")
1188        .into_iter()
1189        .flat_map(env::split_paths)
1190        .filter(|directory| directory.is_absolute())
1191        .map(|directory| directory.join(&executable_name));
1192    for candidate in candidates {
1193        match Repository::new(folder, candidate) {
1194            Ok(repository) => return Ok(repository),
1195            Err(
1196                error @ (RepositoryError::Root { .. }
1197                | RepositoryError::RootIsGitAdministrative { .. }),
1198            ) => return Err(format!("Invalid harness worktree: {error}")),
1199            Err(_) => {}
1200        }
1201    }
1202
1203    Err("The harness needs a Git executable on PATH.".to_string())
1204}
1205
1206/// Returns an error mapper that prefixes a harness failure with `context`.
1207pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
1208    move |error| format!("{context}: {error}")
1209}
1210
1211/// Maps Agentty's reasoning level to the harness reasoning effort.
1212fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
1213    match reasoning_level {
1214        ReasoningLevel::Low => ReasoningEffort::Low,
1215        ReasoningLevel::Medium => ReasoningEffort::Medium,
1216        ReasoningLevel::High => ReasoningEffort::High,
1217        ReasoningLevel::XHigh => ReasoningEffort::XHigh,
1218        ReasoningLevel::Max => ReasoningEffort::Max,
1219    }
1220}
1221
1222/// Adds the harness's OpenTelemetry span projection after `observer` when
1223/// the current execution span is recording. Its `execute_tool` spans repeat
1224/// the run identity the turn inherits, like other harnesses' tool spans.
1225fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
1226    let observers = LifecycleObserverSet::new(observer);
1227    if !Context::current().span().is_recording() {
1228        return observers;
1229    }
1230
1231    observers.with_observer(
1232        LifecycleTraceObserver::new().with_tool_attributes(ag_telemetry::run_identity),
1233    )
1234}
1235
1236/// Stand-in for a recorded model that only lets its session resume and switch
1237/// away.
1238struct ResumeOnlyModel {
1239    metadata: ModelMetadata,
1240}
1241
1242#[async_trait]
1243impl Model for ResumeOnlyModel {
1244    fn metadata(&self) -> Option<ModelMetadata> {
1245        Some(self.metadata.clone())
1246    }
1247
1248    async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
1249        Err(ModelError::request(io::Error::other(
1250            "the recorded harness model can only resume its session",
1251        )))
1252    }
1253}
1254
1255#[cfg(test)]
1256#[path = "config_test.rs"]
1257mod tests;