adk_kernel/channels/
host.rs1use std::sync::Arc;
4
5use adk_core::audit_log::{AuditActor, AuditTrail};
6use adk_core::{ApprovalRequest, ApprovalService, NewRun, RunRecord};
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use futures::stream::{BoxStream, StreamExt};
10
11use super::ChannelHost;
12use crate::bus::KernelEvent;
13use crate::error::Result;
14use crate::kernel::Kernel;
15use crate::process::{ProcessKind, ProcessSpec};
16use crate::sched::QuietHours;
17
18fn quiet_end(windows: &[QuietHours], at: DateTime<Utc>) -> Option<DateTime<Utc>> {
21 let mut until = at;
22 for _ in 0..=windows.len() {
24 match windows
25 .iter()
26 .filter(|quiet| quiet.contains(until))
27 .map(|quiet| quiet.release_at(until))
28 .max()
29 {
30 Some(next) if next > until => until = next,
31 _ => break,
32 }
33 }
34 (until > at).then_some(until)
35}
36
37pub(crate) async fn stop_account_turns(kernel: &Kernel, channel: &str, account: &str) -> usize {
41 let open =
42 [adk_core::RunState::Queued, adk_core::RunState::Running, adk_core::RunState::Waiting];
43 let filter =
44 adk_core::RunFilter::default().app_name(kernel.config().app_name.clone()).states(open);
45 let runs = match kernel.processes().run_store().list(filter).await {
46 Ok(runs) => runs,
47 Err(error) => {
48 tracing::warn!(channel.name = channel, error = %error, "could not list a removed chat account's turns");
49 return 0;
50 }
51 };
52 let mut stopped = 0;
53 for run in runs {
54 let Some(origin) = super::TurnOrigin::of(&run) else { continue };
55 if origin.channel != channel || origin.account != account {
56 continue;
57 }
58 match kernel.processes().kill(&run.run_id, "the chat account was removed").await {
59 Ok(()) => stopped += 1,
60 Err(error) => {
61 tracing::warn!(process.pid = %run.run_id, error = %error, "could not stop a removed chat account's turn");
62 }
63 }
64 }
65 stopped
66}
67
68#[async_trait]
69impl ChannelHost for Kernel {
70 fn app_name(&self) -> &str {
71 &self.config().app_name
72 }
73
74 fn now(&self) -> DateTime<Utc> {
75 self.config().clock.now()
76 }
77
78 fn quiet_until(&self, at: DateTime<Utc>) -> Option<DateTime<Utc>> {
81 let config = self.config();
82 let windows: Vec<QuietHours> = config
83 .quiet_hours
84 .iter()
85 .chain(config.proactivity.quiet_hours.iter())
86 .copied()
87 .collect();
88 quiet_end(&windows, at)
89 }
90
91 async fn quiet_ends(
96 &self,
97 request: &ApprovalRequest,
98 at: DateTime<Utc>,
99 ) -> Option<DateTime<Utc>> {
100 let sup = self.supervision();
101 let area = match &request.run_id {
102 Some(pid) => sup.processes.get(pid).await.ok().flatten().map(|meta| meta.partition),
103 None => None,
104 };
105 let windows = sup.quiet_windows(&area.unwrap_or_default()).await;
106 quiet_end(&windows, at)
107 }
108
109 fn approvals(&self) -> Option<Arc<dyn ApprovalService>> {
110 self.approval_service().cloned()
111 }
112
113 fn moves_money(&self, request: &ApprovalRequest) -> bool {
116 #[cfg(feature = "drivers")]
117 if let Some(drivers) = Kernel::drivers(self) {
118 return drivers.mounted().iter().filter_map(|id| drivers.record(id)).any(|record| {
119 record.manifest.class_of(&request.tool_name)
120 == crate::drivers::EffectClass::Financial
121 });
122 }
123 let _ = request;
124 false
125 }
126
127 fn rates_high(&self, request: &ApprovalRequest) -> bool {
130 crate::control::rated_high(Some(self), request)
131 }
132
133 fn audit_trail(&self) -> Option<AuditTrail> {
134 Kernel::audit_trail(self).cloned()
135 }
136
137 async fn turn(&self, pid: &str) -> Result<Option<RunRecord>> {
138 Ok(self.processes().run_store().get(pid).await?)
139 }
140
141 async fn start_turn(&self, run: NewRun) -> Result<String> {
142 let process =
143 self.processes().spawn(run, ProcessSpec::new(ProcessKind::Interactive)).await?;
144 Ok(process.meta.pid)
145 }
146
147 async fn steer(
149 &self,
150 user: &str,
151 session: &str,
152 text: &str,
153 ) -> Result<Option<adk_core::SteerReceipt>> {
154 Ok(Kernel::steer(self, user, session, text).await?.map(|steering| steering.receipt))
155 }
156
157 async fn finished_turns(&self) -> Result<BoxStream<'static, RunRecord>> {
159 let runs = self.processes().run_store().clone();
160 let events = self.events().into_stream();
161 Ok(events
162 .filter_map(move |record| {
163 let runs = runs.clone();
164 async move {
165 let KernelEvent::Process { pid, to, .. } = record.event else { return None };
166 if !to.is_terminal() {
167 return None;
168 }
169 let run = runs.get(&pid).await.ok().flatten()?;
170 super::TurnOrigin::of(&run).map(|_| run)
171 }
172 })
173 .boxed())
174 }
175
176 async fn stop_all(&self, reason: &str, by: AuditActor) -> Result<()> {
177 Kernel::freeze(self, reason, by).await
178 }
179}