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::catalog::{Capabilities, ModelCatalog, ModelId, ModelSelector, ModelSpec};
14use ag_harness::lifecycle::{LifecycleObserver, LifecycleObserverSet, LifecycleTraceObserver};
15use ag_harness::model::{
16 ModelClient, ModelCompletion, ModelMetadata, ModelProfile, ModelRegistry, ModelRequest,
17 ReasoningEffort,
18};
19use ag_harness::provider::{
20 ChatGptConfig, CostTier, LocalServerKind, ModelConfiguration, ModelProvider,
21 chatgpt_auth_file_in,
22};
23use ag_harness::{
24 Harness, Model, ModelError, OutputSchema, Repository, RepositoryError, RunRequest, ToolSet,
25 TurnInput,
26};
27use ag_protocol::{ProtocolRequestProfile, SchemaRequiredPolicy, protocol_output_schema};
28use ag_session::{
29 AgentKind, AgentModel, HarnessModelOption, HarnessModelStatus, MINIMUM_RUNNING_CONTEXT_WINDOW,
30 ModelCost, ServedModel,
31};
32use ag_telemetry::{Context, TraceContextExt as _};
33use async_trait::async_trait;
34
35use crate::agent::model_profile;
36
37const REGISTRATION_REVISION: &str = "agentty-native-2";
45const FALLBACK_MODEL_PROFILE: ModelProfile =
49 ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
50const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
53const SESSION_DATABASE_FILE: &str = "harness.db";
55const BASH_EXECUTABLE: &str = "/bin/bash";
57const BASH_POLICY_REVISION: &str = "agentty-unsandboxed-1";
59const BASH_TIMEOUT: Duration = Duration::from_secs(600);
61const OPENAI_COMPATIBLE_MODEL_ENV: &str = "OPENAI_COMPATIBLE_MODEL";
64const CHATGPT_SIGN_IN_COMMAND: &str = "ag-harness login chatgpt";
66const AGENTTY_ROOT_ENV: &str = "AGENTTY_ROOT";
69const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 6] = [
73 "ANTHROPIC_",
74 "CHATGPT_",
75 "DASHSCOPE_",
76 "KIMI_",
77 "MODEL_",
78 "OPENAI_",
79];
80const PRIORITY_ENVIRONMENT: [&str; 17] = [
83 "PATH",
84 "HOME",
85 "USER",
86 "LOGNAME",
87 "SHELL",
88 "LANG",
89 "LC_ALL",
90 "TERM",
91 "TMPDIR",
92 "SSH_AUTH_SOCK",
93 "GIT_SSH_COMMAND",
94 "CARGO_HOME",
95 "RUSTUP_HOME",
96 "RUSTUP_TOOLCHAIN",
97 "VIRTUAL_ENV",
98 "XDG_CONFIG_HOME",
99 "XDG_CACHE_HOME",
100];
101const SYSTEM_PROMPT: &str = concat!(
103 "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
104 "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
105 "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
106 "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
107 "the tool reports it."
108);
109
110type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
112
113#[derive(Clone)]
119pub struct NativeHarnessConfig {
120 data_root: PathBuf,
121 environment: EnvironmentSource,
122}
123
124impl NativeHarnessConfig {
125 pub fn new(data_root: PathBuf) -> Self {
128 Self::with_environment(data_root, process_environment)
129 }
130
131 pub fn with_environment(
134 data_root: PathBuf,
135 environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
136 ) -> Self {
137 Self {
138 data_root,
139 environment: Arc::new(environment),
140 }
141 }
142
143 pub(crate) fn environment(&self) -> BTreeMap<String, String> {
145 (self.environment)()
146 }
147
148 pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
154 let is_single_component = !session_id.is_empty()
155 && session_id != "."
156 && session_id != ".."
157 && !session_id.contains(['/', '\\', '\0']);
158 if !is_single_component {
159 return Err(format!("Invalid harness session id `{session_id}`."));
160 }
161 let directory = self.data_root.join(session_id);
162 tokio::fs::create_dir_all(&directory)
163 .await
164 .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;
165
166 Ok(directory.join(SESSION_DATABASE_FILE))
167 }
168}
169
170pub(crate) fn process_environment() -> BTreeMap<String, String> {
173 unicode_environment(env::vars_os())
174}
175
176pub(crate) async fn harness_models(
185 environment: &BTreeMap<String, String>,
186 is_signed_in: impl Fn(&Path) -> bool,
187) -> Vec<HarnessModelOption> {
188 let mut options = local_models(environment).await;
189 options.extend(
190 AgentKind::Harness
191 .models()
192 .iter()
193 .filter_map(|model| hosted_model(*model, environment, &is_signed_in)),
194 );
195
196 options
197}
198
199async fn local_models(environment: &BTreeMap<String, String>) -> Vec<HarnessModelOption> {
202 let server = ModelProvider::OpenAiCompatible
203 .local_server(lookup(environment))
204 .ok()
205 .flatten();
206 let inventory = async { server?.inventory().await.ok() }.await;
207 let provider = inventory
208 .as_ref()
209 .map_or(LocalServerKind::OpenAiCompatible, |inventory| {
210 inventory.kind
211 })
212 .display_name();
213 let local_option = |model: AgentModel, status: HarnessModelStatus| HarnessModelOption {
214 context_window: None,
215 cost: ModelCost::Local,
216 loaded_context_window: None,
217 model,
218 provider: provider.to_string(),
219 status,
220 trains_on_prompts: false,
221 };
222 let mut options = inventory
223 .map_or_else(Vec::new, |inventory| inventory.models)
224 .into_iter()
225 .filter_map(|served| {
226 let status = if served.supports_tools == Some(false) {
227 HarnessModelStatus::NoToolSupport
228 } else {
229 HarnessModelStatus::Ready
230 };
231
232 Some(HarnessModelOption {
233 context_window: served.context_window,
234 loaded_context_window: served.loaded_context_window,
235 ..local_option(
236 AgentModel::OpenAiCompatible(ServedModel::new(&served.id)?),
237 status,
238 )
239 })
240 })
241 .collect::<Vec<_>>();
242 let configured = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV)
243 .and_then(ServedModel::new)
244 .map(AgentModel::OpenAiCompatible);
245 if let Some(configured) = configured
246 && !options.iter().any(|option| option.model == configured)
247 {
248 options.insert(0, local_option(configured, HarnessModelStatus::Ready));
249 }
250
251 options
252}
253
254fn hosted_model(
257 model: AgentModel,
258 environment: &BTreeMap<String, String>,
259 is_signed_in: impl Fn(&Path) -> bool,
260) -> Option<HarnessModelOption> {
261 let selection = ModelSelection::resolve_known(model.as_str()).ok()?;
262 let provider = selection.provider;
263 let cost = model_cost(provider.cost_tier(&selection.model)?);
264 let status = configuration_status(provider, environment, is_signed_in);
265
266 Some(HarnessModelOption {
267 context_window: selection
268 .profile(environment, None)
269 .ok()
270 .map(ModelProfile::context_window_tokens),
271 cost,
272 loaded_context_window: None,
273 model,
274 provider: provider_display_name(provider).to_string(),
275 status,
276 trains_on_prompts: provider.trains_on_prompts(&selection.model),
277 })
278}
279
280fn model_cost(tier: CostTier) -> ModelCost {
283 match tier {
284 CostTier::Local => ModelCost::Local,
285 CostTier::Plan => ModelCost::Plan,
286 CostTier::Cheap => ModelCost::Cheap,
287 CostTier::Standard => ModelCost::Standard,
288 CostTier::Premium => ModelCost::Premium,
289 }
290}
291
292fn provider_display_name(provider: ModelProvider) -> &'static str {
294 match provider {
295 ModelProvider::Anthropic => "Anthropic",
296 ModelProvider::ChatGpt => "ChatGPT plan",
297 ModelProvider::Kimi => "Kimi",
298 ModelProvider::Muse => "Muse",
299 ModelProvider::OpenAi => "OpenAI",
300 ModelProvider::OpenAiCompatible => LocalServerKind::OpenAiCompatible.display_name(),
301 ModelProvider::Qwen => "Qwen",
302 }
303}
304
305pub(crate) async fn running_context_window(
317 selection: &ModelSelection,
318 environment: &BTreeMap<String, String>,
319) -> Result<Option<u64>, String> {
320 let Ok(Some(server)) = selection.provider.local_server(lookup(environment)) else {
321 return Ok(None);
322 };
323 let Ok(Some(window)) = server.running_context_window(&selection.model).await else {
324 return Ok(None);
325 };
326 if window < MINIMUM_RUNNING_CONTEXT_WINDOW {
327 return Err(format!(
328 "The local server runs `{}` with a {window}-token context window, below the \
329 {MINIMUM_RUNNING_CONTEXT_WINDOW} tokens harness turns need, so it would drop the \
330 start of the conversation. Restart Ollama with `OLLAMA_CONTEXT_LENGTH=32768` (or \
331 raise the context length in the Ollama app's settings), or pick another model with \
332 `/model`.",
333 selection.model
334 ));
335 }
336
337 Ok(Some(window))
338}
339
340pub(super) fn lookup(
342 environment: &BTreeMap<String, String>,
343) -> impl FnMut(&str) -> Result<String, env::VarError> + '_ {
344 |name| {
345 environment
346 .get(name)
347 .cloned()
348 .ok_or(env::VarError::NotPresent)
349 }
350}
351
352pub(super) fn chatgpt_auth_file(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
359 let set = |name: &str| {
360 environment
361 .get(name)
362 .filter(|value| !value.is_empty())
363 .map(PathBuf::from)
364 };
365 let data_dir = set(AGENTTY_ROOT_ENV).or_else(|| set("HOME").map(|home| home.join(".agentty")));
366
367 chatgpt_auth_file_in(lookup(environment), data_dir.as_deref())
368}
369
370fn unicode_environment(
372 variables: impl IntoIterator<Item = (OsString, OsString)>,
373) -> BTreeMap<String, String> {
374 variables
375 .into_iter()
376 .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
377 .collect()
378}
379
380fn configuration_status(
384 provider: ModelProvider,
385 environment: &BTreeMap<String, String>,
386 is_signed_in: impl Fn(&Path) -> bool,
387) -> HarnessModelStatus {
388 if provider.requires_sign_in() {
389 let signed_in =
390 chatgpt_auth_file(environment).is_some_and(|auth_file| is_signed_in(&auth_file));
391
392 return if signed_in {
393 HarnessModelStatus::Ready
394 } else {
395 HarnessModelStatus::SignInRequired(CHATGPT_SIGN_IN_COMMAND)
396 };
397 }
398 if provider.requires_api_key() && !has_value(environment, provider.api_key_environment()) {
399 return HarnessModelStatus::MissingConfiguration(provider.api_key_environment());
400 }
401 if provider.default_base_url().is_none()
402 && !has_value(environment, provider.base_url_environment())
403 {
404 return HarnessModelStatus::MissingConfiguration(provider.base_url_environment());
405 }
406
407 HarnessModelStatus::Ready
408}
409
410fn nonblank<'a>(environment: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
412 environment
413 .get(name)
414 .map(|value| value.trim())
415 .filter(|value| !value.is_empty())
416}
417
418fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
420 nonblank(environment, name).is_some()
421}
422
423#[derive(Clone, Debug, Eq, PartialEq)]
426pub(crate) struct ModelSelection {
427 model: String,
428 provider: ModelProvider,
429}
430
431impl ModelSelection {
432 pub(crate) fn resolve(
440 model: &str,
441 environment: &BTreeMap<String, String>,
442 ) -> Result<Self, String> {
443 let Some(AgentModel::OpenAiCompatible(served)) = AgentKind::Harness.parse_model(model)
444 else {
445 return Self::resolve_known(model);
446 };
447 if let Some(name) = served.name() {
448 return Ok(Self {
449 model: name.to_string(),
450 provider: ModelProvider::OpenAiCompatible,
451 });
452 }
453 let served = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV).ok_or_else(|| {
454 format!(
455 "Cannot use harness model `{model}`: {OPENAI_COMPATIBLE_MODEL_ENV} is unset. Pick \
456 a local model with `/model`, or set it to the model your OpenAI-compatible \
457 server serves, such as `qwen3:latest`, before starting Agentty."
458 )
459 })?;
460
461 Ok(Self {
462 model: served.to_string(),
463 provider: ModelProvider::OpenAiCompatible,
464 })
465 }
466
467 pub(crate) fn from_key(key: &str) -> Option<Self> {
471 let (provider, model) = key.split_once('/')?;
472 if provider == ModelProvider::OpenAiCompatible.as_str() {
473 return (!model.trim().is_empty()).then(|| Self {
474 model: model.to_string(),
475 provider: ModelProvider::OpenAiCompatible,
476 });
477 }
478 let id = if provider == ModelProvider::ChatGpt.as_str() {
480 key
481 } else {
482 model
483 };
484
485 Self::resolve_known(id)
486 .ok()
487 .filter(|selection| selection.key() == key)
488 }
489
490 fn resolve_known(model: &str) -> Result<Self, String> {
495 let unknown = || format!("The harness does not serve model `{model}`.");
496 if let Some(plan_model) = model
497 .strip_prefix(ModelProvider::ChatGpt.as_str())
498 .and_then(|rest| rest.strip_prefix('/'))
499 {
500 return ModelProvider::ChatGpt
501 .known_models()
502 .contains(&plan_model)
503 .then(|| Self {
504 model: plan_model.to_string(),
505 provider: ModelProvider::ChatGpt,
506 })
507 .ok_or_else(unknown);
508 }
509
510 ModelProvider::all()
511 .iter()
512 .copied()
513 .filter(|provider| !provider.requires_sign_in())
514 .find(|provider| provider.known_models().contains(&model))
515 .map(|provider| Self {
516 model: model.to_string(),
517 provider,
518 })
519 .ok_or_else(unknown)
520 }
521
522 pub(crate) fn key(&self) -> String {
524 format!("{}/{}", self.provider, self.model)
525 }
526
527 pub(crate) fn registry(
533 &self,
534 environment: &BTreeMap<String, String>,
535 provider_call_budget: Option<&ProviderCallBudget>,
536 running_context_window: Option<u64>,
537 ) -> Result<ModelRegistry, String> {
538 let mut configuration = ModelConfiguration::new(self.provider, &self.model);
539 if self.provider.requires_sign_in()
542 && let Some(auth_file) = chatgpt_auth_file(environment)
543 {
544 configuration = configuration.auth_file(auth_file);
545 }
546 let client = configuration
547 .client_from_environment(lookup(environment))
548 .map_err(|error| {
549 let remedy = if self.provider.requires_sign_in() {
550 format!("Run `{CHATGPT_SIGN_IN_COMMAND}`, then retry.")
551 } else if self.provider.requires_api_key() {
552 format!(
553 "Set {} before starting Agentty.",
554 self.provider.api_key_environment()
555 )
556 } else {
557 format!(
558 "Check {OPENAI_COMPATIBLE_MODEL_ENV} and {} before starting Agentty.",
559 self.provider.base_url_environment()
560 )
561 };
562
563 format!(
564 "Cannot use harness model `{}`: {error}. {remedy}",
565 self.model
566 )
567 })?;
568
569 let model: Arc<dyn Model> = match provider_call_budget {
570 Some(budget) => Arc::new(BudgetedModel {
571 budget: budget.clone(),
572 inner: client,
573 }),
574 None => Arc::new(client),
575 };
576
577 self.register(model, self.profile(environment, running_context_window)?)
578 }
579
580 pub(crate) fn harness(
585 &self,
586 context: &HarnessContext<'_>,
587 observer: impl LifecycleObserver + 'static,
588 ) -> Result<Harness, String> {
589 let registry = self.registry(
590 context.environment,
591 context.provider_call_budget,
592 context.running_context_window,
593 )?;
594
595 self.harness_from(®istry, context, observer)
596 }
597
598 pub(crate) fn resume_only_harness(
605 &self,
606 context: &HarnessContext<'_>,
607 observer: impl LifecycleObserver + 'static,
608 ) -> Result<Harness, String> {
609 let client = if self.provider.requires_sign_in() {
612 ModelClient::chatgpt(ChatGptConfig {
613 auth_file: PathBuf::new(),
614 base_url: RESUME_ONLY_BASE_URL.to_string(),
615 model: self.model.clone(),
616 })
617 .map_err(failure("Invalid resume-only harness model"))?
618 } else {
619 ModelConfiguration::new(self.provider, &self.model)
620 .base_url(RESUME_ONLY_BASE_URL)
621 .client_from_environment(|_| Ok(String::new()))
622 .map_err(failure("Invalid resume-only harness model"))?
623 };
624 let metadata = client.metadata().clone();
625 let profile = self.profile(context.environment, None)?;
626 let registry = self.register(Arc::new(ResumeOnlyModel { metadata }), profile)?;
627
628 self.harness_from(®istry, context, observer)
629 }
630
631 fn register(
641 &self,
642 model: Arc<dyn Model>,
643 profile: ModelProfile,
644 ) -> Result<ModelRegistry, String> {
645 let id = ModelId::cataloged(self.provider, &self.model);
646 let declared = self
647 .provider
648 .capabilities(&self.model)
649 .unwrap_or(Capabilities::NONE);
650 let spec = ModelSpec::new(id.clone())
651 .with_provider(self.provider)
652 .with_capabilities(declared)
653 .with_profile(profile);
654 let handle = ModelCatalog::builder()
655 .model(spec, model)
656 .build()
657 .and_then(|catalog| catalog.resolve(&ModelSelector::Id(id)))
658 .map_err(failure("Invalid harness model registration"))?;
659 let mut registry = ModelRegistry::new();
660 registry
661 .register_catalog_entry(&handle, REGISTRATION_REVISION)
662 .map_err(failure("Invalid harness model registration"))?;
663
664 Ok(registry)
665 }
666
667 fn harness_from(
673 &self,
674 registry: &ModelRegistry,
675 context: &HarnessContext<'_>,
676 observer: impl LifecycleObserver + 'static,
677 ) -> Result<Harness, String> {
678 Ok(Harness::from_registry(registry, &self.key())
679 .map_err(failure("Invalid harness model registration"))?
680 .repository(context.repository.clone())
681 .model_reasoning_effort(reasoning_effort(context.reasoning_level))
682 .with_lifecycle_observer(traced(observer)))
683 }
684
685 fn profile(
695 &self,
696 environment: &BTreeMap<String, String>,
697 running_context_window: Option<u64>,
698 ) -> Result<ModelProfile, String> {
699 let declared = match running_context_window {
700 Some(window) => self.provider.running_profile(lookup(environment), window),
701 None => self
702 .provider
703 .declared_profile(&self.model, lookup(environment)),
704 }
705 .map_err(failure("Invalid harness model profile"))?;
706
707 Ok(declared
708 .or_else(|| {
709 AgentKind::Harness
710 .parse_model(&self.model)
711 .and_then(model_profile::declared)
712 })
713 .unwrap_or(FALLBACK_MODEL_PROFILE))
714 }
715}
716
717pub(crate) struct HarnessContext<'a> {
719 pub(crate) environment: &'a BTreeMap<String, String>,
721 pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
723 pub(crate) reasoning_level: ReasoningLevel,
725 pub(crate) repository: &'a Repository,
727 pub(crate) running_context_window: Option<u64>,
729}
730
731pub(crate) fn system_prompt() -> &'static str {
733 SYSTEM_PROMPT
734}
735
736pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
741 OutputSchema::new(protocol_output_schema(
742 profile,
743 SchemaRequiredPolicy::MinimumProtocolKeys,
744 ))
745 .map_err(failure("The harness rejected the protocol schema"))
746}
747
748pub(crate) struct RunOptions {
750 bash: Option<BashConfig>,
751 output: OutputSchema,
752 tools: ToolSet,
753}
754
755impl RunOptions {
756 pub(crate) fn new(
762 profile: ProtocolRequestProfile,
763 permission_mode: PermissionMode,
764 environment: &BTreeMap<String, String>,
765 ) -> Result<Self, String> {
766 let output = output_schema(profile)?;
767 if permission_mode == PermissionMode::ReadOnly {
768 return Ok(Self {
769 bash: None,
770 output,
771 tools: ToolSet::empty().with_read(),
772 });
773 }
774
775 Ok(Self {
776 bash: Some(bash_config(environment)?),
777 output,
778 tools: ToolSet::builtins(),
779 })
780 }
781
782 pub(crate) fn request(self, input: String) -> RunRequest {
784 let request = RunRequest::new(input).output(self.output).tools(self.tools);
785
786 match self.bash {
787 Some(bash) => request.bash(bash),
788 None => request,
789 }
790 }
791}
792
793fn bash_config(environment: &BTreeMap<String, String>) -> Result<BashConfig, String> {
796 let mut config = BashConfig::for_executor(
797 Arc::new(UnsandboxedExecutor::without_isolation()),
798 PathBuf::from(BASH_EXECUTABLE),
799 BASH_POLICY_REVISION.to_string(),
800 BASH_TIMEOUT,
801 BashConfig::DEFAULT_CAPTURE_BYTES,
802 )
803 .map_err(failure("Invalid harness bash policy"))?
804 .with_host_information();
805 for (name, value) in bash_environment(environment) {
806 if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
807 config = granted;
808 }
809 }
810
811 Ok(config)
812}
813
814fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
816 let is_granted = |name: &str| {
817 !PROVIDER_ENVIRONMENT_PREFIXES
818 .iter()
819 .any(|prefix| name.starts_with(prefix))
820 };
821 let priority = PRIORITY_ENVIRONMENT
822 .iter()
823 .filter_map(|name| environment.get_key_value(*name));
824 let remaining = environment
825 .iter()
826 .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));
827
828 priority
829 .chain(remaining)
830 .filter(|(name, _)| is_granted(name))
831 .collect()
832}
833
834pub(crate) fn repository(
839 folder: &Path,
840 environment: &BTreeMap<String, String>,
841) -> Result<Repository, String> {
842 let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
843 let candidates = environment
844 .get("PATH")
845 .into_iter()
846 .flat_map(env::split_paths)
847 .filter(|directory| directory.is_absolute())
848 .map(|directory| directory.join(&executable_name));
849 for candidate in candidates {
850 match Repository::new(folder, candidate) {
851 Ok(repository) => return Ok(repository),
852 Err(
853 error @ (RepositoryError::Root { .. }
854 | RepositoryError::RootIsGitAdministrative { .. }),
855 ) => return Err(format!("Invalid harness worktree: {error}")),
856 Err(_) => {}
857 }
858 }
859
860 Err("The harness needs a Git executable on PATH.".to_string())
861}
862
863pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
865 move |error| format!("{context}: {error}")
866}
867
868fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
870 match reasoning_level {
871 ReasoningLevel::Low => ReasoningEffort::Low,
872 ReasoningLevel::Medium => ReasoningEffort::Medium,
873 ReasoningLevel::High => ReasoningEffort::High,
874 ReasoningLevel::XHigh => ReasoningEffort::XHigh,
875 ReasoningLevel::Max => ReasoningEffort::Max,
876 }
877}
878
879fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
883 let observers = LifecycleObserverSet::new(observer);
884 if !Context::current().span().is_recording() {
885 return observers;
886 }
887
888 observers.with_observer(
889 LifecycleTraceObserver::new().with_tool_attributes(ag_telemetry::run_identity),
890 )
891}
892
893struct BudgetedModel {
895 budget: ProviderCallBudget,
896 inner: ModelClient,
897}
898
899#[async_trait]
900impl Model for BudgetedModel {
901 fn metadata(&self) -> Option<ModelMetadata> {
902 Model::metadata(&self.inner)
903 }
904
905 fn validate_schema(&self, schema: &OutputSchema) -> Result<(), ModelError> {
906 Model::validate_schema(&self.inner, schema)
907 }
908
909 fn validate_input(&self, input: &TurnInput) -> Result<(), ModelError> {
910 Model::validate_input(&self.inner, input)
911 }
912
913 fn keeps_prefix_across_schemas(&self) -> bool {
914 Model::keeps_prefix_across_schemas(&self.inner)
915 }
916
917 fn replays_reasoning_text(&self) -> bool {
918 Model::replays_reasoning_text(&self.inner)
919 }
920
921 fn replays_turn_instructions(&self) -> bool {
922 Model::replays_turn_instructions(&self.inner)
923 }
924
925 async fn complete(&self, request: ModelRequest) -> Result<ModelCompletion, ModelError> {
926 self.budget.consume().map_err(ModelError::request)?;
927
928 Model::complete(&self.inner, request).await
929 }
930}
931
932struct ResumeOnlyModel {
935 metadata: ModelMetadata,
936}
937
938#[async_trait]
939impl Model for ResumeOnlyModel {
940 fn metadata(&self) -> Option<ModelMetadata> {
941 Some(self.metadata.clone())
942 }
943
944 async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
945 Err(ModelError::request(io::Error::other(
946 "the recorded harness model can only resume its session",
947 )))
948 }
949}
950
951#[cfg(test)]
952#[path = "config_test.rs"]
953mod tests;