1use 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
43const REGISTRATION_REVISION: &str = "agentty-native-2";
51const FALLBACK_MODEL_PROFILE: ModelProfile =
55 ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
56const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
59const RESUME_ONLY_API_KEY: &str = "resume-only";
62const SESSION_DATABASE_FILE: &str = "harness.db";
64const BASH_EXECUTABLE: &str = "/bin/bash";
66const BASH_POLICY_REVISION: &str = "agentty-native-sandbox-1";
70const HOST_CACHE_POLICY_REVISION: &str = "agentty-native-sandbox-1-host-caches";
74const SESSION_TEMPORARY_DIRECTORY: &str = "tmp";
77const UTILITY_TEMPORARY_PARENT: &str = ".utility";
80const BASH_TIMEOUT: Duration = Duration::from_secs(600);
82const OPENAI_COMPATIBLE_MODEL_ENV: &str = "OPENAI_COMPATIBLE_MODEL";
85const CHATGPT_SIGN_IN_COMMAND: &str = "ag-harness login chatgpt";
87const AGENTTY_ROOT_ENV: &str = "AGENTTY_ROOT";
90const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 7] = [
95 "ANTHROPIC_",
96 "CHATGPT_",
97 "CLAUDE_CODE_OAUTH_TOKEN",
98 "DASHSCOPE_",
99 "KIMI_",
100 "MODEL_",
101 "OPENAI_",
102];
103const CREDENTIAL_PREFIXES: [&str; 5] = ["AWS_", "GH_", "GITHUB_", "GITLAB_", "GLAB_"];
106const CREDENTIAL_SUFFIXES: [&str; 3] = ["_KEY", "DATABASE_URL", "_DSN"];
110const CREDENTIAL_WORDS: [&str; 5] = ["TOKEN", "SECRET", "PASSWORD", "PASSWD", "CREDENTIAL"];
114const 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];
135const 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
144type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
146
147#[derive(Clone)]
159pub struct NativeHarnessConfig {
160 cargo_cache_root: Option<PathBuf>,
163 data_root: PathBuf,
164 environment: EnvironmentSource,
165 swept_utility_directories: Arc<AtomicBool>,
168}
169
170impl NativeHarnessConfig {
171 pub fn new(data_root: PathBuf) -> Self {
174 Self::with_environment(data_root, process_environment)
175 }
176
177 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 #[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 pub(crate) fn environment(&self) -> BTreeMap<String, String> {
211 (self.environment)()
212 }
213
214 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 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 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
319pub(crate) fn process_environment() -> BTreeMap<String, String> {
322 unicode_environment(env::vars_os())
323}
324
325pub(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
348async 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
403fn 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
429fn 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
441fn 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
463pub(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
498pub(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
510pub(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
520pub(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
534fn 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
544fn 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
576fn 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
584fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
586 nonblank(environment, name).is_some()
587}
588
589#[derive(Clone, Debug, Eq, PartialEq)]
592pub(crate) struct ModelSelection {
593 model: String,
594 provider: ModelProvider,
595}
596
597impl ModelSelection {
598 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 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 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 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 pub(crate) fn key(&self) -> String {
690 format!("{}/{}", self.provider, self.model)
691 }
692
693 pub(crate) fn catalog_spec(&self) -> Option<ModelSpec> {
697 self.provider.model_spec(&self.model)
698 }
699
700 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 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 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 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 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 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 fn client(&self, environment: &BTreeMap<String, String>) -> Result<Arc<dyn Model>, String> {
821 let mut configuration = ModelConfiguration::new(self.provider, &self.model);
822 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 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(®istry, context, observer)?;
865 context.apply_summary_model(|summary| harness.set_summary_model(summary));
866
867 Ok(harness)
868 }
869
870 pub(crate) fn resume_only_harness(
877 &self,
878 context: &HarnessContext<'_>,
879 observer: impl LifecycleObserver + 'static,
880 ) -> Result<Harness, String> {
881 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(®istry, context, observer)
901 }
902
903 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 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 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
1000pub(crate) struct HarnessContext<'a> {
1002 pub(crate) compacts: bool,
1004 pub(crate) environment: &'a BTreeMap<String, String>,
1006 pub(crate) reasoning_level: ReasoningLevel,
1008 pub(crate) repository: &'a Repository,
1010 pub(crate) running_context_window: Option<u64>,
1012 pub(crate) sandbox: Sandbox,
1014 pub(crate) summary_model: Option<&'a ModelSelection>,
1017}
1018
1019impl HarnessContext<'_> {
1020 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
1041pub(crate) fn system_prompt() -> &'static str {
1043 SYSTEM_PROMPT
1044}
1045
1046pub(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
1058pub(crate) struct RunOptions {
1060 bash: Option<BashConfig>,
1061 output: OutputSchema,
1062 tools: ToolSet,
1063}
1064
1065impl RunOptions {
1066 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 pub(crate) fn offers_bash(&self) -> bool {
1095 self.bash.is_some()
1096 }
1097
1098 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
1109fn 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
1139fn 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
1161fn 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
1177pub(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
1206pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
1208 move |error| format!("{context}: {error}")
1209}
1210
1211fn 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
1222fn 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
1236struct 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;