1use 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
14const DIGEST_MAX_RULES: usize = 20;
16const DIGEST_MAX_BYTES: usize = 1024;
18const DIGEST_REASON_CHARS: usize = 80;
20
21struct RulesDigest {
24 store: Arc<dyn StandingRuleStore>,
25 origins: Vec<(String, ToolOrigin)>,
28}
29
30impl RulesDigest {
31 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 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
78fn 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
98fn 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#[async_trait]
124pub(crate) trait RequestObserver: Send + Sync {
125 async fn before_request(
127 &self,
128 ctx: &Arc<dyn ReadonlyContext>,
129 request: &mut LlmRequest,
130 ) -> Result<()>;
131}
132
133pub 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 rules: Option<RulesDigest>,
159 effort: Option<crate::posture::EffortPolicy>,
161 member: bool,
163 banner: fn(HarnessMode) -> String,
165 #[cfg(feature = "memory")]
166 facts: Option<Arc<crate::facts::runtime::FactsRuntime>>,
167 #[cfg(any(feature = "docker", feature = "remote-shell"))]
170 containers: Option<Arc<crate::shell::ContainerPool>>,
171 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 pub(crate) fn with_shells(mut self, shells: Arc<crate::shell::ShellSupervisor>) -> Self {
203 self.shells = Some(shells);
204 self
205 }
206
207 pub fn shells(&self) -> Option<&Arc<crate::shell::ShellSupervisor>> {
209 self.shells.as_ref()
210 }
211
212 #[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 #[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 #[cfg(feature = "memory")]
228 pub(crate) fn facts(&self) -> Option<&Arc<crate::facts::runtime::FactsRuntime>> {
229 self.facts.as_ref()
230 }
231
232 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 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 pub(crate) fn with_effort(mut self, policy: crate::posture::EffortPolicy) -> Self {
252 self.effort = Some(policy);
253 self
254 }
255
256 pub(crate) fn with_observers(mut self, observers: &[Arc<dyn RequestObserver>]) -> Self {
259 self.observers.extend(observers.iter().cloned());
260 self
261 }
262
263 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 #[must_use]
310 pub(crate) fn with_banner(mut self, banner: fn(HarnessMode) -> String) -> Self {
311 self.banner = banner;
312 self
313 }
314
315 pub fn tool_names(&self) -> Vec<String> {
317 self.tools.iter().map(|tool| tool.name().to_string()).collect()
318 }
319
320 pub fn all_tools(&self) -> Vec<Arc<dyn Tool>> {
323 self.tools.clone()
324 }
325}
326
327pub(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
347pub(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 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 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 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}