Skip to main content

goose_agent/
slash_command.rs

1//! Runs the command named by a kickoff message that starts with `/`.
2
3use std::sync::Arc;
4
5use anyhow::Result;
6use async_trait::async_trait;
7use goose_provider_types::conversation::Conversation;
8use goose_provider_types::maybe_send::{MaybeSend, MaybeSync};
9
10use crate::command::Command;
11use crate::operation::{
12    messages_since_kickoff, not_applicable, Emitter, Operation, OperationResult,
13};
14
15#[cfg(not(target_arch = "wasm32"))]
16type Resolver<'a, S, E> =
17    dyn for<'c> Fn(Vec<Command<'c, S, E>>) -> Vec<Command<'c, S, E>> + Send + Sync + 'a;
18
19#[cfg(target_arch = "wasm32")]
20type Resolver<'a, S, E> = dyn for<'c> Fn(Vec<Command<'c, S, E>>) -> Vec<Command<'c, S, E>> + 'a;
21
22pub struct SlashCommandOperation<'a, S, E: MaybeSend + 'static> {
23    operations: Vec<Arc<dyn Operation<S, E> + 'a>>,
24    resolver: Option<Box<Resolver<'a, S, E>>>,
25}
26
27impl<'a, S, E: MaybeSend + 'static> SlashCommandOperation<'a, S, E> {
28    pub fn new(operations: Vec<Arc<dyn Operation<S, E> + 'a>>) -> Self {
29        Self {
30            operations,
31            resolver: None,
32        }
33    }
34
35    pub fn with_resolver(
36        mut self,
37        resolver: impl for<'c> Fn(Vec<Command<'c, S, E>>) -> Vec<Command<'c, S, E>>
38            + MaybeSend
39            + MaybeSync
40            + 'a,
41    ) -> Self {
42        self.resolver = Some(Box::new(resolver));
43        self
44    }
45}
46
47#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
48#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
49impl<S, E> Operation<S, E> for SlashCommandOperation<'_, S, E>
50where
51    S: MaybeSend + MaybeSync,
52    E: MaybeSend + 'static,
53{
54    fn name(&self) -> &'static str {
55        "slash_command"
56    }
57
58    async fn run(
59        &self,
60        session: &S,
61        conversation: &Conversation,
62        emit: &Emitter,
63    ) -> Result<OperationResult<E>> {
64        let [kickoff] = messages_since_kickoff(conversation)? else {
65            return not_applicable();
66        };
67        let text = kickoff.agent_visible_content().as_concat_text();
68        let Some(invocation) = text.trim().strip_prefix('/') else {
69            return not_applicable();
70        };
71        let (name, arguments) = invocation.split_once(' ').unwrap_or((invocation, ""));
72        let name = name.to_lowercase();
73
74        let mut commands = Vec::new();
75        for operation in &self.operations {
76            commands.extend(operation.commands(session).await?);
77        }
78        if let Some(resolver) = &self.resolver {
79            commands = resolver(commands);
80        }
81        let Some(command) = commands.iter().find(|command| command.answers_to(&name)) else {
82            return not_applicable();
83        };
84        command
85            .run(arguments.trim(), session, conversation, emit)
86            .await
87    }
88}