1use 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
31const REGISTRATION_REVISION: &str = "agentty-native-2";
34const FALLBACK_MODEL_PROFILE: ModelProfile =
38 ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
39const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
42const SESSION_DATABASE_FILE: &str = "harness.db";
44const BASH_EXECUTABLE: &str = "/bin/bash";
46const BASH_POLICY_REVISION: &str = "agentty-unsandboxed-1";
48const BASH_TIMEOUT: Duration = Duration::from_secs(600);
50const BASH_CAPTURE_BYTES: usize = 8192;
52const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 3] = ["DASHSCOPE_", "KIMI_", "MODEL_"];
55const 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];
76const 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
85type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
87
88#[derive(Clone)]
94pub struct NativeHarnessConfig {
95 data_root: PathBuf,
96 environment: EnvironmentSource,
97}
98
99impl NativeHarnessConfig {
100 pub fn new(data_root: PathBuf) -> Self {
103 Self::with_environment(data_root, process_environment)
104 }
105
106 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 pub(crate) fn environment(&self) -> BTreeMap<String, String> {
120 (self.environment)()
121 }
122
123 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
145pub(crate) fn process_environment() -> BTreeMap<String, String> {
148 unicode_environment(env::vars_os())
149}
150
151pub(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
160fn 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
170fn 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#[derive(Clone, Debug, Eq, PartialEq)]
184pub(crate) struct ModelSelection {
185 model: String,
186 provider: ModelProvider,
187}
188
189impl ModelSelection {
190 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 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 pub(crate) fn key(&self) -> String {
218 format!("{}/{}", self.provider, self.model)
219 }
220
221 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 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(®istry, context, observer)
267 }
268
269 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(®istry, context, observer)
289 }
290
291 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 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 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
334pub(crate) struct HarnessContext<'a> {
336 pub(crate) environment: &'a BTreeMap<String, String>,
338 pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
340 pub(crate) reasoning_level: ReasoningLevel,
342 pub(crate) repository: &'a Repository,
344}
345
346pub(crate) fn system_prompt() -> &'static str {
348 SYSTEM_PROMPT
349}
350
351pub(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
363pub(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
385fn 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
406fn 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
426pub(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
455pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
457 move |error| format!("{context}: {error}")
458}
459
460fn 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
471fn 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
482struct 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
509struct 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;