Skip to main content

adk_harness/
toolset.rs

1//! `HarnessToolset`: the harness tools and per-request reminders (spec 3.1 §7.6, §7.7).
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6use adk_core::{Content, LlmRequest, ReadonlyContext, Result, Tool, ToolOrigin, Toolset};
7use async_trait::async_trait;
8
9use crate::approvals::matcher::glob_matches;
10use crate::approvals::{StandingDecision, StandingRule, StandingRuleStore};
11use crate::mode::{HarnessMode, ModeStore};
12use crate::tools::TodoList;
13
14/// The most rules the reminder's digest lists (spec 3.1 §7.25).
15const DIGEST_MAX_RULES: usize = 20;
16/// The most bytes of the digest's rule lines (spec 3.1 §7.25).
17const DIGEST_MAX_BYTES: usize = 1024;
18/// The most characters of a deny reason the digest quotes.
19const DIGEST_REASON_CHARS: usize = 80;
20
21/// The standing rules that apply to a session, for the per-request reminder
22/// (spec 3.1 §7.25): rules a call of this harness's declared tools can match.
23struct RulesDigest {
24    store: Arc<dyn StandingRuleStore>,
25    /// Every declared tool with its origin, so a rule pinned to another declaration is left
26    /// out.
27    origins: Vec<(String, ToolOrigin)>,
28}
29
30impl RulesDigest {
31    /// The digest for (`app`, `user`, `session`), or `None` when no rule applies. Rules
32    /// are numbered as `/rules` numbers them: every rule of the user, oldest first.
33    async fn render(&self, app: &str, user: &str, session: &str) -> Option<String> {
34        let mut rules = self.store.list(app, user).await.ok()?;
35        rules.sort_by_key(|rule| rule.created_at);
36        let now = chrono::Utc::now();
37        let mut applicable: Vec<(usize, &StandingRule)> = rules
38            .iter()
39            .enumerate()
40            .map(|(index, rule)| (index + 1, rule))
41            .filter(|(_, rule)| {
42                !rule.is_expired(now)
43                    && rule.scope.session_id().is_none_or(|id| id == session)
44                    && self.origins.iter().any(|(name, origin)| {
45                        glob_matches(&rule.tool, name) && rule.origin.admits(origin)
46                    })
47            })
48            .collect();
49        if applicable.is_empty() {
50            return None;
51        }
52        // Deny before allow, then by number.
53        applicable.sort_by_key(|(number, rule)| {
54            (!matches!(rule.decision, StandingDecision::Deny { .. }), *number)
55        });
56        let mut lines = vec![
57            "Standing rules for you here; a call one matches runs or is refused without asking:"
58                .to_string(),
59        ];
60        let mut used = 0;
61        let mut shown = 0;
62        for (number, rule) in &applicable {
63            let line = digest_line(*number, rule);
64            if shown == DIGEST_MAX_RULES || used + line.len() > DIGEST_MAX_BYTES {
65                break;
66            }
67            used += line.len();
68            shown += 1;
69            lines.push(line);
70        }
71        if shown < applicable.len() {
72            lines.push(format!("(+{} more; /rules lists them)", applicable.len() - shown));
73        }
74        Some(lines.join("\n"))
75    }
76}
77
78/// One rule of the digest: number, decision, tool, what it matches and its scope; the
79/// label passes the secret redaction and a deny reason is quoted and cut.
80fn digest_line(number: usize, rule: &StandingRule) -> String {
81    let scope = match rule.scope.session_id() {
82        Some(_) => "this session",
83        None => "every session",
84    };
85    let label = redact(&rule.label);
86    match &rule.decision {
87        StandingDecision::Allow => format!("- [{number}] allow {label} ({scope})"),
88        StandingDecision::Deny { reason } => {
89            let mut reason: String = redact(reason).chars().take(DIGEST_REASON_CHARS).collect();
90            if reason.chars().count() == DIGEST_REASON_CHARS {
91                reason.push('…');
92            }
93            format!("- [{number}] deny {label} ({scope}): \"{reason}\"")
94        }
95    }
96}
97
98/// `text` with secrets replaced: the web screen's patterns where compiled, and any
99/// whitespace-free token of 24 or more letters and digits otherwise.
100fn redact(text: &str) -> String {
101    #[cfg(feature = "web")]
102    let text = crate::web::redact_secrets(text).0;
103    #[cfg(not(feature = "web"))]
104    let text = text.to_string();
105    text.split(' ')
106        .map(|word| {
107            let alnum = word.chars().filter(char::is_ascii_alphanumeric).count();
108            if alnum >= 24
109                && word.chars().any(|c| c.is_ascii_digit())
110                && word.chars().any(|c| c.is_ascii_alphabetic())
111            {
112                "[redacted]".to_string()
113            } else {
114                word.to_string()
115            }
116        })
117        .collect::<Vec<_>>()
118        .join(" ")
119}
120
121/// Harness work that runs before each model request, ahead of the reminders: identity
122/// observation (spec 3.1 §9.2 I6) and the loop guard (§7.13).
123#[async_trait]
124pub(crate) trait RequestObserver: Send + Sync {
125    /// Observes `ctx` before its next model request; an error ends the turn.
126    async fn before_request(
127        &self,
128        ctx: &Arc<dyn ReadonlyContext>,
129        request: &mut LlmRequest,
130    ) -> Result<()>;
131}
132
133/// The harness tools as one [`Toolset`] (spec 3.1 §7.1).
134///
135/// The tool list is fixed for the agent's lifetime — `exit_plan_mode` is declared in
136/// every mode — so the tool surface and the provider's prompt cache stay stable; the
137/// policy decides what each mode allows. [`process_llm_request`](Toolset::process_llm_request)
138/// appends a one-line mode banner to every request and a reminder of the open todos when
139/// the list changed, at the end of the request, keeping the cached prefix stable
140/// (spec 3.1 §7.6, §7.7). The harness's toolset also sets the request's
141/// [`GenerateContentConfig::effort`](adk_core::GenerateContentConfig::effort) to the
142/// [`EffortPolicy`](crate::EffortPolicy) level of the mode it reads, and a member's to
143/// `members` (spec 3.1 §7.23).
144///
145/// # Example
146///
147/// ```rust,ignore
148/// let names = harness.runtime().toolset().tool_names();
149/// assert!(names.contains(&"exit_plan_mode".to_string()));
150/// ```
151pub struct HarnessToolset {
152    tools: Vec<Arc<dyn Tool>>,
153    mode_store: Arc<dyn ModeStore>,
154    default_mode: HarnessMode,
155    reminded: Mutex<HashMap<String, u64>>,
156    observers: Vec<Arc<dyn RequestObserver>>,
157    /// The standing-rules digest of the reminder (spec 3.1 §7.25).
158    rules: Option<RulesDigest>,
159    /// The effort each request carries (spec 3.1 §7.23); `None` leaves requests as they are.
160    effort: Option<crate::posture::EffortPolicy>,
161    /// A team member's toolset, whose requests run at `members` rather than the mode's level.
162    member: bool,
163    /// The line that tells the model what its mode allows.
164    banner: fn(HarnessMode) -> String,
165    #[cfg(feature = "memory")]
166    facts: Option<Arc<crate::facts::runtime::FactsRuntime>>,
167    /// The session containers of the container shell, stopped when the toolset closes
168    /// (spec 3.1 §7.9 "Container").
169    #[cfg(any(feature = "docker", feature = "remote-shell"))]
170    containers: Option<Arc<crate::shell::ContainerPool>>,
171    /// Background shells: named in the reminder when they end, killed when the toolset
172    /// closes (spec 3.1 §7.29).
173    shells: Option<Arc<crate::shell::ShellSupervisor>>,
174}
175
176impl HarnessToolset {
177    pub(crate) fn new(
178        tools: Vec<Arc<dyn Tool>>,
179        mode_store: Arc<dyn ModeStore>,
180        default_mode: HarnessMode,
181    ) -> Self {
182        Self {
183            tools,
184            mode_store,
185            default_mode,
186            reminded: Mutex::new(HashMap::new()),
187            observers: Vec::new(),
188            rules: None,
189            effort: None,
190            member: false,
191            banner: mode_banner,
192            #[cfg(feature = "memory")]
193            facts: None,
194            #[cfg(any(feature = "docker", feature = "remote-shell"))]
195            containers: None,
196            shells: None,
197        }
198    }
199
200    /// Names the session's ended background shells in each reminder and kills every shell
201    /// when the toolset closes (spec 3.1 §7.29).
202    pub(crate) fn with_shells(mut self, shells: Arc<crate::shell::ShellSupervisor>) -> Self {
203        self.shells = Some(shells);
204        self
205    }
206
207    /// The background shells, when the harness has a shell.
208    pub fn shells(&self) -> Option<&Arc<crate::shell::ShellSupervisor>> {
209        self.shells.as_ref()
210    }
211
212    /// Stops the container shell's session containers when the toolset closes.
213    #[cfg(any(feature = "docker", feature = "remote-shell"))]
214    pub(crate) fn with_containers(mut self, containers: Arc<crate::shell::ContainerPool>) -> Self {
215        self.containers = Some(containers);
216        self
217    }
218
219    /// Recalls long-term facts into each user turn (spec 3.1 §7.15.2).
220    #[cfg(feature = "memory")]
221    pub(crate) fn with_facts(mut self, facts: Arc<crate::facts::runtime::FactsRuntime>) -> Self {
222        self.facts = Some(facts);
223        self
224    }
225
226    /// The harness's long-term memory, when on.
227    #[cfg(feature = "memory")]
228    pub(crate) fn facts(&self) -> Option<&Arc<crate::facts::runtime::FactsRuntime>> {
229        self.facts.as_ref()
230    }
231
232    /// The origin of the tool named `name`, as a call to it records it.
233    pub(crate) fn origin_of(&self, name: &str) -> Option<ToolOrigin> {
234        self.tools.iter().find(|tool| tool.name() == name).map(|tool| ToolOrigin::of(tool.as_ref()))
235    }
236
237    /// Lists the standing rules that apply to the session in every request's reminder
238    /// (spec 3.1 §7.25): rules of `store` that a call of this toolset's tools can match.
239    pub(crate) fn with_rules_digest(mut self, store: Arc<dyn StandingRuleStore>) -> Self {
240        let origins = self
241            .tools
242            .iter()
243            .map(|tool| (tool.name().to_string(), ToolOrigin::of(tool.as_ref())))
244            .collect();
245        self.rules = Some(RulesDigest { store, origins });
246        self
247    }
248
249    /// Sets each request's effort from `policy` (spec 3.1 §7.23): the level of the mode the
250    /// request reads, or `members` on a team member's toolset.
251    pub(crate) fn with_effort(mut self, policy: crate::posture::EffortPolicy) -> Self {
252        self.effort = Some(policy);
253        self
254    }
255
256    /// Adds work to run before each model request, in order; a team member gets its
257    /// coordinator's (spec 3.1 §7.10).
258    pub(crate) fn with_observers(mut self, observers: &[Arc<dyn RequestObserver>]) -> Self {
259        self.observers.extend(observers.iter().cloned());
260        self
261    }
262
263    /// The toolset of a team member (spec 3.1 §7.10): `tools` without `exit_plan_mode`,
264    /// `memory_write`, `memory_delete`, `memory_search`, `memory_remember` or any agent
265    /// delegation, so a member can neither change the mode nor delegate further, and
266    /// neither recalls nor writes long-term facts (§9.2 I42). The member reads the parent's mode, because it
267    /// shares the parent's (app, user, session).
268    ///
269    /// # Example
270    ///
271    /// ```rust
272    /// use adk_harness::{HarnessMode, HarnessToolset, InMemoryModeStore};
273    /// use std::sync::Arc;
274    ///
275    /// let plan_exit = Arc::new(adk_harness::ExitPlanModeTool::new(
276    ///     Arc::new(InMemoryModeStore::new()),
277    ///     HarnessMode::Ask,
278    /// ));
279    /// let toolset = HarnessToolset::member(
280    ///     vec![plan_exit],
281    ///     Arc::new(InMemoryModeStore::new()),
282    ///     HarnessMode::Ask,
283    /// );
284    /// assert!(toolset.tool_names().is_empty());
285    /// ```
286    pub fn member(
287        tools: Vec<Arc<dyn Tool>>,
288        mode_store: Arc<dyn ModeStore>,
289        default_mode: HarnessMode,
290    ) -> Self {
291        let tools = tools
292            .into_iter()
293            .filter(|tool| {
294                !matches!(
295                    tool.name(),
296                    "exit_plan_mode"
297                        | "memory_write"
298                        | "memory_delete"
299                        | "memory_search"
300                        | "memory_remember"
301                ) && !tool.is_agent_delegation()
302            })
303            .collect();
304        Self { member: true, ..Self::new(tools, mode_store, default_mode) }
305    }
306
307    /// Tells the model what its mode allows with `banner` instead of the harness's own
308    /// (the website preset's, spec 3.5 §7.11).
309    #[must_use]
310    pub(crate) fn with_banner(mut self, banner: fn(HarnessMode) -> String) -> Self {
311        self.banner = banner;
312        self
313    }
314
315    /// Names of the tools, in declaration order.
316    pub fn tool_names(&self) -> Vec<String> {
317        self.tools.iter().map(|tool| tool.name().to_string()).collect()
318    }
319
320    /// The tools, in declaration order, for a surface that registers them with a runtime
321    /// of its own (the voice surface, spec 3.1 §7.17).
322    pub fn all_tools(&self) -> Vec<Arc<dyn Tool>> {
323        self.tools.clone()
324    }
325}
326
327/// The one-line banner describing what `mode` allows.
328pub(crate) fn mode_banner(mode: HarnessMode) -> String {
329    let rule = match mode {
330        HarnessMode::ReadOnly => "read-only: read and keep todos",
331        HarnessMode::Plan => {
332            "plan: investigate, then present a plan with exit_plan_mode and end your turn"
333        }
334        HarnessMode::Ask => {
335            "ask: call the tools you need directly; when a call needs approval the harness asks \
336             the user, so do not ask for permission in your reply or wait for a go-ahead, and \
337             do not call exit_plan_mode"
338        }
339        HarnessMode::Auto => "auto: call the tools you need directly",
340    };
341    format!(
342        "Harness mode is {rule}. The <harness> block's class lines say which calls run, ask or \
343         are refused in this mode."
344    )
345}
346
347/// The website preset's banner (spec 3.5 §7.11): the mode is the agent's jobs' autonomy
348/// level, set by the charter and raised only by the owner, so the agent never asks to leave
349/// it; at Propose it drafts, and drafts run in plan mode.
350pub(crate) fn website_banner(mode: HarnessMode) -> String {
351    let rule = match mode {
352        HarnessMode::ReadOnly => "read-only: read and report; nothing changes",
353        HarnessMode::Plan => {
354            "propose: draft every change with the drafting tools (content_draft, content_edit, \
355             translation_draft, media_intake, charter_draft) and raise decision cards; drafts \
356             and cards run in this mode, and nothing goes live until the owner approves it"
357        }
358        HarnessMode::Ask => {
359            "act with approval: call the tools you need directly; a call that needs the owner is \
360             held as a decision card, so do not ask for permission in your reply"
361        }
362        HarnessMode::Auto => {
363            "act: call the tools you need directly; a call beyond your authority is held for \
364             the owner"
365        }
366    };
367    format!(
368        "Your mode is {rule}. Your jobs' autonomy levels set the mode and only the owner raises \
369         them, so never ask to leave it. The <harness> block's class lines say which calls run, \
370         ask or are refused in this mode."
371    )
372}
373
374fn todo_reminder(list: &TodoList) -> String {
375    let open: Vec<String> = list
376        .open_items()
377        .map(|item| {
378            format!(
379                "- [{}] {}: {}",
380                serde_json::to_value(item.status)
381                    .ok()
382                    .and_then(|v| v.as_str().map(String::from))
383                    .unwrap_or_default(),
384                item.id,
385                item.content
386            )
387        })
388        .collect();
389    if open.is_empty() {
390        "All todos are complete.".to_string()
391    } else {
392        format!("Open todos (revision {}):\n{}", list.revision, open.join("\n"))
393    }
394}
395
396#[async_trait]
397impl Toolset for HarnessToolset {
398    fn name(&self) -> &str {
399        "harness"
400    }
401
402    async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
403        Ok(self.tools.clone())
404    }
405
406    /// Kills every background shell (spec 3.1 §7.29) and stops every session container of
407    /// the container shell (`Harness::close` reaches it through `Runner::close`, spec 3.1
408    /// §7.9).
409    async fn close(&self) {
410        if let Some(shells) = &self.shells {
411            shells.close().await;
412        }
413        #[cfg(any(feature = "docker", feature = "remote-shell"))]
414        if let Some(containers) = &self.containers {
415            containers.close().await;
416        }
417    }
418
419    async fn process_llm_request(
420        &self,
421        ctx: Arc<dyn ReadonlyContext>,
422        request: &mut LlmRequest,
423    ) -> Result<()> {
424        for observer in &self.observers {
425            observer.before_request(&ctx, request).await?;
426        }
427        #[cfg(feature = "memory")]
428        if let Some(facts) = &self.facts {
429            facts.before_request(&ctx, request).await?;
430        }
431        let mode = match self.mode_store.get(ctx.app_name(), ctx.user_id(), ctx.session_id()).await
432        {
433            Ok(Some(record)) => record.mode_for_invocation(ctx.invocation_id()),
434            Ok(None) => self.default_mode,
435            Err(_) => HarnessMode::ReadOnly,
436        };
437        // The effort travels in the request's config, never in its contents, so the prefix
438        // stays byte-stable when the mode changes (spec 3.1 §7.23, I56).
439        if let Some(policy) = &self.effort {
440            let level = if self.member { policy.members } else { policy.for_mode(mode) };
441            request.config.get_or_insert_with(Default::default).effort = Some(level);
442        }
443        let mut lines = vec![(self.banner)(mode)];
444        // Rules change mid-session: the digest is rebuilt for every request and never
445        // saved, so it stays out of the cached prefix (spec 3.1 §7.25, I56).
446        if let Some(digest) = &self.rules
447            && let Some(text) = digest.render(ctx.app_name(), ctx.user_id(), ctx.session_id()).await
448        {
449            lines.push(text);
450        }
451        if let Some(shells) = &self.shells
452            && let Some(text) =
453                shells.notices(ctx.app_name(), ctx.user_id(), ctx.session_id()).await
454        {
455            lines.push(text);
456        }
457        if let Some(list) = ctx.state().map(TodoList::from_state)
458            && list.revision > 0
459        {
460            let key = format!("{}\u{1f}{}", ctx.session_id(), ctx.agent_name());
461            let mut reminded = self.reminded.lock().unwrap_or_else(|e| e.into_inner());
462            if reminded.len() > 4096 {
463                reminded.clear();
464            }
465            if reminded.get(&key) != Some(&list.revision) {
466                reminded.insert(key, list.revision);
467                lines.push(todo_reminder(&list));
468            }
469        }
470        request.contents.push(
471            Content::new("user")
472                .with_text(format!("<system-reminder>\n{}\n</system-reminder>", lines.join("\n"))),
473        );
474        Ok(())
475    }
476}