1use std::marker::PhantomData;
4
5use anyhow::Result;
6use goose_provider_types::conversation::Conversation;
7use goose_provider_types::maybe_send::{MaybeSend, MaybeSync};
8
9use crate::operation::{Emitter, OperationFuture, OperationResult};
10
11pub struct CommandCall<'c, 'a, S> {
12 pub arguments: &'c str,
13 pub session: &'c S,
14 pub conversation: &'c Conversation,
15 pub emit: &'c Emitter,
16 scope: PhantomData<&'c &'a ()>,
20}
21
22#[cfg(not(target_arch = "wasm32"))]
23type Action<'a, S, E> = dyn for<'c> Fn(CommandCall<'c, 'a, S>) -> OperationFuture<'c, Result<OperationResult<E>>>
24 + Send
25 + Sync
26 + 'a;
27
28#[cfg(target_arch = "wasm32")]
29type Action<'a, S, E> =
30 dyn for<'c> Fn(CommandCall<'c, 'a, S>) -> OperationFuture<'c, Result<OperationResult<E>>> + 'a;
31
32pub struct Command<'a, S, E> {
33 pub name: String,
34 pub aliases: Vec<String>,
35 pub description: String,
36 pub input_hint: Option<String>,
37 pub meta: serde_json::Map<String, serde_json::Value>,
38 action: Box<Action<'a, S, E>>,
39}
40
41impl<'a, S, E> Command<'a, S, E> {
42 pub fn new(
43 name: impl Into<String>,
44 description: impl Into<String>,
45 action: impl for<'c> Fn(CommandCall<'c, 'a, S>) -> OperationFuture<'c, Result<OperationResult<E>>>
46 + MaybeSend
47 + MaybeSync
48 + 'a,
49 ) -> Self {
50 Self {
51 name: name.into(),
52 aliases: Vec::new(),
53 description: description.into(),
54 input_hint: None,
55 meta: serde_json::Map::new(),
56 action: Box::new(action),
57 }
58 }
59
60 pub fn answers_to(&self, name: &str) -> bool {
61 std::iter::once(&self.name)
62 .chain(&self.aliases)
63 .any(|own| own == name)
64 }
65
66 pub async fn run(
67 &self,
68 arguments: &str,
69 session: &S,
70 conversation: &Conversation,
71 emit: &Emitter,
72 ) -> Result<OperationResult<E>> {
73 (self.action)(CommandCall {
74 arguments,
75 session,
76 conversation,
77 emit,
78 scope: PhantomData,
79 })
80 .await
81 }
82}