1use std::collections::HashMap;
10use std::sync::Arc;
11
12use aidaemon_events::conversation::{ConversationSummary, Message};
13use aidaemon_events::provider::TokenUsageRecord;
14use aidaemon_tools::duration_format::{ZeroUnitStyle, compact_chrono_duration};
15use aidaemon_tools::semantics::UserRole;
16use async_trait::async_trait;
17use chrono::{DateTime, Utc};
18
19use crate::ports::ChannelAgentRuntime;
20use crate::tasks::{TaskRegistry, TaskStatus};
21
22pub fn is_slash_command(text: &str) -> bool {
26 let Some(first) = text.split_whitespace().next() else {
27 return false;
28 };
29 let Some(rest) = first.strip_prefix('/') else {
30 return false;
31 };
32 let name = rest.split_once('@').map_or(rest, |(name, _bot)| name);
33 !name.is_empty()
34 && name.starts_with(|c: char| c.is_ascii_alphabetic())
35 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
36}
37
38#[cfg(test)]
39mod slash_command_tests {
40 use super::is_slash_command;
41
42 #[test]
43 fn commands_are_names_and_paths_are_messages() {
44 for command in [
45 "/help",
46 "/model gpt-5.6-terra",
47 "/clear",
48 "/start@aidaemon_bot",
49 "/set_up now",
50 ] {
51 assert!(is_slash_command(command), "{command}");
52 }
53 for message in [
54 "/tmp/aidaemon-live/prime/prime.py has a bug",
55 "/Users/alice/notes.txt",
56 "/ what",
57 "/",
58 "/123",
59 "hello /help",
60 ] {
61 assert!(!is_slash_command(message), "{message}");
62 }
63 }
64}
65
66pub struct CommandDef {
72 pub name: &'static str,
74 pub description: &'static str,
77 pub usage: Option<&'static str>,
79 pub category: CommandCategory,
81}
82
83#[derive(Clone, Copy, PartialEq, Eq)]
85pub enum CommandCategory {
86 Core,
88 Restart,
90 Connect,
92 Terminal,
94}
95
96pub fn shared_commands() -> Vec<CommandDef> {
98 vec![
99 CommandDef {
100 name: "model",
101 description: "Show or switch AI model",
102 usage: Some("/model [name]"),
103 category: CommandCategory::Core,
104 },
105 CommandDef {
106 name: "models",
107 description: "List available models",
108 usage: None,
109 category: CommandCategory::Core,
110 },
111 CommandDef {
112 name: "auto",
113 description: "Re-enable automatic model routing",
114 usage: None,
115 category: CommandCategory::Core,
116 },
117 CommandDef {
118 name: "reload",
119 description: "Reload configuration",
120 usage: None,
121 category: CommandCategory::Core,
122 },
123 CommandDef {
124 name: "tasks",
125 description: "List running tasks",
126 usage: None,
127 category: CommandCategory::Core,
128 },
129 CommandDef {
130 name: "status",
131 description: "Show this chat's mode, running tasks and what's next",
132 usage: None,
133 category: CommandCategory::Core,
134 },
135 CommandDef {
136 name: "work",
137 description: "See and manage longer work that waits or runs on its own",
138 usage: Some("/work [ready|running|blocked|show|comment|unblock|retry]"),
139 category: CommandCategory::Core,
140 },
141 CommandDef {
142 name: "cancel",
143 description: "Stop what's running in this chat",
144 usage: Some("/cancel [all|number]"),
145 category: CommandCategory::Core,
146 },
147 CommandDef {
148 name: "clear",
149 description: "Start fresh conversation (history kept)",
150 usage: None,
151 category: CommandCategory::Core,
152 },
153 CommandDef {
154 name: "wipe",
155 description: "Permanently delete this conversation (send twice to confirm)",
156 usage: None,
157 category: CommandCategory::Core,
158 },
159 CommandDef {
160 name: "cost",
161 description: "Show token usage stats",
162 usage: None,
163 category: CommandCategory::Core,
164 },
165 CommandDef {
166 name: "context",
167 description: "Show conversation context coverage",
168 usage: None,
169 category: CommandCategory::Core,
170 },
171 CommandDef {
172 name: "checkpoints",
173 description: "List filesystem checkpoints",
174 usage: None,
175 category: CommandCategory::Core,
176 },
177 CommandDef {
178 name: "readonly",
179 description: "Make this chat read-only for 4 hours",
180 usage: None,
181 category: CommandCategory::Core,
182 },
183 CommandDef {
184 name: "private",
185 description: "Don't remember or learn from your next message",
186 usage: Some("/private [off]"),
187 category: CommandCategory::Core,
188 },
189 CommandDef {
190 name: "mode",
191 description: "Show or change this chat's access mode",
192 usage: Some("/mode [full|unrestricted|readonly]"),
193 category: CommandCategory::Core,
194 },
195 CommandDef {
196 name: "rollback",
197 description: "Preview or confirm a checkpoint rollback",
198 usage: Some("/rollback [checkpoint-id|confirm TOKEN]"),
199 category: CommandCategory::Core,
200 },
201 ]
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
206pub enum ChatMode {
207 ReadOnly,
208 Full,
209 Unrestricted,
210}
211
212#[async_trait]
214pub trait CommandHost: Send + Sync {
215 async fn set_next_message_private(
218 &self,
219 session_id: &str,
220 sender_id: Option<&str>,
221 on: bool,
222 ) -> anyhow::Result<()>;
223 async fn chat_mode(
225 &self,
226 session_id: &str,
227 now: DateTime<Utc>,
228 ) -> Option<(ChatMode, Option<DateTime<Utc>>)>;
229 async fn set_chat_mode(
231 &self,
232 session_id: &str,
233 mode: ChatMode,
234 now: DateTime<Utc>,
235 ) -> anyhow::Result<DateTime<Utc>>;
236 fn chat_mode_hours(&self) -> i64;
238 async fn history(&self, session_id: &str, limit: usize) -> anyhow::Result<Vec<Message>>;
239 async fn conversation_summary(
240 &self,
241 session_id: &str,
242 ) -> anyhow::Result<Option<ConversationSummary>>;
243 fn estimate_message_tokens(&self, messages: &[serde_json::Value]) -> usize;
245 fn estimate_text_tokens(&self, text: &str) -> usize;
246 async fn token_usage_since(&self, since: &str) -> anyhow::Result<Vec<TokenUsageRecord>>;
248 async fn next_scheduled(&self) -> Option<ScheduledItem> {
251 None
252 }
253
254 fn owner_time(&self, _at: DateTime<Utc>) -> Option<String> {
257 None
258 }
259}
260
261#[derive(Debug, Clone, PartialEq, Eq)]
263pub struct ScheduledItem {
264 pub what: String,
266 pub when: String,
268}
269
270const SCHEDULED_NAME_MAX: usize = 60;
273
274pub fn scheduled_name(name: Option<&str>, description: &str) -> String {
278 if let Some(name) = name.map(str::trim).filter(|name| !name.is_empty()) {
279 return name.to_string();
280 }
281 let description = description.split_whitespace().collect::<Vec<_>>().join(" ");
282 if !description.is_empty() && description.chars().count() <= SCHEDULED_NAME_MAX {
283 return description;
284 }
285 "An automation without a name (see /work)".to_string()
286}
287
288#[derive(Debug, Clone)]
290pub struct StatusView {
291 pub now: Option<String>,
293 pub mode: Option<(ChatMode, Option<DateTime<Utc>>)>,
295 pub running: crate::stop::WorkList,
299 pub next_scheduled: Option<ScheduledItem>,
300}
301
302fn mode_line(mode: Option<(ChatMode, Option<DateTime<Utc>>)>, now: DateTime<Utc>) -> String {
304 let left = |until: Option<DateTime<Utc>>| {
305 until.map_or_else(String::new, |at| {
306 format!(
307 " (about {} left)",
308 compact_chrono_duration(at - now, ZeroUnitStyle::Trim)
309 )
310 })
311 };
312 match mode {
313 Some((ChatMode::ReadOnly, until)) => format!("Mode: read-only{}.", left(until)),
314 Some((ChatMode::Unrestricted, until)) => format!("Mode: unrestricted{}.", left(until)),
315 Some((ChatMode::Full, _)) | None => "Mode: full.".to_string(),
316 }
317}
318
319fn cancel_hint(running: &crate::stop::WorkList) -> &'static str {
321 match running.entries.len() {
322 0 => "",
323 1 => "Send /cancel to stop it.",
324 _ if running.requests() > 1 => {
325 "Send /cancel <number> to stop one, or /cancel all to stop everything."
326 }
327 _ => "Send /cancel to stop all of it, or /cancel <number> for one.",
328 }
329}
330
331pub fn render_tasks(
336 running: &crate::stop::WorkList,
337 failed: &[crate::tasks::TaskEntry],
338 now: DateTime<Utc>,
339 as_of: Option<&str>,
340) -> String {
341 let stamp = as_of.map(|at| format!("As of {at}:\n"));
342 let stamp = stamp.as_deref().unwrap_or("");
343 if running.entries.is_empty() && failed.is_empty() {
344 return format!(
345 "{stamp}Nothing is running in this chat right now. Use /work for longer work that \
346 waits or runs on its own."
347 );
348 }
349 let mut sections = Vec::new();
350 if running.entries.is_empty() {
351 sections.push("Nothing is running in this chat right now.".to_string());
352 } else {
353 sections.push(format!(
354 "Running in this chat:\n{}\n\n{}",
355 running.lines(now).join("\n"),
356 cancel_hint(running)
357 ));
358 }
359 if !failed.is_empty() {
360 let lines: Vec<String> = failed
361 .iter()
362 .map(|entry| {
363 let at = entry.finished_at.unwrap_or(now);
364 format!(
365 "#{} {} – it failed after {}",
366 entry.id,
367 crate::stop::TURN_LABEL,
368 compact_chrono_duration(at - entry.started_at, ZeroUnitStyle::Trim)
369 )
370 })
371 .collect();
372 sections.push(format!("Recently failed:\n{}", lines.join("\n")));
373 }
374 sections.push("Use /work for longer work that waits or runs on its own.".to_string());
375 format!("{stamp}{}", sections.join("\n\n"))
376}
377
378pub fn render_status(view: &StatusView, now: DateTime<Utc>) -> String {
380 let mode = mode_line(view.mode, now);
381 let mut lines = vec![match &view.now {
382 Some(local) => format!("As of {local}: {mode}"),
383 None => mode,
384 }];
385 if view.running.entries.is_empty() {
386 lines.push("Running: nothing right now.".to_string());
387 } else {
388 lines.push("Running:".to_string());
389 for entry in &view.running.entries {
390 lines.push(format!(
391 "• {} ({} so far, /cancel {} to stop it)",
392 crate::presentation::word_preview(&entry.title, 120),
393 compact_chrono_duration(now - entry.started_at, ZeroUnitStyle::Trim),
394 entry.number
395 ));
396 }
397 }
398 lines.push(match &view.next_scheduled {
399 Some(item) => format!("Next scheduled: {} – {}", item.what, item.when),
400 None => "Next scheduled: nothing.".to_string(),
401 });
402 lines.join("\n")
403}
404
405fn stopped_with_turns(turns: usize, work: Vec<String>) -> Vec<String> {
410 let mut stopped = vec![crate::stop::TURN_LABEL.to_string(); turns];
411 stopped.extend(work);
412 stopped
413}
414
415fn clear_suffix(cancellations: &[String], stopped_work: &[String]) -> String {
419 let mut suffix = if cancellations.is_empty() {
420 String::new()
421 } else {
422 format!(" ({} cancelled.)", cancellations.join(" and "))
423 };
424 let stopped = crate::stop::stopped_list(stopped_work);
425 if !stopped.is_empty() {
426 suffix.push_str("\n\n");
427 suffix.push_str(&stopped);
428 }
429 suffix
430}
431
432pub fn cancel_request(args: &str) -> Option<crate::stop::StopRequest> {
434 let args = args.trim();
435 if args.is_empty() {
436 return Some(crate::stop::StopRequest::Bare);
437 }
438 if args.eq_ignore_ascii_case("all") {
439 return Some(crate::stop::StopRequest::All);
440 }
441 let numbers: Option<Vec<u64>> = args
442 .split(|c: char| c.is_whitespace() || c == ',')
443 .filter(|part| !part.is_empty())
444 .map(|part| part.trim_start_matches('#').parse::<u64>().ok())
445 .collect();
446 numbers
447 .filter(|numbers| !numbers.is_empty())
448 .map(crate::stop::StopRequest::Numbers)
449}
450
451pub fn closest_command<'a>(name: &str, commands: &'a [CommandDef]) -> Option<&'a str> {
454 let name = name.to_ascii_lowercase();
455 let len = name.chars().count();
456 if len == 0 {
457 return None;
458 }
459 let limit = if len <= 4 { 1 } else { 2 };
460 commands
461 .iter()
462 .map(|command| (edit_distance(&name, command.name), command.name))
463 .filter(|(distance, _)| *distance <= limit)
464 .min_by_key(|(distance, _)| *distance)
465 .map(|(_, command)| command)
466}
467
468fn edit_distance(a: &str, b: &str) -> usize {
469 let b: Vec<char> = b.chars().collect();
470 let mut previous: Vec<usize> = (0..=b.len()).collect();
471 for (i, ca) in a.chars().enumerate() {
472 let mut current = vec![i + 1; b.len() + 1];
473 for (j, cb) in b.iter().enumerate() {
474 let substitution = previous[j] + usize::from(ca != *cb);
475 current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
476 }
477 previous = current;
478 }
479 previous[b.len()]
480}
481
482pub fn unknown_command_reply(cmd: &str, commands: &[CommandDef], prefix: &str) -> String {
485 let name = cmd
486 .trim_start_matches(prefix)
487 .split('@')
488 .next()
489 .unwrap_or("");
490 match closest_command(name, commands) {
491 Some(suggestion) => format!(
492 "I don't know {cmd}. Did you mean {prefix}{suggestion}? Send {prefix}help to see \
493 the commands."
494 ),
495 None => format!("I don't know {cmd}. Send {prefix}help to see the commands."),
496 }
497}
498
499#[derive(Debug, Clone, Copy, PartialEq, Eq)]
501pub enum PrivateRequest<'a> {
502 Next,
505 With(&'a str),
508}
509
510pub fn private_request(text: &str) -> Option<PrivateRequest<'_>> {
514 let mut rest = text.trim_start();
515 let mut seen = 0usize;
516 while let Some(after) = strip_prefix_ignore_case(rest, "/private") {
517 seen += 1;
518 rest = match after.strip_prefix('@') {
520 Some(bot) => bot.find(char::is_whitespace).map_or("", |at| &bot[at..]),
521 None => after,
522 };
523 rest = rest.trim_start();
524 }
525 if seen == 0 {
526 return None;
527 }
528 let message = rest.trim();
529 if message.is_empty() {
530 return (seen > 1).then_some(PrivateRequest::Next);
531 }
532 if message.eq_ignore_ascii_case("off") {
533 return None;
534 }
535 Some(PrivateRequest::With(message))
536}
537
538fn strip_prefix_ignore_case<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
539 let head = text.get(..prefix.len())?;
540 head.eq_ignore_ascii_case(prefix)
541 .then(|| &text[prefix.len()..])
542}
543
544pub const EVERYDAY_COMMANDS: &[&str] = &["clear", "tasks", "status", "private", "readonly", "mode"];
546
547#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub enum HelpScope {
550 Everyday,
552 All,
554}
555
556impl HelpScope {
557 pub fn from_args(args: &str) -> Self {
558 if args.trim().eq_ignore_ascii_case("all") {
559 Self::All
560 } else {
561 Self::Everyday
562 }
563 }
564}
565
566pub struct SlashCall<'a> {
568 pub session_id: &'a str,
569 pub sender_id: Option<&'a str>,
570 pub user_role: UserRole,
571}
572
573#[async_trait]
575pub trait SlashCommand: Send + Sync {
576 fn handles(&self, cmd: &str) -> bool;
578 async fn run(&self, cmd: &str, args: &str, call: &SlashCall<'_>) -> String;
579 fn commands(&self) -> Vec<CommandDef> {
582 Vec::new()
583 }
584}
585
586pub struct SharedCommands {
589 pub agent: Arc<dyn ChannelAgentRuntime>,
590 pub host: Arc<dyn CommandHost>,
591 pub task_registry: Arc<TaskRegistry>,
592 pub extensions: Vec<Arc<dyn SlashCommand>>,
594}
595
596impl SharedCommands {
597 pub fn extension_commands(&self) -> Vec<CommandDef> {
599 self.extensions
600 .iter()
601 .flat_map(|extension| extension.commands())
602 .collect()
603 }
604
605 pub async fn dispatch(
608 &self,
609 cmd: &str,
610 args: &str,
611 session_id: &str,
612 sender_id: Option<&str>,
613 user_role: UserRole,
614 ) -> Option<String> {
615 if user_role != UserRole::Owner
621 && !matches!(
622 cmd,
623 "/private" | "/tasks" | "/cancel" | "/context" | "/readonly" | "/mode"
624 )
625 {
626 let shared = matches!(
627 cmd,
628 "/model" | "/models" | "/auto" | "/clear" | "/new" | "/status" | "/wipe" | "/cost"
629 ) || self.extensions.iter().any(|ext| ext.handles(cmd));
630 return shared.then(|| format!("Only the owner can use {cmd}."));
631 }
632 Some(match cmd {
633 "/model" => self.handle_model(args).await,
634 "/models" => self.handle_models().await,
635 "/auto" => self.handle_auto().await,
636 "/tasks" => self.handle_tasks(session_id).await,
637 "/cancel" => self.handle_cancel(args, session_id, user_role).await,
638 "/clear" | "/new" => self.handle_clear(session_id).await,
639 "/status" => self.handle_status(session_id).await,
640 "/wipe" => self.handle_wipe(session_id).await,
641 "/cost" => self.handle_cost().await,
642 "/context" => self.handle_context(session_id, user_role).await,
643 "/readonly" => self.handle_readonly(session_id, user_role).await,
644 "/private" => self.handle_private(args, session_id, sender_id).await,
645 "/mode" => self.handle_mode(args, session_id, user_role).await,
646 _ => {
647 let extension = self.extensions.iter().find(|ext| ext.handles(cmd))?;
648 let call = SlashCall {
649 session_id,
650 sender_id,
651 user_role,
652 };
653 extension.run(cmd, args, &call).await
654 }
655 })
656 }
657
658 async fn handle_status(&self, session_id: &str) -> String {
659 let now = Utc::now();
660 let view = StatusView {
661 now: self.host.owner_time(now),
662 mode: self.host.chat_mode(session_id, now).await,
663 running: crate::stop::running_work(
664 &self.task_registry,
665 self.agent.as_ref(),
666 session_id,
667 )
668 .await,
669 next_scheduled: self.host.next_scheduled().await,
670 };
671 render_status(&view, now)
672 }
673
674 async fn handle_private(
679 &self,
680 args: &str,
681 session_id: &str,
682 sender_id: Option<&str>,
683 ) -> String {
684 let on = match args.trim().to_ascii_lowercase().as_str() {
685 "" => true,
686 "off" => false,
687 _ => return "Usage: /private [off]".to_string(),
688 };
689 match self
690 .host
691 .set_next_message_private(session_id, sender_id, on)
692 .await
693 {
694 Ok(()) if on => "Your next message won't be remembered or learned from. \
695 Memory can still be used to answer it."
696 .to_string(),
697 Ok(()) => "Cancelled: your next message is remembered as usual.".to_string(),
698 Err(error) => format!("Could not set that: {error}"),
699 }
700 }
701
702 async fn handle_readonly(&self, session_id: &str, user_role: UserRole) -> String {
703 self.handle_mode("readonly", session_id, user_role).await
704 }
705
706 async fn handle_mode(&self, args: &str, session_id: &str, user_role: UserRole) -> String {
709 let session_mode_ttl_hours = self.host.chat_mode_hours();
710 const NOT_OWNER: &str = "Only the owner can change the mode.";
711 const USAGE: &str = "Usage: /mode [full|unrestricted|readonly]";
712 if user_role != UserRole::Owner {
713 return NOT_OWNER.to_string();
714 }
715 let now = Utc::now();
716 let requested = match args.trim().to_ascii_lowercase().as_str() {
717 "" => return mode_line(self.host.chat_mode(session_id, now).await, now),
718 "full" => ChatMode::Full,
719 "unrestricted" => ChatMode::Unrestricted,
720 "readonly" | "read-only" | "read_only" => ChatMode::ReadOnly,
721 _ => return USAGE.to_string(),
722 };
723 match self.host.set_chat_mode(session_id, requested, now).await {
724 Ok(_) => match requested {
725 ChatMode::ReadOnly => format!(
726 "Read-only for this chat for the next {session_mode_ttl_hours} hours, starting now, including work already running. aidaemon can look but not change anything. Send /mode full to end it early."
727 ),
728 ChatMode::Unrestricted => format!(
729 "Unrestricted for this chat for the next {session_mode_ttl_hours} hours, starting with your next message."
730 ),
731 ChatMode::Full => "Back to full access from your next message.".to_string(),
732 },
733 Err(error) => {
734 tracing::warn!(session_id, %error, "Could not change the session mode");
735 "Couldn't change the mode right now.".to_string()
736 }
737 }
738 }
739
740 async fn handle_context(&self, session_id: &str, user_role: UserRole) -> String {
741 if user_role != UserRole::Owner {
742 return "Only the owner can inspect conversation context coverage.".to_string();
743 }
744 let model = self.agent.current_model().await;
745 let (enabled, model_budget, trigger_tokens, recent_tokens, anchor) =
746 self.agent.context_debug_settings(session_id, &model).await;
747 let history = self.host.history(session_id, 10_000).await;
748 let summary = self.host.conversation_summary(session_id).await;
749 match (history, summary) {
750 (Ok(history), Ok(summary)) => {
751 let raw_values = history
752 .iter()
753 .map(|message| {
754 serde_json::json!({
755 "role": message.role,
756 "content": message.content,
757 "name": message.tool_name,
758 })
759 })
760 .collect::<Vec<_>>();
761 let exact_tokens = self.host.estimate_message_tokens(&raw_values);
762 let compacted_messages = summary
763 .as_ref()
764 .map(|value| value.message_count)
765 .unwrap_or(0);
766 let raw_recent_messages = history.len().saturating_sub(compacted_messages);
767 let summary_line = summary.as_ref().map_or_else(
768 || "Summary: none yet".to_string(),
769 |value| {
770 format!(
771 "Summary: {} messages through turn {} / message {} (~{} tokens)",
772 value.message_count,
773 value
774 .last_turn_seq
775 .map(|seq| seq.to_string())
776 .unwrap_or_else(|| "legacy".to_string()),
777 value.last_message_id,
778 self.host.estimate_text_tokens(&value.summary)
779 )
780 },
781 );
782 format!(
783 "Conversation context\nEnabled: {enabled}\nModel: {model}\nModel window: ~{model_budget} tokens\nCompaction high-water: ~{trigger_tokens} tokens\nRecent raw overlap target: ~{recent_tokens} tokens\n{summary_line}\nPersisted exact messages inspected: {} (~{exact_tokens} tokens)\nEstimated uncompacted messages: {raw_recent_messages}\nCurrent raw-turn anchor: {}\n\nExact retained history remains searchable even when it is not in the active prompt.",
784 history.len(),
785 anchor
786 .map(|seq| seq.to_string())
787 .unwrap_or_else(|| "not initialized".to_string())
788 )
789 }
790 (Err(error), _) | (_, Err(error)) => {
791 format!("Could not inspect conversation context: {error}")
792 }
793 }
794 }
795
796 async fn handle_model(&self, arg: &str) -> String {
797 if arg.is_empty() {
798 let current = self.agent.current_model().await;
799 format!(
800 "Current model: {}\n\nUsage: /model <model-name>\nExample: /model gemini-3-pro-preview",
801 current
802 )
803 } else {
804 self.agent.set_model(arg.to_string()).await;
805 format!(
806 "Model switched to: {}\nAuto-routing disabled. Use /auto to re-enable.",
807 arg
808 )
809 }
810 }
811
812 async fn handle_models(&self) -> String {
813 match self.agent.list_models().await {
814 Ok(models) => {
815 if models.is_empty() {
816 "No models found from provider.".to_string()
817 } else {
818 let current = self.agent.current_model().await;
819 let list: Vec<String> = models
820 .iter()
821 .map(|m| {
822 if *m == current {
823 format!("• {} (active)", m)
824 } else {
825 format!("• {}", m)
826 }
827 })
828 .collect();
829 format!("Available models:\n{}", list.join("\n"))
830 }
831 }
832 Err(e) => format!("Failed to list models: {}", e),
833 }
834 }
835
836 async fn handle_auto(&self) -> String {
837 self.agent.clear_model_override().await;
838 "Auto-routing re-enabled. Model will be selected automatically based on query complexity."
839 .to_string()
840 }
841
842 async fn handle_tasks(&self, session_id: &str) -> String {
843 let running =
844 crate::stop::running_work(&self.task_registry, self.agent.as_ref(), session_id).await;
845 let failed = self
846 .task_registry
847 .list_for_session(session_id)
848 .await
849 .into_iter()
850 .filter(|entry| matches!(entry.status, TaskStatus::Failed(_)))
851 .collect::<Vec<_>>();
852 let now = Utc::now();
853 render_tasks(&running, &failed, now, self.host.owner_time(now).as_deref())
854 }
855
856 async fn handle_cancel(&self, arg: &str, session_id: &str, user_role: UserRole) -> String {
860 if user_role != UserRole::Owner {
861 return "Only the owner can stop running work in this chat.".to_string();
862 }
863 let Some(request) = cancel_request(arg) else {
864 return "Usage: /cancel, /cancel all or /cancel <number>. Send /tasks to see the \
865 numbers."
866 .to_string();
867 };
868 crate::stop::stop(
869 &self.task_registry,
870 self.agent.as_ref(),
871 session_id,
872 request,
873 )
874 .await
875 }
876
877 async fn handle_clear(&self, session_id: &str) -> String {
878 let stopped_work =
882 crate::stop::stop_background_work(&self.task_registry, self.agent.as_ref(), session_id)
883 .await;
884 let cancelled_tasks = self
885 .task_registry
886 .cancel_running_for_session(session_id)
887 .await;
888 let cancelled_goals = self
892 .agent
893 .cancel_active_finite_work_for_session(session_id)
894 .await;
895
896 match self.agent.clear_session_context(session_id).await {
900 Ok(_) => {
901 let mut cancellations = Vec::new();
902 if !cancelled_goals.is_empty() {
903 cancellations.push(format!(
904 "{} background goal{}",
905 cancelled_goals.len(),
906 if cancelled_goals.len() == 1 { "" } else { "s" }
907 ));
908 }
909 let stopped = stopped_with_turns(cancelled_tasks.len(), stopped_work);
910 let suffix = clear_suffix(&cancellations, &stopped);
911 format!(
912 "Context cleared. Starting fresh – your history is kept; use /wipe to \
913 delete this chat's history.{suffix}"
914 )
915 }
916 Err(e) => format!("Failed to clear context: {}", e),
917 }
918 }
919
920 async fn handle_wipe(&self, session_id: &str) -> String {
921 if self
924 .task_registry
925 .request_wipe(session_id, std::time::Instant::now())
926 == crate::tasks::WipeRequest::Requested
927 {
928 return format!(
929 "Nothing was erased. /wipe permanently deletes this conversation from the \
930 database: its messages, search index, summaries and episodes. Facts already \
931 saved to memory are kept. To start fresh and keep the history, use /clear \
932 instead. To erase it, send /wipe again within {} minutes.",
933 crate::tasks::WIPE_CONFIRM_WINDOW.as_secs() / 60
934 );
935 }
936 let stopped_work =
937 crate::stop::stop_background_work(&self.task_registry, self.agent.as_ref(), session_id)
938 .await;
939 let cancelled = self
940 .task_registry
941 .cancel_running_for_session(session_id)
942 .await;
943
944 match self.agent.clear_session(session_id).await {
946 Ok(_) => {
947 let stopped = stopped_with_turns(cancelled.len(), stopped_work);
948 let suffix = clear_suffix(&[], &stopped);
949 format!(
950 "Conversation erased from the active database (events, exact-search index, \
951 summaries, episodes, and raw memory spans). Facts already saved to memory \
952 are kept without raw-message provenance. Existing encrypted backups may \
953 retain older copies until their own lifecycle removes them.{suffix}"
954 )
955 }
956 Err(e) => format!("Failed to wipe conversation: {}", e),
957 }
958 }
959
960 async fn handle_cost(&self) -> String {
961 let now = Utc::now();
962 let since_24h = (now - chrono::Duration::hours(24))
963 .format("%Y-%m-%d %H:%M:%S")
964 .to_string();
965 let since_7d = (now - chrono::Duration::days(7))
966 .format("%Y-%m-%d %H:%M:%S")
967 .to_string();
968
969 let records_24h = match self.host.token_usage_since(&since_24h).await {
970 Ok(r) => r,
971 Err(e) => return format!("Failed to query token usage: {}", e),
972 };
973 let records_7d = match self.host.token_usage_since(&since_7d).await {
974 Ok(r) => r,
975 Err(e) => return format!("Failed to query token usage: {}", e),
976 };
977
978 let (input_24h, output_24h) = records_24h.iter().fold((0i64, 0i64), |(i, o), r| {
979 (i + r.input_tokens, o + r.output_tokens)
980 });
981 let (input_7d, output_7d) = records_7d.iter().fold((0i64, 0i64), |(i, o), r| {
982 (i + r.input_tokens, o + r.output_tokens)
983 });
984
985 let mut model_totals: HashMap<&str, i64> = HashMap::new();
987 for r in &records_7d {
988 *model_totals.entry(&r.model).or_insert(0) += r.input_tokens + r.output_tokens;
989 }
990 let mut models_sorted: Vec<(&&str, &i64)> = model_totals.iter().collect();
991 models_sorted.sort_by(|a, b| b.1.cmp(a.1));
992
993 let mut reply = format!(
994 "Token usage (last 24h):\n Input: {} tokens\n Output: {} tokens\n\n\
995 Token usage (last 7d):\n Input: {} tokens\n Output: {} tokens",
996 format_number(input_24h),
997 format_number(output_24h),
998 format_number(input_7d),
999 format_number(output_7d),
1000 );
1001
1002 if !models_sorted.is_empty() {
1003 reply.push_str("\n\nTop models (7d):");
1004 for (model, total) in models_sorted.iter().take(5) {
1005 reply.push_str(&format!("\n {}: {} tokens", model, format_number(**total)));
1006 }
1007 }
1008
1009 reply
1010 }
1011}
1012
1013pub fn format_number(n: i64) -> String {
1015 let s = n.to_string();
1016 let mut result = String::with_capacity(s.len() + s.len() / 3);
1017 for (i, c) in s.chars().rev().enumerate() {
1018 if i > 0 && i % 3 == 0 {
1019 result.push(',');
1020 }
1021 result.push(c);
1022 }
1023 result.chars().rev().collect()
1024}
1025
1026pub fn build_help_text(commands: &[CommandDef], prefix: &str, scope: HelpScope) -> String {
1033 let p = prefix;
1034 let shown: Vec<&CommandDef> = match scope {
1035 HelpScope::Everyday => EVERYDAY_COMMANDS
1036 .iter()
1037 .filter_map(|name| commands.iter().find(|cmd| cmd.name == *name))
1038 .collect(),
1039 HelpScope::All => commands.iter().collect(),
1040 };
1041 let mut text = match scope {
1042 HelpScope::Everyday => String::from(
1043 "Just ask in plain words – I'll pick the right tools. For example: \
1044 _\"Check my disk space every 6 hours\"_ or _\"Send me the latest log file\"_.\n\n\
1045 **Everyday commands**",
1046 ),
1047 HelpScope::All => String::from("**All commands**"),
1048 };
1049 for cmd in shown {
1050 let label = match cmd.usage {
1051 Some(usage) => {
1052 if let Some(rest) = usage.strip_prefix('/') {
1054 format!("{p}{rest}")
1055 } else {
1056 usage.to_string()
1057 }
1058 }
1059 None => format!("{p}{}", cmd.name),
1060 };
1061 text.push_str(&format!("\n{} – {}", label, cmd.description));
1062 }
1063 if scope == HelpScope::Everyday {
1064 text.push_str(&format!("\n\nSend {p}help all for every command."));
1065 }
1066 text
1067}
1068
1069#[cfg(test)]
1070mod help_and_status_tests {
1071 use super::*;
1072
1073 #[test]
1076 fn clear_names_what_it_stopped() {
1077 let suffix = clear_suffix(
1078 &["1 running task".to_string()],
1079 &[
1080 "Sub-agent: Counter A".to_string(),
1081 "Background command: a shell loop".to_string(),
1082 ],
1083 );
1084 assert_eq!(
1085 suffix,
1086 " (1 running task cancelled.)\n\n⏹️ Stopped:\n• Sub-agent: Counter A\n• \
1087 Background command: a shell loop"
1088 );
1089 assert_eq!(clear_suffix(&[], &[]), "");
1090 }
1091
1092 fn defs() -> Vec<CommandDef> {
1093 shared_commands()
1094 }
1095
1096 #[test]
1097 fn help_shows_the_everyday_commands_and_how_to_see_the_rest() {
1098 let help = build_help_text(&defs(), "/", HelpScope::Everyday);
1099 for name in EVERYDAY_COMMANDS {
1100 assert!(help.contains(&format!("\n/{name}")), "{name}: {help}");
1101 }
1102 assert!(!help.contains("/models"), "{help}");
1103 assert!(!help.contains('`'), "{help}");
1104 assert!(
1105 help.ends_with("Send /help all for every command."),
1106 "{help}"
1107 );
1108 let all = build_help_text(&defs(), "!", HelpScope::All);
1109 assert!(all.contains("!models – List available models"), "{all}");
1110 assert_eq!(HelpScope::from_args(" ALL "), HelpScope::All);
1111 assert_eq!(HelpScope::from_args(""), HelpScope::Everyday);
1112 }
1113
1114 #[test]
1115 fn an_unknown_command_suggests_the_closest_one() {
1116 let commands = defs();
1117 assert_eq!(closest_command("cleer", &commands), Some("clear"));
1118 assert_eq!(closest_command("stauts", &commands), Some("status"));
1119 assert_eq!(closest_command("weather", &commands), None);
1120 assert_eq!(
1121 unknown_command_reply("/claer", &commands, "/"),
1122 "I don't know /claer. Did you mean /clear? Send /help to see the commands."
1123 );
1124 assert_eq!(
1125 unknown_command_reply("/weather@my_bot", &commands, "/"),
1126 "I don't know /weather@my_bot. Send /help to see the commands."
1127 );
1128 }
1129
1130 #[test]
1131 fn private_can_carry_its_message() {
1132 assert_eq!(private_request("/private"), None);
1133 assert_eq!(private_request("/private off"), None);
1134 assert_eq!(private_request("/clear"), None);
1135 assert_eq!(
1136 private_request("/private/private"),
1137 Some(PrivateRequest::Next)
1138 );
1139 assert_eq!(
1140 private_request("/privateAnother test"),
1141 Some(PrivateRequest::With("Another test"))
1142 );
1143 assert_eq!(
1144 private_request("/private@my_bot what's my balance?"),
1145 Some(PrivateRequest::With("what's my balance?"))
1146 );
1147 assert_eq!(
1148 private_request("/private /private hi"),
1149 Some(PrivateRequest::With("hi"))
1150 );
1151 }
1152
1153 #[test]
1154 fn tasks_lists_every_running_thing_with_a_number() {
1155 let now = Utc::now();
1156 let running = crate::stop::WorkList::for_tests(vec![
1157 (
1158 7,
1159 crate::stop::TURN_LABEL,
1160 now - chrono::Duration::seconds(40),
1161 "req-1",
1162 ),
1163 (
1164 8,
1165 "Sub-agent: Counting agent A",
1166 now - chrono::Duration::seconds(30),
1167 "req-1",
1168 ),
1169 (
1170 9,
1171 "Background command: for i in $(seq 1 300); do echo $i; sleep 2; done",
1172 now - chrono::Duration::seconds(30),
1173 "req-1",
1174 ),
1175 ]);
1176 let tasks = render_tasks(&running, &[], now, None);
1177 assert!(
1178 tasks.starts_with("Running in this chat:\n#7 Working on your message (40s so far)"),
1179 "{tasks}"
1180 );
1181 assert!(
1182 tasks.contains("\n#8 Sub-agent: Counting agent A (30s so far)"),
1183 "{tasks}"
1184 );
1185 assert!(
1186 tasks.contains("\n#9 Background command: for i in"),
1187 "{tasks}"
1188 );
1189 assert!(
1190 tasks.contains("Send /cancel to stop all of it, or /cancel <number> for one."),
1191 "{tasks}"
1192 );
1193 let quiet = render_tasks(&crate::stop::WorkList::default(), &[], now, None);
1194 assert!(
1195 quiet.starts_with("Nothing is running in this chat right now."),
1196 "{quiet}"
1197 );
1198 }
1199
1200 #[test]
1204 fn tasks_says_when_it_was_read() {
1205 let now = Utc::now();
1206 let running = crate::stop::WorkList::for_tests(vec![(
1207 1,
1208 crate::stop::TURN_LABEL,
1209 now - chrono::Duration::seconds(40),
1210 "req-1",
1211 )]);
1212 let tasks = render_tasks(&running, &[], now, Some("5:44 PM ET"));
1213 assert!(
1214 tasks.starts_with(
1215 "As of 5:44 PM ET:\nRunning in this chat:\n#1 Working on your message"
1216 ),
1217 "{tasks}"
1218 );
1219 let quiet = render_tasks(
1220 &crate::stop::WorkList::default(),
1221 &[],
1222 now,
1223 Some("5:44 PM ET"),
1224 );
1225 assert!(
1226 quiet.starts_with("As of 5:44 PM ET:\nNothing is running"),
1227 "{quiet}"
1228 );
1229 }
1230
1231 #[test]
1234 fn clear_lists_the_cancelled_turn_with_the_stopped_helpers() {
1235 let stopped = stopped_with_turns(
1236 1,
1237 vec!["Sub-agent: Counter A".into(), "Sub-agent: Counter B".into()],
1238 );
1239 let suffix = clear_suffix(&[], &stopped);
1240 assert!(!suffix.contains("cancelled"), "{suffix}");
1241 assert_eq!(
1242 suffix,
1243 "\n\n⏹️ Stopped:\n• Working on your message\n• Sub-agent: Counter A\n• Sub-agent: Counter B"
1244 );
1245 }
1246
1247 #[test]
1248 fn cancel_arguments_are_bare_all_or_numbers() {
1249 use crate::stop::StopRequest;
1250 assert_eq!(cancel_request(""), Some(StopRequest::Bare));
1251 assert_eq!(cancel_request(" ALL "), Some(StopRequest::All));
1252 assert_eq!(cancel_request("3"), Some(StopRequest::Numbers(vec![3])));
1253 assert_eq!(
1254 cancel_request("#3, 4"),
1255 Some(StopRequest::Numbers(vec![3, 4]))
1256 );
1257 assert_eq!(cancel_request("both"), None);
1258 }
1259
1260 #[test]
1261 fn status_says_mode_running_work_and_whats_next() {
1262 let now = Utc::now();
1263 let quiet = StatusView {
1264 now: None,
1265 mode: None,
1266 running: crate::stop::WorkList::default(),
1267 next_scheduled: None,
1268 };
1269 assert_eq!(
1270 render_status(&quiet, now),
1271 "Mode: full.\nRunning: nothing right now.\nNext scheduled: nothing."
1272 );
1273 let busy = StatusView {
1274 now: Some("2:05 PM ET".to_string()),
1275 mode: Some((ChatMode::ReadOnly, Some(now + chrono::Duration::hours(3)))),
1276 running: crate::stop::WorkList::for_tests(vec![
1277 (
1278 7,
1279 crate::stop::TURN_LABEL,
1280 now - chrono::Duration::minutes(2),
1281 "a",
1282 ),
1283 (
1284 8,
1285 "Sub-agent: Install a Drupal demo site with DDEV",
1286 now - chrono::Duration::minutes(4),
1287 "a",
1288 ),
1289 ]),
1290 next_scheduled: Some(ScheduledItem {
1291 what: "Check disk space".to_string(),
1292 when: "2:39 PM ET".to_string(),
1293 }),
1294 };
1295 let status = render_status(&busy, now);
1296 assert!(
1297 status.starts_with("As of 2:05 PM ET: Mode: read-only (about 3h left)."),
1298 "{status}"
1299 );
1300 assert!(
1301 status.contains("• Working on your message (2m so far, /cancel 7 to stop it)"),
1302 "{status}"
1303 );
1304 assert!(
1305 status.contains(
1306 "• Sub-agent: Install a Drupal demo site with DDEV (4m so far, /cancel 8 to stop it)"
1307 ),
1308 "{status}"
1309 );
1310 assert!(
1311 status.ends_with("Next scheduled: Check disk space – 2:39 PM ET"),
1312 "{status}"
1313 );
1314 }
1315
1316 #[test]
1320 fn a_scheduled_item_is_named_never_cut() {
1321 let long = "Every day, independently manage and publish to the synthetic blog at \
1322 https://blog.example.test following the editorial plan";
1323 assert_eq!(scheduled_name(Some(" Daily blog "), long), "Daily blog");
1324 assert_eq!(scheduled_name(None, "Check disk space"), "Check disk space");
1325 let unnamed = scheduled_name(None, long);
1326 assert_eq!(unnamed, "An automation without a name (see /work)");
1327 for name in [unnamed, scheduled_name(Some("Daily blog"), long)] {
1328 assert!(!name.contains('…') && !name.contains("..."), "{name}");
1329 }
1330 }
1331}
1332
1333#[cfg(test)]
1334mod format_tests {
1335 use super::*;
1336
1337 #[test]
1338 fn test_format_number() {
1339 assert_eq!(format_number(0), "0");
1340 assert_eq!(format_number(999), "999");
1341 assert_eq!(format_number(1000), "1,000");
1342 assert_eq!(format_number(12450), "12,450");
1343 assert_eq!(format_number(1_000_000), "1,000,000");
1344 }
1345}