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::{ModelConfiguration, ModelProvider};
19use ag_harness::recovery::ExecutionIdentity;
20use ag_harness::{
21    Harness, Model, ModelError, OutputSchema, Repository, RepositoryError, Tool, ToolPolicy,
22    TurnInput, TurnOptions,
23};
24use ag_protocol::{ProtocolRequestProfile, SchemaRequiredPolicy, protocol_output_schema};
25use ag_session::{AgentKind, AgentModel};
26use ag_telemetry::{Context, TraceContextExt as _};
27use async_trait::async_trait;
28
29use crate::agent::model_profile;
30
31/// Revision of Agentty's harness model registrations. Durable sessions record
32/// it and require the same value on resume.
33const REGISTRATION_REVISION: &str = "agentty-native-2";
34/// Conservative profile for a harness model without a declared profile. Its
35/// default estimator runs up to 46% under dense content and further under
36/// small requests whose fixed provider cost it never weighs.
37const FALLBACK_MODEL_PROFILE: ModelProfile =
38    ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
39/// Placeholder endpoint for resume-only registrations, which never send
40/// requests.
41const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
42/// SQLite file holding one session's durable harness history.
43const SESSION_DATABASE_FILE: &str = "harness.db";
44/// Trusted Bash executable used by edit-mode `bash` calls.
45const BASH_EXECUTABLE: &str = "/bin/bash";
46/// Nonsecret identity of the unsandboxed Bash policy.
47const BASH_POLICY_REVISION: &str = "agentty-unsandboxed-1";
48/// Deadline for one `bash` call.
49const BASH_TIMEOUT: Duration = Duration::from_secs(600);
50/// Output bytes kept from one `bash` call, the harness maximum.
51const BASH_CAPTURE_BYTES: usize = 8192;
52/// Environment prefixes that carry provider keys and endpoints, withheld from
53/// `bash`.
54const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 3] = ["DASHSCOPE_", "KIMI_", "MODEL_"];
55/// Variables granted to `bash` first, so the harness environment limit never
56/// drops them.
57const PRIORITY_ENVIRONMENT: [&str; 17] = [
58    "PATH",
59    "HOME",
60    "USER",
61    "LOGNAME",
62    "SHELL",
63    "LANG",
64    "LC_ALL",
65    "TERM",
66    "TMPDIR",
67    "SSH_AUTH_SOCK",
68    "GIT_SSH_COMMAND",
69    "CARGO_HOME",
70    "RUSTUP_HOME",
71    "RUSTUP_TOOLCHAIN",
72    "VIRTUAL_ENV",
73    "XDG_CONFIG_HOME",
74    "XDG_CACHE_HOME",
75];
76/// Session-scoped instructions stored with every harness session.
77const SYSTEM_PROMPT: &str = concat!(
78    "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
79    "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
80    "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
81    "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
82    "the tool reports it."
83);
84
85/// Environment snapshot provider used for credentials and `bash` grants.
86type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
87
88/// Host configuration that enables in-process [`AgentKind::Harness`] turns.
89///
90/// Each session keeps its durable harness history in
91/// `<data_root>/<session id>/`, outside the session worktree; hosts remove that
92/// directory when they delete the session.
93#[derive(Clone)]
94pub struct NativeHarnessConfig {
95    data_root: PathBuf,
96    environment: EnvironmentSource,
97}
98
99impl NativeHarnessConfig {
100    /// Configures harness storage under `data_root`, reading provider
101    /// credentials from the process environment.
102    pub fn new(data_root: PathBuf) -> Self {
103        Self::with_environment(data_root, process_environment)
104    }
105
106    /// Configures harness storage under `data_root` with an explicit
107    /// environment source for provider credentials and `bash` grants.
108    pub fn with_environment(
109        data_root: PathBuf,
110        environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
111    ) -> Self {
112        Self {
113            data_root,
114            environment: Arc::new(environment),
115        }
116    }
117
118    /// Returns a fresh environment snapshot.
119    pub(crate) fn environment(&self) -> BTreeMap<String, String> {
120        (self.environment)()
121    }
122
123    /// Creates and returns the session database path.
124    ///
125    /// # Errors
126    /// Returns an error for an identifier that is not one path component or
127    /// when the session directory cannot be created.
128    pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
129        let is_single_component = !session_id.is_empty()
130            && session_id != "."
131            && session_id != ".."
132            && !session_id.contains(['/', '\\', '\0']);
133        if !is_single_component {
134            return Err(format!("Invalid harness session id `{session_id}`."));
135        }
136        let directory = self.data_root.join(session_id);
137        tokio::fs::create_dir_all(&directory)
138            .await
139            .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;
140
141        Ok(directory.join(SESSION_DATABASE_FILE))
142    }
143}
144
145/// Returns the process environment, skipping variables that are not valid
146/// Unicode.
147pub(crate) fn process_environment() -> BTreeMap<String, String> {
148    unicode_environment(env::vars_os())
149}
150
151/// Returns the first harness model whose provider has an API key and a
152/// reachable endpoint, or `None` when no provider is configured.
153pub(crate) fn default_model(environment: &BTreeMap<String, String>) -> Option<AgentModel> {
154    AgentKind::Harness.models().iter().copied().find(|model| {
155        ModelSelection::resolve(model.as_str())
156            .is_ok_and(|selection| provider_configured(selection.provider, environment))
157    })
158}
159
160/// Keeps the variables whose name and value are both valid Unicode.
161fn unicode_environment(
162    variables: impl IntoIterator<Item = (OsString, OsString)>,
163) -> BTreeMap<String, String> {
164    variables
165        .into_iter()
166        .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
167        .collect()
168}
169
170/// Returns whether one provider has a nonempty key and a base URL.
171fn provider_configured(provider: ModelProvider, environment: &BTreeMap<String, String>) -> bool {
172    let has_value = |name: &str| {
173        environment
174            .get(name)
175            .is_some_and(|value| !value.trim().is_empty())
176    };
177
178    has_value(provider.api_key_environment())
179        && (provider.default_base_url().is_some() || has_value(provider.base_url_environment()))
180}
181
182/// One harness model resolved to its built-in provider.
183#[derive(Clone, Debug, Eq, PartialEq)]
184pub(crate) struct ModelSelection {
185    model: String,
186    provider: ModelProvider,
187}
188
189impl ModelSelection {
190    /// Resolves an Agentty harness model id to its provider.
191    ///
192    /// # Errors
193    /// Returns an error when no built-in provider serves `model`.
194    pub(crate) fn resolve(model: &str) -> Result<Self, String> {
195        ModelProvider::all()
196            .iter()
197            .copied()
198            .find(|provider| provider.known_models().contains(&model))
199            .map(|provider| Self {
200                model: model.to_string(),
201                provider,
202            })
203            .ok_or_else(|| format!("The harness does not serve model `{model}`."))
204    }
205
206    /// Resolves a recorded registration key such as `kimi/kimi-k3`, or
207    /// `None` for a key without a known provider and model.
208    pub(crate) fn from_key(key: &str) -> Option<Self> {
209        let (_, model) = key.split_once('/')?;
210
211        Self::resolve(model)
212            .ok()
213            .filter(|selection| selection.key() == key)
214    }
215
216    /// Returns the stable registry key.
217    pub(crate) fn key(&self) -> String {
218        format!("{}/{}", self.provider, self.model)
219    }
220
221    /// Registers this model's provider client under its key.
222    ///
223    /// # Errors
224    /// Returns an actionable error when credentials or the endpoint are
225    /// missing, or the registration is invalid.
226    pub(crate) fn registry(
227        &self,
228        environment: &BTreeMap<String, String>,
229        provider_call_budget: Option<&ProviderCallBudget>,
230    ) -> Result<ModelRegistry, String> {
231        let client = ModelConfiguration::new(self.provider, &self.model)
232            .client_from_environment(|name| {
233                environment
234                    .get(name)
235                    .cloned()
236                    .ok_or(env::VarError::NotPresent)
237            })
238            .map_err(|error| {
239                format!(
240                    "Cannot use harness model `{}`: {error}. Set {} before starting Agentty.",
241                    self.model,
242                    self.provider.api_key_environment()
243                )
244            })?;
245
246        match provider_call_budget {
247            Some(budget) => self.register(BudgetedModel {
248                budget: budget.clone(),
249                inner: client,
250            }),
251            None => self.register(client),
252        }
253    }
254
255    /// Builds a harness for this model with Agentty's defaults.
256    ///
257    /// # Errors
258    /// Returns the registration failure.
259    pub(crate) fn harness(
260        &self,
261        context: &HarnessContext<'_>,
262        observer: impl LifecycleObserver + 'static,
263    ) -> Result<Harness, String> {
264        let registry = self.registry(context.environment, context.provider_call_budget)?;
265
266        self.harness_from(&registry, context, observer)
267    }
268
269    /// Builds a harness that resumes a session recorded on this model without
270    /// its provider credentials. Switch the session to another model before
271    /// running a turn; this registration never sends a request.
272    ///
273    /// # Errors
274    /// Returns the registration failure.
275    pub(crate) fn resume_only_harness(
276        &self,
277        context: &HarnessContext<'_>,
278        observer: impl LifecycleObserver + 'static,
279    ) -> Result<Harness, String> {
280        let metadata = ModelConfiguration::new(self.provider, &self.model)
281            .base_url(RESUME_ONLY_BASE_URL)
282            .client_from_environment(|_| Ok(String::new()))
283            .map_err(failure("Invalid resume-only harness model"))?
284            .metadata()
285            .clone();
286        let registry = self.register(ResumeOnlyModel { metadata })?;
287
288        self.harness_from(&registry, context, observer)
289    }
290
291    /// Registers `model` under this selection's key and declared capabilities.
292    fn register(&self, model: impl Model + 'static) -> Result<ModelRegistry, String> {
293        let identity = ExecutionIdentity::new(self.key(), REGISTRATION_REVISION)
294            .map_err(failure("Invalid harness model registration"))?;
295        let capabilities = ModelCapabilities {
296            tool_calls: true,
297            ..ModelCapabilities::new(self.profile())
298        };
299        let mut registry = ModelRegistry::new();
300        registry
301            .register(identity, model, capabilities)
302            .map_err(failure("Invalid harness model registration"))?;
303
304        Ok(registry)
305    }
306
307    /// Builds a harness over this selection's registration in `registry`.
308    ///
309    /// A turn built inside a recording trace also exports the harness's
310    /// `invoke_agent`, `chat`, and `execute_tool` spans beneath the current
311    /// span; an untraced turn skips that projection.
312    fn harness_from(
313        &self,
314        registry: &ModelRegistry,
315        context: &HarnessContext<'_>,
316        observer: impl LifecycleObserver + 'static,
317    ) -> Result<Harness, String> {
318        Ok(Harness::from_registry(registry, &self.key())
319            .map_err(failure("Invalid harness model registration"))?
320            .repository(context.repository.clone())
321            .model_reasoning_effort(reasoning_effort(context.reasoning_level))
322            .with_lifecycle_observer(traced(observer)))
323    }
324
325    /// Returns the declared context profile for this model.
326    fn profile(&self) -> ModelProfile {
327        AgentKind::Harness
328            .parse_model(&self.model)
329            .and_then(model_profile::declared)
330            .unwrap_or(FALLBACK_MODEL_PROFILE)
331    }
332}
333
334/// Inputs shared by every harness built for one turn.
335pub(crate) struct HarnessContext<'a> {
336    /// Environment snapshot used for credentials.
337    pub(crate) environment: &'a BTreeMap<String, String>,
338    /// Optional limit charged for every model request.
339    pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
340    /// Requested reasoning depth.
341    pub(crate) reasoning_level: ReasoningLevel,
342    /// Validated worktree available to tools.
343    pub(crate) repository: &'a Repository,
344}
345
346/// Returns the instructions stored with new harness sessions.
347pub(crate) fn system_prompt() -> &'static str {
348    SYSTEM_PROMPT
349}
350
351/// Returns the protocol output schema for one request profile.
352///
353/// # Errors
354/// Returns an error when the harness rejects the protocol schema.
355pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
356    OutputSchema::new(protocol_output_schema(
357        profile,
358        SchemaRequiredPolicy::MinimumProtocolKeys,
359    ))
360    .map_err(failure("The harness rejected the protocol schema"))
361}
362
363/// Builds explicit options for one turn: `read` always, plus `write` and
364/// unsandboxed `bash` outside read-only mode.
365///
366/// # Errors
367/// Returns an error when the schema or `bash` policy is rejected.
368pub(crate) fn turn_options(
369    profile: ProtocolRequestProfile,
370    permission_mode: PermissionMode,
371    environment: &BTreeMap<String, String>,
372) -> Result<TurnOptions, String> {
373    let schema = output_schema(profile)?;
374    let policy = ToolPolicy::default().allow(Tool::Read);
375    if permission_mode == PermissionMode::ReadOnly {
376        return Ok(TurnOptions::new(schema, policy));
377    }
378
379    Ok(
380        TurnOptions::new(schema, policy.allow(Tool::Write).allow(Tool::Bash))
381            .with_bash(bash_config(environment)?),
382    )
383}
384
385/// Configures unsandboxed `bash` with the host environment minus provider
386/// variables, keeping essentials first within the harness grant limits.
387fn bash_config(environment: &BTreeMap<String, String>) -> Result<BashConfig, String> {
388    let mut config = BashConfig::for_executor(
389        Arc::new(UnsandboxedExecutor::without_isolation()),
390        PathBuf::from(BASH_EXECUTABLE),
391        BASH_POLICY_REVISION.to_string(),
392        BASH_TIMEOUT,
393        BASH_CAPTURE_BYTES,
394    )
395    .map_err(failure("Invalid harness bash policy"))?
396    .with_host_information();
397    for (name, value) in bash_environment(environment) {
398        if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
399            config = granted;
400        }
401    }
402
403    Ok(config)
404}
405
406/// Orders granted variables: essentials first, then the rest by name.
407fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
408    let is_granted = |name: &str| {
409        !PROVIDER_ENVIRONMENT_PREFIXES
410            .iter()
411            .any(|prefix| name.starts_with(prefix))
412    };
413    let priority = PRIORITY_ENVIRONMENT
414        .iter()
415        .filter_map(|name| environment.get_key_value(*name));
416    let remaining = environment
417        .iter()
418        .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));
419
420    priority
421        .chain(remaining)
422        .filter(|(name, _)| is_granted(name))
423        .collect()
424}
425
426/// Validates the worktree with the first absolute `git` on `PATH`.
427///
428/// # Errors
429/// Returns an error for an invalid worktree or when no usable Git exists.
430pub(crate) fn repository(
431    folder: &Path,
432    environment: &BTreeMap<String, String>,
433) -> Result<Repository, String> {
434    let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
435    let candidates = environment
436        .get("PATH")
437        .into_iter()
438        .flat_map(env::split_paths)
439        .filter(|directory| directory.is_absolute())
440        .map(|directory| directory.join(&executable_name));
441    for candidate in candidates {
442        match Repository::new(folder, candidate) {
443            Ok(repository) => return Ok(repository),
444            Err(
445                error @ (RepositoryError::Root { .. }
446                | RepositoryError::RootIsGitAdministrative { .. }),
447            ) => return Err(format!("Invalid harness worktree: {error}")),
448            Err(_) => {}
449        }
450    }
451
452    Err("The harness needs a Git executable on PATH.".to_string())
453}
454
455/// Returns an error mapper that prefixes a harness failure with `context`.
456pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
457    move |error| format!("{context}: {error}")
458}
459
460/// Maps Agentty's reasoning level to the harness reasoning effort.
461fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
462    match reasoning_level {
463        ReasoningLevel::Low => ReasoningEffort::Low,
464        ReasoningLevel::Medium => ReasoningEffort::Medium,
465        ReasoningLevel::High => ReasoningEffort::High,
466        ReasoningLevel::XHigh => ReasoningEffort::XHigh,
467        ReasoningLevel::Max => ReasoningEffort::Max,
468    }
469}
470
471/// Adds the harness's OpenTelemetry span projection after `observer` when
472/// the current execution span is recording.
473fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
474    let observers = LifecycleObserverSet::new(observer);
475    if !Context::current().span().is_recording() {
476        return observers;
477    }
478
479    observers.with_observer(LifecycleTraceObserver::new())
480}
481
482/// Model wrapper that charges one provider call before every request.
483struct BudgetedModel {
484    budget: ProviderCallBudget,
485    inner: ModelClient,
486}
487
488#[async_trait]
489impl Model for BudgetedModel {
490    fn metadata(&self) -> Option<ModelMetadata> {
491        Model::metadata(&self.inner)
492    }
493
494    fn validate_schema(&self, schema: &OutputSchema) -> Result<(), ModelError> {
495        Model::validate_schema(&self.inner, schema)
496    }
497
498    fn validate_input(&self, input: &TurnInput) -> Result<(), ModelError> {
499        Model::validate_input(&self.inner, input)
500    }
501
502    async fn complete(&self, request: ModelRequest) -> Result<ModelCompletion, ModelError> {
503        self.budget.consume().map_err(ModelError::request)?;
504
505        Model::complete(&self.inner, request).await
506    }
507}
508
509/// Stand-in for a recorded model that only lets its session resume and switch
510/// away.
511struct ResumeOnlyModel {
512    metadata: ModelMetadata,
513}
514
515#[async_trait]
516impl Model for ResumeOnlyModel {
517    fn metadata(&self) -> Option<ModelMetadata> {
518        Some(self.metadata.clone())
519    }
520
521    async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
522        Err(ModelError::request(io::Error::other(
523            "the recorded harness model can only resume its session",
524        )))
525    }
526}
527
528#[cfg(test)]
529#[path = "config_test.rs"]
530mod tests;