1#[cfg(test)]
25use nostr_sdk::prelude::FinalizeEvent;
26use crate::event_ext::FinalizeOnClock;
27use std::collections::HashMap;
28
29use nostr_sdk::prelude::{Event, EventBuilder, Keys, Kind, Tag};
30use serde::{Deserialize, Serialize};
31use crate::ClientRelayExt;
32
33pub const KIND_BOT_MANIFEST: u16 = 10304;
36
37pub const TAG_BOT: &str = "bot";
48
49pub const MAX_BOT_TAGS: usize = 8;
51
52pub fn bot_tag(bot: &nostr_sdk::prelude::PublicKey) -> Tag {
54 Tag::custom(TAG_BOT, [bot.to_hex()])
55}
56
57pub fn addressed_bots<'a, I: IntoIterator<Item = &'a Tag>>(tags: I) -> Vec<String> {
60 use nostr_sdk::prelude::ToBech32;
61 let mut out: Vec<String> = Vec::new();
62 for t in tags {
63 let s = t.as_slice();
64 if s.first().map(|k| k.as_str()) != Some(TAG_BOT) {
65 continue;
66 }
67 let Some(v) = s.get(1) else { continue };
68 let Ok(pk) = nostr_sdk::prelude::PublicKey::from_hex(v) else { continue };
69 let Ok(npub) = pk.to_bech32();
70 if !out.contains(&npub) {
71 out.push(npub);
72 }
73 if out.len() >= MAX_BOT_TAGS {
74 break;
75 }
76 }
77 out
78}
79
80pub const MAX_COMMANDS: usize = 64;
83pub const MAX_ARGS: usize = 8;
84pub const MAX_CHOICES: usize = 32;
85pub const MAX_NAME_LEN: usize = 32;
86pub const MAX_DESCRIPTION_LEN: usize = 200;
87pub const MAX_MANIFEST_BYTES: usize = 32_768;
88pub const MAX_ARG_VALUE_LEN: usize = 1_024;
90
91#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
95#[serde(rename_all = "lowercase")]
96pub enum ArgType {
97 String,
100 Int,
102 Number,
104 Bool,
106 User,
108 Choice,
110}
111
112#[derive(Serialize, Deserialize, Clone, Debug)]
114pub struct ArgSpec {
115 pub name: String,
116 #[serde(rename = "type")]
117 pub arg_type: ArgType,
118 #[serde(default)]
119 pub description: String,
120 #[serde(default)]
121 pub required: bool,
122 #[serde(default, skip_serializing_if = "Vec::is_empty")]
124 pub choices: Vec<String>,
125}
126
127#[derive(Serialize, Deserialize, Clone, Debug)]
129pub struct CommandSpec {
130 pub name: String,
131 pub description: String,
132 #[serde(default, skip_serializing_if = "Vec::is_empty")]
133 pub args: Vec<ArgSpec>,
134}
135
136#[derive(Serialize, Deserialize, Clone, Debug)]
139pub struct BotManifest {
140 pub v: u32,
141 #[serde(default, skip_serializing_if = "Vec::is_empty")]
142 pub commands: Vec<CommandSpec>,
143}
144
145fn valid_name(s: &str) -> bool {
148 !s.is_empty()
149 && s.len() <= MAX_NAME_LEN
150 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
151}
152
153impl BotManifest {
154 pub fn validate(&self) -> Result<(), String> {
157 if self.v != 1 {
158 return Err(format!("unsupported manifest version {}", self.v));
159 }
160 if self.commands.len() > MAX_COMMANDS {
161 return Err(format!("too many commands ({} > {MAX_COMMANDS})", self.commands.len()));
162 }
163 let mut seen = std::collections::HashSet::new();
164 for c in &self.commands {
165 if !valid_name(&c.name) {
166 return Err(format!("bad command name {:?}", c.name));
167 }
168 if !seen.insert(c.name.as_str()) {
169 return Err(format!("duplicate command {:?}", c.name));
170 }
171 if c.description.len() > MAX_DESCRIPTION_LEN {
172 return Err(format!("description too long on /{}", c.name));
173 }
174 if c.args.len() > MAX_ARGS {
175 return Err(format!("too many args on /{}", c.name));
176 }
177 let mut arg_seen = std::collections::HashSet::new();
178 let mut optional_seen = false;
179 for a in &c.args {
180 if !valid_name(&a.name) {
181 return Err(format!("bad arg name {:?} on /{}", a.name, c.name));
182 }
183 if !arg_seen.insert(a.name.as_str()) {
184 return Err(format!("duplicate arg {:?} on /{}", a.name, c.name));
185 }
186 if a.description.len() > MAX_DESCRIPTION_LEN {
187 return Err(format!("arg description too long on /{}", c.name));
188 }
189 if a.required && optional_seen {
192 return Err(format!("required arg {:?} after an optional one on /{}", a.name, c.name));
193 }
194 optional_seen |= !a.required;
195 match a.arg_type {
196 ArgType::Choice => {
197 if a.choices.is_empty() || a.choices.len() > MAX_CHOICES {
198 return Err(format!("choice arg {:?} needs 1..={MAX_CHOICES} choices", a.name));
199 }
200 if a.choices.iter().any(|ch| ch.is_empty() || ch.len() > MAX_NAME_LEN) {
201 return Err(format!("bad choice value on {:?}", a.name));
202 }
203 }
204 _ if !a.choices.is_empty() => {
205 return Err(format!("choices on non-choice arg {:?}", a.name));
206 }
207 _ => {}
208 }
209 }
210 }
211 let bytes = serde_json::to_string(self).map_err(|e| e.to_string())?.len();
212 if bytes > MAX_MANIFEST_BYTES {
213 return Err(format!("manifest too large ({bytes} > {MAX_MANIFEST_BYTES} bytes)"));
214 }
215 Ok(())
216 }
217
218 pub fn command(&self, name: &str) -> Option<&CommandSpec> {
220 self.commands.iter().find(|c| c.name == name)
221 }
222
223 pub fn from_event(event: &Event) -> Result<Self, String> {
226 if event.kind != Kind::Custom(KIND_BOT_MANIFEST) {
227 return Err(format!("not a bot manifest (kind {})", event.kind));
228 }
229 if event.content.len() > MAX_MANIFEST_BYTES {
230 return Err("manifest content over the size cap".into());
231 }
232 let m: BotManifest = serde_json::from_str(&event.content).map_err(|e| format!("manifest parse: {e}"))?;
233 m.validate()?;
234 Ok(m)
235 }
236
237 pub fn to_event(&self, keys: &Keys) -> Result<Event, String> {
240 self.validate()?;
241 let content = serde_json::to_string(self).map_err(|e| e.to_string())?;
242 let event = EventBuilder::new(Kind::Custom(KIND_BOT_MANIFEST), content)
243 .finalize_on_clock(keys)
244 .map_err(|e| e.to_string())?;
245 crate::event_size::check(&event)?;
246 Ok(event)
247 }
248}
249
250#[derive(Clone, Debug, PartialEq)]
255pub struct ParsedCommand {
256 pub name: String,
257 pub args: Vec<(String, String)>,
259}
260
261pub fn command_text(name: &str, args: &[(String, String)]) -> String {
266 let mut out = format!("/{name}");
267 for (_, v) in args {
268 out.push(' ');
269 if v.is_empty() || v.contains(char::is_whitespace) || v.contains('"') {
270 out.push('"');
271 out.push_str(&v.replace('\\', "\\\\").replace('"', "\\\""));
272 out.push('"');
273 } else {
274 out.push_str(v);
275 }
276 }
277 out
278}
279
280fn next_token(s: &str, mut i: usize) -> Option<(String, usize)> {
284 let b = s.as_bytes();
285 while i < b.len() && b[i].is_ascii_whitespace() {
286 i += 1;
287 }
288 if i >= b.len() {
289 return None;
290 }
291 let mut out = String::new();
292 if b[i] == b'"' {
293 i += 1;
294 while i < b.len() {
295 match b[i] {
296 b'\\' if i + 1 < b.len() && (b[i + 1] == b'"' || b[i + 1] == b'\\') => {
297 out.push(b[i + 1] as char);
298 i += 2;
299 }
300 b'"' => return Some((out, i + 1)),
301 _ => {
302 let ch = s[i..].chars().next()?;
304 out.push(ch);
305 i += ch.len_utf8();
306 }
307 }
308 }
309 None } else {
311 let start = i;
312 while i < b.len() && !b[i].is_ascii_whitespace() {
313 i += 1;
314 }
315 out.push_str(&s[start..i]);
316 Some((out, i))
317 }
318}
319
320pub fn parse_command_text(manifest: &BotManifest, content: &str) -> Option<ParsedCommand> {
330 let content = content.trim();
331 let rest = content.strip_prefix('/')?;
332 if rest.starts_with('"') {
336 return None;
337 }
338 let (raw_name, mut cursor) = next_token(rest, 0)?;
339 if raw_name.is_empty() {
340 return None;
341 }
342 let name = raw_name.to_ascii_lowercase();
345 let spec = manifest.command(&name)?;
346 let mut args: Vec<(String, String)> = Vec::new();
347 for (i, a) in spec.args.iter().enumerate() {
348 let remainder = rest.get(cursor..).unwrap_or("").trim_start();
349 if remainder.is_empty() {
350 break;
351 }
352 let is_last_declared = i + 1 == spec.args.len();
353 let value = if is_last_declared && matches!(a.arg_type, ArgType::String) && !remainder.starts_with('"') {
354 cursor = rest.len();
356 remainder.trim_end().to_string()
357 } else {
358 let (tok, next) = next_token(rest, cursor)?;
359 cursor = next;
360 tok
361 };
362 if value.len() > MAX_ARG_VALUE_LEN {
363 return None;
364 }
365 if value.is_empty() && !a.required {
371 continue;
372 }
373 args.push((a.name.clone(), value));
374 }
375 Some(ParsedCommand { name, args })
376}
377
378#[derive(Clone, Debug, PartialEq)]
382pub enum ArgValue {
383 String(String),
384 Int(i64),
385 Number(f64),
386 Bool(bool),
387 User(String),
389 Choice(String),
390}
391
392impl ArgValue {
393 pub fn as_str(&self) -> &str {
394 match self {
395 ArgValue::String(s) | ArgValue::User(s) | ArgValue::Choice(s) => s,
396 _ => "",
397 }
398 }
399 pub fn as_int(&self) -> Option<i64> {
400 match self {
401 ArgValue::Int(i) => Some(*i),
402 _ => None,
403 }
404 }
405 pub fn as_number(&self) -> Option<f64> {
406 match self {
407 ArgValue::Number(n) => Some(*n),
408 ArgValue::Int(i) => Some(*i as f64),
409 _ => None,
410 }
411 }
412 pub fn as_bool(&self) -> Option<bool> {
413 match self {
414 ArgValue::Bool(b) => Some(*b),
415 _ => None,
416 }
417 }
418}
419
420pub fn typed_args(spec: &CommandSpec, parsed: &ParsedCommand) -> Result<HashMap<String, ArgValue>, String> {
430 let mut out = HashMap::new();
431 for (k, v) in &parsed.args {
432 let Some(a) = spec.args.iter().find(|a| &a.name == k) else {
433 continue;
434 };
435 let typed = match a.arg_type {
436 ArgType::String => ArgValue::String(v.clone()),
437 ArgType::Int => ArgValue::Int(v.parse::<i64>().map_err(|_| format!("{k}: not an integer"))?),
438 ArgType::Number => ArgValue::Number(v.parse::<f64>().map_err(|_| format!("{k}: not a number"))?),
439 ArgType::Bool => match v.to_ascii_lowercase().as_str() {
440 "true" | "yes" | "1" => ArgValue::Bool(true),
441 "false" | "no" | "0" => ArgValue::Bool(false),
442 _ => return Err(format!("{k}: not a boolean")),
443 },
444 ArgType::User => {
445 let raw = v.strip_prefix("nostr:").unwrap_or(v);
449 if !raw.starts_with("npub1") {
450 return Err(format!("{k}: not an npub"));
451 }
452 let pk = nostr_sdk::prelude::PublicKey::parse(raw).map_err(|_| format!("{k}: not an npub"))?;
453 let npub = nostr_sdk::prelude::ToBech32::to_bech32(&pk).map_err(|_| format!("{k}: not an npub"))?;
454 ArgValue::User(npub)
455 }
456 ArgType::Choice => {
457 if !a.choices.iter().any(|c| c == v) {
458 return Err(format!("{k}: not one of {}", a.choices.join(", ")));
459 }
460 ArgValue::Choice(v.clone())
461 }
462 };
463 out.insert(k.clone(), typed);
464 }
465 for a in &spec.args {
466 if a.required && !out.contains_key(&a.name) {
467 return Err(format!("{}: required", a.name));
468 }
469 }
470 Ok(out)
471}
472
473#[derive(Serialize, Clone, Debug)]
478pub struct ChatBotCommands {
479 pub bot: String,
481 pub commands: Vec<CommandSpec>,
482}
483
484pub const DISCOVERY_RELAYS: &[&str] =
490 &["wss://purplepag.es", "wss://relay.nostr.band", "wss://nos.lol"];
491
492#[derive(Serialize, Clone, Debug)]
496pub struct ChatCommandsSnapshot {
497 pub bots: usize,
499 pub commands: Vec<ChatBotCommands>,
502 pub fresh: bool,
504}
505
506pub async fn fetch_manifests<T: crate::community::transport::Transport + ?Sized>(
515 transport: &T,
516 authors: &[nostr_sdk::prelude::PublicKey],
517 relays: &[String],
518) -> Result<Vec<(nostr_sdk::prelude::PublicKey, BotManifest, u64)>, String> {
519 use crate::community::transport::Query;
520 if authors.is_empty() {
521 return Ok(Vec::new());
522 }
523 let query = Query {
524 kinds: vec![KIND_BOT_MANIFEST],
525 authors: authors.iter().map(|p| p.to_hex()).collect(),
526 ..Default::default()
527 };
528 let events = transport.fetch(&query, relays).await?;
529 let mut best: HashMap<nostr_sdk::prelude::PublicKey, &Event> = HashMap::new();
530 for ev in &events {
531 if !authors.contains(&ev.pubkey) || ev.verify().is_err() {
532 continue;
533 }
534 match best.get(&ev.pubkey) {
535 Some(b) if b.created_at >= ev.created_at => {}
536 _ => {
537 best.insert(ev.pubkey, ev);
538 }
539 }
540 }
541 let mut out: Vec<(nostr_sdk::prelude::PublicKey, BotManifest, u64)> = best
542 .into_iter()
543 .filter_map(|(pk, ev)| BotManifest::from_event(ev).ok().map(|m| (pk, m, ev.created_at.as_secs())))
544 .collect();
545 out.sort_by_key(|(pk, _, _)| pk.to_hex());
546 Ok(out)
547}
548
549pub fn assemble_from_store(bot_hexes: &[String]) -> Vec<ChatBotCommands> {
553 use nostr_sdk::prelude::ToBech32;
554 let rows = crate::db::bots::get_bot_manifests(bot_hexes).unwrap_or_default();
555 let by_pk: HashMap<&str, &str> = rows.iter().map(|(pk, m)| (pk.as_str(), m.as_str())).collect();
556 bot_hexes
557 .iter()
558 .filter_map(|hex| {
559 let json = by_pk.get(hex.as_str())?;
560 let manifest: BotManifest = serde_json::from_str(json).ok()?;
561 manifest.validate().ok()?;
562 let npub = nostr_sdk::prelude::PublicKey::from_hex(hex).ok()?.to_bech32().ok()?;
563 Some(ChatBotCommands { bot: npub, commands: manifest.commands })
564 })
565 .collect()
566}
567
568const COMMANDS_TTL: std::time::Duration = std::time::Duration::from_secs(60);
573type CommandsFreshness = HashMap<String, (u64, web_time::Instant, Vec<String>)>;
574static COMMANDS_FRESH: std::sync::LazyLock<std::sync::Mutex<CommandsFreshness>> =
575 std::sync::LazyLock::new(|| std::sync::Mutex::new(HashMap::new()));
576static REFRESH_INFLIGHT: std::sync::LazyLock<std::sync::Mutex<std::collections::HashSet<String>>> =
578 std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
579
580pub fn commands_fresh(chat_id: &str, bot_hexes: &[String]) -> bool {
583 let generation = crate::db::current_session_id();
584 let map = match COMMANDS_FRESH.lock() {
585 Ok(m) => m,
586 Err(_) => return false,
587 };
588 match map.get(chat_id) {
589 Some((g, at, bots)) => *g == generation && at.elapsed() < COMMANDS_TTL && bots == bot_hexes,
590 None => false,
591 }
592}
593
594fn mark_commands_fresh(chat_id: &str, generation: u64, bot_hexes: &[String]) {
595 if let Ok(mut map) = COMMANDS_FRESH.lock() {
596 if map.len() > 256 {
597 map.clear();
598 }
599 map.insert(chat_id.to_string(), (generation, web_time::Instant::now(), bot_hexes.to_vec()));
600 }
601}
602
603pub fn spawn_commands_refresh(chat_id: String, bots: Vec<nostr_sdk::prelude::PublicKey>, relays: Vec<String>) {
608 {
609 let Ok(mut inflight) = REFRESH_INFLIGHT.lock() else { return };
610 if !inflight.insert(chat_id.clone()) {
611 return; }
613 }
614 let session = crate::db::current_session();
615 crate::db::spawn_bound(async move {
616 let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
617 let fetched = fetch_manifests(&transport, &bots, &relays).await;
618 if let Ok(mut inflight) = REFRESH_INFLIGHT.lock() {
619 inflight.remove(&chat_id);
620 }
621 let Ok(found) = fetched else { return }; for (pk, manifest, created_at) in &found {
623 if let Ok(json) = serde_json::to_string(manifest) {
624 let _ = crate::db::bots::upsert_bot_manifest(&pk.to_hex(), &json, *created_at);
625 }
626 }
627 let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
628 let commands = assemble_from_store(&bot_hexes);
629 mark_commands_fresh(&chat_id, session.id(), &bot_hexes);
630 crate::traits::emit_event(
631 "chat_commands_updated",
632 &serde_json::json!({ "chat_id": chat_id, "bots": bots.len(), "commands": commands }),
633 );
634 });
635}
636
637pub async fn publish_manifest(manifest: &BotManifest, keys: &Keys, relays: &[String]) -> Result<usize, String> {
643 publish_manifest_event(&manifest.to_event(keys)?, relays).await
644}
645
646pub async fn publish_manifest_event(event: &Event, relays: &[String]) -> Result<usize, String> {
649 let client = crate::state::nostr_client().ok_or("no client connected")?;
650 for r in relays {
653 let _ = client.add_managed_relay(r.as_str()).capabilities(crate::community_relay_capabilities()).await;
654 }
655 client.connect().await;
656 let out = crate::transport_aware(client.send_event(event))
657 .to(relays.to_vec())
658 .await
659 .map_err(|e| e.to_string())?;
660 Ok(out.success.len())
661}
662
663pub async fn fetch_manifest(bot: &nostr_sdk::prelude::PublicKey, relays: &[String]) -> Option<BotManifest> {
666 let client = crate::state::nostr_client()?;
667 let filter = nostr_sdk::prelude::Filter::new()
668 .kind(Kind::Custom(KIND_BOT_MANIFEST))
669 .author(*bot)
670 .limit(1);
671 let events = if relays.is_empty() {
672 client.fetch_events(filter).timeout(crate::relay_request_timeout(std::time::Duration::from_secs(8))).await.ok()?
673 } else {
674 client
675 .fetch_events(nostr_sdk::prelude::ReqTarget::manual(
676 relays.iter().cloned().map(|u| (u, vec![filter.clone()])),
677 ))
678 .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(8)))
679 .await
680 .ok()?
681 };
682 events
683 .into_iter()
684 .max_by_key(|e| e.created_at)
685 .and_then(|e| BotManifest::from_event(&e).ok())
686}
687
688#[cfg(test)]
689mod tests {
690 use super::*;
691 use nostr_sdk::prelude::Keys;
692
693 fn price_manifest() -> BotManifest {
694 BotManifest {
695 v: 1,
696 commands: vec![
697 CommandSpec {
698 name: "price".into(),
699 description: "Get a coin price".into(),
700 args: vec![ArgSpec {
701 name: "asset".into(),
702 arg_type: ArgType::Choice,
703 description: "Which coin".into(),
704 required: true,
705 choices: vec!["btc".into(), "xmr".into(), "pivx".into()],
706 }],
707 },
708 CommandSpec {
709 name: "say".into(),
710 description: "Echo".into(),
711 args: vec![
712 ArgSpec {
713 name: "count".into(),
714 arg_type: ArgType::Int,
715 description: String::new(),
716 required: true,
717 choices: vec![],
718 },
719 ArgSpec {
720 name: "text".into(),
721 arg_type: ArgType::String,
722 description: String::new(),
723 required: false,
724 choices: vec![],
725 },
726 ],
727 },
728 ],
729 }
730 }
731
732 #[test]
733 fn manifest_round_trips_through_its_event() {
734 let keys = Keys::generate();
735 let m = price_manifest();
736 let ev = m.to_event(&keys).unwrap();
737 assert_eq!(ev.kind, Kind::Custom(KIND_BOT_MANIFEST));
738 let back = BotManifest::from_event(&ev).unwrap();
739 assert_eq!(back.commands.len(), 2);
740 assert_eq!(back.command("price").unwrap().args[0].choices.len(), 3);
741 }
742
743 #[test]
747 fn an_empty_token_skips_an_optional_arg_so_later_ones_are_reachable() {
748 let m = BotManifest {
749 v: 1,
750 commands: vec![CommandSpec {
751 name: "listings".into(),
752 description: String::new(),
753 args: vec![
754 ArgSpec {
755 name: "category".into(),
756 arg_type: ArgType::Choice,
757 description: String::new(),
758 required: false,
759 choices: vec!["general".into(), "gaming".into()],
760 },
761 ArgSpec {
762 name: "page".into(),
763 arg_type: ArgType::Int,
764 description: String::new(),
765 required: false,
766 choices: vec![],
767 },
768 ],
769 }],
770 };
771 m.validate().expect("a legal manifest — required-first forbids the reverse shape");
772 let spec = m.command("listings").unwrap();
773
774 let parsed = parse_command_text(&m, r#"/listings "" 2"#).unwrap();
775 assert_eq!(parsed.args, vec![("page".to_string(), "2".to_string())], "the hole never becomes an argument");
776 let typed = typed_args(spec, &parsed).expect("a skipped optional passes typing");
777 assert!(!typed.contains_key("category"));
778 assert_eq!(typed.get("page").and_then(|v| v.as_int()), Some(2));
779
780 let pm = price_manifest();
782 let parsed = parse_command_text(&pm, r#"/say "" hello"#).unwrap();
783 assert_eq!(parsed.args.len(), 2, "an empty required token still binds");
784 assert!(typed_args(pm.command("say").unwrap(), &parsed).is_err(), "and fails as a non-integer, not silently absent");
785 }
786
787 #[test]
788 fn a_quoted_command_word_is_ordinary_chat() {
789 let m = price_manifest();
795 assert!(parse_command_text(&m, r#"/"price" btc"#).is_none());
796 assert!(parse_command_text(&m, r#"/"" btc"#).is_none());
797
798 assert!(parse_command_text(&m, "/price btc").is_some());
800 }
801
802 #[test]
803 fn the_command_word_is_case_folded() {
804 let m = price_manifest();
806 let p = parse_command_text(&m, "/PRICE btc").expect("an uppercase command resolves");
807 assert_eq!(p.name, "price");
808 assert_eq!(p.args, vec![("asset".to_string(), "btc".to_string())]);
809
810 let p = parse_command_text(&m, "/Say 2 Hello There").expect("a mixed-case command resolves");
812 assert_eq!(p.name, "say");
813 assert_eq!(p.args[1], ("text".to_string(), "Hello There".to_string()));
814 }
815
816 #[test]
817 fn user_args_accept_the_nip21_uri_and_normalize_to_a_bare_npub() {
818 use nostr_sdk::prelude::ToBech32;
819 let npub = Keys::generate().public_key().to_bech32().unwrap();
820 let spec = CommandSpec {
821 name: "greet".into(),
822 description: String::new(),
823 args: vec![ArgSpec {
824 name: "who".into(),
825 arg_type: ArgType::User,
826 description: String::new(),
827 required: true,
828 choices: vec![],
829 }],
830 };
831 let m = BotManifest { v: 1, commands: vec![spec.clone()] };
832
833 let p = parse_command_text(&m, &format!("/greet {npub}")).unwrap();
835 assert_eq!(typed_args(&spec, &p).unwrap()["who"], ArgValue::User(npub.clone()));
836
837 let p = parse_command_text(&m, &format!("/greet nostr:{npub}")).unwrap();
839 assert_eq!(typed_args(&spec, &p).unwrap()["who"], ArgValue::User(npub.clone()));
840
841 let p = parse_command_text(&m, "/greet npub1nope").unwrap();
843 assert!(typed_args(&spec, &p).is_err());
844 }
845
846 #[test]
847 fn typing_errors_are_canonical_and_parsable() {
848 let m = price_manifest();
851 let price = m.command("price").unwrap().clone();
852 let say = m.command("say").unwrap().clone();
853
854 let p = parse_command_text(&m, "/price doge").unwrap();
855 assert_eq!(typed_args(&price, &p).unwrap_err(), "asset: not one of btc, xmr, pivx");
856
857 let p = parse_command_text(&m, "/price").unwrap();
858 assert_eq!(typed_args(&price, &p).unwrap_err(), "asset: required");
859
860 let p = parse_command_text(&m, "/say notanint hi").unwrap();
861 assert_eq!(typed_args(&say, &p).unwrap_err(), "count: not an integer");
862 }
863
864 #[test]
865 fn validation_rejects_the_sharp_edges() {
866 let mut m = price_manifest();
867 m.commands[0].name = "Bad Name".into();
868 assert!(m.validate().is_err());
869
870 let mut m = price_manifest();
871 m.commands.push(m.commands[0].clone());
872 assert!(m.validate().is_err(), "duplicate command name");
873
874 let mut m = price_manifest();
875 m.commands[0].args[0].choices.clear();
876 assert!(m.validate().is_err(), "choice without choices");
877
878 let mut m = price_manifest();
880 m.commands[1].args[0].required = false;
881 m.commands[1].args[1].required = true;
882 assert!(m.validate().is_err());
883 }
884
885 fn announce_manifest() -> BotManifest {
887 BotManifest {
888 v: 1,
889 commands: vec![CommandSpec {
890 name: "announce".into(),
891 description: "Post an announcement".into(),
892 args: vec![
893 ArgSpec { name: "title".into(), arg_type: ArgType::String, description: String::new(), required: true, choices: vec![] },
894 ArgSpec { name: "body".into(), arg_type: ArgType::String, description: String::new(), required: true, choices: vec![] },
895 ],
896 }],
897 }
898 }
899
900 #[test]
901 fn command_text_and_parse_are_inverses() {
902 let m = price_manifest();
903 let args = vec![("asset".to_string(), "btc".to_string())];
904 let content = command_text("price", &args);
905 assert_eq!(content, "/price btc");
906 let p = parse_command_text(&m, &content).unwrap();
907 assert_eq!(p.name, "price");
908 assert_eq!(p.args, args);
909
910 let m = announce_manifest();
912 let args = vec![
913 ("title".to_string(), "Big \"news\" day".to_string()),
914 ("body".to_string(), "Meeting at 5pm".to_string()),
915 ];
916 let content = command_text("announce", &args);
917 let p = parse_command_text(&m, &content).unwrap();
918 assert_eq!(p.args, args);
919
920 for nasty in [
923 "\"", "\\", "ends with backslash \\", "\\\" fake close", "line one\nline two", "\" \\\" \\\\ \"\"", " leading and trailing ", ] {
931 let args = vec![
932 ("title".to_string(), nasty.to_string()),
933 ("body".to_string(), format!("after {nasty} end")),
934 ];
935 let content = command_text("announce", &args);
936 let p = parse_command_text(&m, &content)
937 .unwrap_or_else(|| panic!("adversarial value failed to re-parse: {nasty:?}"));
938 assert_eq!(p.args, args, "value must survive the wire byte-exact: {nasty:?}");
939 }
940 }
941
942 #[test]
943 fn text_parses_positionally_and_greedily() {
944 let m = price_manifest();
945 let p = parse_command_text(&m, "/price btc").unwrap();
946 assert_eq!(p.args, vec![("asset".to_string(), "btc".to_string())]);
947
948 let p = parse_command_text(&m, "/say 3 hello there world").unwrap();
950 assert_eq!(p.args[0], ("count".to_string(), "3".to_string()));
951 assert_eq!(p.args[1], ("text".to_string(), "hello there world".to_string()));
952
953 assert!(parse_command_text(&m, "/unknown x").is_none());
954 assert!(parse_command_text(&m, "not a command").is_none());
955 assert!(parse_command_text(&m, "/").is_none());
956 }
957
958 #[test]
959 fn bot_recipient_tags_extract_dedup_and_cap() {
960 use nostr_sdk::prelude::ToBech32;
961 let a = Keys::generate().public_key();
962 let b = Keys::generate().public_key();
963 let tags: Vec<Tag> = vec![
964 bot_tag(&a),
965 bot_tag(&a), bot_tag(&b),
967 Tag::custom(TAG_BOT, ["nothex"]),
968 Tag::custom("p", [a.to_hex()]), ];
970 let out = addressed_bots(tags.iter());
971 assert_eq!(out, vec![a.to_bech32().unwrap(), b.to_bech32().unwrap()]);
972
973 let many: Vec<Tag> = (0..20).map(|_| bot_tag(&Keys::generate().public_key())).collect();
975 assert_eq!(addressed_bots(many.iter()).len(), MAX_BOT_TAGS);
976
977 assert!(addressed_bots([].iter()).is_empty());
979 }
980
981 #[test]
982 fn quoting_terminates_multi_word_values() {
983 let m = announce_manifest();
984 let p = parse_command_text(&m, r#"/announce "Hello everyone" "Meeting at 5pm""#).unwrap();
986 assert_eq!(p.args[0].1, "Hello everyone");
987 assert_eq!(p.args[1].1, "Meeting at 5pm");
988
989 let p = parse_command_text(&m, r#"/announce "Hello everyone" Meeting at 5pm"#).unwrap();
991 assert_eq!(p.args[0].1, "Hello everyone");
992 assert_eq!(p.args[1].1, "Meeting at 5pm");
993
994 let p = parse_command_text(&m, "/announce Hello Meeting at 5pm").unwrap();
996 assert_eq!(p.args[0].1, "Hello");
997 assert_eq!(p.args[1].1, "Meeting at 5pm");
998
999 let p = parse_command_text(&m, r#"/announce "say \"hi\" \\ ok" done"#).unwrap();
1001 assert_eq!(p.args[0].1, r#"say "hi" \ ok"#);
1002
1003 assert!(parse_command_text(&m, r#"/announce "dangling"#).is_none());
1005 }
1006
1007 #[tokio::test]
1008 async fn batch_fetch_returns_newest_valid_per_author_and_ignores_strangers() {
1009 use crate::community::transport::{memory::MemoryRelay, Transport};
1010 use nostr_sdk::prelude::Timestamp;
1011 let relay = MemoryRelay::new();
1012 let relays = vec!["r1".to_string()];
1013 let bot_a = Keys::generate();
1014 let bot_b = Keys::generate();
1015 let stranger = Keys::generate();
1016
1017 let manifest_event = |m: &BotManifest, keys: &Keys, at: u64| {
1018 EventBuilder::new(Kind::Custom(KIND_BOT_MANIFEST), serde_json::to_string(m).unwrap())
1019 .custom_created_at(Timestamp::from_secs(at))
1020 .finalize(keys)
1021 .unwrap()
1022 };
1023 let old_ev = manifest_event(&price_manifest(), &bot_a, 100);
1025 let newer = BotManifest {
1026 v: 1,
1027 commands: vec![CommandSpec { name: "newer".into(), description: "n".into(), args: vec![] }],
1028 };
1029 let new_ev = manifest_event(&newer, &bot_a, 200);
1030 let b_garbage = EventBuilder::new(Kind::Custom(KIND_BOT_MANIFEST), "not json")
1032 .custom_created_at(Timestamp::from_secs(300))
1033 .finalize(&bot_b)
1034 .unwrap();
1035 let s_ev = price_manifest().to_event(&stranger).unwrap();
1037 for ev in [&old_ev, &new_ev, &b_garbage, &s_ev] {
1038 relay.publish(ev, &relays).await.unwrap();
1039 }
1040
1041 let found = fetch_manifests(&relay, &[bot_a.public_key(), bot_b.public_key()], &relays)
1042 .await
1043 .unwrap();
1044 assert_eq!(found.len(), 1, "only A has a usable newest manifest: {found:?}");
1045 assert_eq!(found[0].0, bot_a.public_key());
1046 assert!(found[0].1.command("newer").is_some(), "the newest edition won");
1047 assert!(found[0].1.command("price").is_none(), "the older edition lost");
1048 assert_eq!(found[0].2, 200, "the winning edition's timestamp rides along");
1049
1050 let none = fetch_manifests(&relay, &[], &relays).await.unwrap();
1051 assert!(none.is_empty(), "empty author set short-circuits");
1052 }
1053
1054 #[test]
1055 fn command_freshness_is_generation_ttl_and_botset_scoped() {
1056 let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|p| p.into_inner());
1058 let generation = crate::db::current_session_id();
1059 let bots = vec!["aa".to_string(), "bb".to_string()];
1060
1061 assert!(!commands_fresh("cmd-fresh-a", &bots), "unseen chat is stale");
1062 mark_commands_fresh("cmd-fresh-a", generation, &bots);
1063 assert!(commands_fresh("cmd-fresh-a", &bots));
1064
1065 let grown = vec!["aa".to_string(), "bb".to_string(), "cc".to_string()];
1067 assert!(!commands_fresh("cmd-fresh-a", &grown));
1068
1069 mark_commands_fresh("cmd-fresh-b", generation.wrapping_add(1), &bots);
1071 assert!(!commands_fresh("cmd-fresh-b", &bots));
1072 }
1073
1074 #[test]
1075 fn typing_enforces_the_manifest() {
1076 let m = price_manifest();
1077 let spec = m.command("price").unwrap();
1078
1079 let ok = ParsedCommand {
1080 name: "price".into(),
1081 args: vec![("asset".into(), "btc".into())],
1082 };
1083 let t = typed_args(spec, &ok).unwrap();
1084 assert_eq!(t["asset"], ArgValue::Choice("btc".into()));
1085
1086 let bad_choice = ParsedCommand {
1087 name: "price".into(),
1088 args: vec![("asset".into(), "doge".into())],
1089 };
1090 assert!(typed_args(spec, &bad_choice).is_err());
1091
1092 let missing = ParsedCommand { name: "price".into(), args: vec![] };
1093 assert!(typed_args(spec, &missing).is_err());
1094
1095 let extra = ParsedCommand {
1097 name: "price".into(),
1098 args: vec![("asset".into(), "btc".into()), ("future".into(), "1".into())],
1099 };
1100 let t = typed_args(spec, &extra).unwrap();
1101 assert!(!t.contains_key("future"));
1102
1103 let spec = m.command("say").unwrap();
1104 let typed = typed_args(
1105 spec,
1106 &ParsedCommand {
1107 name: "say".into(),
1108 args: vec![("count".into(), "5".into()), ("text".into(), "hi".into())],
1109 },
1110 )
1111 .unwrap();
1112 assert_eq!(typed["count"].as_int(), Some(5));
1113 assert_eq!(typed["text"].as_str(), "hi");
1114
1115 let not_int = ParsedCommand {
1116 name: "say".into(),
1117 args: vec![("count".into(), "many".into())],
1118 };
1119 assert!(typed_args(spec, ¬_int).is_err());
1120 }
1121}