Skip to main content

vector_core/
bot_interface.rs

1//! Bot Interface — manifests + slash commands (Phase 1 of the bot-UI layer).
2//!
3//! Transport-agnostic by design: everything here is CONTENT-level (structured
4//! tags on ordinary chat rumors, plus one plain replaceable discovery event),
5//! so the same commands work in NIP-17 DMs and Concord channels — the
6//! envelope is whatever the conversation already uses.
7//!
8//! Two pieces:
9//!
10//! 1. **Manifest** ([`BotManifest`], kind [`KIND_BOT_MANIFEST`]): a replaceable
11//!    event signed by the bot's key describing every command with typed args.
12//!    Clients fetch it by pubkey to render a `/` picker with argument hints and
13//!    validate input before anything hits the wire.
14//! 2. **Invocation** ([`parse_command_text`]): a command is a NORMAL chat
15//!    message whose `content` IS the invocation ("/price btc") — no extra
16//!    structure on the wire. The manifest's ordering rules (required args
17//!    first, a greedy String only in trailing position) make the text
18//!    deterministically parseable, so the bot recovers exact typed arguments
19//!    from content alone, and EVERY existing client is already a fully
20//!    capable command sender.
21//!
22//! The kind number is provisional pending upstream registry coordination.
23
24#[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
33/// Replaceable bot-interface manifest (outside any wrap): one authoritative
34/// command catalog per bot pubkey, the same shape as a profile or relay list.
35pub const KIND_BOT_MANIFEST: u16 = 10304;
36
37/// Optional recipient tag a picker client attaches to an invocation:
38/// `["bot", <bot pubkey hex>]`. Addressing is the ONE piece of a command not
39/// derivable from content — two bots can share a command name — so it rides a
40/// tag while the invocation stays plain text. Semantics: tagged → only the
41/// named bot(s) execute (others skip even on a manifest match); untagged →
42/// broadcast, any matching bot may answer (the legacy-client path — bots never
43/// REQUIRE the tag). Deliberately NOT `p`: chat rumors already carry `p` for
44/// DM recipients and reply parents, and a skip-unless-me rule keyed on `p`
45/// would silently swallow a command sent as a reply to a human. The tag is
46/// routing, not authority — bots authorize by SENDER, never by tag.
47pub const TAG_BOT: &str = "bot";
48
49/// Recipient tags honored per message (routing metadata must stay cheap).
50pub const MAX_BOT_TAGS: usize = 8;
51
52/// Build the recipient tag a picker attaches: `["bot", <hex>]`.
53pub fn bot_tag(bot: &nostr_sdk::prelude::PublicKey) -> Tag {
54    Tag::custom(TAG_BOT, [bot.to_hex()])
55}
56
57/// Extract the addressed bots from a rumor's tags as npubs (deduped, capped,
58/// invalid values skipped). Empty = untagged/broadcast.
59pub 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
80/// Bounds (validated on BOTH build and parse — a foreign manifest is untrusted
81/// input and must never cost unbounded memory or render work).
82pub 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;
88/// A single argument value on the wire (tag or text) is clamped before typing.
89pub const MAX_ARG_VALUE_LEN: usize = 1_024;
90
91// ── Manifest ─────────────────────────────────────────────────────────────────
92
93/// The typed shape of one command argument.
94#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
95#[serde(rename_all = "lowercase")]
96pub enum ArgType {
97    /// Free text. As the LAST argument it greedily swallows the remainder of a
98    /// plain-text invocation ("/say hello there" → one value "hello there").
99    String,
100    /// Signed integer (i64).
101    Int,
102    /// Float (f64).
103    Number,
104    /// "true"/"false" (also accepts "yes"/"no"/"1"/"0" from text).
105    Bool,
106    /// A user reference — an `npub1…` string on the wire.
107    User,
108    /// One of a fixed set of strings (renders as a picker).
109    Choice,
110}
111
112/// One declared argument of a command.
113#[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    /// Populated only for [`ArgType::Choice`].
123    #[serde(default, skip_serializing_if = "Vec::is_empty")]
124    pub choices: Vec<String>,
125}
126
127/// One command a bot answers.
128#[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/// The bot's full published interface. Unknown fields are ignored on read
137/// (forward compatibility); `v` gates breaking schema changes.
138#[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
145/// Command/arg names are lowercase slugs so every client renders and matches
146/// them identically (the cross-client contract).
147fn 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    /// Fail-closed structural validation, applied to our own manifests before
155    /// publish AND to fetched foreign ones before use.
156    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                // Positional text fallback needs required args to come first —
190                // an optional hole would make "/cmd a b" ambiguous.
191                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    /// Look up a command by name.
219    pub fn command(&self, name: &str) -> Option<&CommandSpec> {
220        self.commands.iter().find(|c| c.name == name)
221    }
222
223    /// Parse + validate a manifest from an event's content. The event must be
224    /// the manifest kind and is otherwise treated as untrusted input.
225    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    /// Build the signed replaceable manifest event (one manifest per bot
238    /// identity, keyed by `(kind, pubkey)` with no `d` tag).
239    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// ── Invocation ───────────────────────────────────────────────────────────────
251
252/// A command invocation recovered from a message's content. Values are raw
253/// strings in manifest order; type them via [`typed_args`].
254#[derive(Clone, Debug, PartialEq)]
255pub struct ParsedCommand {
256    pub name: String,
257    /// Named argument values in manifest order.
258    pub args: Vec<(String, String)>,
259}
260
261/// The canonical content for an invocation a picker client builds — exactly
262/// what a human would have typed ("/name value…"). Values containing spaces
263/// or quotes are quoted with `\"` escapes so the text re-parses to the same
264/// arguments.
265pub 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
280/// One shell-style token: either a bare word or a `"quoted span"` (which may
281/// contain spaces; `\"` is a literal quote, `\\` a literal backslash). Returns
282/// (value, byte offset just past the token).
283fn 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                    // Multi-byte chars pass through verbatim.
303                    let ch = s[i..].chars().next()?;
304                    out.push(ch);
305                    i += ch.len_utf8();
306                }
307            }
308        }
309        None // unterminated quote — malformed, not a command
310    } 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
320/// Parse "/name arg arg…" content against the manifest's arg order — THE
321/// invocation parse. Returns `None` when the text isn't a known command (it is
322/// then ordinary chat).
323///
324/// Multi-word values: a `"quoted value"` groups words in ANY position (`\"`
325/// escapes a literal quote), and an UNQUOTED trailing String arg swallows the
326/// raw remainder of the line — so the common forms ("/price btc",
327/// "/say hello there") need no syntax at all, and two multi-word strings are
328/// still expressible: `/announce "Big news" "Meeting at 5pm"`.
329pub fn parse_command_text(manifest: &BotManifest, content: &str) -> Option<ParsedCommand> {
330    let content = content.trim();
331    let rest = content.strip_prefix('/')?;
332    // The grammar is `"/" name`: a quoted first token is ordinary chat, not a
333    // command word. Test the RAW input — `next_token` hands back a quoted span
334    // with its quotes already stripped, so inspecting the token can never see one.
335    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    // Manifest names are lowercase slugs, so fold the invocation's command word:
343    // `/Help` and `/HELP` resolve like `/help`. Argument VALUES keep their case.
344    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            // Greedy tail: take the raw remainder verbatim (spacing preserved).
355            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        // An explicitly empty token (`""`) is the positional format's hole
366        // marker: it skips an OPTIONAL arg so a later one is still reachable
367        // ("/listings \"\" 2" = no category, page 2). A required arg keeps the
368        // empty value — an empty String can be a deliberate answer, and typing
369        // judges it, not the tokenizer.
370        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// ── Typing + validation against the manifest ─────────────────────────────────
379
380/// One argument value, typed per its spec.
381#[derive(Clone, Debug, PartialEq)]
382pub enum ArgValue {
383    String(String),
384    Int(i64),
385    Number(f64),
386    Bool(bool),
387    /// An `npub1…` user reference (kept as the bech32 string).
388    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
420/// Type-check a parsed invocation against the manifest: every provided value
421/// parses as its declared type, choices are members, required args are present.
422/// Unknown arg names are DROPPED (a newer client may know newer args; the bot's
423/// manifest is authoritative for what it consumes).
424///
425/// Errors are CANONICAL and machine-parsable — always `{arg}: {reason}`, so any
426/// implementation (in any language) emits byte-identical text and a client can
427/// split on the first `": "`. Reasons: `not an integer`, `not a number`,
428/// `not a boolean`, `not an npub`, `not one of a, b, c`, `required`.
429pub 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                // Canonical wire form is the bare npub, but clients commonly insert a
446                // mention as the NIP-21 `nostr:npub1…` URI — accept it and normalize
447                // back to the bare npub. Parsing also rejects a bad bech32 checksum.
448                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// ── Picker surface: batch discovery + per-chat cache ─────────────────────────
474
475/// One bot's published commands, shaped for a client's `/` picker. The client
476/// resolves the bot's display name/avatar from its own profile cache.
477#[derive(Serialize, Clone, Debug)]
478pub struct ChatBotCommands {
479    /// The bot's npub.
480    pub bot: String,
481    pub commands: Vec<CommandSpec>,
482}
483
484/// Public relays that index replaceable events network-wide — the reliable
485/// discovery path for bot manifests. Read side: always queried ALONGSIDE a
486/// chat's own relays, so a manifest resolves even when a community relay is
487/// unreachable or drops stranger events (Ditto does). Write side: the SDK
488/// publishes every bot's manifest here for the same reason.
489pub const DISCOVERY_RELAYS: &[&str] =
490    &["wss://purplepag.es", "wss://relay.nostr.band", "wss://nos.lol"];
491
492/// What the composer's `/` picker renders, instantly answerable from local
493/// state. `fresh: false` means a background refetch was spawned — a
494/// `chat_commands_updated` event follows with the converged list.
495#[derive(Serialize, Clone, Debug)]
496pub struct ChatCommandsSnapshot {
497    /// How many bot-flagged members this chat has (spinner copy: "Loading N bots").
498    pub bots: usize,
499    /// Last-known command sets, one entry per bot with a stored manifest,
500    /// commands in MANIFEST order (bots arrange their own list).
501    pub commands: Vec<ChatBotCommands>,
502    /// `true` = served from the fresh-TTL cache; nothing further will arrive.
503    pub fresh: bool,
504}
505
506/// Batch-fetch validated manifests for a set of authors over specific relays —
507/// the picker's ONE REQ (all bots of a room in a single query). Transport-
508/// generic so community relays are queried directly and tests run offline.
509/// Per author: the NEWEST event wins, then must validate (a bot that breaks
510/// its own manifest has no usable interface — parity with [`fetch_manifest`]);
511/// authors the relay volunteers beyond the asked set are dropped, as is
512/// anything failing signature verification. Returns each manifest with its
513/// event timestamp (the store's newest-wins key).
514pub 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
549/// Assemble picker entries from the persistent manifest store for a set of bot
550/// pubkeys (hex, pre-sorted order preserved). Bots with no stored manifest are
551/// absent; a stored row that no longer parses/validates is skipped.
552pub 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
568/// Freshness memory per chat: (session generation, refreshed-at, the bot set
569/// the refresh covered). One REQ per chat per minute; a CHANGED bot set (a bot
570/// joined/left) counts as stale immediately. The generation tag makes an
571/// account swap a natural invalidation.
572const 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()));
576/// Chats with a refresh REQ in flight (stampede guard for `/` keystrokes).
577static 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
580/// `true` while the last completed refresh for this chat is within TTL AND
581/// covered exactly `bot_hexes`.
582pub 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
603/// Background half of the picker flow: ONE REQ for every bot's manifest (5s
604/// unification window), persist newer editions, mark the chat fresh, and tell
605/// the UI to swap in the converged list. Deduped per chat; session-guarded
606/// before every write.
607pub 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; // already fetching for this chat
612        }
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 }; // transient failure: stay stale, next `/` retries
622        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
637// ── Network: publish + fetch ─────────────────────────────────────────────────
638
639/// Publish `manifest` as the signed replaceable event over the given relays
640/// (targeted send — the caller decides the reach: login relays, communities,
641/// indexers). Returns how many relays accepted it.
642pub 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
646/// [`publish_manifest`] for a manifest already signed with [`BotManifest::to_event`], so the
647/// signing key need not live across the publish.
648pub 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    // Targeted-only, like every Community and Discovery Relay: pooled for reading, an indexer
651    // or a Community relay would carry the account's DM subscription and DM sync too.
652    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
663/// Fetch + validate a bot's manifest by pubkey from the given relays. Returns
664/// the newest valid one, or `None` when the bot has published no interface.
665pub 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    /// The positional format needs a hole marker or a later arg is unreachable
744    /// past a skipped one: a composer skipping an optional first Choice used to
745    /// have no way to send the second arg at all.
746    #[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        // A REQUIRED arg's explicit empty is a value, not a hole — typing judges it.
781        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        // The grammar is `"/" name`, so a quoted first token is not a command.
790        // The guard has to read the RAW input: `next_token` returns a quoted span
791        // with its quotes stripped, so a check on the token can never fire — and
792        // this parsed as a valid `/price` until it did. A message another client
793        // sends as chat must not execute here.
794        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        // The unquoted form still parses, so the guard is narrow.
799        assert!(parse_command_text(&m, "/price btc").is_some());
800    }
801
802    #[test]
803    fn the_command_word_is_case_folded() {
804        // Manifest names are lowercase slugs, so `/PRICE` and `/Say` still resolve.
805        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        // Only the command WORD folds — argument values keep their case.
811        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        // The bare npub — what a compliant picker emits.
834        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        // A NIP-21 `nostr:` mention URI: accepted, normalized back to the bare npub.
838        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        // A malformed npub is still refused (the bech32 checksum is verified).
842        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        // Every error is `{arg}: {reason}` — byte-identical in any implementation,
849        // so a client splits on the first ": " to recover which arg failed and why.
850        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        // Required after optional breaks positional text parsing.
879        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    /// A command with TWO multi-word strings — expressible only via quoting.
886    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        // Multi-word + embedded-quote values round-trip via quoting.
911        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        // Adversarial values: no value can escape its quoted slot — every
921        // combination of quotes/backslashes/newlines re-parses to itself.
922        for nasty in [
923            "\"",                        // a lone quote
924            "\\",                        // a lone backslash
925            "ends with backslash \\",    // trailing backslash before the closing quote
926            "\\\" fake close",           // escaped-quote prefix
927            "line one\nline two",        // literal newline inside a value
928            "\" \\\" \\\\ \"\"",         // quote/escape soup
929            " leading and trailing ",    // spaces preserved verbatim
930        ] {
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        // Unquoted trailing String arg swallows the RAW remainder (spacing kept).
949        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), // dup
966            bot_tag(&b),
967            Tag::custom(TAG_BOT, ["nothex"]),
968            Tag::custom("p", [a.to_hex()]), // not ours
969        ];
970        let out = addressed_bots(tags.iter());
971        assert_eq!(out, vec![a.to_bech32().unwrap(), b.to_bech32().unwrap()]);
972
973        // Cap: 20 distinct tags → MAX_BOT_TAGS honored.
974        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        // Untagged → empty (broadcast).
978        assert!(addressed_bots([].iter()).is_empty());
979    }
980
981    #[test]
982    fn quoting_terminates_multi_word_values() {
983        let m = announce_manifest();
984        // Both strings quoted — unambiguous.
985        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        // First quoted, trailing unquoted → greedy tail.
990        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        // Unquoted first string takes ONE word (position rules unchanged).
995        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        // Escapes inside quotes.
1000        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        // Unterminated quote → not a command (ordinary chat).
1004        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        // A: an old manifest, then a newer edition with a different command set.
1024        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        // B: newest is garbage — B has no usable interface (no fallback to older).
1031        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        // Stranger: a VALID manifest outside the asked author set.
1036        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        // Serialize with bed tests — they bump the session generation mid-test.
1057        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        // A CHANGED bot set is immediately stale (a bot joined/left the room).
1066        let grown = vec!["aa".to_string(), "bb".to_string(), "cc".to_string()];
1067        assert!(!commands_fresh("cmd-fresh-a", &grown));
1068
1069        // Another generation's entry is invisible — the account-swap invalidation.
1070        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        // Unknown arg names are dropped, not fatal (newer-manifest tolerance).
1096        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, &not_int).is_err());
1120    }
1121}