1use std::collections::{HashMap, VecDeque};
60use std::future::Future;
61use std::path::PathBuf;
62use std::sync::{Arc, Mutex};
63use std::time::{Duration, SystemTime, UNIX_EPOCH};
64
65use aidaemon_core::{
66 Agent, CoreError, Event, Image, Message, Resolution, Role, RunId, RunOutcome, RunState,
67 RunStatus, RunStore,
68};
69use base64::Engine as _;
70use tokio::sync::{Semaphore, mpsc};
71use tokio::time::{Instant, MissedTickBehavior};
72use tokio_util::sync::CancellationToken;
73use tokio_util::task::TaskTracker;
74
75use crate::approvals::{ApprovalStore, StoredApproval};
76use crate::channel::{
77 ApprovalChoice, ApprovalDetails, ApprovalPrompt, Attachment, AttachmentKind, Channel,
78 ChannelError, ChannelEvent, CommandInvocation, CommandSpec, Conversation, ConversationKind,
79 InboundMessage, MessageRef, OutboundMessage, RunEnding,
80};
81use crate::commands::{
82 CommandContext, CommandHandler, CommandReply, builtin_commands, invalid_spec, is_builtin,
83};
84use crate::inbound_files::{ATTACHMENTS_HEADING, list_line, save_attachment, sniff_image};
85use crate::latex::strip_latex_keeping_code;
86use crate::policy::{AccessPolicy, Admission, SenderRole};
87use crate::render::{self, Progress};
88use crate::router::EventRouter;
89use crate::session::{MemorySessionIndex, SessionIndex, session_id};
90use crate::split::split_message;
91
92pub const APPROVE_CHOICE: &str = "approve";
94pub const DENY_CHOICE: &str = "deny";
96
97#[derive(Debug, Clone)]
100pub struct AttachmentConfig {
101 pub max_per_message: usize,
104 pub max_image_bytes: u64,
107 pub max_file_bytes: u64,
109 pub download_timeout: Duration,
111 pub save_dir: Option<PathBuf>,
118}
119
120impl Default for AttachmentConfig {
121 fn default() -> Self {
122 Self {
123 max_per_message: 8,
124 max_image_bytes: 5 * 1024 * 1024,
125 max_file_bytes: 20 * 1024 * 1024,
126 download_timeout: Duration::from_secs(60),
127 save_dir: None,
128 }
129 }
130}
131
132#[derive(Debug, Clone)]
134pub struct RunnerConfig {
135 pub max_queued_per_session: usize,
138 pub max_concurrent_runs: usize,
140 pub status_edit_interval: Duration,
142 pub typing_interval: Duration,
144 pub approval_timeout: Duration,
146 pub max_argument_chars: usize,
148 pub restart_backoff: Duration,
150 pub max_restart_backoff: Duration,
151 pub event_buffer: usize,
153 pub shutdown_grace: Duration,
155 pub attachments: AttachmentConfig,
157}
158
159impl Default for RunnerConfig {
160 fn default() -> Self {
161 Self {
162 max_queued_per_session: 8,
163 max_concurrent_runs: 4,
164 status_edit_interval: Duration::from_millis(1500),
165 typing_interval: Duration::from_secs(4),
166 approval_timeout: Duration::from_secs(3600),
167 max_argument_chars: 1500,
168 restart_backoff: Duration::from_secs(1),
169 max_restart_backoff: Duration::from_secs(60),
170 event_buffer: 256,
171 shutdown_grace: Duration::from_secs(5),
172 attachments: AttachmentConfig::default(),
173 }
174 }
175}
176
177#[derive(Debug, thiserror::Error, PartialEq, Eq)]
178pub enum RunnerBuildError {
179 #[error("a runner needs at least one channel")]
180 NoChannels,
181 #[error("two channels are named `{0}`; channel names must be unique")]
182 DuplicateChannel(String),
183 #[error("invalid config: {0}")]
184 InvalidConfig(&'static str),
185}
186
187pub struct ChannelRunnerBuilder {
189 agent: Agent,
190 channels: Vec<Arc<dyn Channel>>,
191 policy: AccessPolicy,
192 router: Option<EventRouter>,
193 store: Option<Arc<dyn RunStore>>,
194 index: Option<Arc<dyn SessionIndex>>,
195 approval_store: Option<Arc<dyn ApprovalStore>>,
196 commands: Vec<HostCommand>,
197 config: RunnerConfig,
198}
199
200impl ChannelRunnerBuilder {
201 pub fn channel(mut self, channel: Arc<dyn Channel>) -> Self {
206 self.channels.push(channel);
207 self
208 }
209
210 pub fn access(mut self, policy: AccessPolicy) -> Self {
211 self.policy = policy;
212 self
213 }
214
215 pub fn event_router(mut self, router: EventRouter) -> Self {
218 self.router = Some(router);
219 self
220 }
221
222 pub fn store(mut self, store: Arc<dyn RunStore>) -> Self {
224 self.store = Some(store);
225 self
226 }
227
228 pub fn session_index(mut self, index: Arc<dyn SessionIndex>) -> Self {
231 self.index = Some(index);
232 self
233 }
234
235 pub fn approval_store(mut self, approvals: Arc<dyn ApprovalStore>) -> Self {
238 self.approval_store = Some(approvals);
239 self
240 }
241
242 pub fn command(
246 mut self,
247 name: impl Into<String>,
248 description: impl Into<String>,
249 handler: impl CommandHandler + 'static,
250 ) -> Self {
251 self.commands.push(HostCommand {
252 spec: CommandSpec::new(name, description),
253 handler: Arc::new(handler),
254 });
255 self
256 }
257
258 pub fn config(mut self, config: RunnerConfig) -> Self {
259 self.config = config;
260 self
261 }
262
263 pub fn build(self) -> Result<ChannelRunner, RunnerBuildError> {
264 if self.channels.is_empty() {
265 return Err(RunnerBuildError::NoChannels);
266 }
267 let mut seen = std::collections::HashSet::new();
268 for channel in &self.channels {
269 if !seen.insert(channel.name().to_string()) {
270 return Err(RunnerBuildError::DuplicateChannel(
271 channel.name().to_string(),
272 ));
273 }
274 }
275 if self.config.max_queued_per_session == 0 {
276 return Err(RunnerBuildError::InvalidConfig(
277 "max_queued_per_session must be at least 1",
278 ));
279 }
280 if self.config.max_concurrent_runs == 0 {
281 return Err(RunnerBuildError::InvalidConfig(
282 "max_concurrent_runs must be at least 1",
283 ));
284 }
285 if self.config.event_buffer == 0 {
286 return Err(RunnerBuildError::InvalidConfig(
287 "event_buffer must be at least 1",
288 ));
289 }
290 if self.approval_store.is_some() && self.store.is_none() {
291 return Err(RunnerBuildError::InvalidConfig(
292 "an approval store needs a run store",
293 ));
294 }
295 let mut commands = HashMap::new();
296 for command in &self.commands {
297 if let Some(problem) = invalid_spec(&command.spec) {
298 return Err(RunnerBuildError::InvalidConfig(problem));
299 }
300 if is_builtin(&command.spec.name) {
301 return Err(RunnerBuildError::InvalidConfig(
302 "a command cannot replace a built-in",
303 ));
304 }
305 if commands
306 .insert(command.spec.name.clone(), command.handler.clone())
307 .is_some()
308 {
309 return Err(RunnerBuildError::InvalidConfig(
310 "two commands have the same name",
311 ));
312 }
313 }
314 let command_specs = self.commands.into_iter().map(|c| c.spec).collect();
315 let permits = Arc::new(Semaphore::new(self.config.max_concurrent_runs));
316 Ok(ChannelRunner {
317 inner: Arc::new(Inner {
318 channels: self
321 .channels
322 .into_iter()
323 .map(|channel| {
324 Arc::new(crate::outbound::RedactingChannel::new(
325 channel,
326 self.agent.redaction_scope().clone(),
327 )) as Arc<dyn Channel>
328 })
329 .collect(),
330 agent: self.agent,
331 policy: self.policy,
332 router: self.router,
333 store: self.store,
334 index: self
335 .index
336 .unwrap_or_else(|| Arc::new(MemorySessionIndex::new())),
337 approval_store: self.approval_store,
338 commands,
339 command_specs,
340 config: self.config,
341 sessions: Mutex::new(HashMap::new()),
342 approvals: Mutex::new(HashMap::new()),
343 permits,
344 root: CancellationToken::new(),
345 tasks: TaskTracker::new(),
346 }),
347 })
348 }
349}
350
351#[derive(Clone)]
353pub struct ChannelRunner {
354 inner: Arc<Inner>,
355}
356
357impl ChannelRunner {
358 pub fn builder(agent: Agent) -> ChannelRunnerBuilder {
359 ChannelRunnerBuilder {
360 agent,
361 channels: Vec::new(),
362 policy: AccessPolicy::default(),
363 router: None,
364 store: None,
365 index: None,
366 approval_store: None,
367 commands: Vec::new(),
368 config: RunnerConfig::default(),
369 }
370 }
371
372 pub async fn run(&self, shutdown: CancellationToken) {
379 let inner = self.inner.clone();
380 let root = inner.root.clone();
381 let restored = inner.restore_approvals().await;
383 inner.register_commands();
384 let mut handles = Vec::new();
385 for (index, channel) in inner.channels.iter().enumerate() {
386 let (tx, rx) = mpsc::channel(inner.config.event_buffer);
387 handles.push(tokio::spawn(supervise(
388 channel.clone(),
389 tx,
390 root.clone(),
391 inner.config.clone(),
392 )));
393 handles.push(tokio::spawn(dispatch(inner.clone(), index, rx)));
394 }
395 for (prompt_id, remaining) in restored {
396 inner.arm_expiry(prompt_id, remaining);
397 }
398 tokio::select! {
399 _ = shutdown.cancelled() => {}
400 _ = root.cancelled() => {}
401 }
402 root.cancel();
403 for handle in handles {
404 let _ = handle.await;
405 }
406 inner.tasks.close();
407 if tokio::time::timeout(inner.config.shutdown_grace, inner.tasks.wait())
408 .await
409 .is_err()
410 {
411 tracing::warn!("channel runner: in-flight work did not finish before shutdown");
412 }
413 }
414}
415
416#[derive(Debug, Clone)]
418struct Origin {
419 channel: usize,
420 conversation: Conversation,
421 reply_to: Option<String>,
422}
423
424enum Job {
425 Message {
426 origin: Origin,
427 text: String,
428 attachments: Vec<Attachment>,
431 role: SenderRole,
432 },
433 Resume {
434 origin: Origin,
435 state: Box<RunState>,
436 resolution: Resolution,
437 stopped: bool,
439 },
440}
441
442impl Job {
443 fn origin(&self) -> &Origin {
444 match self {
445 Job::Message { origin, .. } | Job::Resume { origin, .. } => origin,
446 }
447 }
448}
449
450enum SlotState {
451 Idle,
452 Running { cancel: CancellationToken },
453 Awaiting { prompt_id: String },
454}
455
456struct Slot {
457 state: SlotState,
458 queue: VecDeque<Job>,
459 last_state: Option<RunState>,
461 generation: u64,
464}
465
466impl Default for Slot {
467 fn default() -> Self {
468 Self {
469 state: SlotState::Idle,
470 queue: VecDeque::new(),
471 last_state: None,
472 generation: 0,
473 }
474 }
475}
476
477enum Loaded {
479 Image(Image),
480 Saved(PathBuf),
481 Listed(&'static str),
483}
484
485struct PendingApproval {
486 prompt_id: String,
487 session_id: String,
488 origin: Origin,
489 state: RunState,
490 prompt_text: String,
491 prompt_ref: Option<MessageRef>,
492 expires_at_ms: u64,
493}
494
495enum Command {
496 Stop,
497 New,
498 Status,
499 Approve(Option<String>),
500 Deny(Option<String>),
501}
502
503fn command_parts(text: &str) -> Option<(String, &str)> {
505 let rest = text.trim().strip_prefix('/')?;
506 let head = rest.split_whitespace().next()?;
507 let name = head.split('@').next().unwrap_or(head).to_ascii_lowercase();
509 Some((name, rest[head.len()..].trim()))
510}
511
512fn parse_command(text: &str) -> Option<Command> {
514 let (name, args) = command_parts(text)?;
515 let arg = args.split_whitespace().next().map(str::to_string);
516 match name.as_str() {
517 "stop" => Some(Command::Stop),
518 "new" => Some(Command::New),
519 "status" => Some(Command::Status),
520 "approve" => Some(Command::Approve(arg)),
521 "deny" => Some(Command::Deny(arg)),
522 _ => None,
523 }
524}
525
526struct HostCommand {
527 spec: CommandSpec,
528 handler: Arc<dyn CommandHandler>,
529}
530
531struct CommandCall {
533 context: CommandContext,
534 origin: Origin,
535 invocation: Option<CommandInvocation>,
537}
538
539const COMMAND_DONE: &str = "Done.";
542const COMMAND_FAILED: &str = "That command failed.";
543const COMMAND_REFUSED: &str = "Not available.";
544
545struct Inner {
546 agent: Agent,
547 channels: Vec<Arc<dyn Channel>>,
548 policy: AccessPolicy,
549 router: Option<EventRouter>,
550 store: Option<Arc<dyn RunStore>>,
551 index: Arc<dyn SessionIndex>,
552 approval_store: Option<Arc<dyn ApprovalStore>>,
553 commands: HashMap<String, Arc<dyn CommandHandler>>,
554 command_specs: Vec<CommandSpec>,
555 config: RunnerConfig,
556 sessions: Mutex<HashMap<String, Slot>>,
557 approvals: Mutex<HashMap<String, PendingApproval>>,
558 permits: Arc<Semaphore>,
559 root: CancellationToken,
561 tasks: TaskTracker,
562}
563
564async fn supervise(
565 channel: Arc<dyn Channel>,
566 tx: mpsc::Sender<ChannelEvent>,
567 root: CancellationToken,
568 config: RunnerConfig,
569) {
570 let mut backoff = config.restart_backoff;
571 loop {
572 let started = Instant::now();
573 let result = channel.run(tx.clone(), root.child_token()).await;
574 if root.is_cancelled() {
575 return;
576 }
577 match result {
578 Err(ChannelError::Auth(reason)) => {
579 tracing::error!(
580 channel = channel.name(),
581 %reason,
582 "channel authentication failed; not restarting it"
583 );
584 return;
585 }
586 Err(err) => {
587 tracing::warn!(channel = channel.name(), error = %err, "channel task failed; restarting")
588 }
589 Ok(()) => {
590 tracing::warn!(
591 channel = channel.name(),
592 "channel task returned; restarting"
593 )
594 }
595 }
596 if started.elapsed() >= config.max_restart_backoff {
597 backoff = config.restart_backoff;
598 }
599 tokio::select! {
600 _ = tokio::time::sleep(backoff) => {}
601 _ = root.cancelled() => return,
602 }
603 backoff = (backoff * 2).min(config.max_restart_backoff);
604 }
605}
606
607async fn dispatch(inner: Arc<Inner>, channel: usize, mut rx: mpsc::Receiver<ChannelEvent>) {
608 loop {
609 tokio::select! {
610 _ = inner.root.cancelled() => return,
611 event = rx.recv() => match event {
612 Some(event) => inner.handle_event(channel, event).await,
613 None => return,
614 },
615 }
616 }
617}
618
619async fn recv_opt(rx: &mut Option<mpsc::UnboundedReceiver<Event>>) -> Option<Event> {
621 match rx {
622 Some(rx) => rx.recv().await,
623 None => std::future::pending().await,
624 }
625}
626
627impl Inner {
628 fn channel_name(&self, channel: usize) -> &str {
629 self.channels[channel].name()
630 }
631
632 fn register_commands(self: &Arc<Self>) {
635 for channel in &self.channels {
636 let caps = channel.capabilities();
637 if !caps.commands {
638 continue;
639 }
640 let mut menu = builtin_commands(caps.buttons);
641 menu.extend(self.command_specs.iter().cloned());
642 let (channel, root) = (channel.clone(), self.root.clone());
643 self.tasks.spawn(async move {
644 tokio::select! {
645 _ = root.cancelled() => {}
646 result = channel.register_commands(&menu) => {
647 if let Err(error) = result {
648 tracing::warn!(channel = channel.name(), %error, "could not register commands");
649 }
650 }
651 }
652 });
653 }
654 }
655
656 fn outbound_text(&self, channel: &dyn Channel, text: &str) -> String {
658 if channel.strips_latex() {
659 strip_latex_keeping_code(text)
660 } else {
661 text.to_string()
662 }
663 }
664
665 async fn say(&self, origin: &Origin, text: &str) {
666 let channel = &self.channels[origin.channel];
667 let max = channel.capabilities().max_message_len;
668 for part in split_message(text, max) {
669 let message = OutboundMessage::text(part);
670 if let Err(err) = channel.send(&origin.conversation, &message).await {
671 tracing::warn!(channel = channel.name(), error = %err, "send failed");
672 }
673 }
674 }
675
676 async fn reply(&self, origin: &Origin, text: &str) {
678 let channel = &self.channels[origin.channel];
679 let max = channel.capabilities().max_message_len;
680 let text = self.outbound_text(channel.as_ref(), text);
681 for (i, part) in split_message(&text, max).into_iter().enumerate() {
682 let message = OutboundMessage {
683 text: part,
684 reply_to: if i == 0 {
685 origin.reply_to.clone()
686 } else {
687 None
688 },
689 };
690 if let Err(err) = channel.send(&origin.conversation, &message).await {
691 tracing::warn!(channel = channel.name(), error = %err, "send failed");
692 }
693 }
694 }
695
696 async fn handle_event(self: &Arc<Self>, channel: usize, event: ChannelEvent) {
697 match event {
698 ChannelEvent::Message(message) => self.handle_message(channel, message).await,
699 ChannelEvent::Command(command) => self.handle_invocation(channel, command).await,
700 ChannelEvent::Approval(answer) => {
701 let approve = match answer.choice_id.as_str() {
702 APPROVE_CHOICE => true,
703 DENY_CHOICE => false,
704 other => {
705 tracing::debug!(choice = other, "ignoring unknown approval choice");
706 return;
707 }
708 };
709 let origin = Origin {
710 channel,
711 conversation: answer.conversation,
712 reply_to: None,
713 };
714 self.answer(
715 origin,
716 &answer.sender.id,
717 Some(answer.prompt_id),
718 approve,
719 answer.message,
720 )
721 .await;
722 }
723 }
724 }
725
726 async fn handle_invocation(self: &Arc<Self>, channel: usize, command: CommandInvocation) {
731 let name = self.channel_name(channel).to_string();
732 let adapter = self.channels[channel].clone();
733 let mut message = InboundMessage::new(
734 command.conversation.clone(),
735 command.sender.clone(),
736 String::new(),
737 command.as_text(),
738 );
739 message.addressed = true;
740 let role = match self.policy.admit(&name, &message) {
741 Admission::Ignore => return,
742 Admission::Refuse => {
743 tracing::info!(channel = %name, sender = %command.sender.id, "refused a command from an unknown sender");
744 let text = self.policy.refusal().unwrap_or(COMMAND_REFUSED);
745 if let Err(error) = adapter.answer_command(&command, text).await {
746 tracing::debug!(%error, "could not answer a command invocation");
747 }
748 return;
749 }
750 Admission::Accept(role) => role,
751 };
752 let command_name = command.name.to_ascii_lowercase();
753 if let Some(handler) = self.commands.get(&command_name).cloned() {
754 let origin = Origin {
755 channel,
756 reply_to: None,
757 conversation: command.conversation.clone(),
758 };
759 let context = CommandContext {
760 session_id: session_id(&name, &command.conversation.id),
761 channel: name,
762 conversation: command.conversation.clone(),
763 sender: command.sender.clone(),
764 role,
765 name: command_name,
766 args: command.args.trim().to_string(),
767 };
768 let invocation = Some(command);
769 self.spawn_command(
770 handler,
771 CommandCall {
772 context,
773 origin,
774 invocation,
775 },
776 );
777 return;
778 }
779 if let Err(error) = adapter.answer_command(&command, "Got it.").await {
780 tracing::debug!(%error, "could not answer a command invocation");
781 }
782 self.handle_message(channel, message).await;
783 }
784
785 fn spawn_command(self: &Arc<Self>, handler: Arc<dyn CommandHandler>, call: CommandCall) {
788 let inner = self.clone();
789 self.tasks.spawn(async move {
790 let CommandCall {
791 context,
792 origin,
793 invocation,
794 } = call;
795 let command = context.name.clone();
796 let mut run = tokio::spawn(async move { handler.handle(context).await });
797 let result = tokio::select! {
798 _ = inner.root.cancelled() => {
799 run.abort();
800 return;
801 }
802 result = &mut run => result,
803 };
804 let text = match result {
805 Ok(CommandReply::Text(text)) => Some(text),
806 Ok(CommandReply::Silent) => None,
807 Err(error) => {
808 tracing::warn!(%command, %error, "command handler failed");
809 Some(COMMAND_FAILED.to_string())
810 }
811 };
812 match (invocation, text) {
813 (Some(invocation), text) => {
814 let channel = &inner.channels[origin.channel];
815 let text = text.as_deref().unwrap_or(COMMAND_DONE);
816 if let Err(error) = channel.answer_command(&invocation, text).await {
817 tracing::debug!(%error, "could not answer a command invocation");
818 }
819 }
820 (None, Some(text)) => inner.say(&origin, &text).await,
821 (None, None) => {}
822 }
823 });
824 }
825
826 async fn handle_message(self: &Arc<Self>, channel: usize, message: InboundMessage) {
827 let name = self.channel_name(channel).to_string();
828 let origin = Origin {
829 channel,
830 reply_to: (message.conversation.kind != ConversationKind::Direct
832 && !message.message_id.is_empty())
833 .then(|| message.message_id.clone()),
834 conversation: message.conversation.clone(),
835 };
836 let role = match self.policy.admit(&name, &message) {
837 Admission::Ignore => return,
838 Admission::Refuse => {
839 tracing::info!(channel = %name, sender = %message.sender.id, "refused unknown sender");
840 if let Some(refusal) = self.policy.refusal() {
841 self.say(&origin, refusal).await;
842 }
843 return;
844 }
845 Admission::Accept(role) => role,
846 };
847 let session = session_id(&name, &message.conversation.id);
848 match parse_command(&message.text) {
849 Some(Command::Stop) => self.stop(&session, &origin).await,
850 Some(Command::New) => self.reset(&session, &origin).await,
851 Some(Command::Status) => self.status(&session, &origin).await,
852 Some(Command::Approve(id)) => {
853 self.answer(origin, &message.sender.id, id, true, None)
854 .await;
855 }
856 Some(Command::Deny(id)) => {
857 self.answer(origin, &message.sender.id, id, false, None)
858 .await;
859 }
860 None => {
861 if let Some((command, args)) = command_parts(&message.text)
862 && let Some(handler) = self.commands.get(&command).cloned()
863 {
864 let context = CommandContext {
865 channel: name,
866 conversation: message.conversation.clone(),
867 sender: message.sender.clone(),
868 role,
869 session_id: session,
870 args: args.to_string(),
871 name: command,
872 };
873 let call = CommandCall {
874 context,
875 origin,
876 invocation: None,
877 };
878 self.spawn_command(handler, call);
879 return;
880 }
881 self.submit(
882 session,
883 Job::Message {
884 origin,
885 text: message.text,
886 attachments: message.attachments,
887 role,
888 },
889 )
890 .await;
891 }
892 }
893 }
894
895 async fn submit(self: &Arc<Self>, session: String, job: Job) {
897 let mut notices: Vec<(Origin, String)> = Vec::new();
898 let start = {
899 let mut sessions = self.sessions.lock().expect("sessions poisoned");
900 let slot = sessions.entry(session.clone()).or_default();
901 match &slot.state {
902 SlotState::Idle => {
903 slot.state = SlotState::Running {
904 cancel: self.root.child_token(),
905 };
906 Some(job)
907 }
908 busy => {
909 if let SlotState::Awaiting { prompt_id } = busy {
910 notices.push((
911 job.origin().clone(),
912 format!(
913 "Waiting for an answer to approval `{prompt_id}`; I will handle \
914 this message afterwards."
915 ),
916 ));
917 }
918 if slot.queue.len() >= self.config.max_queued_per_session
919 && let Some(dropped) = slot.queue.pop_front()
920 {
921 notices.push((
922 dropped.origin().clone(),
923 "Too many messages are waiting, so I dropped the oldest one."
924 .to_string(),
925 ));
926 }
927 slot.queue.push_back(job);
928 None
929 }
930 }
931 };
932 for (origin, text) in notices {
933 self.say(&origin, &text).await;
934 }
935 if let Some(job) = start {
936 self.spawn_worker(session, job);
937 }
938 }
939
940 fn spawn_worker(self: &Arc<Self>, session: String, job: Job) {
941 let inner = self.clone();
942 self.tasks
943 .spawn(async move { inner.worker(session, job).await });
944 }
945
946 async fn worker(self: Arc<Self>, session: String, mut job: Job) {
950 loop {
951 let cancel = {
952 let mut sessions = self.sessions.lock().expect("sessions poisoned");
953 let slot = sessions.entry(session.clone()).or_default();
954 match &slot.state {
955 SlotState::Running { cancel } => cancel.clone(),
956 _ => {
957 let cancel = self.root.child_token();
958 slot.state = SlotState::Running {
959 cancel: cancel.clone(),
960 };
961 cancel
962 }
963 }
964 };
965 let permit = self.permits.clone().acquire_owned().await;
966 let approval = self.process(&session, job, cancel).await;
967 drop(permit);
968
969 let next = {
970 let mut sessions = self.sessions.lock().expect("sessions poisoned");
971 let slot = sessions.entry(session.clone()).or_default();
972 if let Some(pending) = &approval {
973 slot.state = SlotState::Awaiting {
974 prompt_id: pending.prompt_id.clone(),
975 };
976 None
977 } else if let Some(next) = slot.queue.pop_front() {
978 slot.state = SlotState::Running {
979 cancel: self.root.child_token(),
980 };
981 Some(next)
982 } else {
983 slot.state = SlotState::Idle;
984 None
985 }
986 };
987 if let Some(pending) = approval {
988 self.open_approval(pending).await;
989 return;
990 }
991 match next {
992 Some(next) => job = next,
993 None => return,
994 }
995 }
996 }
997
998 async fn continuation(&self, session: &str) -> Option<RunState> {
1000 let usable =
1001 |state: &RunState| state.pending.is_none() && state.agent_id == self.agent.id();
1002 if let Some(store) = &self.store
1003 && let Some(run_id) = self.index.latest_run(session).await
1004 {
1005 match store.load_state(run_id).await {
1006 Ok(Some(state)) if usable(&state) => return Some(state),
1007 Ok(Some(_)) => {
1008 tracing::warn!(session, %run_id, "latest run cannot be continued; starting fresh")
1009 }
1010 Ok(None) => tracing::warn!(session, %run_id, "latest run not found in store"),
1011 Err(err) => {
1012 tracing::warn!(session, error = %err, "loading session state failed")
1013 }
1014 }
1015 }
1016 let sessions = self.sessions.lock().expect("sessions poisoned");
1017 sessions
1018 .get(session)
1019 .and_then(|slot| slot.last_state.clone())
1020 .filter(|state| usable(state))
1021 }
1022
1023 fn generation(&self, session: &str) -> u64 {
1024 let sessions = self.sessions.lock().expect("sessions poisoned");
1025 sessions.get(session).map_or(0, |slot| slot.generation)
1026 }
1027
1028 async fn process(
1031 self: &Arc<Self>,
1032 session: &str,
1033 job: Job,
1034 cancel: CancellationToken,
1035 ) -> Option<PendingApproval> {
1036 let generation = self.generation(session);
1037 let agent = self.agent.clone();
1038 let (origin, outcome, base) = match job {
1039 Job::Message {
1040 origin,
1041 text,
1042 attachments,
1043 role,
1044 } => {
1045 let (message, untrusted) = self
1046 .input_message(session, &origin, text, &attachments, role, &cancel)
1047 .await;
1048 let mut state = match self.continuation(session).await {
1049 Some(state) => state.with_user_message(message),
1050 None => RunState::new(self.agent.id(), session, message),
1051 };
1052 if untrusted {
1053 state = state.with_untrusted_context();
1054 }
1055 let base = state.messages.len();
1056 let run_id = state.run_id;
1057 let run = {
1058 let cancel = cancel.clone();
1059 async move { agent.run_from(state, cancel).await }
1060 };
1061 let outcome = self.drive(session, &origin, Some(run_id), run).await;
1062 (origin, outcome, base)
1063 }
1064 Job::Resume {
1065 origin,
1066 state,
1067 resolution,
1068 stopped,
1069 } => {
1070 if stopped {
1071 cancel.cancel();
1072 }
1073 let state = *state;
1074 let base = state.messages.len();
1075 let run_id = state.run_id;
1076 let run = {
1077 let cancel = cancel.clone();
1078 async move { agent.resume_with_cancel(state, resolution, cancel).await }
1079 };
1080 let outcome = self.drive(session, &origin, Some(run_id), run).await;
1081 (origin, outcome, base)
1082 }
1083 };
1084
1085 let outcome = match outcome {
1086 Ok(outcome) => outcome,
1087 Err(err) => {
1088 tracing::error!(session, error = %err, "agent run failed");
1089 self.say(
1090 &origin,
1091 &format!(
1092 "Something went wrong while running the agent: {}",
1093 render::truncate_chars(&err, 200)
1094 ),
1095 )
1096 .await;
1097 return None;
1098 }
1099 };
1100
1101 self.remember(session, generation, &outcome).await;
1102
1103 match &outcome.status {
1104 RunStatus::Completed | RunStatus::Finished { .. } => {
1107 let text = outcome.final_text.as_deref().unwrap_or("").trim();
1108 if text.is_empty() {
1109 self.reply(&origin, &render::outcome_ending_text(&outcome))
1110 .await;
1111 } else {
1112 self.reply(&origin, text).await;
1113 }
1114 None
1115 }
1116 RunStatus::Interrupted { interruption } => {
1117 let prompt_id = self.new_prompt_id();
1118 let prompt_text =
1119 render::approval_text(interruption, self.config.max_argument_chars);
1120 Some(PendingApproval {
1121 prompt_id,
1122 session_id: session.to_string(),
1123 origin,
1124 state: outcome.state,
1125 prompt_text,
1126 prompt_ref: None,
1127 expires_at_ms: now_ms()
1128 .saturating_add(self.config.approval_timeout.as_millis() as u64),
1129 })
1130 }
1131 status => {
1132 let mut text = render::ending_text(status);
1133 if let Some(partial) = partial_text(&outcome.state, base) {
1134 text.push_str("\n\nWhat I had so far:\n\n");
1135 text.push_str(&partial);
1136 }
1137 self.reply(&origin, &text).await;
1138 None
1139 }
1140 }
1141 }
1142
1143 async fn input_message(
1146 &self,
1147 session: &str,
1148 origin: &Origin,
1149 text: String,
1150 attachments: &[Attachment],
1151 role: SenderRole,
1152 cancel: &CancellationToken,
1153 ) -> (Message, bool) {
1154 if attachments.is_empty() {
1155 return (Message::user(text), false);
1156 }
1157 let channel = self.channels[origin.channel].clone();
1158 let caps = channel.capabilities();
1159 if caps.typing_indicator {
1160 let _ = channel.typing(&origin.conversation).await;
1161 }
1162 let mut images = Vec::new();
1163 let mut untrusted = false;
1164 let mut body = text;
1165 if !body.is_empty() {
1166 body.push_str("\n\n");
1167 }
1168 body.push_str(ATTACHMENTS_HEADING);
1169 for (index, attachment) in attachments.iter().enumerate() {
1170 let loaded = if caps.files && index < self.config.attachments.max_per_message {
1171 self.load_attachment(session, channel.as_ref(), attachment, role, cancel)
1172 .await
1173 } else {
1174 Loaded::Listed("not loaded")
1175 };
1176 let saved_note;
1177 let status = match loaded {
1178 Loaded::Image(image) => {
1179 images.push(image);
1180 untrusted = true;
1181 "included as an image"
1182 }
1183 Loaded::Saved(path) => {
1184 untrusted = true;
1185 saved_note = format!("saved at {}", path.display());
1186 saved_note.as_str()
1187 }
1188 Loaded::Listed(reason) => reason,
1189 };
1190 body.push('\n');
1191 body.push_str(&list_line(attachment, status));
1192 }
1193 (Message::user(body).with_images(images), untrusted)
1194 }
1195
1196 async fn load_attachment(
1198 &self,
1199 session: &str,
1200 channel: &dyn Channel,
1201 attachment: &Attachment,
1202 role: SenderRole,
1203 cancel: &CancellationToken,
1204 ) -> Loaded {
1205 let config = &self.config.attachments;
1206 let save_dir = config
1207 .save_dir
1208 .as_ref()
1209 .filter(|_| role == SenderRole::Owner);
1210 let wants_image = attachment.kind == AttachmentKind::Image;
1211 if !wants_image && save_dir.is_none() {
1212 return Loaded::Listed("not loaded");
1213 }
1214 let limit = if save_dir.is_some() {
1215 config.max_file_bytes
1216 } else {
1217 config.max_image_bytes
1218 };
1219 let download = tokio::time::timeout(
1220 config.download_timeout,
1221 channel.download_limited(attachment, limit),
1222 );
1223 let bytes = tokio::select! {
1224 _ = cancel.cancelled() => return Loaded::Listed("not loaded (the run was stopped)"),
1225 result = download => match result {
1226 Ok(Ok(bytes)) => bytes,
1227 Ok(Err(ChannelError::TooLarge { .. })) => {
1228 return Loaded::Listed("not loaded (over the size limit)")
1229 }
1230 Ok(Err(err)) => {
1231 tracing::warn!(channel = channel.name(), error = %err, "attachment download failed");
1233 return Loaded::Listed("not loaded (the download failed)");
1234 }
1235 Err(_) => return Loaded::Listed("not loaded (the download timed out)"),
1236 },
1237 };
1238 if wants_image
1239 && bytes.len() as u64 <= config.max_image_bytes
1240 && let Some(media_type) = sniff_image(&bytes)
1241 {
1242 let data = base64::engine::general_purpose::STANDARD.encode(&bytes);
1243 return Loaded::Image(Image::base64(media_type, data));
1244 }
1245 let Some(dir) = save_dir.cloned() else {
1246 return Loaded::Listed("not loaded (not a supported image)");
1247 };
1248 let (session, name) = (session.to_string(), attachment.name.clone());
1249 let saved =
1250 tokio::task::spawn_blocking(move || save_attachment(&dir, &session, &name, &bytes))
1251 .await;
1252 match saved {
1253 Ok(Ok(path)) => Loaded::Saved(path),
1254 Ok(Err(err)) => {
1255 tracing::warn!(error = %err, "could not save an attachment");
1256 Loaded::Listed("not loaded (it could not be saved)")
1257 }
1258 Err(err) => {
1259 tracing::warn!(error = %err, "saving an attachment failed");
1260 Loaded::Listed("not loaded (it could not be saved)")
1261 }
1262 }
1263 }
1264
1265 async fn remember(&self, session: &str, generation: u64, outcome: &RunOutcome) {
1267 if let Some(store) = &self.store
1268 && let Err(err) = store.save_state(&outcome.state).await
1269 {
1270 tracing::warn!(session, error = %err, "saving run state failed");
1271 }
1272 if outcome.state.pending.is_some() || self.generation(session) != generation {
1273 return;
1274 }
1275 if self.store.is_some() {
1276 self.index.set_latest(session, outcome.state.run_id).await;
1277 }
1278 let mut sessions = self.sessions.lock().expect("sessions poisoned");
1279 if let Some(slot) = sessions.get_mut(session)
1280 && slot.generation == generation
1281 {
1282 slot.last_state = Some(outcome.state.clone());
1283 }
1284 }
1285
1286 async fn drive<F>(
1288 &self,
1289 session: &str,
1290 origin: &Origin,
1291 run_id: Option<RunId>,
1292 run: F,
1293 ) -> Result<RunOutcome, String>
1294 where
1295 F: Future<Output = Result<RunOutcome, CoreError>> + Send + 'static,
1296 {
1297 let channel = self.channels[origin.channel].clone();
1298 let caps = channel.capabilities();
1299 let mut events = self.router.as_ref().map(|r| r.attach(session, run_id));
1300 let mut handle = tokio::spawn(run);
1301
1302 let mut progress = Progress::default();
1303 let mut status_ref = None;
1304 if caps.edit_messages && events.is_some() {
1305 match channel
1306 .send_status(&origin.conversation, &progress.working())
1307 .await
1308 {
1309 Ok(r) => status_ref = Some(r),
1310 Err(err) => tracing::warn!(error = %err, "could not post status message"),
1311 }
1312 }
1313 let interval = self.config.status_edit_interval;
1314 let mut last_edit = Instant::now();
1315 let mut dirty = false;
1316 let mut typing = tokio::time::interval(self.config.typing_interval);
1317 typing.set_missed_tick_behavior(MissedTickBehavior::Delay);
1318
1319 let result = loop {
1320 tokio::select! {
1321 joined = &mut handle => {
1322 break match joined {
1323 Ok(Ok(outcome)) => Ok(outcome),
1324 Ok(Err(err)) => Err(err.to_string()),
1325 Err(err) => Err(format!("run task failed: {err}")),
1326 };
1327 }
1328 event = recv_opt(&mut events) => match event {
1329 Some(event) => {
1330 if progress.apply(&event) {
1331 dirty = true;
1332 }
1333 }
1334 None => events = None,
1335 },
1336 _ = typing.tick(), if caps.typing_indicator => {
1337 let _ = channel.typing(&origin.conversation).await;
1338 }
1339 _ = tokio::time::sleep_until(last_edit + interval), if dirty && status_ref.is_some() => {
1340 if let Some(r) = &status_ref
1341 && let Err(err) = channel.update_status(r, &progress.working()).await {
1342 tracing::debug!(error = %err, "status edit failed");
1343 }
1344 last_edit = Instant::now();
1345 dirty = false;
1346 }
1347 }
1348 };
1349
1350 if let Some(rx) = events.as_mut() {
1351 while let Ok(event) = rx.try_recv() {
1352 progress.apply(&event);
1353 }
1354 }
1355 if let Some(router) = &self.router {
1356 router.detach(session);
1357 }
1358 if let Some(r) = &status_ref {
1359 let ending = match &result {
1360 Ok(outcome) => render::outcome_ending(outcome),
1361 Err(_) => RunEnding::Failed,
1362 };
1363 if let Err(err) = channel.update_status(r, &progress.ended(ending)).await {
1364 tracing::debug!(error = %err, "final status edit failed");
1365 }
1366 }
1367 result
1368 }
1369
1370 fn new_prompt_id(&self) -> String {
1371 let approvals = self.approvals.lock().expect("approvals poisoned");
1372 loop {
1373 let id: String = RunId::new().to_string().chars().take(8).collect();
1374 if !approvals.contains_key(&id) {
1375 return id;
1376 }
1377 }
1378 }
1379
1380 async fn open_approval(self: &Arc<Self>, pending: PendingApproval) {
1382 let prompt_id = pending.prompt_id.clone();
1383 let origin = pending.origin.clone();
1384 let mut prompt = ApprovalPrompt::new(
1385 prompt_id.clone(),
1386 origin.conversation.clone(),
1387 pending.prompt_text.clone(),
1388 vec![
1389 ApprovalChoice {
1390 id: APPROVE_CHOICE.to_string(),
1391 label: "Approve".to_string(),
1392 },
1393 ApprovalChoice {
1394 id: DENY_CHOICE.to_string(),
1395 label: "Deny".to_string(),
1396 },
1397 ],
1398 );
1399 if let Some(waiting) = &pending.state.pending {
1400 prompt = prompt.with_details(ApprovalDetails::from_interruption(&waiting.interruption));
1401 }
1402 self.persist_approval(&pending).await;
1405 self.approvals
1406 .lock()
1407 .expect("approvals poisoned")
1408 .insert(prompt_id.clone(), pending);
1409
1410 let channel = self.channels[origin.channel].clone();
1411 let asked = if channel.capabilities().buttons {
1414 channel.ask(&prompt).await
1415 } else {
1416 Err(ChannelError::Unsupported("buttons"))
1417 };
1418 let prompt_ref = match asked {
1419 Ok(r) => Some(r),
1420 Err(err) => {
1421 if !matches!(err, ChannelError::Unsupported(_)) {
1422 tracing::warn!(error = %err, "approval buttons failed; using text commands");
1423 }
1424 let text = format!(
1425 "{}\n\n{}",
1426 prompt.text,
1427 render::approval_fallback(&prompt_id)
1428 );
1429 let message = OutboundMessage::text(render::truncate_chars(
1430 &text,
1431 channel.capabilities().max_message_len,
1432 ));
1433 match channel.send(&origin.conversation, &message).await {
1434 Ok(r) => Some(r),
1435 Err(err) => {
1436 tracing::error!(error = %err, "could not show approval prompt");
1437 None
1438 }
1439 }
1440 }
1441 };
1442 let updated = {
1443 let mut approvals = self.approvals.lock().expect("approvals poisoned");
1444 approvals.get_mut(&prompt_id).and_then(|entry| {
1445 entry.prompt_ref = prompt_ref;
1446 self.stored_approval(entry)
1447 })
1448 };
1449 if let (Some(store), Some(record)) = (&self.approval_store, updated)
1451 && let Err(err) = store.save(&record).await
1452 {
1453 tracing::warn!(prompt = %prompt_id, error = %err, "saving approval failed");
1454 }
1455
1456 self.arm_expiry(prompt_id, self.config.approval_timeout);
1457 }
1458
1459 fn arm_expiry(self: &Arc<Self>, prompt_id: String, after: Duration) {
1461 let inner = self.clone();
1462 self.tasks.spawn(async move {
1463 tokio::select! {
1464 _ = tokio::time::sleep(after) => {}
1465 _ = inner.root.cancelled() => return,
1466 }
1467 let expired = inner
1468 .approvals
1469 .lock()
1470 .expect("approvals poisoned")
1471 .remove(&prompt_id);
1472 if let Some(pending) = expired {
1473 inner.forget_approval(&prompt_id).await;
1474 inner.mark_prompt(&pending, "Expired (denied)", None).await;
1475 inner
1476 .say(
1477 &pending.origin,
1478 &format!("Approval `{prompt_id}` expired, so the action was denied."),
1479 )
1480 .await;
1481 inner.resume(
1482 pending,
1483 Resolution::Deny {
1484 reason: "The approval request expired without an answer.".to_string(),
1485 },
1486 false,
1487 );
1488 }
1489 });
1490 }
1491
1492 fn stored_approval(&self, pending: &PendingApproval) -> Option<StoredApproval> {
1494 self.approval_store.as_ref()?;
1495 Some(StoredApproval {
1496 prompt_id: pending.prompt_id.clone(),
1497 session_id: pending.session_id.clone(),
1498 channel: self.channel_name(pending.origin.channel).to_string(),
1499 conversation: pending.origin.conversation.clone(),
1500 reply_to: pending.origin.reply_to.clone(),
1501 run_id: pending.state.run_id,
1502 prompt_text: pending.prompt_text.clone(),
1503 prompt_ref: pending.prompt_ref.clone(),
1504 expires_at_ms: pending.expires_at_ms,
1505 })
1506 }
1507
1508 async fn persist_approval(&self, pending: &PendingApproval) {
1509 if let (Some(store), Some(record)) = (&self.approval_store, self.stored_approval(pending))
1510 && let Err(err) = store.save(&record).await
1511 {
1512 tracing::warn!(prompt = %pending.prompt_id, error = %err, "saving approval failed");
1513 }
1514 }
1515
1516 async fn forget_approval(&self, prompt_id: &str) {
1518 if let Some(store) = &self.approval_store
1519 && let Err(err) = store.remove(prompt_id).await
1520 {
1521 tracing::warn!(prompt = prompt_id, error = %err, "removing approval failed");
1522 }
1523 }
1524
1525 async fn restore_approvals(&self) -> Vec<(String, Duration)> {
1528 let (Some(approvals), Some(store)) = (&self.approval_store, &self.store) else {
1529 return Vec::new();
1530 };
1531 let records = match approvals.load_all().await {
1532 Ok(records) => records,
1533 Err(err) => {
1534 tracing::error!(error = %err, "could not load pending approvals");
1535 return Vec::new();
1536 }
1537 };
1538 let now = now_ms();
1539 let mut restored = Vec::new();
1540 for record in records {
1541 let Some(channel) = self
1542 .channels
1543 .iter()
1544 .position(|c| c.name() == record.channel)
1545 else {
1546 if record.expires_at_ms <= now {
1548 self.forget_approval(&record.prompt_id).await;
1549 }
1550 continue;
1551 };
1552 let state = match store.load_state(record.run_id).await {
1553 Ok(Some(state)) if state.pending.is_some() && state.agent_id == self.agent.id() => {
1554 state
1555 }
1556 Ok(_) => {
1557 tracing::warn!(prompt = %record.prompt_id, run = %record.run_id, "approval has no interrupted run to resume; dropping it");
1558 self.forget_approval(&record.prompt_id).await;
1559 continue;
1560 }
1561 Err(err) => {
1562 tracing::warn!(prompt = %record.prompt_id, error = %err, "could not load the run of a pending approval");
1563 continue;
1564 }
1565 };
1566 let remaining = Duration::from_millis(record.expires_at_ms.saturating_sub(now));
1567 self.sessions
1568 .lock()
1569 .expect("sessions poisoned")
1570 .entry(record.session_id.clone())
1571 .or_default()
1572 .state = SlotState::Awaiting {
1573 prompt_id: record.prompt_id.clone(),
1574 };
1575 restored.push((record.prompt_id.clone(), remaining));
1576 self.approvals.lock().expect("approvals poisoned").insert(
1577 record.prompt_id.clone(),
1578 PendingApproval {
1579 prompt_id: record.prompt_id,
1580 session_id: record.session_id,
1581 origin: Origin {
1582 channel,
1583 conversation: record.conversation,
1584 reply_to: record.reply_to,
1585 },
1586 state,
1587 prompt_text: record.prompt_text,
1588 prompt_ref: record.prompt_ref,
1589 expires_at_ms: record.expires_at_ms,
1590 },
1591 );
1592 }
1593 restored
1594 }
1595
1596 async fn mark_prompt(
1601 &self,
1602 pending: &PendingApproval,
1603 verdict: &str,
1604 pressed: Option<&MessageRef>,
1605 ) {
1606 let channel = &self.channels[pending.origin.channel];
1607 let caps = channel.capabilities();
1608 let Some(target) = pending.prompt_ref.as_ref().or(pressed) else {
1609 return;
1610 };
1611 if caps.edit_messages {
1612 let room = caps
1614 .max_message_len
1615 .saturating_sub(verdict.chars().count() + 6);
1616 let text = format!(
1617 "{}\n\n**{verdict}**",
1618 render::truncate_chars(&pending.prompt_text, room)
1619 );
1620 match channel.edit(target, &text).await {
1621 Ok(()) => return,
1622 Err(err) => tracing::debug!(error = %err, "could not mark the prompt"),
1623 }
1624 }
1625 if caps.buttons {
1626 self.remove_buttons(pending.origin.channel, target).await;
1627 }
1628 }
1629
1630 async fn remove_buttons(&self, channel: usize, message: &MessageRef) {
1631 if let Err(err) = self.channels[channel].remove_buttons(message).await {
1632 tracing::debug!(error = %err, "could not remove the buttons");
1633 }
1634 }
1635
1636 fn resume(self: &Arc<Self>, pending: PendingApproval, resolution: Resolution, stopped: bool) {
1638 let job = Job::Resume {
1639 origin: pending.origin,
1640 state: Box::new(pending.state),
1641 resolution,
1642 stopped,
1643 };
1644 let start = {
1645 let mut sessions = self.sessions.lock().expect("sessions poisoned");
1646 let slot = sessions.entry(pending.session_id.clone()).or_default();
1647 match slot.state {
1648 SlotState::Running { .. } => {
1649 slot.queue.push_front(job);
1652 None
1653 }
1654 _ => {
1655 slot.state = SlotState::Running {
1656 cancel: self.root.child_token(),
1657 };
1658 Some(job)
1659 }
1660 }
1661 };
1662 if let Some(job) = start {
1663 self.spawn_worker(pending.session_id, job);
1664 }
1665 }
1666
1667 async fn answer(
1669 self: &Arc<Self>,
1670 origin: Origin,
1671 sender_id: &str,
1672 prompt_id: Option<String>,
1673 approve: bool,
1674 pressed: Option<MessageRef>,
1675 ) {
1676 let name = self.channel_name(origin.channel).to_string();
1677 if !self.policy.may_approve(&name, sender_id) {
1678 tracing::info!(channel = %name, sender = sender_id, "ignoring approval from a user who may not approve");
1679 return;
1680 }
1681 let session = session_id(&name, &origin.conversation.id);
1682 let settled = {
1683 let mut approvals = self.approvals.lock().expect("approvals poisoned");
1684 let id = prompt_id.clone().or_else(|| {
1685 let mut ids = approvals
1686 .iter()
1687 .filter(|(_, p)| p.session_id == session)
1688 .map(|(id, _)| id.clone());
1689 match (ids.next(), ids.next()) {
1690 (Some(only), None) => Some(only),
1691 _ => None,
1692 }
1693 });
1694 match id {
1695 Some(id) if approvals.get(&id).is_some_and(|p| p.session_id == session) => {
1696 approvals.remove(&id).map(|p| (id, p))
1697 }
1698 _ => None,
1699 }
1700 };
1701 let Some((id, pending)) = settled else {
1702 let notice = match prompt_id {
1703 Some(id) => {
1704 format!("Approval `{id}` is not pending here (already answered or expired).")
1705 }
1706 None => {
1707 "There is no single pending approval here; use `/approve <id>` or `/deny <id>`."
1708 .to_string()
1709 }
1710 };
1711 if let Some(message) = &pressed {
1713 self.remove_buttons(origin.channel, message).await;
1714 }
1715 self.say(&origin, ¬ice).await;
1716 return;
1717 };
1718 tracing::info!(session = %session, prompt = %id, approve, "approval settled");
1719 self.forget_approval(&id).await;
1720 self.mark_prompt(
1721 &pending,
1722 if approve { "Approved" } else { "Denied" },
1723 pressed.as_ref(),
1724 )
1725 .await;
1726 let resolution = if approve {
1727 Resolution::Approve
1728 } else {
1729 Resolution::Deny {
1730 reason: "The user denied this action.".to_string(),
1731 }
1732 };
1733 self.resume(pending, resolution, false);
1734 }
1735
1736 async fn stop(self: &Arc<Self>, session: &str, origin: &Origin) {
1737 enum Action {
1738 Cancelled(usize),
1739 Settle(Box<PendingApproval>, usize),
1740 Nothing,
1741 }
1742 let action = {
1743 let mut sessions = self.sessions.lock().expect("sessions poisoned");
1744 match sessions.get_mut(session) {
1745 Some(slot) => {
1746 let dropped = slot.queue.len();
1747 slot.queue.clear();
1748 match &slot.state {
1749 SlotState::Running { cancel } => {
1750 cancel.cancel();
1751 Action::Cancelled(dropped)
1752 }
1753 SlotState::Awaiting { prompt_id } => {
1754 let pending = self
1755 .approvals
1756 .lock()
1757 .expect("approvals poisoned")
1758 .remove(prompt_id);
1759 match pending {
1760 Some(pending) => Action::Settle(Box::new(pending), dropped),
1761 None => Action::Cancelled(dropped),
1763 }
1764 }
1765 SlotState::Idle => Action::Nothing,
1766 }
1767 }
1768 None => Action::Nothing,
1769 }
1770 };
1771 match action {
1772 Action::Nothing => self.say(origin, "Nothing is running.").await,
1773 Action::Cancelled(dropped) => {
1774 if dropped > 0 {
1775 self.say(origin, &format!("Dropped {dropped} queued message(s)."))
1776 .await;
1777 }
1778 }
1779 Action::Settle(pending, dropped) => {
1780 if dropped > 0 {
1781 self.say(origin, &format!("Dropped {dropped} queued message(s)."))
1782 .await;
1783 }
1784 self.forget_approval(&pending.prompt_id).await;
1785 self.mark_prompt(&pending, "Stopped", None).await;
1786 self.resume(
1787 *pending,
1788 Resolution::Deny {
1789 reason: "The user stopped the run.".to_string(),
1790 },
1791 true,
1792 );
1793 }
1794 }
1795 }
1796
1797 async fn reset(self: &Arc<Self>, session: &str, origin: &Origin) {
1798 let dropped_approval = {
1799 let mut sessions = self.sessions.lock().expect("sessions poisoned");
1800 let slot = sessions.entry(session.to_string()).or_default();
1801 slot.generation += 1;
1802 slot.last_state = None;
1803 slot.queue.clear();
1804 match &slot.state {
1805 SlotState::Running { cancel } => {
1806 cancel.cancel();
1807 None
1808 }
1809 SlotState::Awaiting { prompt_id } => {
1810 let pending = self
1811 .approvals
1812 .lock()
1813 .expect("approvals poisoned")
1814 .remove(prompt_id);
1815 slot.state = SlotState::Idle;
1816 pending
1817 }
1818 SlotState::Idle => None,
1819 }
1820 };
1821 if let Some(pending) = dropped_approval {
1822 self.forget_approval(&pending.prompt_id).await;
1823 self.mark_prompt(&pending, "Cancelled", None).await;
1824 }
1825 self.index.clear(session).await;
1826 self.say(origin, "Started a new conversation.").await;
1827 }
1828
1829 async fn status(&self, session: &str, origin: &Origin) {
1830 let text = {
1831 let sessions = self.sessions.lock().expect("sessions poisoned");
1832 match sessions.get(session) {
1833 Some(slot) => {
1834 let queued = slot.queue.len();
1835 match &slot.state {
1836 SlotState::Idle => format!("Idle. Queued messages: {queued}."),
1837 SlotState::Running { .. } => {
1838 format!("A run is active. Queued messages: {queued}.")
1839 }
1840 SlotState::Awaiting { prompt_id } => format!(
1841 "Waiting for approval `{prompt_id}`. Queued messages: {queued}."
1842 ),
1843 }
1844 }
1845 None => "Idle. Queued messages: 0.".to_string(),
1846 }
1847 };
1848 self.say(origin, &text).await;
1849 }
1850}
1851
1852fn now_ms() -> u64 {
1853 SystemTime::now()
1854 .duration_since(UNIX_EPOCH)
1855 .map_or(0, |elapsed| elapsed.as_millis() as u64)
1856}
1857
1858fn partial_text(state: &RunState, base: usize) -> Option<String> {
1860 state
1861 .messages
1862 .get(base.min(state.messages.len())..)?
1863 .iter()
1864 .rev()
1865 .find(|m| m.role == Role::Assistant && !m.content.trim().is_empty())
1866 .map(|m| m.content.trim().to_string())
1867}
1868
1869#[cfg(test)]
1870mod tests {
1871 use super::*;
1872
1873 #[test]
1874 fn commands_are_parsed_from_explicit_syntax_only() {
1875 assert!(matches!(parse_command("/stop"), Some(Command::Stop)));
1876 assert!(matches!(
1877 parse_command(" /stop@my_bot "),
1878 Some(Command::Stop)
1879 ));
1880 assert!(matches!(parse_command("/NEW"), Some(Command::New)));
1881 assert!(matches!(
1882 parse_command("/approve ab12cd34"),
1883 Some(Command::Approve(Some(id))) if id == "ab12cd34"
1884 ));
1885 assert!(matches!(parse_command("/deny"), Some(Command::Deny(None))));
1886 assert!(parse_command("please stop").is_none());
1887 assert!(parse_command("/unknown thing").is_none());
1888 }
1889}