1use std::collections::BTreeMap;
4use std::ffi::OsString;
5use std::fmt::Display;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::time::Duration;
9use std::{env, io};
10
11use ag_contracts::{PermissionMode, ProviderCallBudget, ReasoningLevel};
12use ag_harness::bash::{BashConfig, UnsandboxedExecutor};
13use ag_harness::lifecycle::{LifecycleObserver, LifecycleObserverSet, LifecycleTraceObserver};
14use ag_harness::model::{
15 ModelCapabilities, ModelClient, ModelCompletion, ModelMetadata, ModelProfile, ModelRegistry,
16 ModelRequest, ReasoningEffort,
17};
18use ag_harness::provider::{
19 ChatGptConfig, CostTier, LocalServerKind, ModelConfiguration, ModelProvider,
20 chatgpt_auth_file_in,
21};
22use ag_harness::recovery::ExecutionIdentity;
23use ag_harness::{
24 Harness, Model, ModelError, OutputSchema, Repository, RepositoryError, ToolSet, TurnInput,
25 TurnOptions,
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";
40const FALLBACK_MODEL_PROFILE: ModelProfile =
44 ModelProfile::new(128_000).with_estimate_margin(16_384, 50);
45const RESUME_ONLY_BASE_URL: &str = "http://127.0.0.1";
48const SESSION_DATABASE_FILE: &str = "harness.db";
50const BASH_EXECUTABLE: &str = "/bin/bash";
52const BASH_POLICY_REVISION: &str = "agentty-unsandboxed-1";
54const BASH_TIMEOUT: Duration = Duration::from_secs(600);
56const OPENAI_COMPATIBLE_MODEL_ENV: &str = "OPENAI_COMPATIBLE_MODEL";
59const CHATGPT_SIGN_IN_COMMAND: &str = "ag-harness login chatgpt";
61const AGENTTY_ROOT_ENV: &str = "AGENTTY_ROOT";
64const PROVIDER_ENVIRONMENT_PREFIXES: [&str; 5] =
68 ["CHATGPT_", "DASHSCOPE_", "KIMI_", "MODEL_", "OPENAI_"];
69const PRIORITY_ENVIRONMENT: [&str; 17] = [
72 "PATH",
73 "HOME",
74 "USER",
75 "LOGNAME",
76 "SHELL",
77 "LANG",
78 "LC_ALL",
79 "TERM",
80 "TMPDIR",
81 "SSH_AUTH_SOCK",
82 "GIT_SSH_COMMAND",
83 "CARGO_HOME",
84 "RUSTUP_HOME",
85 "RUSTUP_TOOLCHAIN",
86 "VIRTUAL_ENV",
87 "XDG_CONFIG_HOME",
88 "XDG_CACHE_HOME",
89];
90const SYSTEM_PROMPT: &str = concat!(
92 "You are a coding agent working inside one Git worktree through tools. Use only the tools ",
93 "offered on the current turn: `read` inspects files, `write` applies unified-diff patches, ",
94 "and `bash` runs shell commands in the worktree. Call a tool immediately when you need it; ",
95 "never narrate, promise, or defer a tool call. Claim a change or command result only after ",
96 "the tool reports it."
97);
98
99type EnvironmentSource = Arc<dyn Fn() -> BTreeMap<String, String> + Send + Sync>;
101
102#[derive(Clone)]
108pub struct NativeHarnessConfig {
109 data_root: PathBuf,
110 environment: EnvironmentSource,
111}
112
113impl NativeHarnessConfig {
114 pub fn new(data_root: PathBuf) -> Self {
117 Self::with_environment(data_root, process_environment)
118 }
119
120 pub fn with_environment(
123 data_root: PathBuf,
124 environment: impl Fn() -> BTreeMap<String, String> + Send + Sync + 'static,
125 ) -> Self {
126 Self {
127 data_root,
128 environment: Arc::new(environment),
129 }
130 }
131
132 pub(crate) fn environment(&self) -> BTreeMap<String, String> {
134 (self.environment)()
135 }
136
137 pub(crate) async fn session_database(&self, session_id: &str) -> Result<PathBuf, String> {
143 let is_single_component = !session_id.is_empty()
144 && session_id != "."
145 && session_id != ".."
146 && !session_id.contains(['/', '\\', '\0']);
147 if !is_single_component {
148 return Err(format!("Invalid harness session id `{session_id}`."));
149 }
150 let directory = self.data_root.join(session_id);
151 tokio::fs::create_dir_all(&directory)
152 .await
153 .map_err(|error| format!("Failed to create the harness session directory: {error}"))?;
154
155 Ok(directory.join(SESSION_DATABASE_FILE))
156 }
157}
158
159pub(crate) fn process_environment() -> BTreeMap<String, String> {
162 unicode_environment(env::vars_os())
163}
164
165pub(crate) async fn harness_models(
174 environment: &BTreeMap<String, String>,
175 is_signed_in: impl Fn(&Path) -> bool,
176) -> Vec<HarnessModelOption> {
177 let mut options = local_models(environment).await;
178 options.extend(
179 AgentKind::Harness
180 .models()
181 .iter()
182 .filter_map(|model| hosted_model(*model, environment, &is_signed_in)),
183 );
184
185 options
186}
187
188async fn local_models(environment: &BTreeMap<String, String>) -> Vec<HarnessModelOption> {
191 let server = ModelProvider::OpenAiCompatible
192 .local_server(lookup(environment))
193 .ok()
194 .flatten();
195 let inventory = async { server?.inventory().await.ok() }.await;
196 let provider = inventory
197 .as_ref()
198 .map_or(LocalServerKind::OpenAiCompatible, |inventory| {
199 inventory.kind
200 })
201 .display_name();
202 let local_option = |model: AgentModel, status: HarnessModelStatus| HarnessModelOption {
203 context_window: None,
204 cost: ModelCost::Local,
205 loaded_context_window: None,
206 model,
207 provider: provider.to_string(),
208 status,
209 trains_on_prompts: false,
210 };
211 let mut options = inventory
212 .map_or_else(Vec::new, |inventory| inventory.models)
213 .into_iter()
214 .filter_map(|served| {
215 let status = if served.supports_tools == Some(false) {
216 HarnessModelStatus::NoToolSupport
217 } else {
218 HarnessModelStatus::Ready
219 };
220
221 Some(HarnessModelOption {
222 context_window: served.context_window,
223 loaded_context_window: served.loaded_context_window,
224 ..local_option(
225 AgentModel::OpenAiCompatible(ServedModel::new(&served.id)?),
226 status,
227 )
228 })
229 })
230 .collect::<Vec<_>>();
231 let configured = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV)
232 .and_then(ServedModel::new)
233 .map(AgentModel::OpenAiCompatible);
234 if let Some(configured) = configured
235 && !options.iter().any(|option| option.model == configured)
236 {
237 options.insert(0, local_option(configured, HarnessModelStatus::Ready));
238 }
239
240 options
241}
242
243fn hosted_model(
246 model: AgentModel,
247 environment: &BTreeMap<String, String>,
248 is_signed_in: impl Fn(&Path) -> bool,
249) -> Option<HarnessModelOption> {
250 let selection = ModelSelection::resolve_known(model.as_str()).ok()?;
251 let provider = selection.provider;
252 let cost = model_cost(provider.cost_tier(&selection.model)?);
253 let status = configuration_status(provider, environment, is_signed_in);
254
255 Some(HarnessModelOption {
256 context_window: selection
257 .profile(environment, None)
258 .ok()
259 .map(ModelProfile::context_window_tokens),
260 cost,
261 loaded_context_window: None,
262 model,
263 provider: provider_display_name(provider).to_string(),
264 status,
265 trains_on_prompts: provider.trains_on_prompts(&selection.model),
266 })
267}
268
269fn model_cost(tier: CostTier) -> ModelCost {
272 match tier {
273 CostTier::Local => ModelCost::Local,
274 CostTier::Plan => ModelCost::Plan,
275 CostTier::Cheap => ModelCost::Cheap,
276 CostTier::Standard => ModelCost::Standard,
277 CostTier::Premium => ModelCost::Premium,
278 }
279}
280
281fn provider_display_name(provider: ModelProvider) -> &'static str {
283 match provider {
284 ModelProvider::ChatGpt => "ChatGPT plan",
285 ModelProvider::Kimi => "Kimi",
286 ModelProvider::Muse => "Muse",
287 ModelProvider::OpenAi => "OpenAI",
288 ModelProvider::OpenAiCompatible => LocalServerKind::OpenAiCompatible.display_name(),
289 ModelProvider::Qwen => "Qwen",
290 }
291}
292
293pub(crate) async fn running_context_window(
305 selection: &ModelSelection,
306 environment: &BTreeMap<String, String>,
307) -> Result<Option<u64>, String> {
308 let Ok(Some(server)) = selection.provider.local_server(lookup(environment)) else {
309 return Ok(None);
310 };
311 let Ok(Some(window)) = server.running_context_window(&selection.model).await else {
312 return Ok(None);
313 };
314 if window < MINIMUM_RUNNING_CONTEXT_WINDOW {
315 return Err(format!(
316 "The local server runs `{}` with a {window}-token context window, below the \
317 {MINIMUM_RUNNING_CONTEXT_WINDOW} tokens harness turns need, so it would drop the \
318 start of the conversation. Restart Ollama with `OLLAMA_CONTEXT_LENGTH=32768` (or \
319 raise the context length in the Ollama app's settings), or pick another model with \
320 `/model`.",
321 selection.model
322 ));
323 }
324
325 Ok(Some(window))
326}
327
328pub(super) fn lookup(
330 environment: &BTreeMap<String, String>,
331) -> impl FnMut(&str) -> Result<String, env::VarError> + '_ {
332 |name| {
333 environment
334 .get(name)
335 .cloned()
336 .ok_or(env::VarError::NotPresent)
337 }
338}
339
340pub(super) fn chatgpt_auth_file(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
347 let set = |name: &str| {
348 environment
349 .get(name)
350 .filter(|value| !value.is_empty())
351 .map(PathBuf::from)
352 };
353 let data_dir = set(AGENTTY_ROOT_ENV).or_else(|| set("HOME").map(|home| home.join(".agentty")));
354
355 chatgpt_auth_file_in(lookup(environment), data_dir.as_deref())
356}
357
358fn unicode_environment(
360 variables: impl IntoIterator<Item = (OsString, OsString)>,
361) -> BTreeMap<String, String> {
362 variables
363 .into_iter()
364 .filter_map(|(name, value)| Some((name.into_string().ok()?, value.into_string().ok()?)))
365 .collect()
366}
367
368fn configuration_status(
372 provider: ModelProvider,
373 environment: &BTreeMap<String, String>,
374 is_signed_in: impl Fn(&Path) -> bool,
375) -> HarnessModelStatus {
376 if provider.requires_sign_in() {
377 let signed_in =
378 chatgpt_auth_file(environment).is_some_and(|auth_file| is_signed_in(&auth_file));
379
380 return if signed_in {
381 HarnessModelStatus::Ready
382 } else {
383 HarnessModelStatus::SignInRequired(CHATGPT_SIGN_IN_COMMAND)
384 };
385 }
386 if provider.requires_api_key() && !has_value(environment, provider.api_key_environment()) {
387 return HarnessModelStatus::MissingConfiguration(provider.api_key_environment());
388 }
389 if provider.default_base_url().is_none()
390 && !has_value(environment, provider.base_url_environment())
391 {
392 return HarnessModelStatus::MissingConfiguration(provider.base_url_environment());
393 }
394
395 HarnessModelStatus::Ready
396}
397
398fn nonblank<'a>(environment: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
400 environment
401 .get(name)
402 .map(|value| value.trim())
403 .filter(|value| !value.is_empty())
404}
405
406fn has_value(environment: &BTreeMap<String, String>, name: &str) -> bool {
408 nonblank(environment, name).is_some()
409}
410
411#[derive(Clone, Debug, Eq, PartialEq)]
414pub(crate) struct ModelSelection {
415 model: String,
416 provider: ModelProvider,
417}
418
419impl ModelSelection {
420 pub(crate) fn resolve(
428 model: &str,
429 environment: &BTreeMap<String, String>,
430 ) -> Result<Self, String> {
431 let Some(AgentModel::OpenAiCompatible(served)) = AgentKind::Harness.parse_model(model)
432 else {
433 return Self::resolve_known(model);
434 };
435 if let Some(name) = served.name() {
436 return Ok(Self {
437 model: name.to_string(),
438 provider: ModelProvider::OpenAiCompatible,
439 });
440 }
441 let served = nonblank(environment, OPENAI_COMPATIBLE_MODEL_ENV).ok_or_else(|| {
442 format!(
443 "Cannot use harness model `{model}`: {OPENAI_COMPATIBLE_MODEL_ENV} is unset. Pick \
444 a local model with `/model`, or set it to the model your OpenAI-compatible \
445 server serves, such as `qwen3:latest`, before starting Agentty."
446 )
447 })?;
448
449 Ok(Self {
450 model: served.to_string(),
451 provider: ModelProvider::OpenAiCompatible,
452 })
453 }
454
455 pub(crate) fn from_key(key: &str) -> Option<Self> {
459 let (provider, model) = key.split_once('/')?;
460 if provider == ModelProvider::OpenAiCompatible.as_str() {
461 return (!model.trim().is_empty()).then(|| Self {
462 model: model.to_string(),
463 provider: ModelProvider::OpenAiCompatible,
464 });
465 }
466 let id = if provider == ModelProvider::ChatGpt.as_str() {
468 key
469 } else {
470 model
471 };
472
473 Self::resolve_known(id)
474 .ok()
475 .filter(|selection| selection.key() == key)
476 }
477
478 fn resolve_known(model: &str) -> Result<Self, String> {
483 let unknown = || format!("The harness does not serve model `{model}`.");
484 if let Some(plan_model) = model
485 .strip_prefix(ModelProvider::ChatGpt.as_str())
486 .and_then(|rest| rest.strip_prefix('/'))
487 {
488 return ModelProvider::ChatGpt
489 .known_models()
490 .contains(&plan_model)
491 .then(|| Self {
492 model: plan_model.to_string(),
493 provider: ModelProvider::ChatGpt,
494 })
495 .ok_or_else(unknown);
496 }
497
498 ModelProvider::all()
499 .iter()
500 .copied()
501 .filter(|provider| !provider.requires_sign_in())
502 .find(|provider| provider.known_models().contains(&model))
503 .map(|provider| Self {
504 model: model.to_string(),
505 provider,
506 })
507 .ok_or_else(unknown)
508 }
509
510 pub(crate) fn key(&self) -> String {
512 format!("{}/{}", self.provider, self.model)
513 }
514
515 pub(crate) fn registry(
521 &self,
522 environment: &BTreeMap<String, String>,
523 provider_call_budget: Option<&ProviderCallBudget>,
524 running_context_window: Option<u64>,
525 ) -> Result<ModelRegistry, String> {
526 let mut configuration = ModelConfiguration::new(self.provider, &self.model);
527 if self.provider.requires_sign_in()
530 && let Some(auth_file) = chatgpt_auth_file(environment)
531 {
532 configuration = configuration.auth_file(auth_file);
533 }
534 let client = configuration
535 .client_from_environment(lookup(environment))
536 .map_err(|error| {
537 let remedy = if self.provider.requires_sign_in() {
538 format!("Run `{CHATGPT_SIGN_IN_COMMAND}`, then retry.")
539 } else if self.provider.requires_api_key() {
540 format!(
541 "Set {} before starting Agentty.",
542 self.provider.api_key_environment()
543 )
544 } else {
545 format!(
546 "Check {OPENAI_COMPATIBLE_MODEL_ENV} and {} before starting Agentty.",
547 self.provider.base_url_environment()
548 )
549 };
550
551 format!(
552 "Cannot use harness model `{}`: {error}. {remedy}",
553 self.model
554 )
555 })?;
556
557 let profile = self.profile(environment, running_context_window)?;
558 match provider_call_budget {
559 Some(budget) => self.register(
560 BudgetedModel {
561 budget: budget.clone(),
562 inner: client,
563 },
564 profile,
565 ),
566 None => self.register(client, profile),
567 }
568 }
569
570 pub(crate) fn harness(
575 &self,
576 context: &HarnessContext<'_>,
577 observer: impl LifecycleObserver + 'static,
578 ) -> Result<Harness, String> {
579 let registry = self.registry(
580 context.environment,
581 context.provider_call_budget,
582 context.running_context_window,
583 )?;
584
585 self.harness_from(®istry, context, observer)
586 }
587
588 pub(crate) fn resume_only_harness(
595 &self,
596 context: &HarnessContext<'_>,
597 observer: impl LifecycleObserver + 'static,
598 ) -> Result<Harness, String> {
599 let client = if self.provider.requires_sign_in() {
602 ModelClient::chatgpt(ChatGptConfig {
603 auth_file: PathBuf::new(),
604 base_url: RESUME_ONLY_BASE_URL.to_string(),
605 model: self.model.clone(),
606 })
607 .map_err(failure("Invalid resume-only harness model"))?
608 } else {
609 ModelConfiguration::new(self.provider, &self.model)
610 .base_url(RESUME_ONLY_BASE_URL)
611 .client_from_environment(|_| Ok(String::new()))
612 .map_err(failure("Invalid resume-only harness model"))?
613 };
614 let metadata = client.metadata().clone();
615 let profile = self.profile(context.environment, None)?;
616 let registry = self.register(ResumeOnlyModel { metadata }, profile)?;
617
618 self.harness_from(®istry, context, observer)
619 }
620
621 fn register(
623 &self,
624 model: impl Model + 'static,
625 profile: ModelProfile,
626 ) -> Result<ModelRegistry, String> {
627 let identity = ExecutionIdentity::new(self.key(), REGISTRATION_REVISION)
628 .map_err(failure("Invalid harness model registration"))?;
629 let capabilities = ModelCapabilities {
630 tool_calls: true,
631 ..ModelCapabilities::new(profile)
632 };
633 let mut registry = ModelRegistry::new();
634 registry
635 .register(identity, model, capabilities)
636 .map_err(failure("Invalid harness model registration"))?;
637
638 Ok(registry)
639 }
640
641 fn harness_from(
647 &self,
648 registry: &ModelRegistry,
649 context: &HarnessContext<'_>,
650 observer: impl LifecycleObserver + 'static,
651 ) -> Result<Harness, String> {
652 Ok(Harness::from_registry(registry, &self.key())
653 .map_err(failure("Invalid harness model registration"))?
654 .repository(context.repository.clone())
655 .model_reasoning_effort(reasoning_effort(context.reasoning_level))
656 .with_lifecycle_observer(traced(observer)))
657 }
658
659 fn profile(
669 &self,
670 environment: &BTreeMap<String, String>,
671 running_context_window: Option<u64>,
672 ) -> Result<ModelProfile, String> {
673 let declared = match running_context_window {
674 Some(window) => self.provider.running_profile(lookup(environment), window),
675 None => self
676 .provider
677 .declared_profile(&self.model, lookup(environment)),
678 }
679 .map_err(failure("Invalid harness model profile"))?;
680
681 Ok(declared
682 .or_else(|| {
683 AgentKind::Harness
684 .parse_model(&self.model)
685 .and_then(model_profile::declared)
686 })
687 .unwrap_or(FALLBACK_MODEL_PROFILE))
688 }
689}
690
691pub(crate) struct HarnessContext<'a> {
693 pub(crate) environment: &'a BTreeMap<String, String>,
695 pub(crate) provider_call_budget: Option<&'a ProviderCallBudget>,
697 pub(crate) reasoning_level: ReasoningLevel,
699 pub(crate) repository: &'a Repository,
701 pub(crate) running_context_window: Option<u64>,
703}
704
705pub(crate) fn system_prompt() -> &'static str {
707 SYSTEM_PROMPT
708}
709
710pub(crate) fn output_schema(profile: ProtocolRequestProfile) -> Result<OutputSchema, String> {
715 OutputSchema::new(protocol_output_schema(
716 profile,
717 SchemaRequiredPolicy::MinimumProtocolKeys,
718 ))
719 .map_err(failure("The harness rejected the protocol schema"))
720}
721
722pub(crate) fn turn_options(
728 profile: ProtocolRequestProfile,
729 permission_mode: PermissionMode,
730 environment: &BTreeMap<String, String>,
731) -> Result<TurnOptions, String> {
732 let options = TurnOptions::from_output(output_schema(profile)?);
733 if permission_mode == PermissionMode::ReadOnly {
734 return Ok(options.with_tools(ToolSet::empty().with_read()));
735 }
736
737 Ok(options
738 .with_tools(ToolSet::builtins())
739 .with_bash(bash_config(environment)?))
740}
741
742fn bash_config(environment: &BTreeMap<String, String>) -> Result<BashConfig, String> {
745 let mut config = BashConfig::for_executor(
746 Arc::new(UnsandboxedExecutor::without_isolation()),
747 PathBuf::from(BASH_EXECUTABLE),
748 BASH_POLICY_REVISION.to_string(),
749 BASH_TIMEOUT,
750 BashConfig::DEFAULT_CAPTURE_BYTES,
751 )
752 .map_err(failure("Invalid harness bash policy"))?
753 .with_host_information();
754 for (name, value) in bash_environment(environment) {
755 if let Ok(granted) = config.clone().with_environment(name.clone(), value.clone()) {
756 config = granted;
757 }
758 }
759
760 Ok(config)
761}
762
763fn bash_environment(environment: &BTreeMap<String, String>) -> Vec<(&String, &String)> {
765 let is_granted = |name: &str| {
766 !PROVIDER_ENVIRONMENT_PREFIXES
767 .iter()
768 .any(|prefix| name.starts_with(prefix))
769 };
770 let priority = PRIORITY_ENVIRONMENT
771 .iter()
772 .filter_map(|name| environment.get_key_value(*name));
773 let remaining = environment
774 .iter()
775 .filter(|(name, _)| !PRIORITY_ENVIRONMENT.contains(&name.as_str()));
776
777 priority
778 .chain(remaining)
779 .filter(|(name, _)| is_granted(name))
780 .collect()
781}
782
783pub(crate) fn repository(
788 folder: &Path,
789 environment: &BTreeMap<String, String>,
790) -> Result<Repository, String> {
791 let executable_name = format!("git{}", env::consts::EXE_SUFFIX);
792 let candidates = environment
793 .get("PATH")
794 .into_iter()
795 .flat_map(env::split_paths)
796 .filter(|directory| directory.is_absolute())
797 .map(|directory| directory.join(&executable_name));
798 for candidate in candidates {
799 match Repository::new(folder, candidate) {
800 Ok(repository) => return Ok(repository),
801 Err(
802 error @ (RepositoryError::Root { .. }
803 | RepositoryError::RootIsGitAdministrative { .. }),
804 ) => return Err(format!("Invalid harness worktree: {error}")),
805 Err(_) => {}
806 }
807 }
808
809 Err("The harness needs a Git executable on PATH.".to_string())
810}
811
812pub(crate) fn failure<E: Display>(context: &'static str) -> impl FnOnce(E) -> String {
814 move |error| format!("{context}: {error}")
815}
816
817fn reasoning_effort(reasoning_level: ReasoningLevel) -> ReasoningEffort {
819 match reasoning_level {
820 ReasoningLevel::Low => ReasoningEffort::Low,
821 ReasoningLevel::Medium => ReasoningEffort::Medium,
822 ReasoningLevel::High => ReasoningEffort::High,
823 ReasoningLevel::XHigh => ReasoningEffort::XHigh,
824 ReasoningLevel::Max => ReasoningEffort::Max,
825 }
826}
827
828fn traced(observer: impl LifecycleObserver + 'static) -> LifecycleObserverSet {
832 let observers = LifecycleObserverSet::new(observer);
833 if !Context::current().span().is_recording() {
834 return observers;
835 }
836
837 observers.with_observer(
838 LifecycleTraceObserver::new().with_tool_attributes(ag_telemetry::run_identity),
839 )
840}
841
842struct BudgetedModel {
844 budget: ProviderCallBudget,
845 inner: ModelClient,
846}
847
848#[async_trait]
849impl Model for BudgetedModel {
850 fn metadata(&self) -> Option<ModelMetadata> {
851 Model::metadata(&self.inner)
852 }
853
854 fn validate_schema(&self, schema: &OutputSchema) -> Result<(), ModelError> {
855 Model::validate_schema(&self.inner, schema)
856 }
857
858 fn validate_input(&self, input: &TurnInput) -> Result<(), ModelError> {
859 Model::validate_input(&self.inner, input)
860 }
861
862 fn keeps_prefix_across_schemas(&self) -> bool {
863 Model::keeps_prefix_across_schemas(&self.inner)
864 }
865
866 fn replays_reasoning_text(&self) -> bool {
867 Model::replays_reasoning_text(&self.inner)
868 }
869
870 async fn complete(&self, request: ModelRequest) -> Result<ModelCompletion, ModelError> {
871 self.budget.consume().map_err(ModelError::request)?;
872
873 Model::complete(&self.inner, request).await
874 }
875}
876
877struct ResumeOnlyModel {
880 metadata: ModelMetadata,
881}
882
883#[async_trait]
884impl Model for ResumeOnlyModel {
885 fn metadata(&self) -> Option<ModelMetadata> {
886 Some(self.metadata.clone())
887 }
888
889 async fn complete(&self, _request: ModelRequest) -> Result<ModelCompletion, ModelError> {
890 Err(ModelError::request(io::Error::other(
891 "the recorded harness model can only resume its session",
892 )))
893 }
894}
895
896#[cfg(test)]
897#[path = "config_test.rs"]
898mod tests;