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; 5] =
73 ["CHATGPT_", "DASHSCOPE_", "KIMI_", "MODEL_", "OPENAI_"];
74const PRIORITY_ENVIRONMENT: [&str; 17] = [
77 "PATH",
78 "HOME",
79 "USER",
80 "LOGNAME",
81 "SHELL",
82 "LANG",
83 "LC_ALL",
84 "TERM",
85 "TMPDIR",
86 "SSH_AUTH_SOCK",
87 "GIT_SSH_COMMAND",
88 "CARGO_HOME",
89 "RUSTUP_HOME",
90 "RUSTUP_TOOLCHAIN",
91 "VIRTUAL_ENV",
92 "XDG_CONFIG_HOME",
93 "XDG_CACHE_HOME",
94];
95const SYSTEM_PROMPT: &str = concat!(
97 "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
98 "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
99 "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
100 "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
101 "the tool reports it."
102);
103
104type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
106
107#[derive(Clone)]
113pub struct NativeHarnessConfig {
114 data_root: PathBuf,
115 environment: EnvironmentSource,
116}
117
118impl NativeHarnessConfig {
119 pub fn new(data_root: PathBuf) -> Self {
122 Self::with_environment(data_root, process_environment)
123 }
124
125 pub fn with_environment(
128 data_root: PathBuf,
129 environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
130 ) -> Self {
131 Self {
132 data_root,
133 environment: Arc::new(environment),
134 }
135 }
136
137 pub(crate) fn environment(&self) -> BTreeMap<String, String> {
139 (self.environment)()
140 }
141
142 pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
148 let is_single_component = !session_id.is_empty()
149 && session_id != "."
150 && session_id != ".."
151 && !session_id.contains(['/', '\\', '\0']);
152 if !is_single_component {
153 return Err(format!("Invalid harness session id `{session_id}`."));
154 }
155 let directory = self.data_root.join(session_id);
156 tokio::fs::create_dir_all(&directory)
157 .await
158 .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;
159
160 Ok(directory.join(SESSION_DATABASE_FILE))
161 }
162}
163
164pub(crate) fn process_environment() -> BTreeMap<String, String> {
167 unicode_environment(env::vars_os())
168}
169
170pub(crate) async fn harness_models(
179 environment: &BTreeMap<String, String>,
180 is_signed_in: impl Fn(&Path) -> bool,
181) -> Vec<HarnessModelOption> {
182 let mut options = local_models(environment).await;
183 options.extend(
184 AgentKind::Harness
185 .models()
186 .iter()
187 .filter_map(|model| hosted_model(*model, environment, &is_signed_in)),
188 );
189
190 options
191}
192
193async fn local_models(environment: &BTreeMap<String, String>) -> Vec<HarnessModelOption> {
196 let server = ModelProvider::OpenAiCompatible
197 .local_server(lookup(environment))
198 .ok()
199 .flatten();
200 let inventory = async { server?.inventory().await.ok() }.await;
201 let provider = inventory
202 .as_ref()
203 .map_or(LocalServerKind::OpenAiCompatible, |inventory| {
204 inventory.kind
205 })
206 .display_name();
207 let local_option = |model: AgentModel, status: HarnessModelStatus| HarnessModelOption {
208 context_window: None,
209 cost: ModelCost::Local,
210 loaded_context_window: None,
211 model,
212 provider: provider.to_string(),
213 status,
214 trains_on_prompts: false,
215 };
216 let mut options = inventory
217 .map_or_else(Vec::new, |inventory| inventory.models)
218 .into_iter()
219 .filter_map(|served| {
220 let status = if served.supports_tools == Some(false) {
221 HarnessModelStatus::NoToolSupport
222 } else {
223 HarnessModelStatus::Ready
224 };
225
226 Some(HarnessModelOption {
227 context_window: served.context_window,
228 loaded_context_window: served.loaded_context_window,
229 ..local_option(
230 AgentModel::OpenAiCompatible(ServedModel::new(&served.id)?),
231 status,
232 )
233 })
234 })
235 .collect::<Vec<_>>();
236 let configured = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV)
237 .and_then(ServedModel::new)
238 .map(AgentModel::OpenAiCompatible);
239 if let Some(configured) = configured
240 && !options.iter().any(|option| option.model == configured)
241 {
242 options.insert(0, local_option(configured, HarnessModelStatus::Ready));
243 }
244
245 options
246}
247
248fn hosted_model(
251 model: AgentModel,
252 environment: &BTreeMap<String, String>,
253 is_signed_in: impl Fn(&Path) -> bool,
254) -> Option<HarnessModelOption> {
255 let selection = ModelSelection::resolve_known(model.as_str()).ok()?;
256 let provider = selection.provider;
257 let cost = model_cost(provider.cost_tier(&selection.model)?);
258 let status = configuration_status(provider, environment, is_signed_in);
259
260 Some(HarnessModelOption {
261 context_window: selection
262 .profile(environment, None)
263 .ok()
264 .map(ModelProfile::context_window_tokens),
265 cost,
266 loaded_context_window: None,
267 model,
268 provider: provider_display_name(provider).to_string(),
269 status,
270 trains_on_prompts: provider.trains_on_prompts(&selection.model),
271 })
272}
273
274fn model_cost(tier: CostTier) -> ModelCost {
277 match tier {
278 CostTier::Local => ModelCost::Local,
279 CostTier::Plan => ModelCost::Plan,
280 CostTier::Cheap => ModelCost::Cheap,
281 CostTier::Standard => ModelCost::Standard,
282 CostTier::Premium => ModelCost::Premium,
283 }
284}
285
286fn provider_display_name(provider: ModelProvider) -> &'static str {
288 match provider {
289 ModelProvider::ChatGpt => "ChatGPT plan",
290 ModelProvider::Kimi => "Kimi",
291 ModelProvider::Muse => "Muse",
292 ModelProvider::OpenAi => "OpenAI",
293 ModelProvider::OpenAiCompatible => LocalServerKind::OpenAiCompatible.display_name(),
294 ModelProvider::Qwen => "Qwen",
295 }
296}
297
298pub(crate) async fn running_context_window(
310 selection: &ModelSelection,
311 environment: &BTreeMap<String, String>,
312) -> Result<Option<u64>, String> {
313 let Ok(Some(server)) = selection.provider.local_server(lookup(environment)) else {
314 return Ok(None);
315 };
316 let Ok(Some(window)) = server.running_context_window(&selection.model).await else {
317 return Ok(None);
318 };
319 if window < MINIMUM_RUNNING_CONTEXT_WINDOW {
320 return Err(format!(
321 "The local server runs `{}` with a {window}-token context window, below the \
322 {MINIMUM_RUNNING_CONTEXT_WINDOW} tokens harness turns need, so it would drop the \
323 start of the conversation. Restart Ollama with `OLLAMA_CONTEXT_LENGTH=32768` (or \
324 raise the context length in the Ollama app's settings), or pick another model with \
325 `/model`.",
326 selection.model
327 ));
328 }
329
330 Ok(Some(window))
331}
332
333pub(super) fn lookup(
335 environment: &BTreeMap<String, String>,
336) -> impl FnMut(&str) -> Result<String, env::VarError> + '_ {
337 |name| {
338 environment
339 .get(name)
340 .cloned()
341 .ok_or(env::VarError::NotPresent)
342 }
343}
344
345pub(super) fn chatgpt_auth_file(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
352 let set = |name: &str| {
353 environment
354 .get(name)
355 .filter(|value| !value.is_empty())
356 .map(PathBuf::from)
357 };
358 let data_dir = set(AGENTTY_ROOT_ENV).or_else(|| set("HOME").map(|home| home.join(".agentty")));
359
360 chatgpt_auth_file_in(lookup(environment), data_dir.as_deref())
361}
362
363fn unicode_environment(
365 variables: impl IntoIterator<Item = (OsString, OsString)>,
366) -> BTreeMap<String, String> {
367 variables
368 .into_iter()
369 .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
370 .collect()
371}
372
373fn configuration_status(
377 provider: ModelProvider,
378 environment: &BTreeMap<String, String>,
379 is_signed_in: impl Fn(&Path) -> bool,
380) -> HarnessModelStatus {
381 if provider.requires_sign_in() {
382 let signed_in =
383 chatgpt_auth_file(environment).is_some_and(|auth_file| is_signed_in(&auth_file));
384
385 return if signed_in {
386 HarnessModelStatus::Ready
387 } else {
388 HarnessModelStatus::SignInRequired(CHATGPT_SIGN_IN_COMMAND)
389 };
390 }
391 if provider.requires_api_key() && !has_value(environment, provider.api_key_environment()) {
392 return HarnessModelStatus::MissingConfiguration(provider.api_key_environment());
393 }
394 if provider.default_base_url().is_none()
395 && !has_value(environment, provider.base_url_environment())
396 {
397 return HarnessModelStatus::MissingConfiguration(provider.base_url_environment());
398 }
399
400 HarnessModelStatus::Ready
401}
402
403fn nonblank<'a>(environment: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
405 environment
406 .get(name)
407 .map(|value| value.trim())
408 .filter(|value| !value.is_empty())
409}
410
411fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
413 nonblank(environment, name).is_some()
414}
415
416#[derive(Clone, Debug, Eq, PartialEq)]
419pub(crate) struct ModelSelection {
420 model: String,
421 provider: ModelProvider,
422}
423
424impl ModelSelection {
425 pub(crate) fn resolve(
433 model: &str,
434 environment: &BTreeMap<String, String>,
435 ) -> Result<Self, String> {
436 let Some(AgentModel::OpenAiCompatible(served)) = AgentKind::Harness.parse_model(model)
437 else {
438 return Self::resolve_known(model);
439 };
440 if let Some(name) = served.name() {
441 return Ok(Self {
442 model: name.to_string(),
443 provider: ModelProvider::OpenAiCompatible,
444 });
445 }
446 let served = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV).ok_or_else(|| {
447 format!(
448 "Cannot use harness model `{model}`: {OPENAI_COMPATIBLE_MODEL_ENV} is unset. Pick \
449 a local model with `/model`, or set it to the model your OpenAI-compatible \
450 server serves, such as `qwen3:latest`, before starting Agentty."
451 )
452 })?;
453
454 Ok(Self {
455 model: served.to_string(),
456 provider: ModelProvider::OpenAiCompatible,
457 })
458 }
459
460 pub(crate) fn from_key(key: &str) -> Option<Self> {
464 let (provider, model) = key.split_once('/')?;
465 if provider == ModelProvider::OpenAiCompatible.as_str() {
466 return (!model.trim().is_empty()).then(|| Self {
467 model: model.to_string(),
468 provider: ModelProvider::OpenAiCompatible,
469 });
470 }
471 let id = if provider == ModelProvider::ChatGpt.as_str() {
473 key
474 } else {
475 model
476 };
477
478 Self::resolve_known(id)
479 .ok()
480 .filter(|selection| selection.key() == key)
481 }
482
483 fn resolve_known(model: &str) -> Result<Self, String> {
488 let unknown = || format!("The harness does not serve model `{model}`.");
489 if let Some(plan_model) = model
490 .strip_prefix(ModelProvider::ChatGpt.as_str())
491 .and_then(|rest| rest.strip_prefix('/'))
492 {
493 return ModelProvider::ChatGpt
494 .known_models()
495 .contains(&plan_model)
496 .then(|| Self {
497 model: plan_model.to_string(),
498 provider: ModelProvider::ChatGpt,
499 })
500 .ok_or_else(unknown);
501 }
502
503 ModelProvider::all()
504 .iter()
505 .copied()
506 .filter(|provider| !provider.requires_sign_in())
507 .find(|provider| provider.known_models().contains(&model))
508 .map(|provider| Self {
509 model: model.to_string(),
510 provider,
511 })
512 .ok_or_else(unknown)
513 }
514
515 pub(crate) fn key(&self) -> String {
517 format!("{}/{}", self.provider, self.model)
518 }
519
520 pub(crate) fn registry(
526 &self,
527 environment: &BTreeMap<String, String>,
528 provider_call_budget: Option<&ProviderCallBudget>,
529 running_context_window: Option<u64>,
530 ) -> Result<ModelRegistry, String> {
531 let mut configuration = ModelConfiguration::new(self.provider, &self.model);
532 if self.provider.requires_sign_in()
535 && let Some(auth_file) = chatgpt_auth_file(environment)
536 {
537 configuration = configuration.auth_file(auth_file);
538 }
539 let client = configuration
540 .client_from_environment(lookup(environment))
541 .map_err(|error| {
542 let remedy = if self.provider.requires_sign_in() {
543 format!("Run `{CHATGPT_SIGN_IN_COMMAND}`, then retry.")
544 } else if self.provider.requires_api_key() {
545 format!(
546 "Set {} before starting Agentty.",
547 self.provider.api_key_environment()
548 )
549 } else {
550 format!(
551 "Check {OPENAI_COMPATIBLE_MODEL_ENV} and {} before starting Agentty.",
552 self.provider.base_url_environment()
553 )
554 };
555
556 format!(
557 "Cannot use harness model `{}`: {error}. {remedy}",
558 self.model
559 )
560 })?;
561
562 let model: Arc<dyn Model> = match provider_call_budget {
563 Some(budget) => Arc::new(BudgetedModel {
564 budget: budget.clone(),
565 inner: client,
566 }),
567 None => Arc::new(client),
568 };
569
570 self.register(model, self.profile(environment, running_context_window)?)
571 }
572
573 pub(crate) fn harness(
578 &self,
579 context: &HarnessContext<'_>,
580 observer: impl LifecycleObserver + 'static,
581 ) -> Result<Harness, String> {
582 let registry = self.registry(
583 context.environment,
584 context.provider_call_budget,
585 context.running_context_window,
586 )?;
587
588 self.harness_from(®istry, context, observer)
589 }
590
591 pub(crate) fn resume_only_harness(
598 &self,
599 context: &HarnessContext<'_>,
600 observer: impl LifecycleObserver + 'static,
601 ) -> Result<Harness, String> {
602 let client = if self.provider.requires_sign_in() {
605 ModelClient::chatgpt(ChatGptConfig {
606 auth_file: PathBuf::new(),
607 base_url: RESUME_ONLY_BASE_URL.to_string(),
608 model: self.model.clone(),
609 })
610 .map_err(failure("Invalid resume-only harness model"))?
611 } else {
612 ModelConfiguration::new(self.provider, &self.model)
613 .base_url(RESUME_ONLY_BASE_URL)
614 .client_from_environment(|_| Ok(String::new()))
615 .map_err(failure("Invalid resume-only harness model"))?
616 };
617 let metadata = client.metadata().clone();
618 let profile = self.profile(context.environment, None)?;
619 let registry = self.register(Arc::new(ResumeOnlyModel { metadata }), profile)?;
620
621 self.harness_from(®istry, context, observer)
622 }
623
624 fn register(
634 &self,
635 model: Arc<dyn Model>,
636 profile: ModelProfile,
637 ) -> Result<ModelRegistry, String> {
638 let id = ModelId::cataloged(self.provider, &self.model);
639 let declared = self
640 .provider
641 .capabilities(&self.model)
642 .unwrap_or(Capabilities::NONE);
643 let spec = ModelSpec::new(id.clone())
644 .with_provider(self.provider)
645 .with_capabilities(declared)
646 .with_profile(profile);
647 let handle = ModelCatalog::builder()
648 .model(spec, model)
649 .build()
650 .and_then(|catalog| catalog.resolve(&ModelSelector::Id(id)))
651 .map_err(failure("Invalid harness model registration"))?;
652 let mut registry = ModelRegistry::new();
653 registry
654 .register_catalog_entry(&handle, REGISTRATION_REVISION)
655 .map_err(failure("Invalid harness model registration"))?;
656
657 Ok(registry)
658 }
659
660 fn harness_from(
666 &self,
667 registry: &ModelRegistry,
668 context: &HarnessContext<'_>,
669 observer: impl LifecycleObserver + 'static,
670 ) -> Result<Harness, String> {
671 Ok(Harness::from_registry(registry, &self.key())
672 .map_err(failure("Invalid harness model registration"))?
673 .repository(context.repository.clone())
674 .model_reasoning_effort(reasoning_effort(context.reasoning_level))
675 .with_lifecycle_observer(traced(observer)))
676 }
677
678 fn profile(
688 &self,
689 environment: &BTreeMap<String, String>,
690 running_context_window: Option<u64>,
691 ) -> Result<ModelProfile, String> {
692 let declared = match running_context_window {
693 Some(window) => self.provider.running_profile(lookup(environment), window),
694 None => self
695 .provider
696 .declared_profile(&self.model, lookup(environment)),
697 }
698 .map_err(failure("Invalid harness model profile"))?;
699
700 Ok(declared
701 .or_else(|| {
702 AgentKind::Harness
703 .parse_model(&self.model)
704 .and_then(model_profile::declared)
705 })
706 .unwrap_or(FALLBACK_MODEL_PROFILE))
707 }
708}
709
710pub(crate) struct HarnessContext<'a> {
712 pub(crate) environment: &'a BTreeMap<String, String>,
714 pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
716 pub(crate) reasoning_level: ReasoningLevel,
718 pub(crate) repository: &'a Repository,
720 pub(crate) running_context_window: Option<u64>,
722}
723
724pub(crate) fn system_prompt() -> &'static str {
726 SYSTEM_PROMPT
727}
728
729pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
734 OutputSchema::new(protocol_output_schema(
735 profile,
736 SchemaRequiredPolicy::MinimumProtocolKeys,
737 ))
738 .map_err(failure("The harness rejected the protocol schema"))
739}
740
741pub(crate) struct RunOptions {
743 bash: Option<BashConfig>,
744 output: OutputSchema,
745 tools: ToolSet,
746}
747
748impl RunOptions {
749 pub(crate) fn new(
755 profile: ProtocolRequestProfile,
756 permission_mode: PermissionMode,
757 environment: &BTreeMap<String, String>,
758 ) -> Result<Self, String> {
759 let output = output_schema(profile)?;
760 if permission_mode == PermissionMode::ReadOnly {
761 return Ok(Self {
762 bash: None,
763 output,
764 tools: ToolSet::empty().with_read(),
765 });
766 }
767
768 Ok(Self {
769 bash: Some(bash_config(environment)?),
770 output,
771 tools: ToolSet::builtins(),
772 })
773 }
774
775 pub(crate) fn request(self, input: String) -> RunRequest {
777 let request = RunRequest::new(input).output(self.output).tools(self.tools);
778
779 match self.bash {
780 Some(bash) => request.bash(bash),
781 None => request,
782 }
783 }
784}
785
786fn bash_config(environment: &BTreeMap<String, String>) -> Result<BashConfig, String> {
789 let mut config = BashConfig::for_executor(
790 Arc::new(UnsandboxedExecutor::without_isolation()),
791 PathBuf::from(BASH_EXECUTABLE),
792 BASH_POLICY_REVISION.to_string(),
793 BASH_TIMEOUT,
794 BashConfig::DEFAULT_CAPTURE_BYTES,
795 )
796 .map_err(failure("Invalid harness bash policy"))?
797 .with_host_information();
798 for (name, value) in bash_environment(environment) {
799 if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
800 config = granted;
801 }
802 }
803
804 Ok(config)
805}
806
807fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
809 let is_granted = |name: &str| {
810 !PROVIDER_ENVIRONMENT_PREFIXES
811 .iter()
812 .any(|prefix| name.starts_with(prefix))
813 };
814 let priority = PRIORITY_ENVIRONMENT
815 .iter()
816 .filter_map(|name| environment.get_key_value(*name));
817 let remaining = environment
818 .iter()
819 .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));
820
821 priority
822 .chain(remaining)
823 .filter(|(name, _)| is_granted(name))
824 .collect()
825}
826
827pub(crate) fn repository(
832 folder: &Path,
833 environment: &BTreeMap<String, String>,
834) -> Result<Repository, String> {
835 let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
836 let candidates = environment
837 .get("PATH")
838 .into_iter()
839 .flat_map(env::split_paths)
840 .filter(|directory| directory.is_absolute())
841 .map(|directory| directory.join(&executable_name));
842 for candidate in candidates {
843 match Repository::new(folder, candidate) {
844 Ok(repository) => return Ok(repository),
845 Err(
846 error @ (RepositoryError::Root { .. }
847 | RepositoryError::RootIsGitAdministrative { .. }),
848 ) => return Err(format!("Invalid harness worktree: {error}")),
849 Err(_) => {}
850 }
851 }
852
853 Err("The harness needs a Git executable on PATH.".to_string())
854}
855
856pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
858 move |error| format!("{context}: {error}")
859}
860
861fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
863 match reasoning_level {
864 ReasoningLevel::Low => ReasoningEffort::Low,
865 ReasoningLevel::Medium => ReasoningEffort::Medium,
866 ReasoningLevel::High => ReasoningEffort::High,
867 ReasoningLevel::XHigh => ReasoningEffort::XHigh,
868 ReasoningLevel::Max => ReasoningEffort::Max,
869 }
870}
871
872fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
876 let observers = LifecycleObserverSet::new(observer);
877 if !Context::current().span().is_recording() {
878 return observers;
879 }
880
881 observers.with_observer(
882 LifecycleTraceObserver::new().with_tool_attributes(ag_telemetry::run_identity),
883 )
884}
885
886struct BudgetedModel {
888 budget: ProviderCallBudget,
889 inner: ModelClient,
890}
891
892#[async_trait]
893impl Model for BudgetedModel {
894 fn metadata(&self) -> Option<ModelMetadata> {
895 Model::metadata(&self.inner)
896 }
897
898 fn validate_schema(&self, schema: &OutputSchema) -> Result<(), ModelError> {
899 Model::validate_schema(&self.inner, schema)
900 }
901
902 fn validate_input(&self, input: &TurnInput) -> Result<(), ModelError> {
903 Model::validate_input(&self.inner, input)
904 }
905
906 fn keeps_prefix_across_schemas(&self) -> bool {
907 Model::keeps_prefix_across_schemas(&self.inner)
908 }
909
910 fn replays_reasoning_text(&self) -> bool {
911 Model::replays_reasoning_text(&self.inner)
912 }
913
914 async fn complete(&self, request: ModelRequest) -> Result<ModelCompletion, ModelError> {
915 self.budget.consume().map_err(ModelError::request)?;
916
917 Model::complete(&self.inner, request).await
918 }
919}
920
921struct ResumeOnlyModel {
924 metadata: ModelMetadata,
925}
926
927#[async_trait]
928impl Model for ResumeOnlyModel {
929 fn metadata(&self) -> Option<ModelMetadata> {
930 Some(self.metadata.clone())
931 }
932
933 async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
934 Err(ModelError::request(io::Error::other(
935 "the recorded harness model can only resume its session",
936 )))
937 }
938}
939
940#[cfg(test)]
941#[path = "config_test.rs"]
942mod tests;