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