Skip to main content

adk_harness/
builder.rs

1//! `HarnessAgentBuilder` (spec 3.1 §7.2).
2
3use std::borrow::Cow;
4use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
5use std::sync::{Arc, Mutex, OnceLock};
6use std::time::Duration;
7
8use adk_agent::{LlmAgentBuilder, LlmEventSummarizer};
9use adk_core::{
10    ActionLedger, AdkError, ApprovalService, ApprovalStore, EventsCompactionConfig,
11    InMemoryActionLedger, InMemoryApprovalStore, InstructionProvider, Llm, ReadonlyContext, Result,
12    RunBudget, SpendLedger, Tool, ToolConfirmationHandler, ToolConfirmationPolicy, ToolPolicy,
13    Toolset,
14};
15use adk_devtools::{EditFileTool, GlobTool, GrepTool, ReadFileTool, Workspace, WriteFileTool};
16
17use crate::agent::{HarnessAgent, HarnessInfo, HarnessRuntime, InstructionState};
18use crate::approvals::{
19    ApprovalPrompter, InMemoryStandingRuleStore, PromptingConfirmationHandler, StandingRuleStore,
20};
21use crate::instructions::{
22    InMemoryWorkspaceTrustStore, InstructionsConfig, ProjectInstructions, WorkspaceTrustStore,
23};
24use crate::mode::{HarnessMode, InMemoryModeStore, ModeStore};
25use crate::policy::ToolKind;
26use crate::policy::{
27    HARNESS_TOOL_NAMES, HarnessPolicy, PolicyInner, PolicySwitches, PromptContexts, ShellView,
28    ToolClassRegistry,
29};
30use crate::prompt::HARNESS_SYSTEM_PROMPT;
31use crate::shell::{
32    InMemoryShellLedger, IsolationStatus, ShellConfig, ShellIsolation, ShellLedger,
33    resolve_isolation,
34};
35use crate::tools::{ExitPlanModeTool, HarnessBashTool, TodoList, UpdateTodoTool, WriteTodosTool};
36use crate::toolset::{HarnessToolset, mode_banner, website_banner};
37
38/// A pack: a feature that adds tools or a surface under the same policy
39/// (spec 3.1 §7.16–§7.18).
40///
41/// # Example
42///
43/// ```rust
44/// let pack = adk_harness::Pack::Browser;
45/// # let _ = pack;
46/// ```
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48#[non_exhaustive]
49pub enum Pack {
50    /// Browser tools.
51    Browser,
52    /// Governed computer use.
53    ComputerUse,
54    /// Payments under mandates.
55    Payments,
56    /// The voice surface.
57    Voice,
58    /// The managed form (feature `managed`): `packs::managed::HarnessResolver` serves the
59    /// harness on the managed runtime.
60    Managed,
61}
62
63/// Loop detection over the invocation's tool calls (spec 3.1 §7.13, feature `observe`).
64///
65/// # Example
66///
67/// ```rust
68/// let guard = adk_harness::LoopGuard { window: 20, max_identical_calls: 3, max_redundant: 5 };
69/// # let _ = guard;
70/// ```
71#[cfg(feature = "observe")]
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct LoopGuard {
74    /// Tool calls examined.
75    pub window: usize,
76    /// Identical calls that count as a loop.
77    pub max_identical_calls: usize,
78    /// Redundant calls that count as a loop.
79    pub max_redundant: usize,
80}
81
82type Customize = Box<dyn FnOnce(LlmAgentBuilder) -> LlmAgentBuilder + Send + 'static>;
83
84/// Builds a [`HarnessAgent`] (spec 3.1 §7.2).
85///
86/// The builder exposes no `before_tool_callback`, `enhanced_plugin` or
87/// `require_tool_confirmation*`: the first two can answer a call before authorization and
88/// the third forces a confirmation even when the policy allows, which defeats standing
89/// rules. [`customize_llm`](Self::customize_llm) is the escape hatch.
90///
91/// # Example
92///
93/// ```rust
94/// use adk_harness::{HarnessAgent, HarnessMode, InstructionsConfig};
95/// use adk_model::{ScriptedLlm, ScriptedResponse};
96/// use std::sync::Arc;
97///
98/// let dir = tempfile::tempdir().unwrap();
99/// let model = Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("done")]));
100/// let harness = HarnessAgent::builder("harness")
101///     .model(model)
102///     .workspace(adk_devtools::Workspace::new(dir.path()).allow_bash(true))
103///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
104///     .mode(HarnessMode::Plan)
105///     .build()
106///     .unwrap();
107/// assert!(harness.info().tools.contains(&"exit_plan_mode".to_string()));
108/// ```
109pub struct HarnessAgentBuilder {
110    name: String,
111    model: Option<Arc<dyn Llm>>,
112    workspace: Option<Workspace>,
113    description: Option<String>,
114    base_prompt: Cow<'static, str>,
115    instruction: Option<String>,
116    instructions: InstructionsConfig,
117    trust_store: Option<Arc<dyn WorkspaceTrustStore>>,
118    mode: HarnessMode,
119    mode_store: Option<Arc<dyn ModeStore>>,
120    standing_rules: Option<Arc<dyn StandingRuleStore>>,
121    shell_ledger: Option<Arc<dyn ShellLedger>>,
122    background_shells: crate::shell::BackgroundShellConfig,
123    shell_pids: Option<Arc<dyn crate::shell::ShellPidRegistry>>,
124    shell_supervisor: Option<Arc<crate::shell::ShellSupervisor>>,
125    read_records: Option<Arc<dyn adk_devtools::ReadLedger>>,
126    operator_policy: Option<Arc<dyn ToolPolicy>>,
127    origin_classes: Vec<Arc<dyn crate::policy::OriginClasses>>,
128    team_delegates: Vec<String>,
129    prompter: Option<Arc<dyn ApprovalPrompter>>,
130    confirmation_handler: Option<Arc<dyn ToolConfirmationHandler>>,
131    approval_store: Option<Arc<dyn ApprovalStore>>,
132    approval_service: Option<Arc<dyn ApprovalService>>,
133    auto_review: Option<Arc<dyn adk_core::ToolReviewer>>,
134    requested_call_seal: Option<Arc<dyn adk_core::RequestedCallSeal>>,
135    #[cfg(feature = "kernel")]
136    kernel_approvals: Arc<crate::kernel::LateApprovalNotifier>,
137    #[cfg(feature = "kernel")]
138    kernel_agenda: adk_kernel::AgendaHandle,
139    #[cfg(feature = "kernel")]
140    kernel_ledger: adk_kernel::proc::LateLedgerSink,
141    #[cfg(feature = "kernel")]
142    partition: crate::partition::PartitionOptions,
143    /// The agent a person added that this harness is built for (spec 3.3 §5.7, H3).
144    #[cfg(feature = "kernel")]
145    added: Option<crate::agents::AddedAgent>,
146    /// Where `propose_agent` suggests agents: set on the primary agent only (spec 3.3 §5.7).
147    #[cfg(all(feature = "kernel", feature = "web"))]
148    agent_proposer: Option<Arc<dyn crate::agents::SuggestAgent>>,
149    /// The kernel target this harness stamps its sessions with (spec 3.3 §5.7 "Threads").
150    #[cfg(feature = "kernel")]
151    session_stamp: Option<String>,
152    action_ledger: Option<Arc<dyn ActionLedger>>,
153    confirmation_timeout: Duration,
154    shell: ShellConfig,
155    shell_enabled: bool,
156    /// The personal preset offers `bash` only in the OS sandbox or a container (spec 3.3
157    /// §10 H1).
158    isolated_shell_only: bool,
159    /// The website preset leaves `bash` out (spec 3.5 §10 X10).
160    preset_without_shell: bool,
161    /// The website preset: its mode banner, and no `exit_plan_mode`, since the charter's
162    /// autonomy levels set the mode (spec 3.5 §7.11, A-I13).
163    website_preset: bool,
164    /// The public partition's tools: of the harness's own tools the agent is offered these
165    /// and nothing else (spec 3.5 §7.10, A-I2).
166    public_only: Option<BTreeSet<String>>,
167    /// `allow_unsandboxed_retry` was set explicitly, so a container shell keeps it.
168    retry_explicit: bool,
169    trust_mcp_read_only_hints: bool,
170    todos: bool,
171    #[cfg(feature = "skills")]
172    skills: crate::skills::SkillsConfig,
173    #[cfg(feature = "team")]
174    members: Vec<crate::team::MemberSpec>,
175    #[cfg(feature = "team")]
176    member_registry: Option<Arc<dyn adk_agent::TeamAgentRegistry>>,
177    #[cfg(feature = "team")]
178    team_policy: Option<adk_agent::TeamPolicy>,
179    default_members: bool,
180    member_model: Option<Arc<dyn Llm>>,
181    plan_graph: bool,
182    /// The surface the person uses, for the manifest (spec 3.1 §7.25).
183    surface: Option<crate::manifest::SurfaceManifest>,
184    /// Pages `harness_help` returns by name (spec 3.1 §7.25).
185    help_pages: BTreeMap<String, String>,
186    #[cfg(feature = "memory")]
187    memory: Option<crate::memory::MemoryConfig>,
188    #[cfg(feature = "graph")]
189    plan_checkpointer: Option<Arc<dyn adk_graph::Checkpointer>>,
190    /// Snapshots and rewind (spec 3.1 §7.27); off until `snapshots` is set.
191    snapshots: crate::snapshot::SnapshotSetup,
192    goal_store: Option<Arc<dyn crate::goal::GoalStore>>,
193    goal_grader: Option<Arc<dyn Llm>>,
194    #[cfg(feature = "graph")]
195    goal_engine: Option<crate::goal::GoalEngine>,
196    #[cfg(feature = "memory")]
197    long_term: LongTermOptions,
198    budget: Option<RunBudget>,
199    spend_ledger: Option<Arc<dyn SpendLedger>>,
200    audit_log: Option<Arc<dyn adk_core::audit_log::AuditRecorder>>,
201    #[cfg(feature = "auth")]
202    identity: IdentityOptions,
203    #[cfg(feature = "observe")]
204    loop_guard: Option<LoopGuard>,
205    tools: Vec<Arc<dyn Tool>>,
206    toolsets: Vec<Arc<dyn Toolset>>,
207    max_iterations: u32,
208    tool_timeout: Duration,
209    history_max_events: Option<usize>,
210    compaction: Option<EventsCompactionConfig>,
211    compaction_enabled: bool,
212    intra_compaction: Option<adk_core::IntraCompactionConfig>,
213    customize: Option<Customize>,
214    unimplemented: Vec<String>,
215    last_todos: Option<Arc<Mutex<TodoList>>>,
216    web: Option<crate::web::WebConfig>,
217    /// Signs `web_fetch` requests (spec 3.5 §7.3 "Outbound").
218    #[cfg(feature = "web")]
219    web_signer: Option<Arc<dyn crate::web::RequestSigner>>,
220    search_provider: Option<Arc<dyn crate::web::SearchProvider>>,
221    /// `None`: the model provider's search when `web` is set (spec 3.1 §7.20).
222    provider_web_tools: Option<crate::web::ProviderWebTools>,
223    mcp_interaction: crate::mcp::McpInteractionConfig,
224    #[cfg(feature = "mcp")]
225    mcp_servers: Vec<crate::mcp::McpServerSet>,
226    #[cfg(feature = "hooks")]
227    hooks: Option<crate::hooks::HookSet>,
228    #[cfg(feature = "hooks")]
229    hooks_enabled: bool,
230    effort: crate::posture::EffortPolicy,
231    cache_capable: Option<Arc<dyn adk_core::CacheCapable>>,
232    context_caching: bool,
233    #[cfg(feature = "payments")]
234    payments: Option<crate::packs::payments::PaymentsPack>,
235    payments_requested: bool,
236    managed_requested: bool,
237    #[cfg(feature = "browser")]
238    browser: Option<crate::packs::browser::BrowserPack>,
239    browser_requested: bool,
240    #[cfg(feature = "computer-use")]
241    computer_use: Option<crate::packs::computer_use::ComputerUsePack>,
242    computer_use_requested: bool,
243    #[cfg(feature = "vision")]
244    vision: Option<crate::packs::vision::VisionPack>,
245    voice_requested: bool,
246    take_over: Option<crate::take_over::TakeOver>,
247}
248
249impl HarnessAgentBuilder {
250    /// A builder for a harness named `name` (default `"harness"`).
251    pub fn new(name: impl Into<String>) -> Self {
252        Self {
253            name: name.into(),
254            model: None,
255            workspace: None,
256            description: None,
257            base_prompt: Cow::Borrowed(HARNESS_SYSTEM_PROMPT),
258            instruction: None,
259            instructions: InstructionsConfig::default(),
260            trust_store: None,
261            mode: HarnessMode::Ask,
262            mode_store: None,
263            standing_rules: None,
264            shell_ledger: None,
265            background_shells: crate::shell::BackgroundShellConfig::default(),
266            shell_pids: None,
267            shell_supervisor: None,
268            read_records: None,
269            operator_policy: None,
270            origin_classes: Vec::new(),
271            team_delegates: Vec::new(),
272            prompter: None,
273            confirmation_handler: None,
274            approval_store: None,
275            approval_service: None,
276            auto_review: None,
277            requested_call_seal: None,
278            #[cfg(feature = "kernel")]
279            kernel_approvals: Arc::default(),
280            #[cfg(feature = "kernel")]
281            kernel_agenda: adk_kernel::AgendaHandle::default(),
282            #[cfg(feature = "kernel")]
283            kernel_ledger: adk_kernel::proc::LateLedgerSink::new(),
284            #[cfg(feature = "kernel")]
285            partition: crate::partition::PartitionOptions::default(),
286            #[cfg(feature = "kernel")]
287            added: None,
288            #[cfg(all(feature = "kernel", feature = "web"))]
289            agent_proposer: None,
290            #[cfg(feature = "kernel")]
291            session_stamp: None,
292            action_ledger: None,
293            confirmation_timeout: Duration::from_secs(300),
294            shell: ShellConfig::default(),
295            shell_enabled: true,
296            isolated_shell_only: false,
297            preset_without_shell: false,
298            website_preset: false,
299            public_only: None,
300            retry_explicit: false,
301            trust_mcp_read_only_hints: false,
302            todos: true,
303            #[cfg(feature = "skills")]
304            skills: crate::skills::SkillsConfig::default(),
305            #[cfg(feature = "team")]
306            members: Vec::new(),
307            #[cfg(feature = "team")]
308            member_registry: None,
309            #[cfg(feature = "team")]
310            team_policy: None,
311            default_members: true,
312            member_model: None,
313            plan_graph: cfg!(feature = "graph"),
314            surface: None,
315            help_pages: BTreeMap::new(),
316            #[cfg(feature = "memory")]
317            memory: None,
318            #[cfg(feature = "graph")]
319            plan_checkpointer: None,
320            snapshots: crate::snapshot::SnapshotSetup::default(),
321            goal_store: None,
322            goal_grader: None,
323            #[cfg(feature = "graph")]
324            goal_engine: None,
325            #[cfg(feature = "memory")]
326            long_term: LongTermOptions::default(),
327            budget: None,
328            spend_ledger: None,
329            audit_log: None,
330            #[cfg(feature = "auth")]
331            identity: IdentityOptions::default(),
332            #[cfg(feature = "observe")]
333            loop_guard: None,
334            tools: Vec::new(),
335            toolsets: Vec::new(),
336            max_iterations: 100,
337            tool_timeout: Duration::from_secs(300),
338            history_max_events: None,
339            compaction: None,
340            compaction_enabled: true,
341            intra_compaction: None,
342            customize: None,
343            unimplemented: Vec::new(),
344            last_todos: None,
345            web: None,
346            #[cfg(feature = "web")]
347            web_signer: None,
348            search_provider: None,
349            provider_web_tools: None,
350            mcp_interaction: crate::mcp::McpInteractionConfig::default(),
351            #[cfg(feature = "mcp")]
352            mcp_servers: Vec::new(),
353            #[cfg(feature = "hooks")]
354            hooks: None,
355            #[cfg(feature = "hooks")]
356            hooks_enabled: true,
357            effort: crate::posture::EffortPolicy::default(),
358            cache_capable: None,
359            context_caching: true,
360            #[cfg(feature = "payments")]
361            payments: None,
362            payments_requested: false,
363            managed_requested: false,
364            #[cfg(feature = "browser")]
365            browser: None,
366            browser_requested: false,
367            #[cfg(feature = "computer-use")]
368            computer_use: None,
369            computer_use_requested: false,
370            #[cfg(feature = "vision")]
371            vision: None,
372            voice_requested: false,
373            take_over: None,
374        }
375    }
376
377    /// Governed web access (spec 3.1 §7.20): `web_fetch` under `config`'s allowlist and
378    /// caps, and web search — the built-in search of the provider the model's client serves,
379    /// or the governed `web_search` when a [`search_provider`](Self::search_provider) is set.
380    /// Without feature `web` the configuration is kept and no tool is added.
381    ///
382    /// # Example
383    ///
384    /// ```rust,ignore
385    /// let harness = HarnessAgent::builder("harness")
386    ///     .model(model)
387    ///     .workspace(workspace)
388    ///     .web(WebConfig { allowed_domains: vec!["docs.rs".into()], ..WebConfig::default() })
389    ///     .build()?;
390    /// ```
391    pub fn web(mut self, config: crate::web::WebConfig) -> Self {
392        self.web = Some(config);
393        self
394    }
395
396    /// Signs every `web_fetch` request, each redirect hop included, with `signer`: the
397    /// site's Web Bot Auth key, opt-in for general fetches (spec 3.5 §7.3 "Outbound").
398    #[cfg(feature = "web")]
399    pub fn web_signer(mut self, signer: Arc<dyn crate::web::RequestSigner>) -> Self {
400        self.web_signer = Some(signer);
401        self
402    }
403
404    /// The search backend behind the governed `web_search` (spec 3.1 §7.20); none by
405    /// default. A configured provider replaces the model provider's built-in search, so
406    /// every search runs under the policy, screening and a per-call record.
407    ///
408    /// # Example
409    ///
410    /// ```rust,ignore
411    /// let harness = HarnessAgent::builder("harness")
412    ///     .model(model)
413    ///     .workspace(workspace)
414    ///     .web(WebConfig::default())
415    ///     .search_provider(Arc::new(SearxngSearch::new("http://localhost:8888")?))
416    ///     .build()?;
417    /// assert!(harness.info().tools.contains(&"web_search".to_string()));
418    /// ```
419    pub fn search_provider(mut self, provider: Arc<dyn crate::web::SearchProvider>) -> Self {
420        self.search_provider = Some(provider);
421        self
422    }
423
424    /// Provider-executed search and URL tools (spec 3.1 §7.20). Without this call a
425    /// harness with [`web`](Self::web) declares
426    /// [`ProviderWebTools::provider_default`](crate::web::ProviderWebTools::provider_default)
427    /// — the search built-in of the provider the model's client serves — unless a
428    /// [`search_provider`](Self::search_provider) is set; one without `web` declares none.
429    /// [`ProviderWebTools::off`](crate::web::ProviderWebTools::off) turns them off.
430    ///
431    /// An enabled tool is attached for the provider the model's client serves only
432    /// ([`adk_core::Llm::native_web_search`]), carries the allowlist where the provider
433    /// supports one, is declared only to a run starting in Ask or Auto, is recorded as
434    /// `harness.web.provider_enabled` once per run, and what it searched is recorded as
435    /// `harness.web.searched` after each response (I49).
436    pub fn provider_web_tools(mut self, tools: crate::web::ProviderWebTools) -> Self {
437        self.provider_web_tools = Some(tools);
438        self
439    }
440
441    /// How the harness answers what MCP servers ask of it (spec 3.1 §7.21): elicitation,
442    /// sampling and resources. Without feature `mcp` the configuration is kept and no
443    /// bridge is installed.
444    pub fn mcp_interaction(mut self, config: crate::mcp::McpInteractionConfig) -> Self {
445        self.mcp_interaction = config;
446        self
447    }
448
449    /// MCP servers the harness starts and governs (spec 3.1 §7.21): their tools are
450    /// `External` tools, their elicitations reach the prompter or the approval inbox,
451    /// their sampling runs under the run's budget, and their resources are reachable
452    /// through `mcp_list_resources` and `mcp_read_resource`.
453    ///
454    /// Operator-declared servers (`trusted: true`) start with the harness; servers a
455    /// workspace file declares start only once the workspace is trusted (spec 3.1 §7.7,
456    /// I3).
457    ///
458    /// # Example
459    ///
460    /// ```rust,ignore
461    /// let servers = McpServerManager::from_json_file(".mcp.json")?.all_configs().await;
462    /// let harness = HarnessAgent::builder("harness")
463    ///     .model(model)
464    ///     .workspace(workspace)
465    ///     .mcp_servers(crate::mcp::McpServerSet::workspace(servers))
466    ///     .build()?;
467    /// ```
468    #[cfg(feature = "mcp")]
469    pub fn mcp_servers(mut self, servers: crate::mcp::McpServerSet) -> Self {
470        self.mcp_servers.push(servers);
471        self
472    }
473
474    /// The model (required).
475    pub fn model(mut self, model: Arc<dyn Llm>) -> Self {
476        self.model = Some(model);
477        self
478    }
479
480    /// The workspace (required). `bash` is offered only when the workspace allows it.
481    pub fn workspace(mut self, workspace: Workspace) -> Self {
482        self.workspace = Some(workspace);
483        self
484    }
485
486    /// The agent description.
487    pub fn description(mut self, text: impl Into<String>) -> Self {
488        self.description = Some(text.into());
489        self
490    }
491
492    /// Replaces the base prompt (default [`HARNESS_SYSTEM_PROMPT`]).
493    pub fn base_prompt(mut self, text: impl Into<Cow<'static, str>>) -> Self {
494        self.base_prompt = text.into();
495        self
496    }
497
498    /// Operator instruction text, placed after the base prompt. It is not
499    /// template-expanded.
500    pub fn instruction(mut self, text: impl Into<String>) -> Self {
501        self.instruction = Some(text.into());
502        self
503    }
504
505    /// The surface the person uses: its commands, the kernel and how each pack turns on,
506    /// for the harness's manifest (spec 3.1 §7.25). Without it the manifest reports
507    /// [`SurfaceManifest::library`](crate::SurfaceManifest::library).
508    ///
509    /// # Example
510    ///
511    /// ```rust
512    /// use adk_harness::{CommandEntry, HarnessAgent, InstructionsConfig, SurfaceManifest};
513    /// use adk_model::{ScriptedLlm, ScriptedResponse};
514    /// use std::sync::Arc;
515    ///
516    /// let dir = tempfile::tempdir().unwrap();
517    /// let surface = SurfaceManifest::new("my-app", "1.0.0")
518    ///     .command(CommandEntry::slash("approvals", "Calls waiting for a decision"));
519    /// let harness = HarnessAgent::builder("assistant")
520    ///     .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("ok")])))
521    ///     .workspace(adk_devtools::Workspace::new(dir.path()))
522    ///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
523    ///     .surface(surface)
524    ///     .build()?;
525    /// assert!(harness.manifest().render().contains("/approvals"));
526    /// # Ok::<(), adk_core::AdkError>(())
527    /// ```
528    pub fn surface(mut self, surface: crate::manifest::SurfaceManifest) -> Self {
529        self.surface = Some(surface);
530        self
531    }
532
533    /// A page `harness_help` returns for topic `name` (spec 3.1 §7.25), such as a page of
534    /// the harness documentation a surface ships.
535    pub fn help_page(mut self, name: impl Into<String>, text: impl Into<String>) -> Self {
536        self.help_pages.insert(name.into(), text.into());
537        self
538    }
539
540    /// Where instruction files come from (spec 3.1 §7.7).
541    pub fn project_instructions(mut self, config: InstructionsConfig) -> Self {
542        self.instructions = config;
543        self
544    }
545
546    /// Where workspace trust decisions are kept (default in memory, so a workspace starts
547    /// untrusted unless `require_trust` is off).
548    pub fn workspace_trust(mut self, store: Arc<dyn WorkspaceTrustStore>) -> Self {
549        self.trust_store = Some(store);
550        self
551    }
552
553    /// The mode of sessions with no mode record (default [`HarnessMode::Ask`]).
554    pub fn mode(mut self, mode: HarnessMode) -> Self {
555        self.mode = mode;
556        self
557    }
558
559    /// Where session modes are kept (default in memory).
560    pub fn mode_store(mut self, store: Arc<dyn ModeStore>) -> Self {
561        self.mode_store = Some(store);
562        self
563    }
564
565    /// Where standing rules are kept (default in memory).
566    pub fn standing_rules(mut self, store: Arc<dyn StandingRuleStore>) -> Self {
567        self.standing_rules = Some(store);
568        self
569    }
570
571    /// Where the shell ledger is kept (default in memory).
572    pub fn shell_ledger(mut self, ledger: Arc<dyn ShellLedger>) -> Self {
573        self.shell_ledger = Some(ledger);
574        self
575    }
576
577    /// The limits of background shells (spec 3.1 §7.29); default
578    /// [`BackgroundShellConfig::unattended`](crate::BackgroundShellConfig::unattended),
579    /// and [`attended`](crate::BackgroundShellConfig::attended) for a REPL a person watches.
580    pub fn background_shells(mut self, config: crate::shell::BackgroundShellConfig) -> Self {
581        self.background_shells = config;
582        self
583    }
584
585    /// Where each background shell's process is recorded (default in memory), so the next
586    /// start reaps what a crash left running (spec 3.1 §7.29).
587    pub fn shell_pid_registry(mut self, registry: Arc<dyn crate::shell::ShellPidRegistry>) -> Self {
588        self.shell_pids = Some(registry);
589        self
590    }
591
592    /// Runs background shells on `shells`, which every harness of a process can share, so a
593    /// harness rebuilt for the same session keeps its shells (spec 3.1 §7.29). Its limits
594    /// and pid registry replace [`background_shells`](Self::background_shells) and
595    /// [`shell_pid_registry`](Self::shell_pid_registry).
596    pub fn shell_supervisor(mut self, shells: Arc<crate::shell::ShellSupervisor>) -> Self {
597        self.shell_supervisor = Some(shells);
598        self
599    }
600
601    /// Where the file tools' read records are kept (default in memory): the sha256 each
602    /// session's agent last read or wrote per file, which `edit_file` takes as its
603    /// precondition (spec 3.1 §7.26, §10 D7). A durable store lets a held edit approved
604    /// from another process run (§7.33 fix 5).
605    pub fn read_records(mut self, records: Arc<dyn adk_devtools::ReadLedger>) -> Self {
606        self.read_records = Some(records);
607        self
608    }
609
610    /// An operator policy, composed with the harness policy; the stricter decision wins.
611    pub fn operator_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
612        self.operator_policy = Some(policy);
613        self
614    }
615
616    /// Adds `policy` to the operator policy, the stricter decision winning, so a later
617    /// [`operator_policy`](Self::operator_policy) or addition keeps it (spec 3.2 §7.7, K-I6).
618    pub fn add_operator_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {
619        self.operator_policy = Some(match self.operator_policy.take() {
620            Some(existing) => Arc::new(adk_core::StrictestPolicy::new(vec![existing, policy])),
621            None => policy,
622        });
623        self
624    }
625
626    /// Builds the harness of `partition` in `partitions`, the partition table its kernel
627    /// shares (spec 3.2 §7.8): the partition's mode as the harness mode, its class and
628    /// tenant on every agent's principal, its `memory_scope` as the project of every
629    /// long-term fact — preferences included — and of a working-notes root of its own, and
630    /// its `PartitionPolicy` composed with the operator policy, so a request reaching
631    /// another partition is denied unless the coordinator makes it, and then needs a
632    /// non-waivable approval (K-I15). The harness gets `partition_memory_search` and
633    /// `partition_memory_remember`, the crossings into other partitions' facts.
634    ///
635    /// Set the mode with this call, not before: it replaces the builder's mode.
636    ///
637    /// # Example
638    ///
639    /// ```rust,ignore
640    /// let partitions = adk_kernel::Partitions::new(store);
641    /// let work = HarnessAgent::builder("harness")
642    ///     .model(model)
643    ///     .workspace(workspace)
644    ///     .long_term_memory(LongTermMemoryConfig::default())
645    ///     .fact_store(shared_facts.clone())
646    ///     .partition(adk_kernel::Partition::new("work", "work"), partitions.clone())
647    ///     .build()?;
648    /// ```
649    #[cfg(feature = "kernel")]
650    pub fn partition(
651        mut self,
652        partition: adk_kernel::Partition,
653        partitions: adk_kernel::Partitions,
654    ) -> Self {
655        self.mode = partition.default_mode.into();
656        #[cfg(feature = "memory")]
657        {
658            self.long_term.project = Some(partition.memory_scope.clone());
659        }
660        self.partition.partition = Some((partition, partitions));
661        match self.partition.drivers.take() {
662            Some(drivers) => self.partition_drivers(&drivers),
663            None => self,
664        }
665    }
666
667    /// Stamps every session this harness runs with `target`, its kernel target, on its first
668    /// run, and refuses a session another agent stamped (spec 3.3 §5.7 "Threads"):
669    /// [`AGENT_STATE_KEY`](crate::AGENT_STATE_KEY). `adk-rust up` stamps the primary agent's
670    /// sessions `adk-rust`; an added agent stamps its own id.
671    ///
672    /// # Example
673    ///
674    /// ```rust
675    /// let builder = adk_harness::HarnessAgent::builder("adk-rust").session_stamp("adk-rust");
676    /// # let _ = builder;
677    /// ```
678    #[cfg(feature = "kernel")]
679    pub fn session_stamp(mut self, target: impl Into<String>) -> Self {
680        self.session_stamp = Some(target.into());
681        self
682    }
683
684    /// Gives this harness `propose_agent`, suggesting agents to the agent table of the kernel
685    /// `handle` is bound to (spec 3.3 §5.7, §10 H3). `adk-rust up` binds it on the primary
686    /// agent only; an added agent never has the tool. Needs feature `web`, whose screening the
687    /// suggestion's instructions pass.
688    ///
689    /// # Example
690    ///
691    /// ```rust
692    /// let handle = adk_kernel::agents::AgentsHandle::new();
693    /// let builder = adk_harness::HarnessAgent::builder("adk-rust").agents_handle(handle);
694    /// # let _ = builder;
695    /// ```
696    #[cfg(all(feature = "kernel", feature = "web"))]
697    pub fn agents_handle(mut self, handle: adk_kernel::agents::AgentsHandle) -> Self {
698        self.agent_proposer = Some(Arc::new(handle));
699        self
700    }
701
702    /// The harness of the agent a person added (spec 3.3 §5.7, H3): see
703    /// [`added_agent`](Self::added_agent).
704    #[cfg(feature = "kernel")]
705    pub(crate) fn lower_added(mut self, added: crate::agents::AddedAgent) -> Self {
706        self.name = added.id.clone();
707        self.session_stamp = Some(added.id.clone());
708        if !added.description.is_empty() {
709            self.description = Some(added.description.clone());
710        }
711        if !added.instructions.is_empty() {
712            self.instruction = Some(added.instructions.clone());
713        }
714        self.mode = added.mode_in(self.mode);
715        #[cfg(feature = "team")]
716        self.members.clear();
717        self.default_members = false;
718        self.partition.coordinator = false;
719        self.goal_store = None;
720        self.goal_grader = None;
721        #[cfg(feature = "graph")]
722        {
723            self.goal_engine = None;
724        }
725        #[cfg(feature = "web")]
726        {
727            self.agent_proposer = None;
728        }
729        let read_only = added.uses.files != adk_kernel::agents::FileAccess::ReadWrite;
730        if let Some(workspace) = self.workspace.take() {
731            let root = match &added.uses.folder {
732                Some(folder) => workspace.root().join(folder),
733                None => workspace.root().to_path_buf(),
734            };
735            self.workspace = Some(
736                Workspace::new(root)
737                    .writable(workspace.is_writable() && !read_only)
738                    .allow_bash(workspace.bash_allowed())
739                    .bash_timeout(workspace.bash_timeout_value())
740                    .max_output_bytes(workspace.max_output())
741                    .inherit_env(workspace.inherits_env()),
742            );
743        }
744        // The provider runs its own search outside the harness policy, so an agent without
745        // any site never has it (spec 3.3 §5.7). Listed sites only narrow where it fetches,
746        // through the deny layer: they are never an allowlist, so each fetch asks as its mode
747        // says (spec 3.1 I2).
748        match &added.uses.web {
749            // Provider search runs outside the deny layer, so an agent kept from
750            // `web_search` declares none (spec 3.1 §7.32).
751            adk_kernel::agents::WebAccess::None => {
752                self.web = None;
753                self.search_provider = None;
754                self.provider_web_tools = Some(crate::web::ProviderWebTools::off());
755            }
756            adk_kernel::agents::WebAccess::Listed { .. } => {
757                self.search_provider = None;
758                self.provider_web_tools = Some(crate::web::ProviderWebTools::off());
759            }
760            adk_kernel::agents::WebAccess::Any => {}
761        }
762        if added.uses.shell == adk_kernel::agents::ShellAccess::Sandboxed {
763            self.isolated_shell_only = true;
764        }
765        self.added = Some(added);
766        self
767    }
768
769    /// Makes this partition's harness the coordinator, the one agent that may reach
770    /// another partition, each crossing under a non-waivable approval (spec 3.2 §7.8, K-I15).
771    #[cfg(feature = "kernel")]
772    pub fn partition_coordinator(mut self) -> Self {
773        self.partition.coordinator = true;
774        self
775    }
776
777    /// Mounts `drivers` for this partition (spec 3.2 §7.7, §7.8), as
778    /// [`kernel_drivers`](Self::kernel_drivers) with the partition's id and its own `drivers`
779    /// list: the harness sees a driver only when its manifest lists the partition and the
780    /// partition lists its id, so a driver of another partition is invisible to it (K-I15).
781    ///
782    /// # Example
783    ///
784    /// ```rust,ignore
785    /// let work = HarnessAgent::builder("harness")
786    ///     .model(model)
787    ///     .workspace(workspace)
788    ///     .partition(adk_kernel::Partition::new("work", "work").with_driver("calendar"), partitions)
789    ///     .partition_drivers(&drivers)
790    ///     .build()?;
791    /// ```
792    ///
793    /// Call it before or after [`partition`](Self::partition); `build` fails when no
794    /// partition is set.
795    #[cfg(feature = "kernel")]
796    pub fn partition_drivers(mut self, drivers: &adk_kernel::drivers::DriverSupervisor) -> Self {
797        let Some((partition, _)) = &self.partition.partition else {
798            // Mounted once `partition` names the partition.
799            self.partition.drivers = Some(drivers.clone());
800            return self;
801        };
802        let (id, ids) = (partition.id.clone(), partition.drivers.clone());
803        self.kernel_drivers(drivers, &id, &ids)
804    }
805
806    /// Offers the coordinator `tool`, which reaches partition `to`'s `resource` named
807    /// `name` — a driver tool of that partition, or a tool reading its sessions — as the
808    /// crossing tool `<to>__<tool>` (spec 3.2 §7.8). `access` is
809    /// [`Read`](adk_kernel::CrossingAccess::Read) only for a tool that only reads, by its
810    /// effect class, never by its own hints; a read approved once holds for the rest of the
811    /// run, anything else is approved one call at a time.
812    #[cfg(feature = "kernel")]
813    pub fn partition_crossing_tool(
814        mut self,
815        tool: Arc<dyn Tool>,
816        to: impl Into<adk_kernel::PartitionId>,
817        resource: adk_kernel::CrossingResource,
818        access: adk_kernel::CrossingAccess,
819        name: impl Into<String>,
820    ) -> Self {
821        self.partition.crossings.push(crate::partition::CrossingSpec {
822            tool,
823            to: to.into(),
824            resource,
825            access,
826            name: name.into(),
827        });
828        self
829    }
830
831    /// Offers the coordinator the drivers of `partitions` as crossings (spec 3.2 §7.7, §7.8,
832    /// K-I15): each tool a target partition's own driver list serves, named `<to>__<tool>`,
833    /// read from the partition table at every listing. Every call is the coordinator's
834    /// crossing under a non-waivable approval: a read of a tool the driver's manifest
835    /// classes `read`, once approved, holds for the rest of the run, and any other class is
836    /// approved one call at a time; no standing rule and no run-wide approval answers one.
837    /// The tools are classed by their manifests under the kernel's driver policy, as
838    /// [`partition_drivers`](Self::partition_drivers) classes the partition's own.
839    ///
840    /// # Example
841    ///
842    /// ```rust,ignore
843    /// let home = HarnessAgent::builder("harness")
844    ///     .model(model)
845    ///     .workspace(workspace)
846    ///     .partition(home_partition, partitions)
847    ///     .partition_coordinator()
848    ///     .partition_drivers(&drivers)
849    ///     .partition_driver_crossings(&drivers, ["work"])
850    ///     .build()?;
851    /// ```
852    ///
853    /// `build` fails unless the harness is a partition's coordinator.
854    #[cfg(feature = "kernel")]
855    pub fn partition_driver_crossings(
856        mut self,
857        drivers: &adk_kernel::drivers::DriverSupervisor,
858        partitions: impl IntoIterator<Item = impl Into<adk_kernel::PartitionId>>,
859    ) -> Self {
860        let targets: Vec<adk_kernel::PartitionId> =
861            partitions.into_iter().map(Into::into).collect();
862        self.partition.driver_crossings = Some((drivers.clone(), targets));
863        self.tool_classes(Arc::new(crate::kernel::DriverClasses::new(drivers.clone())))
864            .add_operator_policy(drivers.policy())
865    }
866
867    /// Classes the tools of publishers `classes` knows by their approved declarations,
868    /// such as the kernel's drivers (spec 3.2 §7.7).
869    pub fn tool_classes(mut self, classes: Arc<dyn crate::policy::OriginClasses>) -> Self {
870        self.origin_classes.push(classes);
871        self
872    }
873
874    /// The members an `adk-agent` `TeamSpec` lets this harness delegate to as its
875    /// coordinator (spec 3.5 §7.19): their delegation tools, which the team adds to each run,
876    /// are classed `Delegate`, as a member of the harness's own team is, so the mode table
877    /// lets the coordinator hand work over and each member's own harness decides its calls.
878    ///
879    /// # Example
880    ///
881    /// ```rust,ignore
882    /// let steward = HarnessAgent::builder("steward")
883    ///     .website_back_office(&kit)
884    ///     .team_delegates(["growth", "revenue", "guardian", "finance"])
885    ///     .build()?;
886    /// ```
887    #[must_use]
888    pub fn team_delegates(mut self, members: impl IntoIterator<Item = impl Into<String>>) -> Self {
889        self.team_delegates.extend(members.into_iter().map(Into::into));
890        self
891    }
892
893    /// Asks a person through `prompter` on interactive surfaces.
894    pub fn prompter(mut self, prompter: Arc<dyn ApprovalPrompter>) -> Self {
895        self.prompter = Some(prompter);
896        self
897    }
898
899    /// Uses `handler` as the confirmation handler instead of the prompting one.
900    pub fn confirmation_handler(mut self, handler: Arc<dyn ToolConfirmationHandler>) -> Self {
901        self.confirmation_handler = Some(handler);
902        self
903    }
904
905    /// Where held calls and decisions are kept (default in memory).
906    pub fn approval_store(mut self, store: Arc<dyn ApprovalStore>) -> Self {
907        self.approval_store = Some(store);
908        self
909    }
910
911    /// Where `bash`, `write_file`, `edit_file` and other non-idempotent calls are recorded
912    /// before they execute, so a call re-issued after a crash, retry or resume is answered
913    /// from its record instead of running twice (spec 3.1 §7.12, §9.2 I37).
914    ///
915    /// The default keeps records in memory, which covers retries and resumes within one
916    /// process; pass a durable ledger, such as one of `adk-session`'s, on the backend the
917    /// sessions and approvals use so the guarantee survives process loss. A run that already
918    /// carries a ledger, for example from `RunnerConfigBuilder::action_ledger`, keeps storing
919    /// in it.
920    ///
921    /// # Example
922    ///
923    /// ```rust
924    /// use adk_core::InMemoryActionLedger;
925    /// use std::sync::Arc;
926    ///
927    /// let builder = adk_harness::HarnessAgent::builder("harness")
928    ///     .action_ledger(Arc::new(InMemoryActionLedger::new()));
929    /// # let _ = builder;
930    /// ```
931    pub fn action_ledger(mut self, ledger: Arc<dyn ActionLedger>) -> Self {
932        self.action_ledger = Some(ledger);
933        self
934    }
935
936    /// Puts the harness's `propose_followup` items on the agenda of the kernel `handle` is
937    /// bound to (spec 3.2 §7.5, §7.13): a kernel built without `Harness::kernel`, such as a
938    /// tenant's in the managed form (`adk_kernel::managed::TenantKernel::agenda_handle`).
939    ///
940    /// # Example
941    ///
942    /// ```rust,ignore
943    /// let agenda = adk_kernel::AgendaHandle::new();
944    /// let resolver = HarnessResolver::new("/srv/workspaces")
945    ///     .configure({ let agenda = agenda.clone(); move |b, _| b.agenda_handle(agenda.clone()) });
946    /// ```
947    #[cfg(feature = "kernel")]
948    pub fn agenda_handle(mut self, handle: adk_kernel::AgendaHandle) -> Self {
949        self.kernel_agenda = handle;
950        self
951    }
952
953    /// The approval inbox held calls are submitted to.
954    ///
955    /// With feature `kernel`, the harness keeps a wrapper that also reports each request
956    /// reaching its outcome to the kernel `Harness::kernel` builds (spec 3.2 §7.4).
957    pub fn approval_service(mut self, service: Arc<dyn ApprovalService>) -> Self {
958        #[cfg(feature = "kernel")]
959        let service = crate::kernel::NotifyingApprovals::wrap(service, &self.kernel_approvals);
960        self.approval_service = Some(service);
961        self
962    }
963
964    /// Checks each requested call (one a person asked for through a form an agent drew)
965    /// against the seal made when the person approved it, right before it runs: a call that
966    /// changed since is refused (spec 3.3 §7.4 rule 5). `adk-surface`'s `ApprovalSeals` makes
967    /// and checks them; give it to the surface engine too.
968    pub fn requested_call_seal(mut self, seal: Arc<dyn adk_core::RequestedCallSeal>) -> Self {
969        self.requested_call_seal = Some(seal);
970        self
971    }
972
973    /// Reviews, in Auto mode, the calls the mode holds with `reviewer` before a person is
974    /// asked: it approves, denies, or escalates each one (autonomy parity item 2). Off by
975    /// default.
976    ///
977    /// It decides only a call the harness holds in Auto mode that a standing rule could
978    /// answer: a host `bash` command or an external tool. Everything Auto denies, and every
979    /// non-waivable approval — an edit of a protected path, an unsandboxed retry,
980    /// `exit_plan_mode`, memory writes, payments, computer use and partition crossings — goes
981    /// to a person as before, and so does every call in `read_only`, `plan` and `ask`. A
982    /// served harness without authenticated identity decides Auto as Ask, so its calls are
983    /// never reviewed. An escalated call is prompted or held as it would be without a
984    /// reviewer. See `adk_core::review` for the verdicts and their records.
985    ///
986    /// # Example
987    ///
988    /// ```rust
989    /// use std::sync::Arc;
990    /// use adk_core::{ModelApprover, ReviewScope};
991    /// use adk_harness::{HarnessAgent, HarnessMode};
992    /// use adk_model::{ScriptedLlm, ScriptedResponse};
993    ///
994    /// let responses: Vec<ScriptedResponse> = Vec::new();
995    /// let reviewer = Arc::new(ScriptedLlm::new("claude-haiku-5-5", responses));
996    /// let builder = HarnessAgent::builder("harness")
997    ///     .mode(HarnessMode::Auto)
998    ///     .auto_review(Arc::new(
999    ///         ModelApprover::new(reviewer).scope(ReviewScope::default().excluding_tools(["mcp_*"])),
1000    ///     ));
1001    /// # let _ = builder;
1002    /// ```
1003    pub fn auto_review(mut self, reviewer: Arc<dyn adk_core::ToolReviewer>) -> Self {
1004        self.auto_review = Some(reviewer);
1005        self
1006    }
1007
1008    /// How long a person may take to decide one call (default 300 s); a call nobody decides
1009    /// in time waits in the approval store for a later decision (spec 3.3 §7.3).
1010    pub fn confirmation_timeout(mut self, timeout: Duration) -> Self {
1011        self.confirmation_timeout = timeout;
1012        self
1013    }
1014
1015    /// Where `bash` runs (default host, spec 3.1 §7.9).
1016    ///
1017    /// Unless [`allow_unsandboxed_retry`](Self::allow_unsandboxed_retry) was called, the
1018    /// unsandboxed retry is on for the host and the OS sandbox and off for a container and
1019    /// a remote sandbox.
1020    pub fn shell(mut self, isolation: ShellIsolation) -> Self {
1021        #[cfg(any(feature = "docker", feature = "remote-shell"))]
1022        let pooled = match &isolation {
1023            #[cfg(feature = "docker")]
1024            ShellIsolation::Container(_) => true,
1025            #[cfg(feature = "remote-shell")]
1026            ShellIsolation::Remote(_) => true,
1027            _ => false,
1028        };
1029        #[cfg(not(any(feature = "docker", feature = "remote-shell")))]
1030        let pooled = false;
1031        if !self.retry_explicit {
1032            self.shell.allow_unsandboxed_retry = !pooled;
1033        }
1034        self.shell.isolation = isolation;
1035        self
1036    }
1037
1038    /// Fails the build, and each call, when the requested sandbox is unavailable.
1039    pub fn fail_if_unavailable(mut self) -> Self {
1040        self.shell.fail_if_unavailable = true;
1041        self
1042    }
1043
1044    /// Applies `.adk/harness.toml` (spec 3.1 §8.3), read with [`HarnessConfig::discover`].
1045    ///
1046    /// The file may only tighten (spec 3.1 §9.2 I3): its mode applies when it is stricter
1047    /// than the mode set so far, `sandbox = true` runs `bash` in the OS sandbox, and
1048    /// `fail_if_unavailable = true` refuses a build without it. What the file asked for and
1049    /// the harness ignored is logged as a warning.
1050    ///
1051    /// # Example
1052    ///
1053    /// ```rust
1054    /// use adk_harness::{HarnessAgent, HarnessConfig, HarnessMode, InstructionsConfig};
1055    /// use adk_model::{ScriptedLlm, ScriptedResponse};
1056    /// use std::sync::Arc;
1057    ///
1058    /// let dir = tempfile::tempdir().unwrap();
1059    /// let config = HarnessConfig::from_toml("mode = \"plan\"")?;
1060    /// let harness = HarnessAgent::builder("harness")
1061    ///     .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("done")])))
1062    ///     .workspace(adk_devtools::Workspace::new(dir.path()))
1063    ///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
1064    ///     .config(config)
1065    ///     .build()?;
1066    /// assert_eq!(harness.info().default_mode, HarnessMode::Plan);
1067    /// # Ok::<(), adk_core::AdkError>(())
1068    /// ```
1069    ///
1070    /// [`HarnessConfig::discover`]: crate::HarnessConfig::discover
1071    pub fn config(mut self, config: crate::config::HarnessConfig) -> Self {
1072        if let Some(mode) = config.mode {
1073            if mode.is_stricter_than(self.mode) {
1074                self.mode = mode;
1075            } else if mode != self.mode {
1076                tracing::warn!(
1077                    config.mode = %mode,
1078                    harness.mode = %self.mode,
1079                    "harness.toml mode ignored: it is looser than the harness's, and workspace files may only tighten"
1080                );
1081            }
1082        }
1083        if config.sandbox {
1084            #[cfg(feature = "sandbox")]
1085            if matches!(self.shell.isolation, ShellIsolation::Host) {
1086                self.shell.isolation = ShellIsolation::OsSandbox(Default::default());
1087            }
1088            #[cfg(not(feature = "sandbox"))]
1089            self.unimplemented.push(format!(
1090                "the OS sandbox {} asks for: build adk-harness with feature `sandbox` (spec 3.1 §9.2 I24)",
1091                crate::config::HARNESS_CONFIG_FILE
1092            ));
1093        }
1094        // The allowlist narrows whatever the code set; the sandbox it needs was turned on
1095        // above, since the file sets `sandbox` with it.
1096        #[cfg(feature = "sandbox")]
1097        if let (Some(allow), ShellIsolation::OsSandbox(sandbox)) =
1098            (&config.network_allow, &mut self.shell.isolation)
1099        {
1100            sandbox.egress = Some(match sandbox.egress.take() {
1101                Some(own) => own.narrow(allow),
1102                None => allow.clone(),
1103            });
1104        }
1105        if config.fail_if_unavailable {
1106            self.shell.fail_if_unavailable = true;
1107        }
1108        for note in &config.notes {
1109            tracing::warn!(note = %note, "harness.toml setting ignored");
1110        }
1111        self
1112    }
1113
1114    /// Runs sandboxed commands without approval in Ask (spec 3.1 §7.9, §9.2 I26).
1115    ///
1116    /// Turns on only under an active OS sandbox whose enforcer keeps protected paths
1117    /// read-only (adk-sandbox S3, checked by a conformance probe) or a container shell that
1118    /// mounts them read-only, with the network denied. Seatbelt also keeps a root-level
1119    /// protected path that does not exist or is a symbolic link from being created or
1120    /// replaced; under bubblewrap and in a container every one must exist and none be a link.
1121    /// Otherwise `build()` fails with `harness.auto_allow_sandboxed_unavailable` naming the
1122    /// reason. No effect on the host or a degraded shell.
1123    pub fn auto_allow_sandboxed(mut self) -> Self {
1124        self.shell.auto_allow_sandboxed = true;
1125        self
1126    }
1127
1128    /// Offers an unsandboxed retry of a failed sandboxed command (default on for the host
1129    /// and the OS sandbox, off for a container).
1130    pub fn allow_unsandboxed_retry(mut self, yes: bool) -> Self {
1131        self.shell.allow_unsandboxed_retry = yes;
1132        self.retry_explicit = true;
1133        self
1134    }
1135
1136    /// Runs host commands without approval in Auto.
1137    pub fn allow_host_shell_in_auto(mut self) -> Self {
1138        self.shell.allow_host_shell_in_auto = true;
1139        self
1140    }
1141
1142    /// Leaves `bash` out.
1143    pub fn without_shell(mut self) -> Self {
1144        self.shell_enabled = false;
1145        self
1146    }
1147
1148    /// Applies `preset` (spec 3.1 §7.19, spec 3.3 §10 H1): its prompt, mode, members and
1149    /// shell, replacing what an earlier preset set. Calls after it override what it sets,
1150    /// except the personal preset's shell: no later call gives it a host shell or an
1151    /// unsandboxed retry on the host.
1152    ///
1153    /// # Example
1154    ///
1155    /// ```rust
1156    /// use adk_harness::{HarnessAgent, InstructionsConfig, Preset};
1157    /// use adk_model::{ScriptedLlm, ScriptedResponse};
1158    /// use std::sync::Arc;
1159    ///
1160    /// let dir = tempfile::tempdir().unwrap();
1161    /// let harness = HarnessAgent::builder("assistant")
1162    ///     .preset(Preset::Personal)
1163    ///     .model(Arc::new(ScriptedLlm::new("scripted", vec![ScriptedResponse::text("ok")])))
1164    ///     .workspace(adk_devtools::Workspace::new(dir.path()).allow_bash(true))
1165    ///     .project_instructions(InstructionsConfig { user_file: None, ..InstructionsConfig::default() })
1166    ///     .build()?;
1167    /// assert!(harness.info().members.is_empty());
1168    /// assert!(!harness.info().tools.contains(&"bash".to_string()), "no host shell");
1169    /// # Ok::<(), adk_core::AdkError>(())
1170    /// ```
1171    pub fn preset(self, preset: crate::Preset) -> Self {
1172        preset.apply(self)
1173    }
1174
1175    /// Offers `bash` only when it runs in the OS sandbox or a container, with no unsandboxed
1176    /// retry (spec 3.3 §10 H1).
1177    pub(crate) fn isolated_shell_only(mut self, yes: bool) -> Self {
1178        self.isolated_shell_only = yes;
1179        self
1180    }
1181
1182    /// Leaves `bash` out for as long as the preset that asked holds (spec 3.5 §10 X10).
1183    #[cfg(feature = "website")]
1184    pub(crate) fn preset_without_shell(mut self) -> Self {
1185        self.preset_without_shell = true;
1186        self
1187    }
1188
1189    /// The website preset's mode banner and no `exit_plan_mode`, for as long as the preset
1190    /// holds (spec 3.5 §7.11, A-I13).
1191    #[cfg(feature = "website")]
1192    pub(crate) fn website_preset(mut self) -> Self {
1193        self.website_preset = true;
1194        self
1195    }
1196
1197    /// Offers the agent no tool of the harness's own beyond `tools`: no workspace, memory,
1198    /// plan or web tool, and no harness toolset (spec 3.5 A-I2).
1199    #[cfg(feature = "website")]
1200    pub(crate) fn public_only(mut self, tools: BTreeSet<String>) -> Self {
1201        self.public_only = Some(tools);
1202        self
1203    }
1204
1205    /// Undoes what a preset set that another preset leaves alone (spec 3.3 §10 H1).
1206    pub(crate) fn clear_preset(mut self) -> Self {
1207        if self.description.as_deref() == Some(crate::personal::PERSONAL_DESCRIPTION) {
1208            self.description = None;
1209        }
1210        #[cfg(feature = "website")]
1211        if self.description.as_deref() == Some(crate::website::WEBSITE_DESCRIPTION) {
1212            self.description = None;
1213        }
1214        self.preset_without_shell = false;
1215        self.website_preset = false;
1216        self.isolated_shell_only(false)
1217    }
1218
1219    /// Trusts an MCP server's `readOnlyHint` for the External class (default `false`).
1220    pub fn trust_mcp_read_only_hints(mut self, yes: bool) -> Self {
1221        self.trust_mcp_read_only_hints = yes;
1222        self
1223    }
1224
1225    /// Leaves `write_todos` and `update_todo` out.
1226    pub fn without_todos(mut self) -> Self {
1227        self.todos = false;
1228        self
1229    }
1230
1231    /// Skills configuration (spec 3.1 §7.8).
1232    #[cfg(feature = "skills")]
1233    pub fn skills(mut self, config: crate::skills::SkillsConfig) -> Self {
1234        self.skills = config;
1235        self
1236    }
1237
1238    /// Adds a team member (spec 3.1 §7.10). A member named like a default member
1239    /// replaces it.
1240    #[cfg(feature = "team")]
1241    pub fn member(mut self, spec: crate::team::MemberSpec) -> Self {
1242        self.members.push(spec);
1243        self
1244    }
1245
1246    /// Discovers members in `registry` (spec 3.1 §7.10): every candidate no other member
1247    /// names becomes a member, resolved and authorized by the registry when the harness is
1248    /// built.
1249    #[cfg(feature = "team")]
1250    pub fn member_registry(mut self, registry: Arc<dyn adk_agent::TeamAgentRegistry>) -> Self {
1251        self.member_registry = Some(registry);
1252        self
1253    }
1254
1255    /// The team policy (spec 3.1 §7.10): its budget, termination, failure policy and
1256    /// concurrency apply; the context is always isolated and the delegation depth 1
1257    /// ([`harness_team_policy`](crate::harness_team_policy)).
1258    #[cfg(feature = "team")]
1259    pub fn team_policy(mut self, policy: adk_agent::TeamPolicy) -> Self {
1260        self.team_policy = Some(policy);
1261        self
1262    }
1263
1264    /// Leaves out the default members (`explore` and `general`).
1265    pub fn without_default_members(mut self) -> Self {
1266        self.default_members = false;
1267        self
1268    }
1269
1270    /// The model of members without their own (model tiering).
1271    pub fn member_model(mut self, model: Arc<dyn Llm>) -> Self {
1272        self.member_model = Some(model);
1273        self
1274    }
1275
1276    /// The goal engine (spec 3.1 §7.11): `Loop` by default, `Graph` by default when a
1277    /// plan checkpointer is configured.
1278    #[cfg(feature = "graph")]
1279    pub fn goal_engine(mut self, engine: crate::goal::GoalEngine) -> Self {
1280        self.goal_engine = Some(engine);
1281        self
1282    }
1283
1284    /// Where session goals are kept (spec 3.1 §7.11; default in memory).
1285    pub fn goal_store(mut self, store: Arc<dyn crate::goal::GoalStore>) -> Self {
1286        self.goal_store = Some(store);
1287        self
1288    }
1289
1290    /// The model that grades goals with a [`GoalRubric`](crate::GoalRubric); the harness
1291    /// model by default. The grader works in a context of its own and its calls count
1292    /// against the run's budget and spend ledger.
1293    ///
1294    /// # Example
1295    ///
1296    /// ```rust,ignore
1297    /// let builder = adk_harness::HarnessAgent::builder("harness")
1298    ///     .model(worker_model)
1299    ///     .goal_grader(grader_model);
1300    /// ```
1301    pub fn goal_grader(mut self, model: Arc<dyn Llm>) -> Self {
1302        self.goal_grader = Some(model);
1303        self
1304    }
1305
1306    /// Compiles approved plans with steps to a plan graph (spec 3.1 §7.11; default on with
1307    /// `graph`). Off, or without `graph`, steps are stored with the plan only.
1308    pub fn plan_graph(mut self, yes: bool) -> Self {
1309        self.plan_graph = yes;
1310        self
1311    }
1312
1313    /// Snapshots the workspace before each user turn, plan step and rewind, so
1314    /// `Harness::rewind` can restore files, transcript and plan (spec 3.1 §7.27; off until
1315    /// set, on in adk-cli). Records and objects stay in memory unless
1316    /// [`snapshot_store`](Self::snapshot_store) and [`snapshot_objects`](Self::snapshot_objects)
1317    /// say otherwise.
1318    ///
1319    /// # Example
1320    ///
1321    /// ```rust,ignore
1322    /// let agent = HarnessAgent::builder("harness")
1323    ///     .model(model)
1324    ///     .workspace(workspace)
1325    ///     .snapshots(adk_harness::SnapshotConfig::default())
1326    ///     .build()?;
1327    /// ```
1328    pub fn snapshots(mut self, config: crate::snapshot::SnapshotConfig) -> Self {
1329        self.snapshots.config = Some(config);
1330        self
1331    }
1332
1333    /// Where snapshot records are kept, such as `SqliteSnapshotStore` in `harness.db`.
1334    pub fn snapshot_store(mut self, store: Arc<dyn crate::snapshot::SnapshotStore>) -> Self {
1335        self.snapshots.store = Some(store);
1336        self
1337    }
1338
1339    /// Where snapshot contents are kept, such as `FileSnapshotObjects::for_workspace` beside
1340    /// `harness.db`; never inside the workspace (I68).
1341    pub fn snapshot_objects(mut self, objects: Arc<dyn crate::snapshot::SnapshotObjects>) -> Self {
1342        self.snapshots.objects = Some(objects);
1343        self
1344    }
1345
1346    /// File memory (spec 3.1 §7.15; off until set): adds `memory_read`, `memory_write`
1347    /// and `memory_delete`, and the memory index at the end of the instruction.
1348    #[cfg(feature = "memory")]
1349    pub fn memory(mut self, config: crate::memory::MemoryConfig) -> Self {
1350        self.memory = Some(config);
1351        self
1352    }
1353
1354    /// Where plan graphs and the `Graph` goal engine are checkpointed (spec 3.1 §7.11,
1355    /// §13 Q5). Without this or [`plan_checkpoint_store`](Self::plan_checkpoint_store),
1356    /// plans live in memory and do not survive a restart; `adk-rust` checkpoints them in
1357    /// the backend that holds its sessions.
1358    #[cfg(feature = "graph")]
1359    pub fn plan_checkpointer(mut self, checkpointer: Arc<dyn adk_graph::Checkpointer>) -> Self {
1360        self.plan_checkpointer = Some(checkpointer);
1361        self
1362    }
1363
1364    /// Checkpoints plan graphs and the `Graph` goal engine in the store `url` names
1365    /// (spec 3.1 §7.11, §13 Q5): `sqlite://`, `postgres://`, `redis://`, `mongodb://`,
1366    /// `neo4j://` or `firestore://`, opened by [`checkpointer_from_url`](crate::checkpointer_from_url).
1367    ///
1368    /// # Example
1369    ///
1370    /// ```rust,no_run
1371    /// # async fn example(model: std::sync::Arc<dyn adk_core::Llm>) -> adk_core::Result<()> {
1372    /// let agent = adk_harness::HarnessAgent::builder("harness")
1373    ///     .model(model)
1374    ///     .plan_checkpoint_store("postgres://harness@db/harness")
1375    ///     .await?
1376    ///     .build()?;
1377    /// # let _ = agent;
1378    /// # Ok(())
1379    /// # }
1380    /// ```
1381    ///
1382    /// # Errors
1383    ///
1384    /// Returns the errors of [`checkpointer_from_url`](crate::checkpointer_from_url): an
1385    /// unknown scheme, a scheme whose feature this build does not include, or a backend
1386    /// that cannot be opened.
1387    #[cfg(feature = "graph")]
1388    pub async fn plan_checkpoint_store(self, url: &str) -> Result<Self> {
1389        Ok(self.plan_checkpointer(crate::checkpoint::checkpointer_from_url(url).await?))
1390    }
1391
1392    /// Long-term facts (spec 3.1 §7.15.2; off until set): recall into each user turn,
1393    /// `memory_search` and `memory_remember`, and session distillation.
1394    #[cfg(feature = "memory")]
1395    pub fn long_term_memory(mut self, config: crate::facts::LongTermMemoryConfig) -> Self {
1396        self.long_term.config = Some(config);
1397        self
1398    }
1399
1400    /// Where long-term facts are kept (default in memory; SQLite in the CLI). Needs
1401    /// [`long_term_memory`](Self::long_term_memory).
1402    #[cfg(feature = "memory")]
1403    pub fn fact_store(mut self, store: Arc<dyn crate::facts::FactStore>) -> Self {
1404        self.long_term.store = Some(store);
1405        self
1406    }
1407
1408    /// How recall finds candidate facts (default a [`LocalFactIndex`](crate::LocalFactIndex)
1409    /// over the fact store; a [`MemoryServiceIndex`](crate::MemoryServiceIndex) on servers).
1410    /// Needs [`long_term_memory`](Self::long_term_memory).
1411    #[cfg(feature = "memory")]
1412    pub fn fact_index(mut self, index: Arc<dyn crate::facts::FactIndex>) -> Self {
1413        self.long_term.index = Some(index);
1414        self
1415    }
1416
1417    /// Embeds facts for the default [`LocalFactIndex`](crate::LocalFactIndex), which then
1418    /// recalls by cosine similarity instead of shared words (spec 3.1 §7.15.2). Needs
1419    /// [`long_term_memory`](Self::long_term_memory).
1420    #[cfg(feature = "memory")]
1421    pub fn memory_embedder(mut self, embedder: Arc<dyn adk_memory::EmbeddingProvider>) -> Self {
1422        self.long_term.embedder = Some(embedder);
1423        self
1424    }
1425
1426    /// Resource limits for every run.
1427    pub fn budget(mut self, budget: RunBudget) -> Self {
1428        self.budget = Some(budget);
1429        self
1430    }
1431
1432    /// The ledger model calls reserve budget against.
1433    pub fn spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
1434        self.spend_ledger = Some(ledger);
1435        self
1436    }
1437
1438    /// Where every run's audit records go, in Block mode (spec 3.1 §7.14, §9.3). A
1439    /// runner's own `audit_log` takes precedence. With feature `auth` the default is an
1440    /// [`EphemeralAuditLog`](crate::EphemeralAuditLog); without it, runs record only to
1441    /// the trail the runner sets.
1442    pub fn audit_log(mut self, recorder: Arc<dyn adk_core::audit_log::AuditRecorder>) -> Self {
1443        self.audit_log = Some(recorder);
1444        self
1445    }
1446
1447    /// Mints short-lived tokens for the subject a run acts for through `broker`, and hands
1448    /// them to `bash` for one call through a credential helper (spec 3.1 §7.14). The
1449    /// resources come from [`shell_credential`](Self::shell_credential), or else from the
1450    /// workspace's HTTPS git remotes.
1451    #[cfg(feature = "auth")]
1452    pub fn credentials(mut self, broker: Arc<dyn adk_core::CredentialBroker>) -> Self {
1453        self.identity.broker = Some(broker);
1454        self
1455    }
1456
1457    /// Adds a resource the credential helper serves a token for (spec 3.1 §7.14).
1458    #[cfg(feature = "auth")]
1459    pub fn shell_credential(mut self, credential: crate::identity::ShellCredential) -> Self {
1460        self.identity.shell_credentials.push(credential);
1461        self
1462    }
1463
1464    /// Requires a permission per tool class, checked when the tool executes
1465    /// (spec 3.1 §7.14).
1466    #[cfg(feature = "auth")]
1467    pub fn rbac(mut self, map: crate::identity::RbacMap) -> Self {
1468        self.identity.rbac = Some(map);
1469        self
1470    }
1471
1472    /// Serves the harness to users the server authenticates: standing rules and Auto apply
1473    /// only to a run whose user was authenticated (`ReadonlyContext::is_authenticated`);
1474    /// any other run is decided as in Ask with no standing rule (spec 3.1 §9.2 I6).
1475    #[cfg(feature = "auth")]
1476    pub fn require_authenticated_identity(mut self) -> Self {
1477        self.identity.require_authenticated = true;
1478        self
1479    }
1480
1481    /// Loop detection (spec 3.1 §7.13; off until set): before each model request the guard
1482    /// checks the invocation's tool calls, and a loop tightens the session to `ReadOnly` and
1483    /// ends the turn.
1484    #[cfg(feature = "observe")]
1485    pub fn loop_guard(mut self, guard: LoopGuard) -> Self {
1486        self.loop_guard = Some(guard);
1487        self
1488    }
1489
1490    /// Adds a pack (spec 3.1 §7.16–§7.18, §7.24). `Pack::Payments` needs the services
1491    /// `pack_payments` carries, so on its own it fails at `build`; `Pack::Managed` marks the
1492    /// harness for the managed runtime (`info().packs` and the prompt name `managed`;
1493    /// `packs::managed::HarnessResolver` serves it) and fails at `build` without feature
1494    /// `managed`; `Pack::Browser` installs the browser pack over `BrowserConfig::default()`
1495    /// (Chrome, headless, WebDriver at `localhost:4444`) and fails at `build` without feature
1496    /// `browser`; `Pack::ComputerUse` needs the runtime `pack_computer_use` carries, so on its
1497    /// own it fails at `build`; `Pack::Voice` marks the harness for the voice surface
1498    /// (`packs::voice::VoiceSurface` runs it, spec 3.1 §7.17) and fails at `build` without
1499    /// feature `voice`.
1500    pub fn pack(mut self, pack: Pack) -> Self {
1501        match pack {
1502            Pack::Payments => self.payments_requested = true,
1503            Pack::Managed => self.managed_requested = true,
1504            Pack::Browser => self.browser_requested = true,
1505            Pack::ComputerUse => self.computer_use_requested = true,
1506            Pack::Voice => self.voice_requested = true,
1507        }
1508        self
1509    }
1510
1511    /// The payments pack (spec 3.1 §7.16, feature `payments`): the `adk-payments` tools as
1512    /// class `Payment` — denied in ReadOnly and Plan, held for a non-waivable approval in
1513    /// Ask and Auto, never covered by a standing rule — under the run budget, the mandate's
1514    /// guardrails and the spend ledger, with the journal receipt linked from
1515    /// `harness.payment`. Every model request names the mandate and the remaining budget.
1516    ///
1517    /// # Example
1518    ///
1519    /// ```rust,ignore
1520    /// let harness = HarnessAgent::builder("harness")
1521    ///     .model(model)
1522    ///     .workspace(workspace)
1523    ///     .pack_payments(PaymentsPack::new(merchant.clone(), merchant, mandate))
1524    ///     .build()?;
1525    /// ```
1526    #[cfg(feature = "payments")]
1527    pub fn pack_payments(mut self, pack: crate::packs::payments::PaymentsPack) -> Self {
1528        self.payments = Some(pack);
1529        self.payments_requested = true;
1530        self
1531    }
1532
1533    /// The browser pack (spec 3.1 §7.24, feature `browser`): `adk-browser`'s tools under the
1534    /// harness policy — observation as `Read`, navigation as `Web` decided by the URL's host
1535    /// under the harness's `WebConfig::allowed_domains`, actions as `External` held for
1536    /// approval in Ask and Auto and denied in ReadOnly and Plan — with the §7.20 URL checks
1537    /// before the browser moves and every result screened and delivered as untrusted text.
1538    ///
1539    /// # Example
1540    ///
1541    /// ```rust,ignore
1542    /// let harness = HarnessAgent::builder("harness")
1543    ///     .model(model)
1544    ///     .workspace(workspace)
1545    ///     .web(WebConfig { allowed_domains: vec!["docs.rs".into()], ..WebConfig::default() })
1546    ///     .pack_browser(BrowserPack::new(session))
1547    ///     .build()?;
1548    /// ```
1549    #[cfg(feature = "browser")]
1550    pub fn pack_browser(mut self, pack: crate::packs::browser::BrowserPack) -> Self {
1551        self.browser = Some(pack);
1552        self.browser_requested = true;
1553        self
1554    }
1555
1556    /// The vision pack (spec 3.7 X15, feature `vision`): the governed vision tools, the
1557    /// egress rules of `.adk/vision.toml` and the privacy guardrail on the harness model.
1558    /// A call that stays on the device is `Read`; one that sends an image off it is
1559    /// `External`, held in Ask and Auto with the exact egress image as evidence unless an
1560    /// `allow` rule covers its host and data class.
1561    ///
1562    /// # Example
1563    ///
1564    /// ```rust,ignore
1565    /// use adk_harness::packs::vision::VisionPack;
1566    ///
1567    /// let harness = HarnessAgent::builder("desk")
1568    ///     .model(model)
1569    ///     .workspace(workspace)
1570    ///     .pack_vision(VisionPack::new(store, |gate, store| runtime(gate, store)))
1571    ///     .build()?;
1572    /// ```
1573    #[cfg(feature = "vision")]
1574    pub fn pack_vision(mut self, pack: crate::packs::vision::VisionPack) -> Self {
1575        self.vision = Some(pack);
1576        self
1577    }
1578
1579    /// The computer-use pack (spec 3.1 §7.24, feature `computer-use`): `computer_use_observe`
1580    /// and `computer_use_preview` as `Read`, and `computer_use_execute` as class
1581    /// `ComputerUse` — denied in ReadOnly and Plan, held for a non-waivable one-shot approval
1582    /// bound to the runtime's action and policy digests in Ask and Auto — through
1583    /// adk-computer-use's reference graph, whose approval interrupt the harness approval
1584    /// answers.
1585    ///
1586    /// # Example
1587    ///
1588    /// ```rust,ignore
1589    /// let harness = HarnessAgent::builder("harness")
1590    ///     .model(model)
1591    ///     .workspace(workspace)
1592    ///     .pack_computer_use(ComputerUsePack::new(runtime, authorizer))
1593    ///     .build()?;
1594    /// ```
1595    #[cfg(feature = "computer-use")]
1596    pub fn pack_computer_use(mut self, pack: crate::packs::computer_use::ComputerUsePack) -> Self {
1597        self.computer_use = Some(pack);
1598        self.computer_use_requested = true;
1599        self
1600    }
1601
1602    /// Lets the harness's tool calls ask the person for a secret through `take_over`
1603    /// (spec 3.3 §8.2, §10 H2): the request reaches surfaces through the approval inbox, the
1604    /// typed value reaches the asking call only, and every occurrence of it in any call's
1605    /// result or error is replaced by
1606    /// [`TAKE_OVER_PLACEHOLDER`](crate::take_over::TAKE_OVER_PLACEHOLDER). Asking needs an
1607    /// [`approval_service`](Self::approval_service); the wait ends at the
1608    /// [`confirmation_timeout`](Self::confirmation_timeout), or shortly before the call's
1609    /// [`tool_timeout`](Self::tool_timeout) when that comes first. The shell never takes
1610    /// over, so passing `take_over` to [`credentials`](Self::credentials) gives `bash` no
1611    /// token.
1612    ///
1613    /// # Example
1614    ///
1615    /// ```rust,ignore
1616    /// let take_over = TakeOver::new();
1617    /// let harness = HarnessAgent::builder("assistant")
1618    ///     .model(model)
1619    ///     .workspace(workspace)
1620    ///     .tool(Arc::new(SignIn { take_over: take_over.clone() }))
1621    ///     .approval_service(inbox)
1622    ///     .take_over(take_over)
1623    ///     .build()?;
1624    /// ```
1625    pub fn take_over(mut self, take_over: crate::take_over::TakeOver) -> Self {
1626        self.take_over = Some(take_over);
1627        self
1628    }
1629
1630    /// Adds a tool, governed as `External`.
1631    pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
1632        self.tools.push(tool);
1633        self
1634    }
1635
1636    /// Adds a toolset, whose tools are governed as `External`.
1637    pub fn toolset(mut self, toolset: Arc<dyn Toolset>) -> Self {
1638        self.toolsets.push(toolset);
1639        self
1640    }
1641
1642    /// Most model turns per run (default 100).
1643    pub fn max_iterations(mut self, n: u32) -> Self {
1644        self.max_iterations = n;
1645        self
1646    }
1647
1648    /// Tool timeout (default 300 s).
1649    pub fn tool_timeout(mut self, timeout: Duration) -> Self {
1650        self.tool_timeout = timeout;
1651        self
1652    }
1653
1654    /// Most recent events loaded per run.
1655    pub fn history_max_events(mut self, n: usize) -> Self {
1656        self.history_max_events = Some(n);
1657        self
1658    }
1659
1660    /// Events compaction for the harness's runner (default interval 10, overlap 4,
1661    /// summarized by the harness model).
1662    pub fn compaction(mut self, config: EventsCompactionConfig) -> Self {
1663        self.compaction = Some(config);
1664        self.compaction_enabled = true;
1665        self
1666    }
1667
1668    /// Turns events compaction off.
1669    pub fn without_compaction(mut self) -> Self {
1670        self.compaction_enabled = false;
1671        self
1672    }
1673
1674    /// When a run compacts the harness agent's history before a model call.
1675    ///
1676    /// Auto-compaction is on without this call: a request is compacted once it passes 80% of
1677    /// the model's context window, or 100,000 estimated tokens when the model reports none,
1678    /// and the summary is written by the harness model. Each run carries the setting in its
1679    /// config, so it applies under any runner.
1680    ///
1681    /// # Example
1682    ///
1683    /// ```rust,ignore
1684    /// use adk_core::IntraCompactionConfig;
1685    ///
1686    /// let builder = HarnessAgent::builder(model).intra_compaction(IntraCompactionConfig::at_window_fraction(0.6));
1687    /// ```
1688    pub fn intra_compaction(mut self, config: adk_core::IntraCompactionConfig) -> Self {
1689        self.intra_compaction = Some(config);
1690        self
1691    }
1692
1693    /// Turns auto-compaction off for the harness's runs.
1694    pub fn without_intra_compaction(mut self) -> Self {
1695        self.intra_compaction = Some(adk_core::IntraCompactionConfig::disabled());
1696        self
1697    }
1698
1699    /// The reasoning effort of each mode and model role (spec 3.1 §7.23); the defaults
1700    /// are the spec's table (plan high, members low).
1701    ///
1702    /// The policy applies per model call (§10 C4): each request of the harness model carries
1703    /// the level of the mode it reads, a member's request `members`, the distiller's
1704    /// `distiller` and an MCP sampling request `sampling`, as `GenerateContentConfig::effort`,
1705    /// which each `adk-model` provider maps to its own control. A mode switch changes the
1706    /// next call's effort without rebuilding a client.
1707    ///
1708    /// # Example
1709    ///
1710    /// ```rust
1711    /// use adk_harness::{Effort, EffortPolicy, HarnessAgent};
1712    ///
1713    /// let builder = HarnessAgent::builder("coder")
1714    ///     .effort(EffortPolicy { plan: Effort::High, ask: Effort::Low, ..EffortPolicy::default() });
1715    /// # let _ = builder;
1716    /// ```
1717    pub fn effort(mut self, policy: crate::posture::EffortPolicy) -> Self {
1718        self.effort = policy;
1719        self
1720    }
1721
1722    /// A model that caches its context explicitly (a `GeminiModel`): the runner gets it
1723    /// with `ContextCacheConfig::default()` (4,096 tokens, 600 s, 3 intervals) so the
1724    /// prompt prefix is cached (spec 3.1 §7.23).
1725    pub fn cache_capable(mut self, model: Arc<dyn adk_core::CacheCapable>) -> Self {
1726        self.cache_capable = Some(model);
1727        self
1728    }
1729
1730    /// Turns explicit context caching off: the runner gets no cache even with
1731    /// [`cache_capable`](Self::cache_capable) (spec 3.1 §7.23).
1732    pub fn without_context_caching(mut self) -> Self {
1733        self.context_caching = false;
1734        self
1735    }
1736
1737    /// Edits the underlying `LlmAgentBuilder` before it is built.
1738    ///
1739    /// This is the escape hatch, with two caveats: a `before_tool_callback` or an enhanced
1740    /// plugin added here can answer a call before authorization, skipping the policy,
1741    /// guardrails and confirmation; and `require_tool_confirmation*` forces a confirmation
1742    /// even when the policy allows the call, which defeats standing rules.
1743    pub fn customize_llm(
1744        mut self,
1745        f: impl FnOnce(LlmAgentBuilder) -> LlmAgentBuilder + Send + 'static,
1746    ) -> Self {
1747        self.customize = Some(Box::new(f));
1748        self
1749    }
1750
1751    /// The hooks the operator and the user configured (spec 3.1 §7.22). The workspace's
1752    /// `.adk/harness.toml` hooks are added at build, after these, and run only under the
1753    /// workspace's content-keyed trust. Hooks observe tool events through the shell's
1754    /// launcher; they can deny, fail or annotate and never allow (spec 3.1 §9.2 I53).
1755    ///
1756    /// # Example
1757    ///
1758    /// ```rust,ignore
1759    /// use adk_harness::hooks::{HookEvent, HookSet, HookSpec};
1760    ///
1761    /// let hooks = HookSet::new()
1762    ///     .with(HookSpec::new(HookEvent::PostEdit, "cargo fmt").matching("write_*"));
1763    /// let harness = HarnessAgent::builder("harness").model(model).workspace(ws).hooks(hooks).build()?;
1764    /// ```
1765    #[cfg(feature = "hooks")]
1766    pub fn hooks(mut self, hooks: crate::hooks::HookSet) -> Self {
1767        self.hooks = Some(hooks);
1768        self
1769    }
1770
1771    /// Runs no hooks, not even the workspace's (`--no-hooks`, spec 3.1 §8.1).
1772    #[cfg(feature = "hooks")]
1773    pub fn without_hooks(mut self) -> Self {
1774        self.hooks_enabled = false;
1775        self.hooks = None;
1776        self
1777    }
1778
1779    pub(crate) fn with_last_todos(mut self, last: Arc<Mutex<TodoList>>) -> Self {
1780        self.last_todos = Some(last);
1781        self
1782    }
1783
1784    /// Builds the harness (spec 3.1 §7.2).
1785    ///
1786    /// # Errors
1787    ///
1788    /// Returns a configuration error when the model or workspace is missing, when an
1789    /// extra tool collides with a harness tool or is a provider shell built-in, when a
1790    /// feature not yet implemented is requested, and `harness.sandbox_unavailable` when
1791    /// the requested sandbox is unavailable under `fail_if_unavailable`.
1792    pub fn build(mut self) -> Result<HarnessAgent> {
1793        // The website preset runs without a shell, whatever the workspace allows (X10).
1794        self.shell_enabled &= !self.preset_without_shell;
1795        let public_only = self.public_only.take();
1796        let model = self.model.ok_or_else(|| AdkError::config("HarnessAgent requires a model"))?;
1797        let mut workspace =
1798            self.workspace.ok_or_else(|| AdkError::config("HarnessAgent requires a workspace"))?;
1799        if let Some(records) = self.read_records.take() {
1800            workspace = workspace.with_read_ledger(records);
1801        }
1802        let unimplemented = self.unimplemented;
1803        if let Some(first) = unimplemented.first() {
1804            return Err(AdkError::config(format!("not yet implemented: {first}")));
1805        }
1806        if self.payments_requested {
1807            #[cfg(feature = "payments")]
1808            let configured = self.payments.is_some();
1809            #[cfg(not(feature = "payments"))]
1810            let configured = false;
1811            if !configured {
1812                return Err(AdkError::config(
1813                    "the payments pack needs a merchant checkout service, a transaction store \
1814                     and a mandate, which only the library API takes: \
1815                     HarnessAgentBuilder::pack_payments(PaymentsPack) with adk-harness feature \
1816                     `payments` (spec 3.1 §7.16)",
1817                ));
1818            }
1819        }
1820        if self.managed_requested && cfg!(not(feature = "managed")) {
1821            return Err(AdkError::config(
1822                "the managed form needs adk-harness feature `managed`: HarnessResolver builds a \
1823                 HarnessDef on the managed runtime and serves a harness marked Pack::Managed \
1824                 (spec 3.1 §7.18)",
1825            ));
1826        }
1827        // The browser pack (spec 3.1 §7.24): `Pack::Browser` alone is the default session.
1828        #[cfg(feature = "browser")]
1829        let browser = match (self.browser, self.browser_requested) {
1830            (Some(pack), _) => Some(pack),
1831            (None, true) => Some(crate::packs::browser::BrowserPack::default()),
1832            (None, false) => None,
1833        };
1834        #[cfg(not(feature = "browser"))]
1835        if self.browser_requested {
1836            return Err(AdkError::config(
1837                "the browser pack needs adk-harness feature `browser`: Pack::Browser or \
1838                 HarnessAgentBuilder::pack_browser(BrowserPack) (spec 3.1 §7.24)",
1839            ));
1840        }
1841        // The computer-use pack (spec 3.1 §7.24): a runtime is a connection to a server, so
1842        // `Pack::ComputerUse` alone cannot build.
1843        #[cfg(feature = "computer-use")]
1844        let computer_use = self.computer_use;
1845        if self.computer_use_requested {
1846            #[cfg(feature = "computer-use")]
1847            let configured = computer_use.is_some();
1848            #[cfg(not(feature = "computer-use"))]
1849            let configured = false;
1850            if !configured {
1851                return Err(AdkError::config(
1852                    "the computer-use pack needs a ComputerUseRuntime and a ScopeAuthorizer, \
1853                     which only the library API takes: \
1854                     HarnessAgentBuilder::pack_computer_use(ComputerUsePack) with adk-harness \
1855                     feature `computer-use` (spec 3.1 §7.24)",
1856                ));
1857            }
1858        }
1859        // The vision pack (spec 3.7 X15): the gate, the runtime and the toolset, and the egress
1860        // rules as an operator policy layer, so a rule that asks holds the call.
1861        #[cfg(feature = "vision")]
1862        let vision = match self.vision.take() {
1863            Some(pack) => Some(pack.into_runtime(workspace.root())?),
1864            None => None,
1865        };
1866        #[cfg(feature = "vision")]
1867        if let Some(vision) = &vision {
1868            let layer = vision.policy();
1869            self.operator_policy = Some(match self.operator_policy.take() {
1870                Some(existing) => Arc::new(adk_core::StrictestPolicy::new(vec![existing, layer])),
1871                None => layer,
1872            });
1873        }
1874        if self.voice_requested && cfg!(not(feature = "voice")) {
1875            return Err(AdkError::config(
1876                "the voice surface needs adk-harness feature `voice`: packs::voice::VoiceSurface \
1877                 runs a harness marked Pack::Voice as the agent of an IntegratedRealtimeRunner \
1878                 (spec 3.1 §7.17)",
1879            ));
1880        }
1881        let harness_names: HashSet<&str> = HARNESS_TOOL_NAMES.iter().copied().collect();
1882        for tool in &self.tools {
1883            if harness_names.contains(tool.name()) {
1884                return Err(AdkError::config(format!(
1885                    "tool '{}' collides with a harness tool of the same name",
1886                    tool.name()
1887                )));
1888            }
1889            #[cfg(feature = "payments")]
1890            if self.payments.is_some() && crate::packs::payments::is_payment_tool(tool.name()) {
1891                return Err(AdkError::config(format!(
1892                    "tool '{}' collides with a payments pack tool of the same name",
1893                    tool.name()
1894                )));
1895            }
1896            #[cfg(feature = "browser")]
1897            if browser.is_some() && crate::packs::browser::is_browser_tool(tool.name()) {
1898                return Err(AdkError::config(format!(
1899                    "tool '{}' collides with a browser pack tool of the same name (spec 3.1 §7.24)",
1900                    tool.name()
1901                )));
1902            }
1903            #[cfg(feature = "vision")]
1904            if vision.is_some() && adk_vision::VISION_TOOL_NAMES.contains(&tool.name()) {
1905                return Err(AdkError::config(format!(
1906                    "tool '{}' collides with a vision pack tool of the same name (spec 3.7 X15)",
1907                    tool.name()
1908                )));
1909            }
1910            #[cfg(feature = "computer-use")]
1911            if computer_use.is_some()
1912                && crate::packs::computer_use::is_computer_use_tool(tool.name())
1913            {
1914                return Err(AdkError::config(format!(
1915                    "tool '{}' collides with a computer-use pack tool of the same name (spec 3.1 §7.24)",
1916                    tool.name()
1917                )));
1918            }
1919            if tool.is_builtin()
1920                && (tool.name().starts_with("bash") || tool.name().contains("shell"))
1921            {
1922                return Err(AdkError::config(format!(
1923                    "'{}' is a provider-executed shell; the harness runs commands only through its own bash (spec 3.1 §9.2 I27)",
1924                    tool.name()
1925                )));
1926            }
1927            // Every other builtin executes inside the provider, where no policy, ledger,
1928            // guardrail or audit record covers it (spec 3.1 §7.20 "Refused builtins").
1929            if tool.is_builtin() {
1930                return Err(AdkError::config(format!(
1931                    "'{}' is a provider-executed tool the harness does not manage; search and URL \
1932                     context are enabled through HarnessAgentBuilder::provider_web_tools, computer \
1933                     use through its pack, and the rest have no governed form (spec 3.1 §7.20)",
1934                    tool.name()
1935                )));
1936            }
1937        }
1938        if self.search_provider.is_some()
1939            && self.provider_web_tools.is_some_and(|tools| tools.anthropic_web_search)
1940        {
1941            return Err(AdkError::config(
1942                "the governed web_search and Anthropic's provider web_search share one tool name; \
1943                 set a search provider or enable anthropic_web_search, not both (spec 3.1 §7.20)",
1944            ));
1945        }
1946
1947        // 1. Shell runtime.
1948        let shell = if self.shell_enabled {
1949            resolve_isolation(&self.shell, workspace.root())?
1950        } else {
1951            resolve_isolation(&ShellConfig::default(), workspace.root())?
1952        };
1953        let status = shell.status.clone();
1954
1955        // 2. Instructions and the class registry.
1956        let instructions = ProjectInstructions::load(workspace.root(), &self.instructions)?;
1957        let instruction_state = Arc::new(InstructionState {
1958            instructions,
1959            trust_store: self
1960                .trust_store
1961                .unwrap_or_else(|| Arc::new(InMemoryWorkspaceTrustStore::new())),
1962            require_trust: self.instructions.require_trust,
1963        });
1964        // Hooks (spec 3.1 §7.22): operator and user hooks, then the workspace's, through the
1965        // shell's launcher and under the workspace's content-keyed trust.
1966        #[cfg(feature = "hooks")]
1967        let hook_runner = build_hook_runner(
1968            self.hooks_enabled,
1969            self.hooks,
1970            &workspace,
1971            &shell,
1972            &status,
1973            &instruction_state,
1974        )?;
1975        #[cfg_attr(not(feature = "team"), allow(unused_mut))]
1976        let mut registry = ToolClassRegistry::harness_defaults(&self.name)
1977            .with_web_allowlist(
1978                self.web.as_ref().map(|web| web.allowed_domains.clone()).unwrap_or_default(),
1979            )
1980            .with_fetch_domains(self.web.as_ref().and_then(|web| web.fetch_domains.clone()));
1981        for classes in &self.origin_classes {
1982            registry = registry.with_origin_classes(classes.clone());
1983        }
1984        for member in &self.team_delegates {
1985            registry.register(member.clone(), ToolKind::Delegate);
1986        }
1987        // The payments pack (spec 3.1 §7.16): every payment tool name is class Payment,
1988        // declared or not, so a lookalike attached as an extra never classes as External.
1989        #[cfg(feature = "payments")]
1990        let payments = self.payments.map(|pack| pack.into_runtime(&self.name));
1991        #[cfg(feature = "payments")]
1992        if payments.is_some() {
1993            for name in crate::packs::payments::PAYMENT_TOOL_NAMES {
1994                registry.register(*name, ToolKind::Payment);
1995            }
1996        }
1997        // The browser pack (spec 3.1 §7.24): every browser tool name is classed, attached
1998        // or not, so a lookalike never classes as a plain External.
1999        #[cfg(feature = "browser")]
2000        if browser.is_some() {
2001            for (name, kind) in crate::packs::browser::browser_classes() {
2002                registry.register(name, kind);
2003            }
2004        }
2005        // The computer-use pack (spec 3.1 §7.24): observation and preview read; execution is
2006        // the never-waivable desktop action.
2007        #[cfg(feature = "computer-use")]
2008        if computer_use.is_some() {
2009            registry.register(crate::packs::computer_use::COMPUTER_USE_OBSERVE, ToolKind::Read);
2010            registry.register(crate::packs::computer_use::COMPUTER_USE_PREVIEW, ToolKind::Read);
2011            registry
2012                .register(crate::packs::computer_use::COMPUTER_USE_EXECUTE, ToolKind::ComputerUse);
2013        }
2014        // The vision pack (spec 3.7 X15): each call classed by where its image goes.
2015        #[cfg(feature = "vision")]
2016        if let Some(vision) = &vision {
2017            registry = registry.with_call_classes(vision.classes());
2018        }
2019        // The partition's policy and crossing tools (spec 3.2 §7.8).
2020        #[cfg(feature = "kernel")]
2021        let partition = self.partition.wire(&self.name, &mut registry)?;
2022        // Crossing tools listed at request time: no run-wide approval names one (K-I15).
2023        #[cfg(feature = "kernel")]
2024        let non_waivable_prefixes: Vec<String> =
2025            partition.as_ref().map(|wired| wired.prefixes.clone()).unwrap_or_default();
2026        #[cfg(not(feature = "kernel"))]
2027        let non_waivable_prefixes: Vec<String> = Vec::new();
2028        // 4 (resolved here: member names register as harness classes, spec 3.1 §7.4).
2029        #[cfg(feature = "team")]
2030        let team_plan = {
2031            let mut reserved: HashSet<String> =
2032                HARNESS_TOOL_NAMES.iter().map(|name| (*name).to_string()).collect();
2033            reserved.extend(self.tools.iter().map(|tool| tool.name().to_string()));
2034            #[cfg(feature = "payments")]
2035            if payments.is_some() {
2036                reserved.extend(
2037                    crate::packs::payments::PAYMENT_TOOL_NAMES
2038                        .iter()
2039                        .map(|name| (*name).to_string()),
2040                );
2041            }
2042            #[cfg(feature = "browser")]
2043            if browser.is_some() {
2044                reserved.extend(
2045                    crate::packs::browser::browser_classes().map(|(name, _)| name.to_string()),
2046                );
2047            }
2048            #[cfg(feature = "computer-use")]
2049            if computer_use.is_some() {
2050                reserved.extend(
2051                    crate::packs::computer_use::COMPUTER_USE_TOOL_NAMES
2052                        .iter()
2053                        .map(|name| (*name).to_string()),
2054                );
2055            }
2056            #[cfg(feature = "vision")]
2057            if vision.is_some() {
2058                reserved.extend(adk_vision::VISION_TOOL_NAMES.iter().map(|name| name.to_string()));
2059            }
2060            let plan = crate::team::TeamPlan::prepare(
2061                &self.name,
2062                self.members,
2063                self.default_members,
2064                self.member_registry,
2065                self.team_policy,
2066                &reserved,
2067            )?;
2068            if let Some(plan) = &plan {
2069                plan.register_classes(&mut registry);
2070            }
2071            plan
2072        };
2073
2074        let mode_store = self.mode_store.unwrap_or_else(|| Arc::new(InMemoryModeStore::new()));
2075        let rules =
2076            self.standing_rules.unwrap_or_else(|| Arc::new(InMemoryStandingRuleStore::new()));
2077        // An added agent applies only the rules pinned to its own id (spec 3.3 S-I19).
2078        #[cfg(feature = "kernel")]
2079        let rules: Arc<dyn StandingRuleStore> = match &self.added {
2080            Some(added) => Arc::new(crate::agents::PinnedOnlyRules::new(rules, added.id.clone())),
2081            None => rules,
2082        };
2083        let ledger = self.shell_ledger.unwrap_or_else(|| Arc::new(InMemoryShellLedger::new()));
2084        let shells = crate::shell::supervisor(
2085            self.shell_supervisor.take(),
2086            self.background_shells.clone(),
2087            self.shell_pids.take(),
2088        );
2089        let approval_store = self
2090            .approval_store
2091            .or_else(|| self.approval_service.as_ref().and_then(|service| service.approval_store()))
2092            .unwrap_or_else(|| Arc::new(InMemoryApprovalStore::new()));
2093
2094        // Filled once the harness is built, from the tools, classes and switches below
2095        // (spec 3.1 §7.25).
2096        let manifest_cell: Arc<OnceLock<crate::manifest::HarnessManifest>> = Arc::default();
2097        let mut tools: Vec<Arc<dyn Tool>> = vec![
2098            Arc::new(ReadFileTool::new(workspace.clone())),
2099            Arc::new(GlobTool::new(workspace.clone())),
2100            Arc::new(GrepTool::new(workspace.clone())),
2101            Arc::new(crate::tools::HarnessHelpTool::new(
2102                manifest_cell.clone(),
2103                std::mem::take(&mut self.help_pages),
2104            )),
2105        ];
2106        if workspace.is_writable() {
2107            tools.push(Arc::new(WriteFileTool::new(workspace.clone())));
2108            tools.push(Arc::new(EditFileTool::new(workspace.clone())));
2109            tools.push(Arc::new(adk_devtools::ApplyPatchTool::new(workspace.clone())));
2110        }
2111        // While sandboxed commands run unapproved, no host file tool overlaps one (I26).
2112        let file_gate = shell.auto_allow_sandboxed.then(crate::shell::FileToolGate::default);
2113        if let Some(gate) = &file_gate {
2114            tools = tools.into_iter().map(|tool| gate.wrap(tool)).collect();
2115        }
2116        // The container and remote shells (spec 3.1 §7.9 "Container"): their environments
2117        // close with the toolset.
2118        // Shell credentials reach `bash` through a launcher layer, which these shells do not
2119        // have; refusing beats commands that silently run without them.
2120        #[cfg(all(any(feature = "docker", feature = "remote-shell"), feature = "auth"))]
2121        if shell.pooled.is_some() && !self.identity.shell_credentials.is_empty() {
2122            return Err(AdkError::config(
2123                "shell credentials cannot be delivered to the container shell or the remote \
2124                 shell yet; use the host shell or the OS sandbox with shell_credential (spec \
2125                 3.1 §7.14)",
2126            ));
2127        }
2128        // The personal preset's shell never retries on the host (spec 3.3 §10 H1), and a shell
2129        // under an egress policy never leaves it for the host's open network (#1281).
2130        #[cfg(feature = "sandbox")]
2131        let egress_policy = matches!(
2132            &self.shell.isolation,
2133            ShellIsolation::OsSandbox(config) if config.egress.is_some()
2134        );
2135        #[cfg(not(feature = "sandbox"))]
2136        let egress_policy = false;
2137        let allow_unsandboxed_retry =
2138            self.shell.allow_unsandboxed_retry && !self.isolated_shell_only && !egress_policy;
2139        #[cfg(any(feature = "docker", feature = "remote-shell"))]
2140        let container_pool = match &shell.pooled {
2141            Some(source) if self.shell_enabled && workspace.bash_allowed() => {
2142                let bash = match source {
2143                    #[cfg(feature = "docker")]
2144                    crate::shell::PoolSource::Container(config) => {
2145                        crate::shell::ContainerBashTool::new(
2146                            workspace.clone(),
2147                            config.clone(),
2148                            ledger.clone(),
2149                        )
2150                    }
2151                    #[cfg(feature = "remote-shell")]
2152                    crate::shell::PoolSource::Remote(config) => {
2153                        crate::shell::ContainerBashTool::remote(
2154                            workspace.clone(),
2155                            config.clone(),
2156                            ledger.clone(),
2157                        )
2158                    }
2159                }
2160                .allow_unsandboxed_retry(allow_unsandboxed_retry)
2161                .with_file_gate(file_gate.clone())
2162                .with_outputs(shells.outputs().clone());
2163                let pool = bash.pool();
2164                tools.push(Arc::new(bash));
2165                Some(pool)
2166            }
2167            _ => None,
2168        };
2169        #[cfg(any(feature = "docker", feature = "remote-shell"))]
2170        let container_shell = container_pool.is_some();
2171        #[cfg(not(any(feature = "docker", feature = "remote-shell")))]
2172        let container_shell = false;
2173        // The personal preset never offers a host shell (spec 3.3 §10 H1).
2174        let isolated_shell = matches!(status, IsolationStatus::OsSandbox { .. });
2175        let host_shell_refused = self.isolated_shell_only && !isolated_shell;
2176        if self.shell_enabled && workspace.bash_allowed() && !container_shell && !host_shell_refused
2177        {
2178            let bash = HarnessBashTool::new(
2179                workspace.clone(),
2180                status.clone(),
2181                self.shell.fail_if_unavailable,
2182                ledger.clone(),
2183            )
2184            .with_mode_store(mode_store.clone(), self.mode)
2185            .allow_unsandboxed_retry(allow_unsandboxed_retry)
2186            .with_file_gate(file_gate.clone())
2187            .with_shells(shells.clone());
2188            #[cfg(feature = "sandbox")]
2189            let bash = match shell.launcher.clone() {
2190                Some(launcher) => bash.with_sandbox(launcher),
2191                None => bash,
2192            };
2193            #[cfg(feature = "auth")]
2194            let bash = self.identity.with_credentials(bash, workspace.root());
2195            #[cfg(not(feature = "auth"))]
2196            let bash: Arc<dyn Tool> = Arc::new(bash);
2197            tools.push(bash);
2198            tools.push(Arc::new(crate::shell::ShellKillTool::new(shells.clone())));
2199        }
2200        if tools.iter().any(|tool| tool.name() == "bash") {
2201            tools.push(Arc::new(crate::shell::ShellOutputTool::new(shells.clone())));
2202        }
2203        if self.todos {
2204            match &self.last_todos {
2205                Some(last) => {
2206                    tools.push(Arc::new(WriteTodosTool::with_last(last.clone())));
2207                    tools.push(Arc::new(UpdateTodoTool::with_last(last.clone())));
2208                }
2209                None => {
2210                    tools.push(Arc::new(WriteTodosTool::new()));
2211                    tools.push(Arc::new(UpdateTodoTool::new()));
2212                }
2213            }
2214        }
2215        #[cfg(feature = "graph")]
2216        let plan_graphs = self.plan_graph.then(|| {
2217            Arc::new(crate::plan_graph::PlanGraphs::new(
2218                self.plan_checkpointer
2219                    .clone()
2220                    .unwrap_or_else(|| Arc::new(adk_graph::MemoryCheckpointer::new())),
2221                &self.name,
2222            ))
2223        });
2224        let snapshots = std::mem::take(&mut self.snapshots).build(&workspace)?;
2225        #[cfg(feature = "graph")]
2226        if let (Some(graphs), Some(snapshots)) = (&plan_graphs, &snapshots) {
2227            graphs.set_snapshots(snapshots.clone());
2228        }
2229        let plan_exit = ExitPlanModeTool::new(mode_store.clone(), self.mode);
2230        #[cfg(feature = "graph")]
2231        let plan_exit = match &plan_graphs {
2232            Some(graphs) => plan_exit.with_plan_graph(graphs.clone()),
2233            None => plan_exit,
2234        };
2235        // A website agent's mode is its jobs' autonomy, which only the owner raises (A-I13).
2236        if !self.website_preset {
2237            tools.push(Arc::new(plan_exit));
2238        }
2239        // Follow-ups go on the agenda of the kernel hosting the harness (spec 3.2 §7.5).
2240        #[cfg(feature = "kernel")]
2241        tools.push(Arc::new(crate::kernel::ProposeFollowupTool::new(
2242            self.kernel_agenda.clone(),
2243            mode_store.clone(),
2244            self.mode,
2245            partition.as_ref().map(|wired| wired.wiring.partition.id.clone()),
2246        )));
2247        // Agents are suggested only by the primary agent, never by an added one (spec 3.3 §5.7).
2248        #[cfg(all(feature = "kernel", feature = "web"))]
2249        let agent_limits = Arc::new(OnceLock::new());
2250        #[cfg(all(feature = "kernel", feature = "web"))]
2251        if let Some(proposer) = self.agent_proposer.clone().filter(|_| self.added.is_none()) {
2252            tools.push(Arc::new(crate::agents::ProposeAgentTool::new(
2253                proposer,
2254                mode_store.clone(),
2255                self.mode,
2256                agent_limits.clone(),
2257                partition
2258                    .as_ref()
2259                    .map(|wired| wired.wiring.partition.id.clone())
2260                    .unwrap_or_default(),
2261            )));
2262        }
2263        #[cfg(feature = "memory")]
2264        let memory_resolver = self.memory.clone().map(|config| {
2265            // A partition keeps working notes of its own (spec 3.2 K-I15).
2266            #[cfg(feature = "kernel")]
2267            let config = match &partition {
2268                Some(wired) => wired.wiring.scope_notes(config, workspace.root()),
2269                None => config,
2270            };
2271            let resolver =
2272                crate::tools::MemoryResolver::new(config, workspace.root().to_path_buf());
2273            tools.push(Arc::new(crate::tools::MemoryReadTool::new(resolver.clone())));
2274            tools.push(Arc::new(crate::tools::MemoryWriteTool::new(resolver.clone())));
2275            tools.push(Arc::new(crate::tools::MemoryDeleteTool::new(resolver.clone())));
2276            resolver
2277        });
2278        let harness_audit = crate::agent::harness_audit_trail(self.audit_log)?;
2279        // Under a kernel, every audit record also writes its content-free ledger row
2280        // (spec 3.2 §7.10).
2281        #[cfg(feature = "kernel")]
2282        let harness_audit =
2283            harness_audit.map(|trail| crate::kernel::tap_audit(trail, &self.kernel_ledger));
2284        #[cfg(feature = "memory")]
2285        let facts = {
2286            #[cfg(feature = "auth")]
2287            let require_authenticated = self.identity.require_authenticated;
2288            #[cfg(not(feature = "auth"))]
2289            let require_authenticated = false;
2290            self.long_term.build(
2291                &self.name,
2292                workspace.root(),
2293                require_authenticated,
2294                harness_audit.clone(),
2295                self.member_model.clone().unwrap_or_else(|| model.clone()),
2296                self.budget.clone(),
2297                (mode_store.clone(), self.mode),
2298                self.effort.distiller,
2299            )?
2300        };
2301        #[cfg(feature = "memory")]
2302        if let Some(facts) = &facts {
2303            tools.push(Arc::new(crate::tools::MemorySearchTool::new(facts.clone())));
2304            tools.push(Arc::new(crate::tools::MemoryRememberTool::new(facts.clone())));
2305        }
2306        // Crossings into other partitions' facts, drivers and sessions (spec 3.2 §7.8).
2307        #[cfg(all(feature = "kernel", feature = "memory"))]
2308        if let (Some(wired), Some(facts)) = (&partition, &facts) {
2309            tools.extend(wired.wiring.memory_tools(facts));
2310        }
2311        #[cfg(feature = "kernel")]
2312        if let Some(wired) = &partition {
2313            tools.extend(wired.crossings.iter().cloned());
2314        }
2315        // Governed web tools (spec 3.1 §7.20): `web_search` only with a provider.
2316        #[cfg(feature = "web")]
2317        if let Some(config) = self.web.clone() {
2318            let runtime = crate::web::WebRuntime::new(
2319                config,
2320                self.web_signer.clone(),
2321                Some((mode_store.clone(), self.mode)),
2322            );
2323            tools.push(Arc::new(crate::tools::WebFetchTool::new(runtime.clone())));
2324            if let Some(provider) = &self.search_provider {
2325                tools.push(Arc::new(crate::tools::WebSearchTool::new(runtime, provider.clone())));
2326            }
2327        }
2328        // MCP interaction (spec 3.1 §7.21): the bridges exist before the prompter they
2329        // answer through, which is bound once the handler is built.
2330        #[cfg(feature = "mcp")]
2331        let mcp = (!self.mcp_servers.is_empty()).then(|| {
2332            // Sampling runs at `sampling` (spec 3.1 §7.23), whichever model answers it.
2333            let at_sampling =
2334                |model: Arc<dyn Llm>| crate::posture::AtEffort::wrap(model, self.effort.sampling);
2335            let mut interaction = self.mcp_interaction.clone();
2336            interaction.sampling_model = interaction.sampling_model.map(at_sampling);
2337            Arc::new(crate::mcp::McpInteractionRuntime::new(
2338                interaction,
2339                self.mcp_servers.clone(),
2340                at_sampling(model.clone()),
2341                self.member_model.clone().map(at_sampling),
2342            ))
2343        });
2344        #[cfg(feature = "mcp")]
2345        if let Some(mcp) = &mcp
2346            && self.mcp_interaction.resources
2347        {
2348            tools.push(Arc::new(crate::tools::McpListResourcesTool::new(mcp.clone())));
2349            tools.push(Arc::new(crate::tools::McpReadResourceTool::new(mcp.clone())));
2350        }
2351        // The payment tools join the harness tools, so RBAC, hooks and the class registry
2352        // cover them like any other (spec 3.1 §7.16).
2353        #[cfg(feature = "payments")]
2354        if let Some(payments) = &payments {
2355            tools.extend(payments.tools.iter().cloned());
2356        }
2357        // The browser pack's tools join the harness tools under the harness's web
2358        // configuration (spec 3.1 §7.24).
2359        #[cfg(feature = "browser")]
2360        let browser = browser.map(|pack| {
2361            pack.into_runtime(self.web.clone().unwrap_or_default(), (mode_store.clone(), self.mode))
2362        });
2363        #[cfg(feature = "browser")]
2364        if let Some(browser) = &browser {
2365            tools.extend(browser.tools.iter().cloned());
2366        }
2367        #[cfg(feature = "computer-use")]
2368        let computer_use = computer_use.map(|pack| pack.into_runtime());
2369        #[cfg(feature = "computer-use")]
2370        if let Some(computer_use) = &computer_use {
2371            tools.extend(computer_use.tools.iter().cloned());
2372        }
2373        // The vision tools join the harness tools (spec 3.7 X15).
2374        #[cfg(feature = "vision")]
2375        if let Some(vision) = &vision {
2376            tools.extend(vision.tools());
2377        }
2378        // Take over (spec 3.3 §10 H2): every call runs in a scope a secret can reach, and
2379        // leaves it scrubbed before RBAC, hooks or members see the result.
2380        if let Some(take_over) = &self.take_over {
2381            take_over.bind(self.approval_service.clone(), self.confirmation_timeout);
2382            let tool_timeout = self.tool_timeout;
2383            tools = tools
2384                .into_iter()
2385                .map(|tool| match tool.name() {
2386                    // The shell runs model-written commands, so it never takes over.
2387                    "bash" => crate::take_over::ScopedTool::wrap_shell(tool, tool_timeout),
2388                    _ => crate::take_over::ScopedTool::wrap(tool, tool_timeout),
2389                })
2390                .collect();
2391        }
2392        // A public-partition agent is offered its partition's tools and nothing else, so no
2393        // workspace, memory or plan tool reaches a model that reads untrusted text (A-I2).
2394        if let Some(allowed) = &public_only {
2395            tools.retain(|tool| allowed.contains(tool.name()));
2396        }
2397        let tool_names: Vec<String> = tools.iter().map(|tool| tool.name().to_string()).collect();
2398        #[cfg(feature = "auth")]
2399        let (tools, identity_gate) = {
2400            let isolation = status.isolation();
2401            let tools = self.identity.protect(tools, &registry, &self.name, isolation);
2402            (
2403                tools,
2404                Arc::new(crate::identity::IdentityGate::new(self.identity.require_authenticated)),
2405            )
2406        };
2407        // Every tool, the members' included, runs the PostTool and PostEdit hooks after it
2408        // executes (spec 3.1 §7.22); the wrapper forwards the declaration, so origins hold.
2409        #[cfg(feature = "hooks")]
2410        let tools = match &hook_runner {
2411            Some(runner) => crate::hooks::HookedTool::wrap_all(
2412                tools,
2413                runner,
2414                &registry,
2415                &self.name,
2416                status.isolation(),
2417                (mode_store.clone(), self.mode),
2418            ),
2419            None => tools,
2420        };
2421        #[cfg(feature = "team")]
2422        let member_tools = tools.clone();
2423        // A purchase is the coordinator's call to put to the person; members never pay
2424        // (spec 3.1 §7.16, §9.2 I38).
2425        #[cfg(all(feature = "team", feature = "payments"))]
2426        let member_tools: Vec<Arc<dyn Tool>> = member_tools
2427            .into_iter()
2428            .filter(|tool| !crate::packs::payments::is_payment_tool(tool.name()))
2429            .collect();
2430        // A member keeps the browser's observation tools and never navigates or acts
2431        // (spec 3.1 §7.24 "Members", §9.2 I60).
2432        #[cfg(all(feature = "team", feature = "browser"))]
2433        let member_tools: Vec<Arc<dyn Tool>> = member_tools
2434            .into_iter()
2435            .filter(|tool| !crate::packs::browser::browser_member_excluded(tool.name()))
2436            .collect();
2437        // A desktop action is the coordinator's to put to the person (spec 3.1 §7.24).
2438        #[cfg(all(feature = "team", feature = "computer-use"))]
2439        let member_tools: Vec<Arc<dyn Tool>> = member_tools
2440            .into_iter()
2441            .filter(|tool| !crate::packs::computer_use::is_computer_use_tool(tool.name()))
2442            .collect();
2443        // Members get the same request observers as the coordinator (spec 3.1 §7.10, §7.13).
2444        #[cfg_attr(not(feature = "observe"), allow(unused_mut))]
2445        #[cfg(feature = "auth")]
2446        let mut observers: Vec<Arc<dyn crate::toolset::RequestObserver>> =
2447            vec![identity_gate.clone()];
2448        #[cfg_attr(not(feature = "observe"), allow(unused_mut))]
2449        #[cfg(not(feature = "auth"))]
2450        let mut observers: Vec<Arc<dyn crate::toolset::RequestObserver>> = Vec::new();
2451        #[cfg(feature = "observe")]
2452        let run_trails = Arc::new(crate::observe::RunTrails::default());
2453        #[cfg(feature = "observe")]
2454        if let Some(guard) = self.loop_guard {
2455            observers.push(Arc::new(crate::observe::LoopGuardObserver::new(
2456                guard,
2457                mode_store.clone(),
2458                self.mode,
2459                run_trails.clone(),
2460            )));
2461        }
2462        // Every request names the mandate and the remaining budget (spec 3.1 §7.16).
2463        #[cfg(feature = "payments")]
2464        if let Some(payments) = &payments {
2465            observers.push(payments.reminder.clone());
2466        }
2467        #[cfg_attr(not(feature = "memory"), allow(unused_mut))]
2468        let mut toolset = HarnessToolset::new(tools, mode_store.clone(), self.mode)
2469            .with_banner(if self.website_preset { website_banner } else { mode_banner })
2470            .with_observers(&observers)
2471            .with_effort(self.effort)
2472            .with_rules_digest(rules.clone())
2473            .with_shells(shells);
2474        // Under a kernel, each run's tool calls write their ledger rows (spec 3.2 §7.10).
2475        #[cfg(all(feature = "kernel", feature = "observe"))]
2476        run_trails.attach_ledger(self.kernel_ledger.clone(), &toolset.all_tools());
2477        #[cfg(any(feature = "docker", feature = "remote-shell"))]
2478        if let Some(pool) = container_pool {
2479            toolset = toolset.with_containers(pool);
2480        }
2481        #[cfg(feature = "memory")]
2482        if let Some(facts) = facts {
2483            toolset = toolset.with_facts(facts);
2484        }
2485        let toolset = Arc::new(toolset);
2486
2487        // Provider-executed search and URL tools, for the provider the model's client
2488        // serves only, declared to runs starting in Ask or Auto; by default the provider's
2489        // search when web is on, replaced by a configured search provider (spec 3.1 §7.20,
2490        // I49).
2491        #[cfg(feature = "web")]
2492        let (provider_web, web_search_path) = {
2493            let tools = self.provider_web_tools.unwrap_or(if self.web.is_some() {
2494                crate::web::ProviderWebTools::provider_default()
2495            } else {
2496                crate::web::ProviderWebTools::off()
2497            });
2498            // The search filter, never the fetch allowlist (spec 3.1 §7.32, I73).
2499            let filter = self.web.as_ref().and_then(|web| web.search_domains.clone());
2500            let toolset = if tools.any() {
2501                Some(crate::web::provider::ProviderWebToolset::new(
2502                    tools,
2503                    model.as_ref(),
2504                    filter.clone(),
2505                    self.search_provider.is_some(),
2506                    mode_store.clone(),
2507                    self.mode,
2508                )?)
2509            } else {
2510                None
2511            };
2512            let path = match (&self.search_provider, &self.web) {
2513                (Some(provider), Some(_)) => crate::web::WebSearchPath::Governed {
2514                    provider: provider.name().to_string(),
2515                    filter,
2516                },
2517                _ => match toolset.as_ref().and_then(|toolset| toolset.search_path()) {
2518                    Some(path) => path,
2519                    None if self.web.is_none() => {
2520                        crate::web::WebSearchPath::None { reason: "web is off".into() }
2521                    }
2522                    None => crate::web::WebSearchPath::None {
2523                        reason: "provider search is off and no search provider is configured"
2524                            .into(),
2525                    },
2526                },
2527            };
2528            let toolset = toolset.filter(|toolset| !toolset.tool_names().is_empty()).map(Arc::new);
2529            (toolset, path)
2530        };
2531        #[cfg(not(feature = "web"))]
2532        let web_search_path = crate::web::WebSearchPath::None {
2533            reason: "adk-harness is built without feature web".into(),
2534        };
2535        #[cfg(feature = "web")]
2536        let provider_web_names: BTreeSet<String> =
2537            provider_web.as_ref().map(|p| p.tool_names().into_iter().collect()).unwrap_or_default();
2538        #[cfg(not(feature = "web"))]
2539        let provider_web_names: BTreeSet<String> = BTreeSet::new();
2540        // 5 (policy first: the handler re-checks against it).
2541        let switches = PolicySwitches {
2542            auto_allow_sandboxed: shell.auto_allow_sandboxed,
2543            allow_host_shell_in_auto: self.shell.allow_host_shell_in_auto,
2544            enforcer_active: matches!(status, IsolationStatus::OsSandbox { .. })
2545                && shell.read_only_runs,
2546            sandbox_protects_paths: shell.protects_paths,
2547        };
2548        let policy = HarnessPolicy::new(PolicyInner {
2549            registry,
2550            mode_store: mode_store.clone(),
2551            default_mode: self.mode,
2552            rules: rules.clone(),
2553            ledger: ledger.clone(),
2554            workspace: workspace.clone(),
2555            shell: ShellView {
2556                status: status.clone(),
2557                allow_unsandboxed_retry,
2558                fail_if_unavailable: self.shell.fail_if_unavailable,
2559                guards_protected_names: shell.guards_protected_names,
2560            },
2561            switches,
2562            trust_mcp_read_only_hints: self.trust_mcp_read_only_hints,
2563            prompts: PromptContexts::default(),
2564            provider_web_tools: provider_web_names,
2565            #[cfg(feature = "hooks")]
2566            hooks: hook_runner.clone(),
2567            #[cfg(feature = "auth")]
2568            identity: identity_gate.clone(),
2569            #[cfg(feature = "observe")]
2570            root_agent: self.name.clone(),
2571            rule_observer: std::sync::OnceLock::new(),
2572        });
2573        let prompting = match (&self.confirmation_handler, self.prompter) {
2574            (None, Some(prompter)) => {
2575                // The person is told about each call a standing rule allows (spec 3.1 §7.33
2576                // fix 3).
2577                policy.observe_rules(prompter.clone());
2578                let handler =
2579                    PromptingConfirmationHandler::new(prompter, rules.clone(), policy.clone());
2580                // A screen plan's steps are approved with one answer (spec 3.7 Q8).
2581                #[cfg(feature = "computer-use")]
2582                let handler = match &computer_use {
2583                    Some(computer_use) => handler.with_screen_plans(computer_use.plans.clone()),
2584                    None => handler,
2585                };
2586                // A crossing is put to the person with its three answers (spec 3.2 §7.8).
2587                #[cfg(feature = "kernel")]
2588                let handler = match &partition {
2589                    Some(wired) => handler.with_partition(wired.wiring.clone()),
2590                    None => handler,
2591                };
2592                Some(Arc::new(handler))
2593            }
2594            _ => None,
2595        };
2596        let handler: Option<Arc<dyn ToolConfirmationHandler>> = match self.confirmation_handler {
2597            Some(handler) => Some(handler),
2598            None => prompting.clone().map(|handler| handler as Arc<dyn ToolConfirmationHandler>),
2599        };
2600        // Elicitations reach the person through the same prompter, or park in the approval
2601        // inbox (spec 3.1 §7.21).
2602        #[cfg(feature = "mcp")]
2603        if let Some(mcp) = &mcp {
2604            mcp.bind_surface(crate::mcp::ElicitationSurface {
2605                prompting: prompting.clone(),
2606                approval_service: self.approval_service.clone(),
2607                timeout: self.confirmation_timeout,
2608                mode_store: mode_store.clone(),
2609                default_mode: self.mode,
2610                isolation: status.clone(),
2611            });
2612        }
2613        #[cfg(not(feature = "mcp"))]
2614        let _ = &prompting;
2615
2616        // 3. The LlmAgent.
2617        #[cfg(feature = "payments")]
2618        let mut packs: Vec<String> =
2619            payments.as_ref().map(|_| vec!["payments".to_string()]).unwrap_or_default();
2620        #[cfg(not(feature = "payments"))]
2621        let mut packs: Vec<String> = Vec::new();
2622        #[cfg(feature = "browser")]
2623        if browser.is_some() {
2624            packs.push("browser".to_string());
2625        }
2626        #[cfg(feature = "computer-use")]
2627        if computer_use.is_some() {
2628            packs.push("computer-use".to_string());
2629        }
2630        if self.managed_requested {
2631            packs.push("managed".to_string());
2632        }
2633        if self.voice_requested {
2634            packs.push("voice".to_string());
2635        }
2636        // What the harness can do, generated from what was just built (spec 3.1 §7.25).
2637        let manifest = {
2638            let isolation = status.isolation();
2639            let rows = toolset
2640                .all_tools()
2641                .iter()
2642                .map(|tool| {
2643                    let origin = adk_core::ToolOrigin::of(tool.as_ref());
2644                    let kind = policy.registry().classify(
2645                        &self.name,
2646                        tool.name(),
2647                        Some(&origin),
2648                        &serde_json::json!({}),
2649                        tool.effect(),
2650                        isolation,
2651                        self.trust_mcp_read_only_hints,
2652                    );
2653                    (tool.name().to_string(), crate::policy::TableRow::of(&kind, false))
2654                })
2655                .collect();
2656            let has_bash = tool_names.iter().any(|name| name == "bash");
2657            #[cfg(feature = "team")]
2658            let members =
2659                team_plan.as_ref().map(crate::team::TeamPlan::member_entries).unwrap_or_default();
2660            #[cfg(not(feature = "team"))]
2661            let members = Vec::new();
2662            #[cfg(feature = "memory")]
2663            let memory = crate::manifest::MemoryEntry {
2664                working_notes: memory_resolver.is_some(),
2665                long_term_facts: toolset.facts().is_some(),
2666                embedder: toolset.facts().map(|_| {
2667                    if let Some(embedder) = &self.long_term.embedder {
2668                        format!("embedded by {}", crate::facts::embedder_id(embedder.as_ref()))
2669                    } else if self.long_term.index.is_some() {
2670                        "a custom index".to_string()
2671                    } else {
2672                        "lexical".to_string()
2673                    }
2674                }),
2675            };
2676            #[cfg(not(feature = "memory"))]
2677            let memory = crate::manifest::MemoryEntry::default();
2678            #[cfg(feature = "graph")]
2679            let plan_rewind = plan_graphs.is_some();
2680            #[cfg(not(feature = "graph"))]
2681            let plan_rewind = false;
2682            crate::manifest::HarnessManifest::generate(crate::manifest::ManifestInputs {
2683                surface: self
2684                    .surface
2685                    .take()
2686                    .unwrap_or_else(crate::manifest::SurfaceManifest::library),
2687                default_mode: self.mode,
2688                rows,
2689                switches,
2690                web_allowlist: policy.registry().web_allowlist(),
2691                shell: has_bash.then_some(&status),
2692                unsandboxed_retry: has_bash
2693                    && allow_unsandboxed_retry
2694                    && matches!(status, IsolationStatus::OsSandbox { .. }),
2695                members,
2696                active_packs: &packs,
2697                web: web_search_path.clone(),
2698                memory,
2699                ledger_durable: self.action_ledger.is_some(),
2700                plan_rewind,
2701                snapshots: snapshots.as_ref().map(|snapshots| snapshots.config().clone()),
2702                model: model.name(),
2703            })
2704        };
2705        let harness_block = manifest.render();
2706        let _ = manifest_cell.set(manifest.clone());
2707        let environment = Environment {
2708            root: workspace.root().display().to_string(),
2709            branch: instruction_state.instructions.git_branch().map(str::to_string),
2710            isolation: if host_shell_refused && !container_shell {
2711                "none".to_string()
2712            } else {
2713                status.to_string()
2714            },
2715            default_mode: self.mode,
2716            packs: packs.clone(),
2717        };
2718        let parts = Arc::new(PromptParts {
2719            base: self.base_prompt,
2720            operator: self.instruction,
2721            environment,
2722            harness: harness_block,
2723            state: instruction_state.clone(),
2724        });
2725        #[cfg(feature = "memory")]
2726        let provider_memory = memory_resolver.clone();
2727        #[cfg(feature = "hooks")]
2728        let provider_hooks = hook_runner.clone();
2729        // Assembled once per run and reused by every model call of it, so the request
2730        // prefix stays byte-stable while tools write memory or trust changes (spec 3.1
2731        // §7.7, §9.2 I56).
2732        let assembled: Arc<Mutex<HashMap<String, String>>> = Arc::new(Mutex::new(HashMap::new()));
2733        let provider: InstructionProvider = Box::new(move |ctx: Arc<dyn ReadonlyContext>| {
2734            let parts = parts.clone();
2735            #[cfg(feature = "hooks")]
2736            let hooks = provider_hooks.clone();
2737            let assembled = assembled.clone();
2738            #[cfg(feature = "memory")]
2739            let memory = provider_memory.clone();
2740            Box::pin(async move {
2741                let key = format!("{}\u{1f}{}", ctx.session_id(), ctx.invocation_id());
2742                if let Some(instruction) =
2743                    assembled.lock().unwrap_or_else(|e| e.into_inner()).get(&key)
2744                {
2745                    return Ok(instruction.clone());
2746                }
2747                let instruction = parts.assemble();
2748                // The session's OnSessionStart notes join the <environment> block; they are
2749                // cached per session, so the prefix stays stable within a run (I56).
2750                #[cfg(feature = "hooks")]
2751                let instruction = match &hooks {
2752                    Some(hooks) => hooks.with_session_notes(
2753                        instruction,
2754                        ctx.app_name(),
2755                        ctx.user_id(),
2756                        ctx.session_id(),
2757                    ),
2758                    None => instruction,
2759                };
2760                #[cfg(feature = "memory")]
2761                let instruction = match memory {
2762                    Some(memory) => memory.append_index(instruction, ctx.as_ref()).await,
2763                    None => instruction,
2764                };
2765                let mut cache = assembled.lock().unwrap_or_else(|e| e.into_inner());
2766                if cache.len() >= 64 {
2767                    cache.clear();
2768                }
2769                cache.insert(key, instruction.clone());
2770                Ok(instruction)
2771            })
2772        });
2773        let non_waivable: BTreeSet<String> = ["exit_plan_mode", "memory_write", "memory_delete"]
2774            .into_iter()
2775            .map(str::to_string)
2776            .collect();
2777        // A payment is never covered by a `tool_approvals` entry (spec 3.1 §7.16, §9.2 I38).
2778        #[cfg(feature = "payments")]
2779        let non_waivable: BTreeSet<String> = if payments.is_some() {
2780            non_waivable
2781                .into_iter()
2782                .chain(
2783                    crate::packs::payments::PAYMENT_TOOL_NAMES
2784                        .iter()
2785                        .map(|name| (*name).to_string()),
2786                )
2787                .collect()
2788        } else {
2789            non_waivable
2790        };
2791        // A desktop action is never covered by a `tool_approvals` entry (spec 3.1 §7.24, I59).
2792        #[cfg(feature = "computer-use")]
2793        let non_waivable: BTreeSet<String> = if computer_use.is_some() {
2794            non_waivable
2795                .into_iter()
2796                .chain(std::iter::once(
2797                    crate::packs::computer_use::COMPUTER_USE_EXECUTE.to_string(),
2798                ))
2799                .collect()
2800        } else {
2801            non_waivable
2802        };
2803        // A provider that refuses its built-in web tools gets the request again without
2804        // them (spec 3.1 §7.20).
2805        #[cfg(feature = "web")]
2806        let agent_model: Arc<dyn Llm> = match &provider_web {
2807            Some(provider_web) => Arc::new(crate::web::provider::ProviderSearchFallback::new(
2808                model.clone(),
2809                provider_web.clone(),
2810            )),
2811            None => model.clone(),
2812        };
2813        #[cfg(not(feature = "web"))]
2814        let agent_model = model.clone();
2815        let mut builder = LlmAgentBuilder::new(self.name.clone())
2816            .model(agent_model)
2817            .description(self.description.unwrap_or_else(|| {
2818                "A governed harness that reads, edits and runs code in the workspace under approvals."
2819                    .to_string()
2820            }))
2821            .instruction_provider(provider)
2822            .toolset(toolset.clone())
2823            .max_iterations(self.max_iterations)
2824            .tool_timeout(self.tool_timeout)
2825            .parallelize_agent_delegations(true)
2826            .tool_confirmation_policy(ToolConfirmationPolicy::PerTool(
2827                ["exit_plan_mode".to_string()].into_iter().collect(),
2828            ));
2829        // What the model is given besides the harness toolset, which a realtime session of
2830        // the harness offers too (spec 3.3 §5.6).
2831        let mut agent_tools: Vec<Arc<dyn Tool>> = Vec::new();
2832        let mut agent_toolsets: Vec<Arc<dyn Toolset>> = Vec::new();
2833        #[cfg(feature = "skills")]
2834        {
2835            match crate::skills::wire(workspace.root(), &self.skills)? {
2836                crate::skills::SkillsWiring::None => {}
2837                crate::skills::SkillsWiring::Toolset(_) if public_only.is_some() => {}
2838                crate::skills::SkillsWiring::Toolset(skills) => {
2839                    agent_toolsets.push(skills.clone());
2840                    builder = builder.toolset(skills);
2841                }
2842                crate::skills::SkillsWiring::Inject(index) => builder = builder.with_skills(index),
2843            }
2844        }
2845        // The operator's own tools and toolsets stay, so the public partition's policy refuses
2846        // one attached by mistake on the record; the harness adds no toolset of its own there.
2847        for tool in self.tools {
2848            let tool = match &self.take_over {
2849                Some(_) => crate::take_over::ScopedTool::wrap(tool, self.tool_timeout),
2850                None => tool,
2851            };
2852            #[cfg(feature = "auth")]
2853            let tool = self.identity.protect_extra(tool);
2854            agent_tools.push(tool.clone());
2855            builder = builder.tool(tool);
2856        }
2857        for extra in self.toolsets {
2858            let extra = match &self.take_over {
2859                Some(_) => crate::take_over::ScopedToolset::wrap(extra, self.tool_timeout),
2860                None => extra,
2861            };
2862            agent_toolsets.push(extra.clone());
2863            builder = builder.toolset(extra);
2864        }
2865        // The coordinator's crossings into other partitions' drivers (spec 3.2 §7.8).
2866        #[cfg(feature = "kernel")]
2867        if let Some(wired) = partition.as_ref().filter(|_| public_only.is_none()) {
2868            for crossings in &wired.toolsets {
2869                let crossings = match &self.take_over {
2870                    Some(_) => {
2871                        crate::take_over::ScopedToolset::wrap(crossings.clone(), self.tool_timeout)
2872                    }
2873                    None => crossings.clone(),
2874                };
2875                agent_toolsets.push(crossings.clone());
2876                builder = builder.toolset(crossings);
2877            }
2878        }
2879        #[cfg(feature = "web")]
2880        if let Some(provider_web) = provider_web.as_ref().filter(|_| public_only.is_none()) {
2881            builder = builder.toolset(provider_web.clone());
2882        }
2883        #[cfg(feature = "mcp")]
2884        if let Some(mcp) = mcp.as_ref().filter(|_| public_only.is_none()) {
2885            agent_toolsets.push(mcp.manager());
2886            builder = builder.toolset(mcp.manager());
2887        }
2888        // The vision pack (spec 3.7 X15): a held remote call carries its egress image, and the
2889        // privacy guardrail gates every image a request to a remote model carries (V-I4).
2890        #[cfg(feature = "vision")]
2891        if let Some(vision) = &vision {
2892            builder = builder.before_tool_callback(vision.toolset.evidence_callback());
2893            if model.data_locality().leaves_machine() {
2894                let guardrail = vision.guardrail(model.as_ref(), harness_audit.clone());
2895                builder = builder.before_model_callback(guardrail.before_model_callback());
2896            }
2897        }
2898        if let Some(customize) = self.customize {
2899            builder = customize(builder);
2900        }
2901        #[cfg(feature = "memory")]
2902        if memory_resolver.is_some() {
2903            builder = builder.tool_confirmation_policy(ToolConfirmationPolicy::PerTool(
2904                ["exit_plan_mode", "memory_write", "memory_delete"]
2905                    .into_iter()
2906                    .map(str::to_string)
2907                    .collect(),
2908            ));
2909        }
2910        // Payments are non-waivable: per-tool confirmation as defence in depth (spec 3.1 §7.2).
2911        #[cfg(feature = "payments")]
2912        if payments.is_some() {
2913            builder = builder
2914                .tool_confirmation_policy(ToolConfirmationPolicy::PerTool(non_waivable.clone()));
2915        }
2916        // An invocation's approved crossing reads end with it (spec 3.2 §13 Q3); a durable
2917        // run's end with the run, released by the kernel's worker.
2918        #[cfg(feature = "kernel")]
2919        if let Some(wired) = &partition {
2920            builder = builder.after_callback(crate::partition::release_on_end(
2921                wired.wiring.policy.clone(),
2922                self.name.clone(),
2923            ));
2924        }
2925        let agent = builder.build()?;
2926        // No run-wide approval answers a crossing (spec 3.2 K-I15).
2927        #[cfg(feature = "kernel")]
2928        let non_waivable: BTreeSet<String> = match &partition {
2929            Some(wired) => non_waivable
2930                .into_iter()
2931                .chain(wired.wiring.non_waivable(&wired.crossings))
2932                .collect(),
2933            None => non_waivable,
2934        };
2935        let coordinator: Arc<dyn adk_core::Agent> = Arc::new(agent);
2936        // 4. Members lowered to one TeamSpec with the coordinator (spec 3.1 §7.10).
2937        #[cfg(feature = "team")]
2938        let team = match team_plan {
2939            Some(plan) => Some(Arc::new(plan.compile(crate::team::TeamInputs {
2940                harness: &self.name,
2941                coordinator: coordinator.clone(),
2942                model: self.member_model.clone().unwrap_or_else(|| model.clone()),
2943                tools: &member_tools,
2944                mode_store: mode_store.clone(),
2945                default_mode: self.mode,
2946                workspace: &workspace,
2947                tool_timeout: self.tool_timeout,
2948                #[cfg(feature = "skills")]
2949                skills: &self.skills,
2950                observers: &observers,
2951                effort: self.effort,
2952                #[cfg(feature = "vision")]
2953                vision: vision.as_ref(),
2954                #[cfg(feature = "vision")]
2955                vision_audit: harness_audit.clone(),
2956            })?)),
2957            None => None,
2958        };
2959        #[cfg(feature = "team")]
2960        let root = team.as_ref().map_or_else(|| coordinator.clone(), |team| team.root().clone());
2961        #[cfg(all(feature = "graph", feature = "team"))]
2962        if let (Some(graphs), Some(team)) = (&plan_graphs, &team)
2963            && let Some(reviewer) = team.reviewer()
2964        {
2965            graphs.set_reviewer(reviewer);
2966        }
2967        #[cfg(not(feature = "team"))]
2968        let root = coordinator.clone();
2969
2970        let goal_store =
2971            self.goal_store.unwrap_or_else(|| Arc::new(crate::goal::InMemoryGoalStore::new()));
2972        // A goal's check runs through the launcher the harness bash uses (spec 3.1 §7.11).
2973        let check_launcher: Arc<dyn adk_devtools::CommandLauncher> =
2974            Arc::new(adk_devtools::HostLauncher);
2975        #[cfg(feature = "sandbox")]
2976        let check_launcher: Arc<dyn adk_devtools::CommandLauncher> = match shell.launcher.clone() {
2977            Some(launcher) => Arc::new(launcher),
2978            None => check_launcher,
2979        };
2980        // The container and remote shells have no launcher; a check never falls back to the
2981        // host (I24).
2982        #[cfg(any(feature = "docker", feature = "remote-shell"))]
2983        let check_launcher: Arc<dyn adk_devtools::CommandLauncher> = match shell.pooled {
2984            Some(_) => Arc::new(crate::shell::ContainerCheckRefusal),
2985            None => check_launcher,
2986        };
2987        let goals = crate::goal::GoalRuntime {
2988            store: goal_store.clone(),
2989            until: Arc::new(
2990                crate::goal::UntilCheckAgent::new(goal_store, workspace.clone(), check_launcher)
2991                    .with_grader(self.goal_grader.clone().unwrap_or_else(|| model.clone()))
2992                    .with_worker(self.name.clone()),
2993            ),
2994            #[cfg(feature = "graph")]
2995            engine: self.goal_engine.unwrap_or(if self.plan_checkpointer.is_some() {
2996                crate::goal::GoalEngine::Graph
2997            } else {
2998                crate::goal::GoalEngine::Loop
2999            }),
3000            #[cfg(feature = "graph")]
3001            checkpointer: self
3002                .plan_checkpointer
3003                .clone()
3004                .unwrap_or_else(|| Arc::new(adk_graph::MemoryCheckpointer::new())),
3005        };
3006        let compaction = if self.compaction_enabled {
3007            Some(self.compaction.unwrap_or_else(|| EventsCompactionConfig {
3008                compaction_interval: 10,
3009                overlap_size: 4,
3010                summarizer: Arc::new(LlmEventSummarizer::new(model)),
3011            }))
3012        } else {
3013            None
3014        };
3015        let degraded_reason = match &status {
3016            IsolationStatus::Degraded { reason, .. } => Some(reason.clone()),
3017            _ => None,
3018        };
3019        #[cfg(all(feature = "kernel", feature = "web"))]
3020        let _ = agent_limits.set(
3021            crate::agents::suggester_ceiling(
3022                tool_names.iter().map(String::as_str),
3023                &packs,
3024                tool_names.iter().any(|tool| tool == "bash").then_some(&status),
3025                self.mode,
3026                &partition
3027                    .as_ref()
3028                    .map(|wired| wired.wiring.partition.drivers.clone())
3029                    .unwrap_or_default(),
3030            )
3031            .uses,
3032        );
3033        let info = HarnessInfo {
3034            name: self.name,
3035            default_mode: self.mode,
3036            isolation: status,
3037            degraded_reason,
3038            #[cfg(feature = "team")]
3039            members: team.as_ref().map(|team| team.member_names()).unwrap_or_default(),
3040            #[cfg(not(feature = "team"))]
3041            members: Vec::new(),
3042            packs,
3043            tools: tool_names,
3044            effort: self.effort,
3045            context_caching: self.context_caching,
3046            web_search: web_search_path,
3047        };
3048        let _ = (self.default_members, self.member_model, self.plan_graph);
3049        Ok(HarnessAgent {
3050            root,
3051            runtime: HarnessRuntime {
3052                policy,
3053                // The partition's policy makes the operator layer stricter (spec 3.2 K-I6).
3054                #[cfg(feature = "kernel")]
3055                operator_policy: match &partition {
3056                    Some(wired) => Some(wired.wiring.operator_policy(self.operator_policy)),
3057                    None => self.operator_policy,
3058                },
3059                #[cfg(not(feature = "kernel"))]
3060                operator_policy: self.operator_policy,
3061                mode_store,
3062                standing_rules: rules,
3063                ledger,
3064                approval_store,
3065                approval_service: self.approval_service,
3066                auto_review: self.auto_review,
3067                requested_call_seal: self.requested_call_seal,
3068                ledgers: crate::ledger::HarnessLedgers::new(
3069                    self.action_ledger.unwrap_or_else(|| Arc::new(InMemoryActionLedger::new())),
3070                ),
3071                handler,
3072                confirmation_timeout: self.confirmation_timeout,
3073                budget: self.budget,
3074                #[cfg(not(feature = "observe"))]
3075                spend_ledger: self.spend_ledger,
3076                // Spend is metered on every run by default (spec 3.1 §7.13).
3077                #[cfg(feature = "observe")]
3078                spend_ledger: self.spend_ledger.or_else(|| {
3079                    Some(Arc::new(adk_core::InMemorySpendLedger::default()) as Arc<dyn SpendLedger>)
3080                }),
3081                history_max_events: self.history_max_events,
3082                compaction,
3083                intra_compaction: self.intra_compaction,
3084                toolset,
3085                instructions: instruction_state,
3086                non_waivable_tools: non_waivable,
3087                non_waivable_prefixes,
3088                workspace,
3089                audit: harness_audit,
3090                #[cfg(feature = "auth")]
3091                identity: identity_gate,
3092                #[cfg(feature = "observe")]
3093                spend: Arc::default(),
3094                #[cfg(feature = "observe")]
3095                run_trails,
3096                #[cfg(feature = "team")]
3097                team,
3098                #[cfg(feature = "graph")]
3099                plan_graph: plan_graphs,
3100                snapshots,
3101                goals,
3102                #[cfg(feature = "kernel")]
3103                kernel_approvals: self.kernel_approvals,
3104                #[cfg(feature = "kernel")]
3105                kernel_agenda: self.kernel_agenda,
3106                #[cfg(feature = "kernel")]
3107                kernel_ledger: self.kernel_ledger,
3108                #[cfg(feature = "kernel")]
3109                partition: partition.map(|wired| wired.wiring),
3110                #[cfg(feature = "kernel")]
3111                session_stamp: self.session_stamp,
3112                #[cfg(feature = "web")]
3113                provider_web,
3114                #[cfg(feature = "mcp")]
3115                mcp,
3116                #[cfg(feature = "hooks")]
3117                hooks: hook_runner,
3118                effort: self.effort,
3119                cache_capable: self.context_caching.then_some(self.cache_capable).flatten(),
3120                #[cfg(feature = "payments")]
3121                payments: payments.map(|payments| payments.reminder),
3122                #[cfg(feature = "computer-use")]
3123                screen_plans: computer_use.as_ref().map(|computer_use| computer_use.plans.clone()),
3124                take_over: self.take_over,
3125                agent_tools: (agent_tools, agent_toolsets),
3126            },
3127            info,
3128            manifest,
3129        })
3130    }
3131}
3132
3133/// The `<environment>` block (spec 3.1 §7.7 item 2).
3134struct Environment {
3135    root: String,
3136    branch: Option<String>,
3137    isolation: String,
3138    default_mode: HarnessMode,
3139    packs: Vec<String>,
3140}
3141
3142/// The parts of the harness instruction, assembled once per run (spec 3.1 §7.7).
3143struct PromptParts {
3144    base: Cow<'static, str>,
3145    operator: Option<String>,
3146    environment: Environment,
3147    /// The `<harness>` block (spec 3.1 §7.25), after `<environment>` in the cached prefix.
3148    harness: String,
3149    state: Arc<InstructionState>,
3150}
3151
3152impl PromptParts {
3153    fn assemble(&self) -> String {
3154        let env = &self.environment;
3155        let mut out = String::with_capacity(self.base.len() + 1024);
3156        out.push_str(&self.base);
3157        out.push_str("\n\n");
3158        if let Some(operator) = &self.operator {
3159            out.push_str(operator);
3160            out.push_str("\n\n");
3161        }
3162        out.push_str(&format!(
3163            "<environment>\nworkspace root: {}\nplatform: {} {}\ndate: {}\ngit branch: {}\nshell: {}\ndefault mode: {}\npacks: {}\n</environment>\n\n",
3164            env.root,
3165            std::env::consts::OS,
3166            std::env::consts::ARCH,
3167            chrono::Utc::now().format("%Y-%m-%d"),
3168            env.branch.as_deref().unwrap_or("none"),
3169            env.isolation,
3170            env.default_mode,
3171            if env.packs.is_empty() { "none".to_string() } else { env.packs.join(", ") },
3172        ));
3173        out.push_str(&self.harness);
3174        out.push_str("\n\n");
3175        out.push_str(&self.state.instructions.render(self.state.trusted()));
3176        out.trim_end().to_string()
3177    }
3178}
3179
3180/// The hook runner of a build (spec 3.1 §7.22), or `None` when hooks are off or none are
3181/// configured. Workspace hooks come from `.adk/harness.toml` and run only while the
3182/// workspace's instruction files, the hooks file included, are trusted (I54).
3183#[cfg(feature = "hooks")]
3184fn build_hook_runner(
3185    enabled: bool,
3186    configured: Option<crate::hooks::HookSet>,
3187    workspace: &Workspace,
3188    shell: &crate::shell::ShellRuntime,
3189    status: &IsolationStatus,
3190    instructions: &Arc<InstructionState>,
3191) -> Result<Option<Arc<crate::hooks::HookRunner>>> {
3192    if !enabled {
3193        return Ok(None);
3194    }
3195    let mut set = configured.unwrap_or_default();
3196    if let Some(workspace_hooks) = crate::hooks::HookSet::load_workspace(workspace.root())? {
3197        set = set.merge(workspace_hooks);
3198    }
3199    set.validate()?;
3200    if set.is_empty() {
3201        return Ok(None);
3202    }
3203    // A hook runs through the shell's launcher (spec 3.1 §9.2 I54); the container shell has
3204    // none, and running `inherit` hooks on the host instead would escape the isolation.
3205    if matches!(status, IsolationStatus::Container { .. } | IsolationStatus::Remote { .. })
3206        && set.hooks.iter().any(|hook| hook.isolation == crate::hooks::HookIsolation::Inherit)
3207    {
3208        return Err(AdkError::new(
3209            adk_core::ErrorComponent::Agent,
3210            adk_core::ErrorCategory::InvalidInput,
3211            crate::hooks::HOOK_CONFIG_CODE,
3212            "hooks with `inherit` isolation cannot run inside the container shell yet; give them \
3213             `isolation = \"host\"`, run the harness with the OS sandbox, or disable hooks \
3214             (spec 3.1 §9.2 I54)",
3215        ));
3216    }
3217    // The Windows restricted-token sandbox starts its processes itself, and a hook needs a
3218    // command it can spawn and feed (spec 3.2 §10 W5).
3219    #[cfg(all(windows, feature = "sandbox"))]
3220    if shell.launcher.as_ref().is_some_and(crate::shell::SandboxLauncher::starts_processes_itself)
3221        && set.hooks.iter().any(|hook| hook.isolation == crate::hooks::HookIsolation::Inherit)
3222    {
3223        return Err(AdkError::new(
3224            adk_core::ErrorComponent::Agent,
3225            adk_core::ErrorCategory::InvalidInput,
3226            crate::hooks::HOOK_CONFIG_CODE,
3227            "hooks with `inherit` isolation cannot run inside the Windows restricted-token \
3228             sandbox yet; give them `isolation = \"host\"`, or disable hooks (spec 3.2 §10 W5)",
3229        ));
3230    }
3231    #[cfg_attr(not(feature = "sandbox"), allow(unused_mut))]
3232    let mut runner = crate::hooks::HookRunner::new(set, workspace.clone(), status.clone());
3233    #[cfg(feature = "sandbox")]
3234    if let Some(launcher) = &shell.launcher {
3235        runner = runner
3236            .with_launcher(Arc::new(launcher.clone()))
3237            .with_read_only_launcher(Arc::new(launcher.read_only()));
3238    }
3239    #[cfg(not(feature = "sandbox"))]
3240    let _ = shell;
3241    let state = instructions.clone();
3242    Ok(Some(Arc::new(runner.with_workspace_trust(move || state.trusted()))))
3243}
3244
3245/// The long-term memory configuration of a builder (spec 3.1 §7.15.2).
3246#[cfg(feature = "memory")]
3247#[derive(Default)]
3248struct LongTermOptions {
3249    config: Option<crate::facts::LongTermMemoryConfig>,
3250    store: Option<Arc<dyn crate::facts::FactStore>>,
3251    index: Option<Arc<dyn crate::facts::FactIndex>>,
3252    embedder: Option<Arc<dyn adk_memory::EmbeddingProvider>>,
3253    /// A partition's memory scope: the project of every fact, read and written, in place
3254    /// of the workspace's (spec 3.2 §7.8).
3255    project: Option<String>,
3256}
3257
3258#[cfg(feature = "memory")]
3259impl LongTermOptions {
3260    /// The harness's long-term memory, or `None` when it is off.
3261    #[allow(clippy::too_many_arguments)]
3262    fn build(
3263        &self,
3264        agent: &str,
3265        workspace_root: &std::path::Path,
3266        require_authenticated: bool,
3267        audit: Option<adk_core::audit_log::AuditTrail>,
3268        member_model: Arc<dyn Llm>,
3269        budget: Option<RunBudget>,
3270        (mode_store, default_mode): (Arc<dyn ModeStore>, HarnessMode),
3271        distiller: crate::posture::Effort,
3272    ) -> Result<Option<Arc<crate::facts::runtime::FactsRuntime>>> {
3273        let Some(config) = self.config.clone() else {
3274            if self.store.is_some() || self.index.is_some() || self.embedder.is_some() {
3275                return Err(AdkError::config(
3276                    "fact_store, fact_index and memory_embedder configure long-term memory; \
3277                     turn it on with long_term_memory(LongTermMemoryConfig::default())",
3278                ));
3279            }
3280            return Ok(None);
3281        };
3282        if self.index.is_some() && self.embedder.is_some() {
3283            return Err(AdkError::config(
3284                "memory_embedder configures the default LocalFactIndex; give your own index \
3285                 its embedder instead, for example LocalFactIndex::with_embedder",
3286            ));
3287        }
3288        let store =
3289            self.store.clone().unwrap_or_else(|| Arc::new(crate::facts::InMemoryFactStore::new()));
3290        let index = match (&self.index, &self.embedder) {
3291            (Some(index), _) => index.clone(),
3292            (None, Some(embedder)) => Arc::new(
3293                crate::facts::LocalFactIndex::new(store.clone()).with_embedder(embedder.clone()),
3294            ),
3295            (None, None) => Arc::new(crate::facts::LocalFactIndex::new(store.clone())),
3296        };
3297        // The distiller runs at `distiller` (spec 3.1 §7.23), whichever model it is.
3298        let distill_model = crate::posture::AtEffort::wrap(
3299            config.distill_model.clone().unwrap_or(member_model),
3300            distiller,
3301        );
3302        // Consolidation embeds with the default index's embedder (spec 3.2 §7.5).
3303        let embedder = if self.index.is_none() { self.embedder.clone() } else { None };
3304        let project =
3305            self.project.clone().unwrap_or_else(|| crate::memory::project_slug(workspace_root));
3306        Ok(Some(Arc::new(
3307            crate::facts::runtime::FactsRuntime::new(
3308                config,
3309                store,
3310                index,
3311                project,
3312                agent.to_string(),
3313                require_authenticated,
3314                audit,
3315                distill_model,
3316                budget,
3317                mode_store,
3318                default_mode,
3319            )
3320            .with_embedder(embedder)
3321            .confined(self.project.is_some()),
3322        )))
3323    }
3324}
3325
3326/// The identity configuration of a builder (spec 3.1 §7.14).
3327#[cfg(feature = "auth")]
3328#[derive(Default)]
3329struct IdentityOptions {
3330    broker: Option<Arc<dyn adk_core::CredentialBroker>>,
3331    shell_credentials: Vec<crate::identity::ShellCredential>,
3332    rbac: Option<crate::identity::RbacMap>,
3333    require_authenticated: bool,
3334}
3335
3336#[cfg(feature = "auth")]
3337impl IdentityOptions {
3338    /// `bash` with the credential helper when a broker is set.
3339    fn with_credentials(&self, bash: HarnessBashTool, root: &std::path::Path) -> Arc<dyn Tool> {
3340        let Some(broker) = &self.broker else {
3341            return Arc::new(bash);
3342        };
3343        let calls = Arc::new(crate::identity::CallEnvironment::default());
3344        let launcher_calls = calls.clone();
3345        let bash = bash.with_launcher_layer(move |inner| {
3346            Arc::new(crate::identity::CredentialLauncher::new(inner, launcher_calls.clone()))
3347        });
3348        Arc::new(crate::identity::CredentialedTool::new(
3349            Arc::new(bash),
3350            broker.clone(),
3351            crate::identity::resolve_credentials(self.shell_credentials.clone(), root),
3352            calls,
3353        ))
3354    }
3355
3356    /// The harness tools, each wrapped for the permission its class needs.
3357    fn protect(
3358        &self,
3359        tools: Vec<Arc<dyn Tool>>,
3360        registry: &ToolClassRegistry,
3361        agent: &str,
3362        isolation: crate::policy::Isolation,
3363    ) -> Vec<Arc<dyn Tool>> {
3364        let Some(rbac) = &self.rbac else {
3365            return tools;
3366        };
3367        tools
3368            .into_iter()
3369            .map(|tool| {
3370                let class = registry.classify(
3371                    agent,
3372                    tool.name(),
3373                    None,
3374                    &serde_json::json!({}),
3375                    tool.effect(),
3376                    isolation,
3377                    false,
3378                );
3379                rbac.protect(tool, &class)
3380            })
3381            .collect()
3382    }
3383
3384    /// An extra tool, wrapped for the permission its `External` class needs.
3385    fn protect_extra(&self, tool: Arc<dyn Tool>) -> Arc<dyn Tool> {
3386        match &self.rbac {
3387            Some(rbac) => {
3388                let class = ToolKind::External {
3389                    effect: tool.effect(),
3390                    trusted_origin: tool.origin() == adk_core::STATIC_TOOL_ORIGIN,
3391                };
3392                rbac.protect(tool, &class)
3393            }
3394            None => tool,
3395        }
3396    }
3397}