Skip to main content

bamboo_engine/runtime/
config.rs

1use std::collections::BTreeSet;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use bamboo_agent_core::composition::CompositionExecutor;
6use bamboo_agent_core::storage::AttachmentReader;
7use bamboo_agent_core::storage::Storage;
8use bamboo_agent_core::tools::ToolSchema;
9use bamboo_agent_core::GoldConfidence;
10use bamboo_compression::TokenBudget;
11use bamboo_config::MemoryConfig;
12use bamboo_config::PermissionMode;
13use bamboo_domain::ReasoningEffort;
14use bamboo_domain::RuntimeSessionPersistence;
15use bamboo_llm::LLMProvider;
16use bamboo_metrics::MetricsCollector;
17use bamboo_skills::SkillManager;
18use bamboo_tools::ToolRegistry;
19use serde::{Deserialize, Serialize};
20
21#[derive(Clone, Default)]
22pub struct AuxiliaryModelConfig {
23    pub fast_model_name: Option<String>,
24    pub fast_model_provider: Option<Arc<dyn LLMProvider>>,
25    pub background_model_name: Option<String>,
26    pub planning_model_name: Option<String>,
27    pub search_model_name: Option<String>,
28    pub summarization_model_name: Option<String>,
29    pub background_model_provider: Option<Arc<dyn LLMProvider>>,
30    pub summarization_model_provider: Option<Arc<dyn LLMProvider>>,
31}
32
33fn default_gold_max_output_tokens() -> u32 {
34    1024
35}
36
37fn default_gold_max_auto_continuations() -> u32 {
38    3
39}
40
41fn default_gold_min_confidence() -> GoldConfidence {
42    GoldConfidence::Medium
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
46#[serde(default)]
47pub struct GoldConfig {
48    /// Master switch for Gold observe-only evaluation.
49    #[serde(default)]
50    pub enabled: bool,
51    /// Independent switch for Phase 2 low-risk auto-answer.
52    ///
53    /// Kept separate from `enabled` so Phase 1 observe-only users do not
54    /// implicitly opt into automatic clarification responses.
55    #[serde(default)]
56    pub auto_answer_enabled: bool,
57    /// Independent switch for Phase 3 server-side auto-continue.
58    ///
59    /// Kept separate from both `enabled` and `auto_answer_enabled` so users can
60    /// opt into terminal auto-resume explicitly without enabling other Gold
61    /// automation behaviors.
62    #[serde(default)]
63    pub auto_continue_enabled: bool,
64    /// Optional dedicated model for Gold evaluation. Falls back to fast model,
65    /// then the main chat model when absent.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub model_name: Option<String>,
68    /// The user's goal for this session.
69    ///
70    /// Unlike `evaluation_prompt` (which only tunes the *judge*), the goal is
71    /// surfaced to the *main* executing agent as a persistent system-prompt
72    /// block so it actively works toward it. The Gold evaluator also measures
73    /// progress against this text.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub goal: Option<String>,
76    /// Optional custom prompt suffix appended to the built-in Gold evaluator
77    /// prompt. This tunes the judge only; it does not set the goal.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub evaluation_prompt: Option<String>,
80    /// Output token limit for the Gold evaluator call.
81    #[serde(default = "default_gold_max_output_tokens")]
82    pub max_output_tokens: u32,
83    /// Maximum number of automatic Gold continuations allowed per session.
84    #[serde(default = "default_gold_max_auto_continuations")]
85    pub max_auto_continuations: u32,
86    /// Minimum evaluator confidence required before Gold auto-continues or
87    /// auto-answers. Defaults to `medium` so the loop fires on reasonably
88    /// confident verdicts rather than only `high`.
89    #[serde(default = "default_gold_min_confidence")]
90    pub min_auto_continue_confidence: GoldConfidence,
91}
92
93impl Default for GoldConfig {
94    fn default() -> Self {
95        Self {
96            enabled: false,
97            auto_answer_enabled: false,
98            auto_continue_enabled: false,
99            model_name: None,
100            goal: None,
101            evaluation_prompt: None,
102            max_output_tokens: default_gold_max_output_tokens(),
103            max_auto_continuations: default_gold_max_auto_continuations(),
104            min_auto_continue_confidence: default_gold_min_confidence(),
105        }
106    }
107}
108
109impl GoldConfig {
110    /// The session goal text, falling back to the legacy `evaluation_prompt`
111    /// for sessions created before the dedicated `goal` field existed.
112    ///
113    /// Returns `None` when neither field holds non-empty text.
114    pub fn effective_goal(&self) -> Option<&str> {
115        self.goal
116            .as_deref()
117            .or(self.evaluation_prompt.as_deref())
118            .map(str::trim)
119            .filter(|value| !value.is_empty())
120    }
121}
122
123fn default_guardian_max_reviews() -> u32 {
124    2
125}
126
127/// Configuration for the guardian adversarial-review terminal gate.
128///
129/// Mirrors [`GoldConfig`]: a plain, serde-defaulting struct surfaced per run.
130/// When `enabled` is false (the default) the guardian gate is inactive and the
131/// terminal completion path is unchanged.
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
133#[serde(default)]
134pub struct GuardianConfig {
135    /// Master switch for the guardian review gate.
136    #[serde(default)]
137    pub enabled: bool,
138    /// Optional dedicated reviewer model. Falls back to the run's main model.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub model_name: Option<String>,
141    /// Maximum guardian review passes per run (budget; mirrors
142    /// [`GoldConfig::max_auto_continuations`]).
143    #[serde(default = "default_guardian_max_reviews")]
144    pub max_reviews: u32,
145}
146
147impl Default for GuardianConfig {
148    fn default() -> Self {
149        Self {
150            enabled: false,
151            model_name: None,
152            max_reviews: default_guardian_max_reviews(),
153        }
154    }
155}
156
157/// Late-bound spawner for the guardian reviewer child.
158///
159/// The runner cannot construct a child directly: the `SpawnScheduler` is built
160/// *after* the `Agent` that drives the runner (a construction-order cycle), so
161/// the terminal gate spawns the reviewer through this trait object, injected
162/// per-request on [`AgentLoopConfig`] exactly like `auxiliary_model_resolver`.
163/// The implementation lives in the server (it captures the already-built
164/// scheduler + child-session adapter); the engine holds only the trait, keeping
165/// the engine free of any dependency on server/AppState types.
166#[async_trait::async_trait]
167pub trait GuardianSpawner: Send + Sync {
168    /// Create a read-only reviewer child for `parent_session_id`, seeded with
169    /// `review_prompt`, enqueue it to run, and return its session id so the
170    /// caller can register a wait on it.
171    async fn spawn_guardian_review(
172        &self,
173        parent_session: &bamboo_agent_core::Session,
174        review_prompt: String,
175        model: String,
176        disabled_tools: Option<BTreeSet<String>>,
177    ) -> Result<String, String>;
178}
179
180/// Hidden resume-message `runtime_kind` metadata value for a bash-completion
181/// self-resume (issue #84 Phase 2b). Shared by the producer (the self-resume
182/// task that appends the resume message) and the consumer (the suspend-
183/// finalization discriminant arm that preserves it), so a typo in one cannot
184/// desync from the other and silently drop the resume trigger.
185pub const BASH_COMPLETION_RESUME_KIND: &str = "bash_completion_resume";
186
187/// Re-exported so peers that already `use crate::runtime::config::{BashResumeHook, …}`
188/// (the runtime/spawn threading) can name the completion sink the same way,
189/// rather than reaching into `bamboo_agent_core` separately.
190pub use bamboo_agent_core::BashCompletionSink;
191
192/// Late-bound hook that arranges a self-resume for a session suspended waiting
193/// on background Bash shells (issue #84 Phase 2b). Injected per-request on
194/// [`AgentLoopConfig`] exactly like [`GuardianSpawner`]; the implementation
195/// lives in the session-app layer (on the completion coordinator) where the
196/// resume port ([`crate::session_app::resume::ResumeExecutionPort`]) is
197/// reachable.
198///
199/// The hook spawns a detached task that **polls the live background-shell
200/// registry** until every captured shell is no longer running, then clears the
201/// wait and resumes the session. Polling — not the one-shot `BashCompleted`
202/// event — is the liveness guarantee: even if a shell completes between the
203/// suspend snapshot and the hook's first poll, or before any event subscriber
204/// exists, the registry will report it as not-running and the session resumes.
205pub trait BashResumeHook: Send + Sync {
206    /// Arrange a detached self-resume for `session_id`, which has just been
207    /// durably suspended waiting on the background shells in `bash_ids`.
208    fn arrange_bash_self_resume(&self, session_id: String, bash_ids: Vec<String>);
209}
210
211/// A child sub-agent's request to have a gated tool approved by its parent.
212///
213/// A non-bypassed child cannot answer its own permission prompt (no human is
214/// attached to a child session), so the request is delegated up to the parent.
215#[derive(Debug, Clone)]
216pub struct ChildApprovalRequest {
217    pub child_session_id: String,
218    pub parent_session_id: String,
219    /// The gated tool call on the child to re-execute once approved.
220    pub child_tool_call_id: String,
221    pub tool_name: String,
222    /// Permission type as a string (e.g. "WriteFile", "ExecuteCommand").
223    pub permission_type: String,
224    /// The concrete resource the permission applies to (path, command, …).
225    pub resource: String,
226    /// Human-facing approval question to surface on the parent.
227    pub question: String,
228    /// The raw `awaiting_permission_approval` payload the child's executor built,
229    /// so the parent can reuse the existing grant-extraction path verbatim.
230    pub approval_payload: serde_json::Value,
231}
232
233/// What the executor should do after delegating a child's approval upward.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum ChildApprovalOutcome {
236    /// Registered on the parent; the child must SUSPEND and await the decision.
237    Delegated,
238    /// Parent policy auto-approved (bypass / existing grant); proceed to execute.
239    AutoApproved,
240    /// Parent policy auto-denied; the executor must deny the tool.
241    AutoDenied,
242}
243
244/// Late-bound delegate that routes a child's approval request up to its parent.
245///
246/// Injected per-request on [`AgentLoopConfig`] exactly like [`GuardianSpawner`];
247/// the trait lives in the engine, the implementation in the server (it owns the
248/// parent session store + pending-question + notification machinery).
249#[async_trait::async_trait]
250pub trait ApprovalDelegate: Send + Sync {
251    /// Register `request` on its parent (or auto-resolve by policy) and report
252    /// what the child's executor should do next.
253    async fn delegate_child_approval(
254        &self,
255        request: ChildApprovalRequest,
256    ) -> Result<ChildApprovalOutcome, String>;
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub enum ImageFallbackMode {
261    Placeholder,
262    Error,
263    Ocr,
264    /// Use a vision-capable LLM to describe the image, then replace the image
265    /// with the textual description so that text-only models can understand
266    /// the content.
267    Vision,
268}
269
270#[derive(Debug, Clone, PartialEq, Eq)]
271pub struct ImageFallbackConfig {
272    pub mode: ImageFallbackMode,
273    /// Vision model name for `Vision` mode. Falls back to the session's main model
274    /// when `None`.
275    pub vision_model: Option<String>,
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub struct PromptMemoryFlags {
280    pub project_prompt_injection: bool,
281    pub relevant_recall: bool,
282    pub relevant_recall_rerank: bool,
283    pub project_first_dream: bool,
284}
285
286impl Default for PromptMemoryFlags {
287    fn default() -> Self {
288        Self {
289            project_prompt_injection: true,
290            relevant_recall: true,
291            relevant_recall_rerank: false,
292            project_first_dream: true,
293        }
294    }
295}
296
297impl From<&MemoryConfig> for PromptMemoryFlags {
298    fn from(value: &MemoryConfig) -> Self {
299        Self {
300            project_prompt_injection: value.project_prompt_injection,
301            relevant_recall: value.relevant_recall,
302            relevant_recall_rerank: value.relevant_recall_rerank,
303            project_first_dream: value.project_first_dream,
304        }
305    }
306}
307
308/// Configuration for the agent loop.
309///
310/// # One-config-per-run invariant (#44)
311///
312/// These values are SNAPSHOTTED once, from the live `Config` under a brief read
313/// lock, at the start of `AgentRuntime::execute()`. The entire multi-round run —
314/// which can last minutes — then uses this frozen snapshot. Changing config
315/// (model names, provider, `disabled_tools`/`disabled_skills`, memory flags,
316/// token budget, …) while a run is in flight does NOT affect that run; the new
317/// values are picked up on the NEXT execution (i.e. the next user turn / session
318/// restart), not the next round of the current run.
319///
320/// This is intentional: a run sees a stable configuration, so its behavior can't
321/// shift underneath it mid-execution. The deliberate exceptions are the
322/// late-bound, per-request trait objects that resolve LIVE each time they're
323/// used rather than being snapshotted — `auxiliary_model_resolver` (auxiliary
324/// model selection) and `guardian_spawner` (the reviewer child). If a frozen
325/// field ever needs to become live-per-round, follow that resolver pattern
326/// rather than widening the snapshot.
327#[non_exhaustive]
328pub struct AgentLoopConfig {
329    pub(crate) max_rounds: usize,
330    pub(crate) system_prompt: Option<String>,
331    /// Skill IDs that are disabled globally for this execution.
332    pub(crate) disabled_skill_ids: BTreeSet<String>,
333    /// Optional explicit skill selection for this execution.
334    /// When set, only these skill IDs are considered for skill context and allowlists.
335    pub(crate) selected_skill_ids: Option<Vec<String>>,
336    /// Optional active skill mode for this execution.
337    ///
338    /// When set, skill discovery prefers `skills-<mode>` directories over generic
339    /// directories for the same skill id.
340    pub(crate) selected_skill_mode: Option<String>,
341    pub(crate) additional_tool_schemas: Vec<ToolSchema>,
342    pub(crate) tool_registry: Arc<ToolRegistry>,
343    pub(crate) composition_executor: Option<Arc<CompositionExecutor>>,
344    pub(crate) skill_manager: Option<Arc<SkillManager>>,
345    /// If true, skip appending the initial user message (already present in session).
346    pub(crate) skip_initial_user_message: bool,
347    /// Optional storage for persisting session changes
348    pub(crate) storage: Option<Arc<dyn Storage>>,
349    /// Optional runtime persistence for non-authoritative session saves.
350    /// When set, engine save sites use this instead of `storage` for writes.
351    pub(crate) persistence: Option<Arc<dyn RuntimeSessionPersistence>>,
352    /// Optional attachment reader for resolving `bamboo-attachment://...` references
353    /// into `data:` URLs for upstream providers. This must not mutate session storage.
354    pub(crate) attachment_reader: Option<Arc<dyn AttachmentReader>>,
355    /// Optional asynchronous metrics collector
356    pub(crate) metrics_collector: Option<MetricsCollector>,
357    /// Model name used for metrics attribution
358    pub(crate) model_name: Option<String>,
359    /// Fast/cheap model for lightweight tasks (task evaluation, search, etc.).
360    ///
361    /// Call sites may fall back to `model_name` when this is unset.
362    pub(crate) fast_model_name: Option<String>,
363    /// Optional provider override for lightweight fast-model LLM calls.
364    pub(crate) fast_model_provider: Option<Arc<dyn LLMProvider>>,
365    /// Fast/cheap model for memory/background tasks.
366    ///
367    /// This must not silently fall back to the main interaction model.
368    pub(crate) background_model_name: Option<String>,
369
370    /// Model for planning/coordination tasks (task decomposition, architecture).
371    /// Falls back to `model_name` when unset.
372    pub(crate) planning_model_name: Option<String>,
373    /// Model for search/navigation tasks (grep, file listing, symbol resolution).
374    /// Falls back to `fast_model_name` when unset.
375    pub(crate) search_model_name: Option<String>,
376    /// Custom instructions for conversation summarization, injected into the
377    /// LLM summary prompt. Lets users control what the summary focuses on.
378    ///
379    /// Resolution order: session-level > config-level > built-in defaults.
380    pub(crate) compression_instructions: Option<String>,
381    /// Dedicated model for summarization. Falls back to `background_model_name`.
382    pub(crate) summarization_model_name: Option<String>,
383    /// Optional provider override for memory/background model LLM calls.
384    ///
385    /// When set, memory recall rerank and other memory/background tasks use this
386    /// provider instead of the shared agent loop provider.
387    pub(crate) background_model_provider: Option<Arc<dyn LLMProvider>>,
388    /// Optional provider override for summarization / context compression calls.
389    ///
390    /// When set, conversation/task summarization uses this provider instead of
391    /// the shared agent loop provider.
392    pub(crate) summarization_model_provider: Option<Arc<dyn LLMProvider>>,
393    /// Provider routing key used for provider-specific request behavior.
394    ///
395    /// In multi-instance mode this may be the instance id.
396    pub(crate) provider_name: Option<String>,
397    /// Underlying provider type (for example `openai`, `anthropic`, `copilot`).
398    ///
399    /// This is distinct from `provider_name` so provider-specific behavior can
400    /// remain correct when routing keys are instance ids.
401    pub(crate) provider_type: Option<String>,
402    /// Optional request-time reasoning effort override.
403    pub(crate) reasoning_effort: Option<ReasoningEffort>,
404    /// Bamboo application data directory (typically `~/.bamboo`).
405    ///
406    /// Used by runtime features that persist auxiliary artifacts outside the
407    /// session store, such as durable plan mode files under `~/.bamboo/plan`.
408    pub(crate) app_data_dir: Option<PathBuf>,
409    /// Tool names that should be excluded from schemas sent to the LLM.
410    pub(crate) disabled_tools: BTreeSet<String>,
411    /// Token budget for context management (optional, defaults to model's limits)
412    pub(crate) token_budget: Option<TokenBudget>,
413    /// Legacy `config.json` `model_limits` value, snapshotted from the live
414    /// in-memory Config when this loop config is built. Consulted only by
415    /// `resolve_token_budget` as a last-resort fallback when `model_limits.json`
416    /// fails to load — so the engine never does a fresh disk-reading
417    /// `Config::new()` (which would also clobber the global env-var cache). #38.
418    pub(crate) legacy_model_limits: Option<serde_json::Value>,
419    /// Optional image fallback behavior applied to *LLM requests only* (never persisted).
420    ///
421    /// This is intended for text-only provider paths where image parts must be degraded
422    /// (placeholder / OCR / error) without leaking into stored session history or UI.
423    pub(crate) image_fallback: Option<ImageFallbackConfig>,
424    /// Feature flags controlling prompt-time memory injection behavior.
425    pub(crate) prompt_memory_flags: PromptMemoryFlags,
426    /// Maximum tool calls allowed per round (default: 80).
427    pub(crate) max_tool_calls_per_round: usize,
428    /// Maximum consecutive failures per tool before circuit breaker (default: 3).
429    pub(crate) max_consecutive_failures_per_tool: usize,
430    /// Tool names that require strict argument validation.
431    pub(crate) strict_argument_tool_names: Vec<String>,
432    /// Per-tool execution timeout in seconds (default: 120).
433    pub(crate) per_tool_timeout_secs: u64,
434    /// Parallel batch execution timeout in seconds (default: 300).
435    pub(crate) parallel_batch_timeout_secs: u64,
436    /// Permission mode for this execution (default: None = use PermissionConfig's mode).
437    pub(crate) permission_mode: Option<PermissionMode>,
438    /// Optional Gold observe-only evaluator configuration.
439    ///
440    /// When `None` or `enabled == false`, Gold evaluation is disabled and the
441    /// existing execute/respond/resume loop remains unchanged.
442    pub(crate) gold_config: Option<GoldConfig>,
443    /// Optional guardian adversarial-review gate configuration. When `None` or
444    /// `enabled == false`, the guardian terminal gate is inactive.
445    pub(crate) guardian_config: Option<GuardianConfig>,
446    /// Late-bound spawner for the guardian reviewer child. `None` (the default)
447    /// leaves the guardian gate inert even when `guardian_config.enabled` is set,
448    /// since the runner cannot create a child without it. Wired by the server.
449    pub(crate) guardian_spawner: Option<Arc<dyn GuardianSpawner>>,
450    /// Late-bound hook that arranges a self-resume for a session suspended
451    /// waiting on background Bash shells (issue #84 Phase 2b). `None` (the
452    /// default) leaves the bash suspend gate inert: the gate refuses to suspend
453    /// without a wired hook, so a session can never strand itself without a
454    /// resume path. Wired by the server (the completion coordinator impl).
455    pub(crate) bash_resume_hook: Option<Arc<dyn BashResumeHook>>,
456    /// Late-bound sink that pushes a completed background Bash shell's result
457    /// into this session's loop (issue #84 Phase 2b follow-up) — injected at the
458    /// next round boundary while the loop is actively iterating, or delivered via
459    /// resume when it is idle. Threaded onto the tool dispatch context (like
460    /// `can_async_resume`) so the Bash tool can hand it to the shell's
461    /// completion-poll task. `None` (the default) leaves the push inert; the
462    /// durable end-of-turn suspend/poll backstop (`bash_resume_hook`) still runs.
463    /// Wired by the server (the completion coordinator impl).
464    pub(crate) bash_completion_sink: Option<Arc<dyn bamboo_agent_core::BashCompletionSink>>,
465    /// Late-bound delegate that routes a child's gated-tool approval request up
466    /// to its parent (Phase 2). `None` (the default) leaves child gating on its
467    /// legacy path. Wired by the server.
468    pub(crate) approval_delegate: Option<Arc<dyn ApprovalDelegate>>,
469    /// Enable dynamic per-round model routing based on task complexity.
470    /// When true, the pipeline classifies complexity at each round end and
471    /// stores the result in session metadata.
472    pub(crate) features_dynamic_model_routing: bool,
473    /// Optional per-round resolver for auxiliary model settings that should
474    /// follow live global config rather than stay frozen for the whole run.
475    ///
476    /// The main chat model remains session/request scoped; this hook is only
477    /// for fast/background/planning/search/summarization helpers.
478    pub(crate) auxiliary_model_resolver:
479        Option<Arc<dyn Fn() -> AuxiliaryModelConfig + Send + Sync>>,
480    /// Optional per-round resolver for the disabled tool/skill sets so they follow
481    /// LIVE global config instead of staying frozen for the whole run. Returns the
482    /// current `(disabled_tools, disabled_skill_ids)`. When `None`, the snapshotted
483    /// `disabled_tools` / `disabled_skill_ids` fields below are used (#44 behavior).
484    /// Re-resolved each round at the tool-schema filter, so disabling/re-enabling a
485    /// tool mid-run takes effect on the next round. #136.
486    pub(crate) disabled_filter_resolver:
487        Option<Arc<dyn Fn() -> (BTreeSet<String>, BTreeSet<String>) + Send + Sync>>,
488    /// Server-level usage guidance contributed by the run's tool executor —
489    /// chiefly the `instructions` connected MCP servers return from `initialize`.
490    /// Captured once at config construction (from `ToolExecutor::tool_guidance`)
491    /// and appended to the tool-guide section of the system prompt, so a server's
492    /// own how-to-use notes appear only while that server is loaded for the run.
493    pub(crate) mcp_tool_guidance: Option<String>,
494}
495
496impl Default for AgentLoopConfig {
497    fn default() -> Self {
498        Self {
499            max_rounds: 200,
500            system_prompt: None,
501            disabled_skill_ids: BTreeSet::new(),
502            selected_skill_ids: None,
503            selected_skill_mode: None,
504            additional_tool_schemas: Vec::new(),
505            tool_registry: Arc::new(ToolRegistry::new()),
506            composition_executor: None,
507            skill_manager: None,
508            skip_initial_user_message: false,
509            storage: None,
510            persistence: None,
511            attachment_reader: None,
512            metrics_collector: None,
513            model_name: None,
514            fast_model_name: None,
515            fast_model_provider: None,
516            background_model_name: None,
517            planning_model_name: None,
518            search_model_name: None,
519            compression_instructions: None,
520            summarization_model_name: None,
521            background_model_provider: None,
522            summarization_model_provider: None,
523            provider_name: None,
524            provider_type: None,
525            reasoning_effort: None,
526            app_data_dir: None,
527            disabled_tools: BTreeSet::new(),
528            token_budget: None,
529            legacy_model_limits: None,
530            image_fallback: None,
531            prompt_memory_flags: PromptMemoryFlags::default(),
532            max_tool_calls_per_round: 80,
533            max_consecutive_failures_per_tool: 3,
534            strict_argument_tool_names: vec![
535                "Write".into(),
536                "Edit".into(),
537                "NotebookEdit".into(),
538                "apply_patch".into(),
539                "Bash".into(),
540                "Task".into(),
541                "SubAgent".into(),
542                "scheduler".into(),
543                "sub_session_manager".into(),
544                "session_note".into(),
545                "memory_note".into(),
546            ],
547            per_tool_timeout_secs: 120,
548            parallel_batch_timeout_secs: 300,
549            permission_mode: None,
550            gold_config: None,
551            guardian_config: None,
552            guardian_spawner: None,
553            bash_resume_hook: None,
554            bash_completion_sink: None,
555            approval_delegate: None,
556            features_dynamic_model_routing: false,
557            auxiliary_model_resolver: None,
558            disabled_filter_resolver: None,
559            mcp_tool_guidance: None,
560        }
561    }
562}
563
564impl AgentLoopConfig {
565    /// Live `(disabled_tools, disabled_skill_ids)` for the current round: the
566    /// resolver if one is wired (#136 — follows live global config between
567    /// rounds), else the per-run snapshot (#44 frozen behavior). `Cow` avoids
568    /// cloning the snapshot in the common no-resolver path (SDK / tests).
569    pub(crate) fn resolve_disabled_filters(
570        &self,
571    ) -> (
572        std::borrow::Cow<'_, BTreeSet<String>>,
573        std::borrow::Cow<'_, BTreeSet<String>>,
574    ) {
575        match &self.disabled_filter_resolver {
576            Some(resolver) => {
577                let (tools, skills) = resolver();
578                (
579                    std::borrow::Cow::Owned(tools),
580                    std::borrow::Cow::Owned(skills),
581                )
582            }
583            None => (
584                std::borrow::Cow::Borrowed(&self.disabled_tools),
585                std::borrow::Cow::Borrowed(&self.disabled_skill_ids),
586            ),
587        }
588    }
589
590    /// The active session goal to surface to the main agent, or `None` when
591    /// Gold is disabled or no goal is set. Falls back to the legacy
592    /// `evaluation_prompt` for back-compat via [`GoldConfig::effective_goal`].
593    pub fn active_goal(&self) -> Option<&str> {
594        self.gold_config
595            .as_ref()
596            .filter(|cfg| cfg.enabled)
597            .and_then(GoldConfig::effective_goal)
598    }
599
600    /// Whether the Codex-style autonomous goal loop is active for this run.
601    ///
602    /// This requires Gold to be enabled, a goal to be set, AND auto-continue to
603    /// be on. Only then is the `update_goal` self-report tool surfaced to the
604    /// model and the terminal double-check allowed to veto a premature stop.
605    /// When Gold is enabled without auto-continue, the evaluator stays purely
606    /// observational (legacy behavior).
607    pub fn goal_loop_active(&self) -> bool {
608        self.gold_config.as_ref().is_some_and(|cfg| {
609            cfg.enabled && cfg.auto_continue_enabled && cfg.effective_goal().is_some()
610        })
611    }
612
613    /// Whether the guardian review gate is active for this run: a spawner is
614    /// wired (so the runner can actually create the reviewer child) AND the
615    /// config is present and enabled.
616    pub fn guardian_active(&self) -> bool {
617        self.guardian_spawner.is_some()
618            && self.guardian_config.as_ref().is_some_and(|cfg| cfg.enabled)
619    }
620
621    /// Maximum guardian review passes for this run (the budget). `0` when no
622    /// guardian config is set.
623    pub fn guardian_max_reviews(&self) -> u32 {
624        self.guardian_config
625            .as_ref()
626            .map_or(0, |cfg| cfg.max_reviews)
627    }
628
629    /// The reviewer model override, if a guardian config sets one.
630    pub fn guardian_model(&self) -> Option<&str> {
631        self.guardian_config
632            .as_ref()
633            .and_then(|cfg| cfg.model_name.as_deref())
634    }
635
636    /// Whether child→parent approval delegation is wired for this run.
637    pub fn delegation_active(&self) -> bool {
638        self.approval_delegate.is_some()
639    }
640}
641
642#[cfg(test)]
643mod tests;