adk_harness/harness.rs
1//! `Harness`: a harness agent with its own `Runner` (spec 3.1 §7.3, feature `runner`).
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use adk_core::audit_log::AuditActor;
7use adk_core::principal::{SubjectKind, SubjectRef};
8use adk_core::{
9 AdkError, ApprovalScope, Content, ErrorCategory, ErrorComponent, Event, EventStream,
10 FunctionResponseData, Part, PendingApproval, RequestContext, RequestedCall, Result, RunConfig,
11 SessionId, ToolApproval, UserId, held_tool_calls,
12};
13use adk_runner::Runner;
14use adk_session::{CreateRequest, GetRequest, SessionService};
15use serde_json::{Value, json};
16
17use crate::agent::HarnessAgent;
18use crate::approvals::{
19 RuleOwner, RuleSuggestion, StandingDecision, StandingRuleStore, rule_audit_fields,
20};
21use crate::audit::HarnessAudit;
22use crate::goal::{GOAL_STATE_KEY, GOAL_TARGET, GoalSpec, GoalState};
23
24/// The queue durable goals go to unless [`Harness::with_goal_queue`] names another.
25const DEFAULT_GOAL_QUEUE: &str = "default";
26use crate::instructions::{TrustDecision, WorkspaceTrust};
27use crate::mode::{HarnessMode, MODE_STATE_KEY, ModeChange, ModeSource, write_mode_change};
28use crate::tools::{TODOS_STATE_KEY, TodoList};
29
30/// Status of the response that cancels a held call on a mode loosening (spec 3.1 §7.4).
31///
32/// # Example
33///
34/// ```rust
35/// assert_eq!(adk_harness::CANCELLED_BY_MODE_CHANGE_STATUS, "cancelled_by_mode_change");
36/// ```
37pub const CANCELLED_BY_MODE_CHANGE_STATUS: &str = "cancelled_by_mode_change";
38
39/// What closing the harness could not finish (spec 3.1 §7.15.2).
40///
41/// # Example
42///
43/// ```rust
44/// let report = adk_harness::CloseReport::default();
45/// assert!(report.distillation_failures.is_empty());
46/// ```
47#[derive(Debug, Default)]
48pub struct CloseReport {
49 /// Sessions whose turns were not distilled into long-term memory, by session id, with
50 /// the error.
51 pub distillation_failures: Vec<(String, AdkError)>,
52}
53
54/// A person's decision on a pending call, through [`Harness::decide`] (spec 3.1 §7.3).
55///
56/// # Example
57///
58/// ```rust
59/// use adk_harness::HarnessDecision;
60///
61/// let decision = HarnessDecision::Deny { message: Some("not on main".into()) };
62/// # let _ = decision;
63/// ```
64#[derive(Clone, Debug, PartialEq)]
65pub enum HarnessDecision {
66 /// Run the call once.
67 Approve,
68 /// Run the call once with these arguments; the policy checks them again.
69 ApproveWithArgs(Value),
70 /// Run the call once and remember the rule.
71 ApproveAndRemember(RuleSuggestion),
72 /// Do not run the call.
73 Deny {
74 /// Reported to the model.
75 message: Option<String>,
76 },
77 /// Do not run the call and remember a Deny rule.
78 DenyAndRemember(RuleSuggestion),
79}
80
81/// A harness agent with the `Runner` that serves it (spec 3.1 §7.3).
82///
83/// `Runner::run` never creates a session, hence [`open_session`](Self::open_session).
84///
85/// # Example
86///
87/// ```rust,ignore
88/// let harness = HarnessAgent::builder("harness").model(model).workspace(ws).build()?
89/// .into_harness("adk-rust", Arc::new(InMemorySessionService::new()))?;
90/// let session = harness.open_session(&user, None).await?;
91/// let events = harness.send(&user, &session, "fix the failing test").await?;
92/// ```
93pub struct Harness {
94 runner: Arc<Runner>,
95 agent: Arc<HarnessAgent>,
96 sessions: Arc<dyn SessionService>,
97 app_name: String,
98 run_store: Option<Arc<dyn adk_core::DurableRunStore>>,
99 goal_queue: String,
100 goals_authenticated: bool,
101}
102
103impl std::fmt::Debug for Harness {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.debug_struct("Harness")
106 .field("app_name", &self.app_name)
107 .field("agent", &self.agent)
108 .finish()
109 }
110}
111
112/// The note `Harness::decide` withdraws a call's inbox requests with. Under a kernel the
113/// withdrawal wakes nothing; the person's decision is reported once it is recorded
114/// (spec 3.3 §7.3).
115pub(crate) const DECIDED_IN_THE_HARNESS: &str = "decided in the harness";
116
117fn store_error(message: impl Into<String>) -> AdkError {
118 AdkError::new(
119 ErrorComponent::Agent,
120 ErrorCategory::InvalidInput,
121 "harness.decision.invalid",
122 message,
123 )
124}
125
126/// A call [`Harness::decide`] is recording a decision for: its approval store, by address,
127/// its scope and its fingerprint.
128type DecidingKey = (usize, ApprovalScope, String);
129
130/// The calls being decided in this process. The approval store's decision write is not
131/// conditional, so two decisions for one call that both found it pending would both be
132/// written; the second is refused instead (spec 3.3 §7.3, §11 S-I2).
133static DECIDING: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<DecidingKey>>> =
134 std::sync::LazyLock::new(Default::default);
135
136/// Holds a call in [`DECIDING`] until the decision is recorded or refused.
137struct Deciding(DecidingKey);
138
139impl Deciding {
140 fn claim(key: DecidingKey) -> Result<Self> {
141 let mut deciding = DECIDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
142 if !deciding.insert(key.clone()) {
143 return Err(store_error(
144 "another decision for this call is being recorded; the first one stands",
145 ));
146 }
147 Ok(Self(key))
148 }
149}
150
151impl Drop for Deciding {
152 fn drop(&mut self) {
153 DECIDING.lock().unwrap_or_else(std::sync::PoisonError::into_inner).remove(&self.0);
154 }
155}
156
157impl Harness {
158 pub(crate) fn new(
159 agent: Arc<HarnessAgent>,
160 app_name: String,
161 sessions: Arc<dyn SessionService>,
162 ) -> Result<Self> {
163 let builder = Runner::builder()
164 .app_name(app_name.clone())
165 .agent(agent.clone())
166 .session_service(sessions.clone());
167 let builder = agent.configure_runner(builder);
168 // Every agent of a partition's harness carries its class and tenant (spec 3.2 §7.8).
169 #[cfg(feature = "kernel")]
170 let builder = match agent.partition() {
171 Some(partition) => builder.identity_source(
172 partition.identity_source(&app_name, adk_core::Agent::name(agent.as_ref())),
173 ),
174 None => builder,
175 };
176 let runner = builder.build()?;
177 #[cfg(feature = "memory")]
178 attach_facts(&agent, &runner, &sessions, &app_name);
179 Ok(Self {
180 runner: Arc::new(runner),
181 agent,
182 sessions,
183 app_name,
184 run_store: None,
185 goal_queue: DEFAULT_GOAL_QUEUE.to_string(),
186 goals_authenticated: false,
187 })
188 }
189
190 /// Wraps a runner built for `agent`, for callers that configure the runner themselves —
191 /// for example to attach a signed audit log with `RunnerConfigBuilder::audit_log`.
192 /// Build it with [`HarnessAgent::configure_runner`] and `agent` as its root.
193 ///
194 /// # Example
195 ///
196 /// ```rust,ignore
197 /// let agent = Arc::new(harness_agent);
198 /// let runner = agent
199 /// .configure_runner(Runner::builder().app_name("adk-rust").agent(agent.clone()).session_service(sessions))
200 /// .audit_log(Arc::new(log))
201 /// .build()?;
202 /// let harness = Harness::with_runner(agent, runner)?;
203 /// ```
204 ///
205 /// # Errors
206 ///
207 /// Returns a configuration error when the runner's root agent is not `agent`.
208 pub fn with_runner(agent: Arc<HarnessAgent>, runner: Runner) -> Result<Self> {
209 if runner.root_agent_name() != adk_core::Agent::name(agent.as_ref()) {
210 return Err(AdkError::config(
211 "Harness::with_runner needs a runner whose root agent is the harness agent",
212 ));
213 }
214 let sessions = runner.session_service().clone();
215 let app_name = runner.app_name().to_string();
216 #[cfg(feature = "memory")]
217 attach_facts(&agent, &runner, &sessions, &app_name);
218 Ok(Self {
219 runner: Arc::new(runner),
220 agent,
221 sessions,
222 app_name,
223 run_store: None,
224 goal_queue: DEFAULT_GOAL_QUEUE.to_string(),
225 goals_authenticated: false,
226 })
227 }
228
229 /// The harness agent.
230 pub fn agent(&self) -> &Arc<HarnessAgent> {
231 &self.agent
232 }
233
234 /// The application name.
235 pub fn app_name(&self) -> &str {
236 &self.app_name
237 }
238
239 /// Opens `session` for `user`, creating it when it does not exist, or a new session.
240 ///
241 /// # Errors
242 ///
243 /// Returns the session service's error.
244 pub async fn open_session(
245 &self,
246 user: &UserId,
247 session: Option<&SessionId>,
248 ) -> Result<SessionId> {
249 if let Some(session) = session {
250 match self
251 .sessions
252 .get(GetRequest {
253 app_name: self.app_name.clone(),
254 user_id: user.to_string(),
255 session_id: session.to_string(),
256 num_recent_events: Some(1),
257 after: None,
258 })
259 .await
260 {
261 Ok(_) => return Ok(session.clone()),
262 Err(error) if error.is_not_found() => {}
263 Err(error) => return Err(error),
264 }
265 }
266 let created = self
267 .sessions
268 .create(CreateRequest {
269 app_name: self.app_name.clone(),
270 user_id: user.to_string(),
271 session_id: session.map(ToString::to_string),
272 state: HashMap::new(),
273 })
274 .await?;
275 Ok(SessionId::try_from(created.id().to_string())?)
276 }
277
278 /// Enqueues goals as durable runs in `store` (spec 3.1 §7.11): [`start_goal`] then
279 /// writes the goal state and enqueues a run of target [`GOAL_TARGET`] for a
280 /// `DurableWorker` serving [`goal_target`]; a held call parks the run until a decision
281 /// wakes it. Long-term memory on a harness that requires authenticated identity reads
282 /// the store too: a session that ran in an earlier process is distilled only when its
283 /// latest run was authenticated (I42).
284 ///
285 /// [`start_goal`]: Self::start_goal
286 /// [`goal_target`]: Self::goal_target
287 ///
288 /// # Example
289 ///
290 /// ```rust,ignore
291 /// let runs: Arc<dyn adk_core::DurableRunStore> = Arc::new(adk_core::InMemoryRunStore::new());
292 /// let harness = harness.with_run_store(runs.clone());
293 /// let (target, runner) = harness.goal_target();
294 /// let worker = adk_server::background::DurableWorker::new(runs).with_agent(target, runner).spawn();
295 /// ```
296 pub fn with_run_store(mut self, store: Arc<dyn adk_core::DurableRunStore>) -> Self {
297 #[cfg(feature = "memory")]
298 if let Ok(facts) = self.facts_runtime() {
299 *facts.runs.lock().unwrap_or_else(|e| e.into_inner()) = Some(store.clone());
300 }
301 self.run_store = Some(store);
302 self
303 }
304
305 /// Enqueues durable goals on `queue` instead of `default` (spec 3.1 §7.11), so a
306 /// `DurableWorker` claiming from it runs goals only and the store's other runs stay
307 /// with their own workers — for example [`GOAL_QUEUE`](crate::GOAL_QUEUE) beside a
308 /// server's background runs on one store.
309 ///
310 /// # Example
311 ///
312 /// ```rust,ignore
313 /// let harness = harness.with_run_store(runs.clone()).with_goal_queue(adk_harness::GOAL_QUEUE);
314 /// let (target, runner) = harness.goal_target();
315 /// let worker = DurableWorker::new(runs)
316 /// .with_agent(target, runner)
317 /// .with_config(DurableWorkerConfig::default().with_queue(harness.goal_queue()))
318 /// .spawn();
319 /// ```
320 pub fn with_goal_queue(mut self, queue: impl Into<String>) -> Self {
321 self.goal_queue = queue.into();
322 self
323 }
324
325 /// The queue durable goals are enqueued on (default `default`).
326 pub fn goal_queue(&self) -> &str {
327 &self.goal_queue
328 }
329
330 /// Enqueues durable goals as runs of an authenticated user (spec 3.1 §9.2 I6), so the
331 /// worker that runs them applies the session's mode and the user's standing rules. For a
332 /// host that established who the user is, such as a terminal of the machine whose kernel
333 /// runs the goal; without it, a harness that requires authenticated identity decides the
334 /// goal's calls with Auto as Ask and no standing rule.
335 ///
336 /// # Example
337 ///
338 /// ```rust,ignore
339 /// let harness = harness
340 /// .with_run_store(runs)
341 /// .with_goal_queue(adk_kernel::QueueClass::BACKGROUND)
342 /// .with_authenticated_goals();
343 /// ```
344 #[must_use]
345 pub fn with_authenticated_goals(mut self) -> Self {
346 self.goals_authenticated = true;
347 self
348 }
349
350 /// Answers, from the action ledger, the calls a stopped process left without a response,
351 /// so a turn after a crash never runs a completed call again (spec 3.1 §7.12, I37).
352 async fn recover(&self, user: &UserId, session: &SessionId) -> Result<()> {
353 if self.runner.active_session_ids().iter().any(|active| active == session.as_ref()) {
354 return Ok(());
355 }
356 let answered =
357 self.runner.recover_unanswered_calls(user.as_ref(), session.as_ref()).await?;
358 if answered > 0 {
359 tracing::info!(session.id = %session, calls.answered = answered, "recovered calls a stopped run left unanswered");
360 }
361 Ok(())
362 }
363
364 /// Sends a user message and returns the turn's events.
365 ///
366 /// Held calls stranded by a run that ended before saving their result are settled
367 /// first (see [`resume`](Self::resume)).
368 ///
369 /// # Errors
370 ///
371 /// Returns an error when the run cannot start, or the approval store's or the action
372 /// ledger's error.
373 pub async fn send(
374 &self,
375 user: &UserId,
376 session: &SessionId,
377 text: impl Into<String>,
378 ) -> Result<EventStream> {
379 self.turn(user, session, Content::new("user").with_text(text.into()), None).await
380 }
381
382 /// [`send`](Self::send) as the caller `context` authenticates (spec 3.3 §6): the run
383 /// carries `context`, so the session's mode and standing rules apply as they do to a
384 /// request a server admitted. `context` names `user`.
385 ///
386 /// # Example
387 ///
388 /// ```rust,no_run
389 /// use adk_core::{RequestContext, SessionId, UserId};
390 /// use adk_harness::Harness;
391 ///
392 /// # async fn example(harness: Harness, user: UserId, session: SessionId) -> adk_core::Result<()> {
393 /// // The caller the server admitted for `user`.
394 /// let context = RequestContext {
395 /// user_id: user.to_string(),
396 /// scopes: vec!["operator".into()],
397 /// metadata: Default::default(),
398 /// };
399 /// let events = harness.send_as(&user, &session, "create note.txt", context).await?;
400 /// # let _ = events;
401 /// # Ok(())
402 /// # }
403 /// ```
404 ///
405 /// # Errors
406 ///
407 /// As [`send`](Self::send); the run fails with `identity.subject_mismatch` when `context`
408 /// names another user.
409 pub async fn send_as(
410 &self,
411 user: &UserId,
412 session: &SessionId,
413 text: impl Into<String>,
414 context: RequestContext,
415 ) -> Result<EventStream> {
416 self.turn(user, session, Content::new("user").with_text(text.into()), Some(context)).await
417 }
418
419 /// [`send_as`](Self::send_as) with a whole message: text and images the person sent
420 /// with it (spec 3.3 §5.1), such as a screenshot. `content` is a `user` turn; any other
421 /// role is refused.
422 ///
423 /// # Example
424 ///
425 /// ```rust,no_run
426 /// use adk_core::{Content, RequestContext, SessionId, UserId};
427 /// use adk_harness::Harness;
428 ///
429 /// # async fn example(harness: Harness, user: UserId, session: SessionId, png: Vec<u8>) -> adk_core::Result<()> {
430 /// let context = RequestContext { user_id: user.to_string(), scopes: Vec::new(), metadata: Default::default() };
431 /// let message = Content::new("user").with_text("Why does CI fail like this?").with_inline_data("image/png", png);
432 /// let events = harness.send_content_as(&user, &session, message, context).await?;
433 /// # let _ = events;
434 /// # Ok(())
435 /// # }
436 /// ```
437 ///
438 /// # Errors
439 ///
440 /// As [`send_as`](Self::send_as), and an invalid-input error for a turn whose role is not
441 /// `user`.
442 pub async fn send_content_as(
443 &self,
444 user: &UserId,
445 session: &SessionId,
446 content: Content,
447 context: RequestContext,
448 ) -> Result<EventStream> {
449 if content.role != "user" {
450 return Err(AdkError::new(
451 ErrorComponent::Agent,
452 ErrorCategory::InvalidInput,
453 "harness.send.role",
454 "a person's message is a user turn",
455 ));
456 }
457 self.turn(user, session, content, Some(context)).await
458 }
459
460 /// Sends `call`, a call the person `context` authenticates asked for through something
461 /// the agent drew, such as a form's Send, with `text` as their message (spec 3.3 §7.4
462 /// rule 5, wave 4 decision 13). It serves hosts without a kernel; a kernel host sends the
463 /// call through the agent's durable runs.
464 ///
465 /// The press is the request, never the approval. The agent holds the call for the
466 /// person's decision as itself, under its own mode, standing rules, acting context and
467 /// approval store — or refuses it — and the run ends without a model call: Go ahead, a
468 /// standing rule that allows the tool, an earlier approval of the identical call and the
469 /// approval prompt all leave it waiting. [`decide`](Self::decide), then
470 /// [`resume_as`](Self::resume_as), runs it once.
471 ///
472 /// # Example
473 ///
474 /// ```rust,no_run
475 /// use adk_core::{RequestContext, RequestedCall, RequestedVia, SessionId, SubjectRef, UserId};
476 /// use adk_harness::Harness;
477 /// use serde_json::json;
478 ///
479 /// # async fn example(harness: Harness, user: UserId, session: SessionId) -> adk_core::Result<()> {
480 /// let context = RequestContext {
481 /// user_id: user.to_string(),
482 /// scopes: Vec::new(),
483 /// metadata: Default::default(),
484 /// };
485 /// let call = RequestedCall::new(
486 /// "send_invoice",
487 /// json!({ "to": "ana@example.com", "amount": 4200, "invoice": "INV-10" }),
488 /// SubjectRef::human(user.to_string()),
489 /// RequestedVia::form("invoice-10", 1, "send"),
490 /// );
491 /// let events = harness.send_requested(&user, &session, "", call, context).await?;
492 /// # let _ = events;
493 /// # Ok(())
494 /// # }
495 /// ```
496 ///
497 /// # Errors
498 ///
499 /// As [`send_as`](Self::send_as).
500 pub async fn send_requested(
501 &self,
502 user: &UserId,
503 session: &SessionId,
504 text: impl Into<String>,
505 call: RequestedCall,
506 context: RequestContext,
507 ) -> Result<EventStream> {
508 self.settle_stranded_calls(user, session).await?;
509 self.recover(user, session).await?;
510 let config = RunConfig {
511 request_context: Some(context),
512 requested_call: Some(call),
513 ..self.runner.run_config().clone()
514 };
515 let content = Content::new("user").with_text(text.into());
516 self.runner.run_with_config(user.clone(), session.clone(), content, Some(config)).await
517 }
518
519 /// Runs an empty turn, which resumes held calls that now have a decision.
520 ///
521 /// A held call whose approval a run consumed but whose result that run never saved —
522 /// the process stopped in between — has no decision and no pending entry, so no run
523 /// would resume it. It is settled first (spec 3.1 §7.12, §9.2 I37): when the action
524 /// ledger records it, it ran, and its record answers it as the agent answers a
525 /// re-issued call, without running it again; otherwise it never began, and without a
526 /// live confirmation handler it is held again for [`pending_approvals`](Self::pending_approvals).
527 ///
528 /// # Errors
529 ///
530 /// Returns an error when the run cannot start, or the approval store's or the action
531 /// ledger's error.
532 pub async fn resume(&self, user: &UserId, session: &SessionId) -> Result<EventStream> {
533 self.turn(user, session, Content::new("user"), None).await
534 }
535
536 /// [`resume`](Self::resume) as the caller `context` authenticates (spec 3.3 §6), as
537 /// [`send_as`](Self::send_as) sends.
538 ///
539 /// # Errors
540 ///
541 /// As [`resume`](Self::resume); the run fails with `identity.subject_mismatch` when
542 /// `context` names another user.
543 pub async fn resume_as(
544 &self,
545 user: &UserId,
546 session: &SessionId,
547 context: RequestContext,
548 ) -> Result<EventStream> {
549 self.turn(user, session, Content::new("user"), Some(context)).await
550 }
551
552 /// A turn of `content`, settling stranded held calls first, run as `context` when given.
553 async fn turn(
554 &self,
555 user: &UserId,
556 session: &SessionId,
557 content: Content,
558 context: Option<RequestContext>,
559 ) -> Result<EventStream> {
560 self.settle_stranded_calls(user, session).await?;
561 self.recover(user, session).await?;
562 let config = context.map(|context| RunConfig {
563 request_context: Some(context),
564 ..self.runner.run_config().clone()
565 });
566 self.runner.run_with_config(user.clone(), session.clone(), content, config).await
567 }
568
569 /// Answers from the action ledger, or holds again, the session's held calls that have
570 /// neither a decision nor a pending entry (spec 3.1 §7.12).
571 async fn settle_stranded_calls(&self, user: &UserId, session: &SessionId) -> Result<()> {
572 // An active run may have taken a decision and not yet begun the call.
573 if self.runner.active_session_ids().iter().any(|active| active == session.as_ref()) {
574 return Ok(());
575 }
576 let runtime = self.agent.runtime();
577 let store = runtime.approval_store();
578 let scope =
579 ApprovalScope::new(self.app_name.clone(), user.to_string(), session.to_string());
580 let events = self.events(user, session).await?;
581 let mut holders = Vec::<(String, String)>::new();
582 for event in &events {
583 if event.actions.tool_confirmation.is_some()
584 && !holders.iter().any(|(a, b)| *a == event.author && *b == event.branch)
585 {
586 holders.push((event.author.clone(), event.branch.clone()));
587 }
588 }
589 if holders.is_empty() {
590 return Ok(());
591 }
592 let pending: Vec<String> =
593 store.pending(&scope).await?.into_iter().map(|entry| entry.fingerprint).collect();
594 let ledger = runtime.ledgers.for_run(self.runner.run_config().action_ledger.as_ref());
595 for (author, branch) in holders {
596 let mut answers = Vec::new();
597 let mut answered = Vec::<String>::new();
598 for call in held_tool_calls(&events, &author, &branch) {
599 let Some(call_id) = call.id.as_deref() else {
600 continue;
601 };
602 let fingerprint = call.request.fingerprint();
603 if pending.contains(&fingerprint)
604 || store.has_decision(&scope, &fingerprint).await?
605 {
606 continue;
607 }
608 let key = crate::ledger::held_call_key(
609 &self.app_name,
610 user.as_ref(),
611 session.as_ref(),
612 call_id,
613 &fingerprint,
614 );
615 match ledger.get(&key).await? {
616 // A delegation holding several member calls is one call: one answer.
617 Some(_) if answered.contains(&call_id.to_string()) => {}
618 Some(record) => {
619 tracing::warn!(
620 tool.name = %call.name,
621 function_call.id = %call_id,
622 "held call ran without its result being saved; answering it from the action ledger"
623 );
624 answered.push(call_id.to_string());
625 answers.push(crate::ledger::recorded_answer(
626 &call.name,
627 call.id.as_ref(),
628 &record,
629 ));
630 }
631 // No handler answers a call a person asked for, so it waits again too
632 // (spec 3.3 §7.4 rule 5).
633 None if runtime.confirmation_handler().is_none()
634 || RequestedCall::is_requested_id(call_id) =>
635 {
636 tracing::warn!(
637 tool.name = %call.name,
638 function_call.id = %call_id,
639 "held call lost its decision before it began; holding it again"
640 );
641 store.record_pending(&scope, &call.request).await?;
642 }
643 // A live handler asks the person when the next run resumes the call.
644 None => {}
645 }
646 }
647 if answers.is_empty() {
648 continue;
649 }
650 let mut event = Event::new(format!("harness-ledger-{}", uuid::Uuid::new_v4()));
651 event.author = author;
652 event.branch = branch;
653 event.llm_response.content =
654 Some(Content { role: "function".to_string(), parts: answers });
655 self.sessions.append_event(session.as_ref(), event).await?;
656 }
657 Ok(())
658 }
659
660 /// The session's current mode.
661 pub async fn mode(&self, user: &UserId, session: &SessionId) -> Result<HarnessMode> {
662 let record = self
663 .agent
664 .runtime()
665 .mode_store()
666 .get(&self.app_name, user.as_ref(), session.as_ref())
667 .await?;
668 Ok(record.map_or(self.agent.runtime().policy().default_mode(), |record| record.mode))
669 }
670
671 fn audit(&self, user: &UserId, session: &SessionId) -> Option<HarnessAudit> {
672 let trail = self.runner.audit_trail()?.clone();
673 Some(HarnessAudit::new(
674 trail,
675 AuditActor::subject(SubjectRef::new(SubjectKind::Human, user.to_string())),
676 session.to_string(),
677 ))
678 }
679
680 /// Sets the session's mode (spec 3.1 §7.4).
681 ///
682 /// Only outside a run. A loosening first answers every held call in the session with a
683 /// "cancelled by mode change" response and removes its pending entry and any decision
684 /// for it, so no call a person has not seen under the looser mode runs on the next
685 /// resume or on a later identical call (spec 3.1 §9.2 I14). A call a person asked for
686 /// through a drawn form or an app keeps waiting: no mode answers it (spec 3.3 §7.4
687 /// rule 5).
688 ///
689 /// # Errors
690 ///
691 /// Returns `harness.mode.run_active` while a run of the session is active, or the
692 /// store's error.
693 pub async fn set_mode(
694 &self,
695 user: &UserId,
696 session: &SessionId,
697 mode: HarnessMode,
698 ) -> Result<()> {
699 if self.runner.active_session_ids().iter().any(|active| active == session.as_ref()) {
700 return Err(AdkError::new(
701 ErrorComponent::Agent,
702 ErrorCategory::Conflict,
703 "harness.mode.run_active",
704 "the session has an active run; set the mode when it ends",
705 ));
706 }
707 let runtime = self.agent.runtime();
708 let current = self.mode(user, session).await?;
709 let audit = self.audit(user, session);
710 let mut cancelled = Vec::new();
711 let mut cancelled_fingerprints = Vec::new();
712 if ModeChange::between(current, mode) == ModeChange::Loosen {
713 let events = self.events(user, session).await?;
714 let mut holders = Vec::<(String, String)>::new();
715 for event in &events {
716 if event.actions.tool_confirmation.is_some()
717 && !holders.iter().any(|(a, b)| *a == event.author && *b == event.branch)
718 {
719 holders.push((event.author.clone(), event.branch.clone()));
720 }
721 }
722 for (author, branch) in holders {
723 // A call a person asked for waits for them in every mode, so a looser mode
724 // never runs it unseen (spec 3.3 §7.4 rule 5).
725 let held: Vec<_> = held_tool_calls(&events, &author, &branch)
726 .into_iter()
727 .filter(|call| !call.id.as_deref().is_some_and(RequestedCall::is_requested_id))
728 .collect();
729 if held.is_empty() {
730 continue;
731 }
732 let mut event = Event::new(format!("harness-mode-{}", uuid::Uuid::new_v4()));
733 event.author = author.clone();
734 event.branch = branch.clone();
735 // A delegation holding several member calls is one call with several
736 // requests, and a call gets exactly one response.
737 let mut answered = Vec::<String>::new();
738 event.llm_response.content = Some(Content {
739 role: "function".to_string(),
740 parts: held
741 .iter()
742 .filter(|call| match &call.id {
743 Some(id) if answered.contains(id) => false,
744 Some(id) => {
745 answered.push(id.clone());
746 true
747 }
748 None => true,
749 })
750 .map(|call| {
751 let mut part = Part::FunctionResponse {
752 function_response: FunctionResponseData::new(
753 call.name.clone(),
754 json!({
755 "error": format!("Tool '{}' was not run: cancelled by mode change to {mode}", call.name),
756 "status": CANCELLED_BY_MODE_CHANGE_STATUS,
757 }),
758 ),
759 id: call.id.clone(),
760 annotations: None,
761 };
762 part.set_tool_result_status(adk_core::ToolResultStatus::NotRun, None);
763 part
764 })
765 .collect(),
766 });
767 cancelled.extend(answered);
768 cancelled_fingerprints.extend(held.iter().map(|call| call.request.fingerprint()));
769 self.sessions.append_event(session.as_ref(), event).await?;
770 }
771 let reason = format!("cancelled by mode change to {mode}");
772 self.clear_inbox(user, session, &cancelled_fingerprints, &reason).await?;
773 if let Some(audit) = &audit
774 && !cancelled.is_empty()
775 {
776 audit
777 .record(
778 "harness.held.cancelled",
779 json!({ "callIds": cancelled, "reason": format!("mode changed from {current} to {mode}") }),
780 )
781 .await?;
782 }
783 }
784 let record = write_mode_change(
785 runtime.mode_store().as_ref(),
786 runtime.policy().default_mode(),
787 (&self.app_name, user.as_ref(), session.as_ref()),
788 mode,
789 ModeSource::User,
790 None,
791 audit.as_ref(),
792 &cancelled,
793 )
794 .await?;
795 let mut mirror = Event::new(format!("harness-mode-{}", uuid::Uuid::new_v4()));
796 mirror.author = self.agent.info().name.clone();
797 mirror.actions.state_delta.insert(
798 MODE_STATE_KEY.to_string(),
799 json!({ "mode": record.mode, "revision": record.revision, "setBy": record.set_by }),
800 );
801 self.sessions.append_event(session.as_ref(), mirror).await?;
802 Ok(())
803 }
804
805 /// Removes the pending entries and any decisions of `fingerprints`, so no later call
806 /// with the same fingerprint is authorized by an entry its cancelled call left (I14).
807 async fn clear_inbox(
808 &self,
809 user: &UserId,
810 session: &SessionId,
811 fingerprints: &[String],
812 reason: &str,
813 ) -> Result<()> {
814 if fingerprints.is_empty() {
815 return Ok(());
816 }
817 let runtime = self.agent.runtime();
818 let scope =
819 ApprovalScope::new(self.app_name.clone(), user.to_string(), session.to_string());
820 let store = runtime.approval_store();
821 for fingerprint in fingerprints {
822 store.decide(&scope, fingerprint, ToolApproval::deny().with_message(reason)).await?;
823 store.take_approval(&scope, fingerprint).await?;
824 }
825 if let Some(service) = runtime.approval_service() {
826 let mut query = adk_core::InboxQuery::default().with_app_name(self.app_name.clone());
827 loop {
828 let page = service.inbox(query.clone()).await?;
829 for request in &page.items {
830 if request.scope == scope && fingerprints.contains(&request.fingerprint) {
831 service.cancel(&request.id, Some(reason.to_string())).await?;
832 }
833 }
834 match page.next_cursor {
835 Some(cursor) => query.cursor = Some(cursor),
836 None => break,
837 }
838 }
839 }
840 Ok(())
841 }
842
843 async fn events(&self, user: &UserId, session: &SessionId) -> Result<Vec<Event>> {
844 Ok(self
845 .sessions
846 .get(GetRequest {
847 app_name: self.app_name.clone(),
848 user_id: user.to_string(),
849 session_id: session.to_string(),
850 num_recent_events: None,
851 after: None,
852 })
853 .await?
854 .events()
855 .all())
856 }
857
858 /// The session's todo list (spec 3.1 §7.6).
859 pub async fn todos(&self, user: &UserId, session: &SessionId) -> Result<TodoList> {
860 let session = self
861 .sessions
862 .get(GetRequest {
863 app_name: self.app_name.clone(),
864 user_id: user.to_string(),
865 session_id: session.to_string(),
866 num_recent_events: Some(1),
867 after: None,
868 })
869 .await?;
870 Ok(session
871 .state()
872 .get(TODOS_STATE_KEY)
873 .map(|value| TodoList::from_value(&value))
874 .unwrap_or_default())
875 }
876
877 /// The spend of `user`, or of every user, per acting agent and vendor: the report
878 /// behind the CLI's `/cost` and the web UI's `harness.spend` (spec 3.1 §7.13).
879 ///
880 /// # Example
881 ///
882 /// ```rust,ignore
883 /// let report = harness.spend(Some(&user));
884 /// println!("{}", report.render());
885 /// ```
886 #[cfg(feature = "observe")]
887 pub fn spend(&self, user: Option<&UserId>) -> crate::observe::SpendReport {
888 self.agent.runtime().spend(user.map(UserId::as_ref))
889 }
890
891 /// Calls of the session waiting for a decision.
892 pub async fn pending_approvals(
893 &self,
894 user: &UserId,
895 session: &SessionId,
896 ) -> Result<Vec<PendingApproval>> {
897 self.agent
898 .runtime()
899 .approval_store()
900 .pending(&ApprovalScope::new(
901 self.app_name.clone(),
902 user.to_string(),
903 session.to_string(),
904 ))
905 .await
906 }
907
908 /// Records a person's decision for the pending call with `fingerprint`; the next
909 /// [`resume`](Self::resume) runs or refuses it (spec 3.1 §7.3). The call's open request
910 /// in the approval service, if any, is withdrawn first, so it cannot decide the call
911 /// again and no run is woken before the person's decision is recorded (spec 3.3 §7.3).
912 ///
913 /// A remembered rule must pin the call's exact declaration, and no rule is remembered
914 /// for a non-waivable call.
915 ///
916 /// # Errors
917 ///
918 /// Returns `harness.decision.invalid` when no pending call has `fingerprint`, a rule
919 /// cannot be remembered for the call, another decision for the call is being recorded in
920 /// this process, or an approver, an expiry or another decision settled the call first —
921 /// before its inbox request was withdrawn or while the person's decision was being
922 /// recorded — or the store's error.
923 pub async fn decide(
924 &self,
925 user: &UserId,
926 session: &SessionId,
927 fingerprint: &str,
928 decision: HarnessDecision,
929 ) -> Result<()> {
930 let runtime = self.agent.runtime();
931 let scope =
932 ApprovalScope::new(self.app_name.clone(), user.to_string(), session.to_string());
933 let _deciding = Deciding::claim((
934 Arc::as_ptr(runtime.approval_store()).cast::<()>().addr(),
935 scope.clone(),
936 fingerprint.to_string(),
937 ))?;
938 let pending = runtime.approval_store().pending(&scope).await?;
939 // A decision for a call that is not pending — decided, cancelled by a mode change, or
940 // never held — would authorize a later call with the same fingerprint unasked (I14).
941 let request = pending
942 .iter()
943 .find(|entry| entry.fingerprint == fingerprint)
944 .map(|entry| entry.request.clone())
945 .ok_or_else(|| {
946 store_error(
947 "no pending call has this fingerprint: it was decided, cancelled by a mode \
948 change, or never held",
949 )
950 })?;
951 let (approval, remember) = match decision {
952 HarnessDecision::Approve => (ToolApproval::approve(), None),
953 HarnessDecision::ApproveWithArgs(args) => {
954 (ToolApproval::approve().with_edited_args(args), None)
955 }
956 HarnessDecision::ApproveAndRemember(rule) => {
957 (ToolApproval::approve(), Some((rule, StandingDecision::Allow)))
958 }
959 HarnessDecision::Deny { message } => {
960 let approval = ToolApproval::deny();
961 (
962 match message {
963 Some(message) => approval.with_message(message),
964 None => approval,
965 },
966 None,
967 )
968 }
969 HarnessDecision::DenyAndRemember(rule) => (
970 ToolApproval::deny(),
971 Some((rule, StandingDecision::Deny { reason: format!("denied by {user}") })),
972 ),
973 };
974 // A rule that cannot be remembered refuses the decision before the inbox request is
975 // withdrawn, so the call stays where every surface shows it (spec 3.3 §7.1).
976 let remember = match remember {
977 Some((suggestion, rule_decision)) => {
978 let owner = RuleOwner {
979 app_name: self.app_name.clone(),
980 user_id: user.to_string(),
981 subject_kind: SubjectKind::Human,
982 session_id: session.to_string(),
983 created_by: SubjectRef::new(SubjectKind::Human, user.to_string()),
984 };
985 Some(self.agent.rule_for_held_call(&request, suggestion, rule_decision, &owner)?)
986 }
987 None => None,
988 };
989 // Withdrawn requests, reported to the kernel once the person's decision is recorded.
990 #[cfg(feature = "kernel")]
991 let mut withdrawn = Vec::new();
992 // The inbox request is withdrawn, not cancelled: a cancel writes a denial and wakes
993 // the run before the person's decision is recorded (spec 3.3 §7.3).
994 if let Some(service) = runtime.approval_service() {
995 let mut query = adk_core::InboxQuery::default()
996 .with_session(&scope)
997 .with_states(adk_core::ApprovalState::ALL);
998 loop {
999 let page = service.inbox(query.clone()).await?;
1000 let open = page
1001 .items
1002 .iter()
1003 .filter(|item| item.fingerprint == fingerprint && item.is_open());
1004 for item in open {
1005 let mut attempts = 0;
1006 loop {
1007 match service.withdraw(&item.id, Some(DECIDED_IN_THE_HARNESS.into())).await
1008 {
1009 Ok(_closed) => {
1010 #[cfg(feature = "kernel")]
1011 withdrawn.push(_closed);
1012 break;
1013 }
1014 // A partial quorum or an escalation step moved it; still pending.
1015 Err(error)
1016 if error.code == "approval.version_conflict" && attempts < 8 =>
1017 {
1018 attempts += 1;
1019 }
1020 Err(error) if error.code == "approval.already_resolved" => {
1021 return Err(store_error(
1022 "an approver decided this call in the approvals inbox first",
1023 ));
1024 }
1025 Err(error) => return Err(error),
1026 }
1027 }
1028 }
1029 match page.next_cursor {
1030 Some(cursor) => query = query.with_cursor(Some(cursor)),
1031 None => break,
1032 }
1033 }
1034 }
1035 #[cfg(feature = "kernel")]
1036 let reported = approval.clone();
1037 let recorded = async move {
1038 // An approver's outcome, an expiry or another run's decision may have settled the
1039 // call while its requests were withdrawn; the person's decision must not outlive
1040 // it (spec 3.3 §7.3, §11 S-I2).
1041 if !runtime
1042 .approval_store()
1043 .pending(&scope)
1044 .await?
1045 .iter()
1046 .any(|entry| entry.fingerprint == fingerprint)
1047 {
1048 return Err(store_error(
1049 "the call was decided another way while this decision was being recorded",
1050 ));
1051 }
1052 if let Some(rule) = remember {
1053 if let Some(audit) = self.audit(user, session) {
1054 let fields = rule_audit_fields(&rule, request.function_call_id.as_deref());
1055 audit.record("harness.rule.created", fields).await?;
1056 }
1057 runtime.standing_rules().grant(rule).await?;
1058 }
1059 runtime.approval_store().decide(&scope, fingerprint, approval).await
1060 }
1061 .await;
1062 #[cfg(feature = "kernel")]
1063 for closed in &withdrawn {
1064 let outcome = recorded.as_ref().ok().map(|()| &reported);
1065 runtime.kernel_approvals.decided_in_the_harness(closed, outcome).await;
1066 }
1067 recorded?;
1068 self.wake_parked(user, session, fingerprint).await
1069 }
1070
1071 /// Wakes the session's durable runs parked on the call with `fingerprint`, as the
1072 /// approval service does, so a durable goal resumes once it is decided (spec 3.1 §7.11).
1073 async fn wake_parked(
1074 &self,
1075 user: &UserId,
1076 session: &SessionId,
1077 fingerprint: &str,
1078 ) -> Result<()> {
1079 let Some(runs) = &self.run_store else {
1080 return Ok(());
1081 };
1082 let parked = runs
1083 .list(
1084 adk_core::RunFilter::default()
1085 .app_name(self.app_name.clone())
1086 .user_id(user.to_string())
1087 .session_id(session.to_string())
1088 .states([adk_core::RunState::Waiting]),
1089 )
1090 .await?;
1091 for run in parked {
1092 if let Some(adk_core::RunCheckpointRef::AwaitingApproval { fingerprints, .. }) =
1093 &run.checkpoint
1094 && fingerprints.iter().any(|parked| parked == fingerprint)
1095 {
1096 runs.wake(&run.run_id).await?;
1097 tracing::info!(run.id = %run.run_id, "woke the durable run waiting for this decision");
1098 }
1099 }
1100 Ok(())
1101 }
1102
1103 /// Records the workspace trust decision for the harness's workspace (spec 3.1 §7.7),
1104 /// bound to the instruction files the harness loaded: a later change to any of them —
1105 /// an edit, a new file, a removed one — leaves the workspace untrusted and records
1106 /// `harness.instructions.changed` until the next decision (spec 3.4 §10 P2).
1107 ///
1108 /// # Errors
1109 ///
1110 /// Returns the trust store's or the audit log's error.
1111 pub async fn trust_workspace(&self, user: &UserId, decision: TrustDecision) -> Result<()> {
1112 let runtime = self.agent.runtime();
1113 let digest = runtime.instructions().root_digest().to_string();
1114 let files = runtime.instructions().instructions_digest();
1115 if let Some(trail) = self.runner.audit_trail() {
1116 HarnessAudit::new(
1117 trail.clone(),
1118 AuditActor::subject(SubjectRef::new(SubjectKind::Human, user.to_string())),
1119 "",
1120 )
1121 .record(
1122 "harness.workspace.trust",
1123 json!({
1124 "files": runtime.instructions().audit_files(decision == TrustDecision::Trusted),
1125 "rootDigest": digest,
1126 "instructionsDigest": files,
1127 "decision": decision,
1128 "by": user.to_string(),
1129 }),
1130 )
1131 .await?;
1132 }
1133 runtime.trust_store().set(
1134 WorkspaceTrust::new(digest, decision, user.to_string()).with_instructions_digest(files),
1135 )
1136 }
1137
1138 /// Starts a goal for the session (spec 3.1 §7.11): the harness iterates until the
1139 /// goal's checks pass — its `until` command exits 0 and its rubric's grader passes every
1140 /// criterion, whichever it has — or a cap is reached.
1141 ///
1142 /// Goals run only in Ask or Auto. The goal state is written to the goal store and
1143 /// mirrored to `harness:goal`. With a run store ([`with_run_store`](Self::with_run_store))
1144 /// the goal is enqueued as a durable run — `NewRun { target: "harness.goal",
1145 /// session_id, concurrency_key: session, idempotency_key: "goal:<session>:<digest>" }` —
1146 /// and the returned stream holds one event naming the run; otherwise the goal's first
1147 /// turn runs here and the stream is its events. While the goal runs, every turn of the
1148 /// session continues it.
1149 ///
1150 /// # Errors
1151 ///
1152 /// Returns `harness.goal.invalid` for an incomplete spec, `harness.goal.mode` outside
1153 /// Ask and Auto, `harness.goal.duplicate` when the same goal already ran in the session
1154 /// as a durable run, or the store's or runner's error.
1155 pub async fn start_goal(
1156 &self,
1157 user: &UserId,
1158 session: &SessionId,
1159 spec: GoalSpec,
1160 ) -> Result<EventStream> {
1161 let mode = self.mode(user, session).await?;
1162 let store = self.agent.runtime().goal_store().clone();
1163 let record = crate::goal::begin(
1164 store.as_ref(),
1165 mode,
1166 (&self.app_name, user.as_ref(), session.as_ref()),
1167 spec,
1168 )
1169 .await?;
1170 let mut mirror = Event::new(format!("harness-goal-{}", uuid::Uuid::new_v4()));
1171 mirror.author = self.agent.info().name.clone();
1172 mirror.actions.state_delta.insert(
1173 GOAL_STATE_KEY.to_string(),
1174 serde_json::to_value(&record.state).unwrap_or(Value::Null),
1175 );
1176 self.sessions.append_event(session.as_ref(), mirror).await?;
1177 tracing::info!(session.id = %session, goal.max_iterations = record.spec.max_iterations, "goal started");
1178 let Some(runs) = &self.run_store else {
1179 return self
1180 .runner
1181 .run(
1182 user.clone(),
1183 session.clone(),
1184 Content::new("user").with_text(record.spec.prompt()),
1185 )
1186 .await;
1187 };
1188 let run = adk_core::NewRun::new(
1189 self.goal_queue.clone(),
1190 self.app_name.clone(),
1191 user.to_string(),
1192 self.goal_target_name(),
1193 json!({ "text": record.spec.prompt() }),
1194 )
1195 .with_session_id(session.to_string())
1196 .with_idempotency_key(format!("goal:{session}:{}", record.spec.digest()))
1197 .with_concurrency_key(session.to_string(), adk_core::OnConflict::Enqueue);
1198 let run = if self.goals_authenticated { run.with_authenticated_user() } else { run };
1199 let (run, note) = match runs.enqueue(run).await? {
1200 adk_core::Enqueued::Created(run) => (run, "enqueued"),
1201 adk_core::Enqueued::Existing(run) if !run.state.is_terminal() => {
1202 (run, "already enqueued")
1203 }
1204 adk_core::Enqueued::Existing(run) => {
1205 let mut cancelled = record.clone();
1206 cancelled.state.status = crate::goal::GoalStatus::Cancelled;
1207 store.set(&self.app_name, user.as_ref(), session.as_ref(), cancelled).await?;
1208 return Err(AdkError::new(
1209 ErrorComponent::Agent,
1210 ErrorCategory::Conflict,
1211 "harness.goal.duplicate",
1212 format!(
1213 "this goal already ran in the session as durable run {}; change the goal or use another session",
1214 run.run_id
1215 ),
1216 ));
1217 }
1218 adk_core::Enqueued::Rejected { blocking_run_id } => {
1219 return Err(AdkError::new(
1220 ErrorComponent::Agent,
1221 ErrorCategory::Conflict,
1222 "harness.goal.rejected",
1223 format!("run {blocking_run_id} holds the session"),
1224 ));
1225 }
1226 };
1227 let mut event = Event::new(format!("harness-goal-{}", uuid::Uuid::new_v4()));
1228 event.author = self.agent.info().name.clone();
1229 event.llm_response.content = Some(
1230 Content::new("model")
1231 .with_text(format!("The goal runs as durable run {} ({note}).", run.run_id)),
1232 );
1233 event.provider_metadata.insert("harness.goal.run_id".to_string(), run.run_id.clone());
1234 Ok(Box::pin(futures::stream::iter(vec![Ok(event)])))
1235 }
1236
1237 /// The session's goal (spec 3.1 §7.11), read from the goal store.
1238 ///
1239 /// # Errors
1240 ///
1241 /// Returns the store's error.
1242 pub async fn goal(&self, user: &UserId, session: &SessionId) -> Result<Option<GoalState>> {
1243 Ok(self
1244 .agent
1245 .runtime()
1246 .goal_store()
1247 .get(&self.app_name, user.as_ref(), session.as_ref())
1248 .await?
1249 .map(|record| record.state))
1250 }
1251
1252 /// The durable-run target and runner a `DurableWorker` runs goals with
1253 /// (`DurableWorker::with_agent`, spec 3.1 §7.11): [`GOAL_TARGET`] and this harness's
1254 /// runner, whose harness continues a session's running goal on every turn. A partition's
1255 /// harness runs goals as `harness.goal@<partition>` (spec 3.2 §7.8).
1256 ///
1257 /// # Example
1258 ///
1259 /// ```rust,ignore
1260 /// let (target, runner) = harness.goal_target();
1261 /// assert_eq!(target, "harness.goal");
1262 /// ```
1263 pub fn goal_target(&self) -> (String, Arc<Runner>) {
1264 (self.goal_target_name(), self.runner.clone())
1265 }
1266
1267 /// [`GOAL_TARGET`], or `harness.goal@<partition>` for a partition's harness.
1268 fn goal_target_name(&self) -> String {
1269 #[cfg(feature = "kernel")]
1270 if let Some(partition) = self.agent.partition() {
1271 return crate::partition::partition_target(GOAL_TARGET, &partition.id);
1272 }
1273 GOAL_TARGET.to_string()
1274 }
1275
1276 /// The session service the harness runner uses.
1277 #[cfg(feature = "kernel")]
1278 pub(crate) fn sessions(&self) -> &Arc<dyn SessionService> {
1279 &self.sessions
1280 }
1281
1282 /// The durable run store goals are enqueued on, when one is set.
1283 #[cfg(feature = "kernel")]
1284 pub(crate) fn run_store(&self) -> Option<&Arc<dyn adk_core::DurableRunStore>> {
1285 self.run_store.as_ref()
1286 }
1287
1288 /// An ambient goal (spec 3.1 §7.11, feature `ambient`): every event of `source` — a
1289 /// `CronTrigger`, `FileWatchTrigger` or `WebhookTrigger` — starts `spec` for `user` in
1290 /// `session`, or in a new session per trigger when `session` is `None`, under the same
1291 /// policy and budget as any goal. Start it with `AmbientAgent::start`.
1292 ///
1293 /// # Example
1294 ///
1295 /// ```rust,ignore
1296 /// let nightly = harness.clone().ambient_goal(
1297 /// Arc::new(adk_agent::CronTrigger::new("0 0 2 * * *")?),
1298 /// UserId::new("ops")?,
1299 /// None,
1300 /// GoalSpec::new("make main green").with_until("cargo test").with_max_iterations(5).with_check_timeout(Duration::from_secs(900)),
1301 /// );
1302 /// ```
1303 #[cfg(feature = "ambient")]
1304 pub fn ambient_goal(
1305 self: Arc<Self>,
1306 source: Arc<dyn adk_agent::EventSource>,
1307 user: UserId,
1308 session: Option<SessionId>,
1309 spec: GoalSpec,
1310 ) -> adk_agent::AmbientAgent {
1311 let agent: Arc<dyn adk_core::Agent> = self.agent.clone();
1312 let handler: adk_agent::ambient::TriggerHandler = Arc::new(move |event, _agent| {
1313 let harness = self.clone();
1314 let (user, session, spec) = (user.clone(), session.clone(), spec.clone());
1315 Box::pin(async move {
1316 let session = harness.open_session(&user, session.as_ref()).await?;
1317 tracing::info!(trigger.source = %event.source, session.id = %session, "ambient goal triggered");
1318 harness.start_goal(&user, &session, spec).await
1319 })
1320 });
1321 adk_agent::AmbientAgent::new(agent, source).with_trigger_handler(handler)
1322 }
1323
1324 /// Where standing rules are kept.
1325 pub fn standing_rules(&self) -> &Arc<dyn StandingRuleStore> {
1326 self.agent.runtime().standing_rules()
1327 }
1328
1329 /// Interrupts the session's active run.
1330 pub fn interrupt(&self, session: &SessionId) -> bool {
1331 self.runner.interrupt(session.as_ref())
1332 }
1333
1334 /// `user`'s background shells in `session`, oldest first (spec 3.1 §7.29): what `/shells`
1335 /// lists.
1336 ///
1337 /// # Example
1338 ///
1339 /// ```rust,ignore
1340 /// for shell in harness.shells(&user, &session).await {
1341 /// println!("{}", shell.line());
1342 /// }
1343 /// ```
1344 pub async fn shells(&self, user: &UserId, session: &SessionId) -> Vec<crate::ShellInfo> {
1345 match self.agent.runtime().toolset().shells() {
1346 Some(shells) => shells.list(&self.app_name, user.as_ref(), session.as_ref()).await,
1347 None => Vec::new(),
1348 }
1349 }
1350
1351 /// Kills `user`'s background shell `shell_id` in `session` and removes it from the
1352 /// reminder; `None` when the session has no such shell (spec 3.1 §7.29).
1353 pub async fn kill_shell(
1354 &self,
1355 user: &UserId,
1356 session: &SessionId,
1357 shell_id: &str,
1358 ) -> Option<crate::ShellInfo> {
1359 let shells = self.agent.runtime().toolset().shells()?;
1360 shells.kill(&self.app_name, user.as_ref(), session.as_ref(), shell_id).await
1361 }
1362
1363 /// Kills every background shell of `user`'s `session`: the session's end (spec 3.1
1364 /// §7.29).
1365 pub async fn end_session_shells(&self, user: &UserId, session: &SessionId) {
1366 if let Some(shells) = self.agent.runtime().toolset().shells() {
1367 shells.end_session(&self.app_name, user.as_ref(), session.as_ref()).await;
1368 }
1369 }
1370
1371 /// The runner.
1372 pub fn runner(&self) -> &Runner {
1373 &self.runner
1374 }
1375
1376 /// Closes the runner and the agent's toolsets, stopping the container shell's session
1377 /// containers (spec 3.1 §7.9).
1378 ///
1379 /// Sessions with turns not yet distilled are distilled first (spec 3.1 §7.15.2); a
1380 /// distillation that fails is logged at `warn`. [`close_with_report`](Self::close_with_report)
1381 /// returns those failures instead. Last, the audit recorder is
1382 /// [sealed](adk_core::audit_log::AuditRecorder::seal): a signed log signs a checkpoint
1383 /// over the records not yet signed, so the log verifies after the process exits.
1384 pub async fn close(&self) {
1385 self.close_with_report().await;
1386 }
1387
1388 /// Closes the harness as [`close`](Self::close) does and reports what it could not
1389 /// finish: each session whose turns were not distilled into long-term memory, with
1390 /// the error (spec 3.1 §7.15.2).
1391 ///
1392 /// # Example
1393 ///
1394 /// ```rust,ignore
1395 /// let report = harness.close_with_report().await;
1396 /// for (session, error) in &report.distillation_failures {
1397 /// eprintln!("long-term memory was not updated for session {session}: {error}");
1398 /// }
1399 /// ```
1400 pub async fn close_with_report(&self) -> CloseReport {
1401 #[cfg_attr(not(feature = "memory"), allow(unused_mut))]
1402 let mut report = CloseReport::default();
1403 #[cfg(feature = "memory")]
1404 if let Some(facts) = self.agent.runtime().toolset().facts() {
1405 report.distillation_failures = facts
1406 .close()
1407 .await
1408 .into_iter()
1409 .map(|((_, _, session), error)| (session, error))
1410 .collect();
1411 }
1412 // The runner closes the root agent: the coordinator's toolsets through a compiled
1413 // team root, the harness toolset included.
1414 self.runner.close().await;
1415 if let Some(trail) = self.agent.runtime().audit_trail()
1416 && let Err(error) = trail.recorder().seal().await
1417 {
1418 tracing::warn!(error = %error, "the audit log was not sealed; its last records stay unsigned");
1419 }
1420 report
1421 }
1422
1423 #[cfg(feature = "memory")]
1424 fn facts_runtime(&self) -> Result<&Arc<crate::facts::runtime::FactsRuntime>> {
1425 self.agent.runtime().toolset().facts().ok_or_else(|| {
1426 AdkError::config(
1427 "long-term memory is off for this harness; turn it on with \
1428 HarnessAgentBuilder::long_term_memory",
1429 )
1430 })
1431 }
1432
1433 /// The long-term facts of `user` in this harness's project, with the user's
1434 /// preferences, newest first and in every status (spec 3.1 §7.15.2).
1435 ///
1436 /// # Errors
1437 ///
1438 /// Returns a configuration error when long-term memory is off, or the store's error.
1439 #[cfg(feature = "memory")]
1440 pub async fn facts(&self, user: &UserId) -> Result<Vec<crate::facts::MemoryFact>> {
1441 let facts = self.facts_runtime()?;
1442 let scope = facts.scope(&self.app_name, user.as_ref());
1443 // A partition's harness lists its own scope only (spec 3.2 K-I15).
1444 let base = match facts.confined {
1445 true => crate::facts::FactFilter::exactly(&scope),
1446 false => crate::facts::FactFilter::recall(&scope),
1447 };
1448 let filter = crate::facts::FactFilter { live_only: false, ..base };
1449 facts.store.list(filter).await
1450 }
1451
1452 /// Promotes `user`'s assumed fact `id` to `Known`, source `UserConfirmed`: a person's
1453 /// confirmation (spec 3.1 §7.15.2, §9.2 I41). Records `harness.memory.fact.promoted`.
1454 ///
1455 /// # Errors
1456 ///
1457 /// Returns `harness.memory.fact_not_found` for a fact that is not the user's in this
1458 /// project, `harness.memory.fact_not_live` for a superseded or forgotten one, or the
1459 /// store's or audit trail's error.
1460 #[cfg(feature = "memory")]
1461 pub async fn accept_fact(&self, user: &UserId, id: &str) -> Result<crate::facts::MemoryFact> {
1462 let facts = self.facts_runtime()?;
1463 let fact = facts.owned(&self.app_name, user.as_ref(), id).await?;
1464 if fact.status != crate::facts::FactStatus::Known {
1465 let by = SubjectRef::human(user.to_string());
1466 facts
1467 .change_status(
1468 facts.audit_as(by.clone(), "").as_ref(),
1469 &fact,
1470 crate::facts::FactStatus::Known,
1471 &by,
1472 )
1473 .await?;
1474 }
1475 facts.owned(&self.app_name, user.as_ref(), id).await
1476 }
1477
1478 /// Forgets `user`'s fact `id`: it is marked `Forgotten` at once, dropped from the index,
1479 /// and never recalled from the next model call on (spec 3.1 §9.2 I44). Records
1480 /// `harness.memory.fact.forgotten`.
1481 ///
1482 /// # Errors
1483 ///
1484 /// As [`accept_fact`](Self::accept_fact).
1485 #[cfg(feature = "memory")]
1486 pub async fn forget_fact(&self, user: &UserId, id: &str) -> Result<()> {
1487 let facts = self.facts_runtime()?;
1488 let fact = facts.owned(&self.app_name, user.as_ref(), id).await?;
1489 let by = SubjectRef::human(user.to_string());
1490 facts
1491 .change_status(
1492 facts.audit_as(by.clone(), "").as_ref(),
1493 &fact,
1494 crate::facts::FactStatus::Forgotten,
1495 &by,
1496 )
1497 .await
1498 }
1499
1500 /// Replaces `user`'s fact `id` with `text`, a person's correction: the new fact is
1501 /// `Known` with source `UserConfirmed`, and the old one `Superseded` by it, its history
1502 /// kept (spec 3.1 §7.15.2).
1503 ///
1504 /// # Errors
1505 ///
1506 /// As [`accept_fact`](Self::accept_fact), and `harness.memory.rejected` for a text that
1507 /// is empty, too long or holds a secret.
1508 #[cfg(feature = "memory")]
1509 pub async fn correct_fact(
1510 &self,
1511 user: &UserId,
1512 id: &str,
1513 text: impl Into<String>,
1514 ) -> Result<crate::facts::MemoryFact> {
1515 let facts = self.facts_runtime()?;
1516 let fact = facts.owned(&self.app_name, user.as_ref(), id).await?;
1517 facts.correct(&SubjectRef::human(user.to_string()), &fact, &text.into()).await
1518 }
1519
1520 /// Distils those of `user`'s `sessions` the per-session distiller never reached, with
1521 /// verified-quote promotion off, so every fact it stores is `Assumed` (spec 3.2 §10 HK2,
1522 /// §9.2 K-I12): the public distillation entry a consolidation tick runs.
1523 ///
1524 /// The store's distillation cursor records how far each session was read, by this
1525 /// entry and by the per-session distiller, so no session is distilled twice. Skipped:
1526 /// a session read up to its last event, one this process will still distil, one active
1527 /// within `distill_idle` of `at`, and one in ReadOnly or Plan mode. On a harness that
1528 /// requires authenticated identity, a session that ran in an earlier process is
1529 /// distilled only when its latest run in the run store
1530 /// ([`with_run_store`](Self::with_run_store)) was authenticated (I42). `budget` bounds the
1531 /// model calls of all sessions together; without one, each session's run has the
1532 /// harness's budget or two model calls.
1533 ///
1534 /// # Example
1535 ///
1536 /// ```rust,ignore
1537 /// let report = harness.distill_sessions(&user, &["s1".into()], chrono::Utc::now(), None).await?;
1538 /// assert!(report.stored.len() <= 10);
1539 /// ```
1540 ///
1541 /// # Errors
1542 ///
1543 /// Returns a configuration error when long-term memory is off, or the store's error.
1544 #[cfg(feature = "memory")]
1545 pub async fn distill_sessions(
1546 &self,
1547 user: &UserId,
1548 sessions: &[String],
1549 at: chrono::DateTime<chrono::Utc>,
1550 budget: Option<adk_core::RunBudget>,
1551 ) -> Result<crate::facts::SessionDistillation> {
1552 self.facts_runtime()?
1553 .distill_sessions(&self.app_name, user.as_ref(), sessions, at, budget)
1554 .await
1555 }
1556
1557 /// How far distillation has read each of `user`'s sessions: the session id and the time
1558 /// of the last event read, by the per-session distiller or
1559 /// [`distill_sessions`](Self::distill_sessions) (spec 3.2 §10 HK2). A session absent from
1560 /// the list was never distilled. A host compares it with each session's last event to
1561 /// find the sessions that ended without being distilled (spec 3.1 §7.33 fix 9).
1562 ///
1563 /// # Example
1564 ///
1565 /// ```rust,ignore
1566 /// let read: std::collections::HashMap<_, _> =
1567 /// harness.distilled_sessions(&user).await?.into_iter().collect();
1568 /// let unsaved = read.get("s1").is_none_or(|upto| *upto < last_event_at);
1569 /// ```
1570 ///
1571 /// # Errors
1572 ///
1573 /// Returns a configuration error when long-term memory is off, or the store's error.
1574 #[cfg(feature = "memory")]
1575 pub async fn distilled_sessions(
1576 &self,
1577 user: &UserId,
1578 ) -> Result<Vec<(String, chrono::DateTime<chrono::Utc>)>> {
1579 self.facts_runtime()?.store.distilled_sessions(&self.app_name, user.as_ref()).await
1580 }
1581
1582 /// Runs one consolidation tick over `user`'s facts in this harness's project and the
1583 /// user-wide ones (spec 3.2 §7.5, §10 HK2): the sessions in `request` the per-session
1584 /// distiller never reached are distilled as [`distill_sessions`](Self::distill_sessions)
1585 /// does; pass 1 collapses `Assumed` near-duplicates and expires stale `Assumed` facts
1586 /// without a model call; pass 2 merges similar `Assumed` facts on the distiller model.
1587 /// `Known` facts are never superseded, merged or expired (K-I22). When the passes would
1588 /// change more than `max_loss_fraction` of a scope's live facts, they apply nothing and
1589 /// the record says why. The record is kept in the fact store for
1590 /// [`undo_consolidation`](Self::undo_consolidation), and one
1591 /// `harness.memory.consolidated` audit record lists ids and counts, never text.
1592 ///
1593 /// # Example
1594 ///
1595 /// ```rust,ignore
1596 /// let record = harness
1597 /// .consolidate_memory(&user, adk_harness::ConsolidationRequest::new().with_sessions(["s1"]))
1598 /// .await?;
1599 /// println!("{} superseded, {} forgotten", record.superseded().count(), record.forgotten().count());
1600 /// ```
1601 ///
1602 /// # Errors
1603 ///
1604 /// Returns a configuration error when long-term memory is off,
1605 /// `harness.memory.consolidation_unsupported` for a fact store that keeps no records,
1606 /// or the store's or audit trail's error.
1607 #[cfg(feature = "memory")]
1608 pub async fn consolidate_memory(
1609 &self,
1610 user: &UserId,
1611 request: crate::facts::ConsolidationRequest,
1612 ) -> Result<crate::facts::ConsolidationRecord> {
1613 self.facts_runtime()?.consolidate(&self.app_name, user.as_ref(), request).await
1614 }
1615
1616 /// `user`'s consolidation records, newest first (spec 3.2 §7.5).
1617 ///
1618 /// # Errors
1619 ///
1620 /// Returns a configuration error when long-term memory is off, or the store's error.
1621 #[cfg(feature = "memory")]
1622 pub async fn consolidations(
1623 &self,
1624 user: &UserId,
1625 ) -> Result<Vec<crate::facts::ConsolidationRecord>> {
1626 self.facts_runtime()?.store.consolidations(&self.app_name, user.as_ref()).await
1627 }
1628
1629 /// Reverts `user`'s consolidation tick `tick_id` (an id or a unique prefix) as
1630 /// [`undo_consolidation`](crate::undo_consolidation) does, and brings the index in line
1631 /// (spec 3.2 §7.5).
1632 ///
1633 /// # Errors
1634 ///
1635 /// As [`undo_consolidation`](crate::undo_consolidation), and a configuration error when
1636 /// long-term memory is off.
1637 #[cfg(feature = "memory")]
1638 pub async fn undo_consolidation(
1639 &self,
1640 user: &UserId,
1641 tick_id: &str,
1642 ) -> Result<crate::facts::ConsolidationUndo> {
1643 let facts = self.facts_runtime()?;
1644 let by = SubjectRef::human(user.to_string());
1645 let report = crate::facts::undo_consolidation(
1646 facts.store.as_ref(),
1647 &self.app_name,
1648 user.as_ref(),
1649 tick_id,
1650 &by,
1651 )
1652 .await?;
1653 for id in report.restored.iter().chain(&report.forgotten) {
1654 let Some(fact) = facts.store.get(id).await? else {
1655 continue;
1656 };
1657 let indexed = if fact.status.is_live() {
1658 facts.index.upsert(&fact).await
1659 } else {
1660 facts.forget_cached(id);
1661 facts.index.remove(&fact).await
1662 };
1663 if let Err(error) = indexed {
1664 tracing::warn!(error = %error, "could not update the fact index after an undo");
1665 }
1666 }
1667 Ok(report)
1668 }
1669}
1670
1671/// Lets the agent's long-term memory distil the runner's sessions (spec 3.1 §7.15.2).
1672#[cfg(feature = "memory")]
1673fn attach_facts(
1674 agent: &HarnessAgent,
1675 runner: &Runner,
1676 sessions: &Arc<dyn SessionService>,
1677 app_name: &str,
1678) {
1679 if let Some(facts) = agent.runtime().toolset().facts() {
1680 facts.attach(
1681 sessions.clone(),
1682 app_name.to_string(),
1683 runner.governance().clone(),
1684 runner.audit_trail().cloned(),
1685 );
1686 }
1687}