graphrt-core 0.7.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Claims without numbers: the words, days and addresses a reply states, looked up in the sources.
//!
//! - **Words**: every word of a sentence that is not a function word or a word any business
//!   chat uses ([`super::words`]) must be in the sources, compared by stem ("delivery" and
//!   "deliver", "pengiriman" and "dikirim" do not need to be the same form).
//! - **Days**: "open on Sunday" needs a source that opens on Sunday (ranges such as "Monday to
//!   Saturday" count every day they span), "closed on Sunday" a source that closes then or
//!   opens only on other days.
//! - **Addresses**: a link, an email address or an `@handle` must be in the sources as written.
//! - **A yes or a no** ("Yes, we do.") with nothing the sources hold is a claim too: it answers
//!   the customer's question with a fact nobody gave.

use std::collections::HashSet;
use std::sync::LazyLock;

use super::words::{CHAT_WORDS, CLOSED_WORDS, DAY_GROUPS, DAYS, FUNCTION_WORDS, NUMBER_WORDS, RANGE_WORDS};

/// Words that answer a yes-or-no question.
const ANSWER_WORDS: &[&str] = &[
    "yes",
    "yeah",
    "yep",
    "sure",
    "certainly",
    "absolutely",
    "indeed",
    "correct",
    "no",
    "not",
    "nope",
    "don",
    "doesn",
    "didn",
    "never",
    "cannot",
    "ya",
    "iya",
    "betul",
    "benar",
    "tentu",
    "tidak",
    "nggak",
    "gak",
    "enggak",
    "bukan",
    "belum",
    "tak",
];

/// Lowercase words of `text`; `-` and `–` between words are words of their own (`mon-sat`).
///
pub(super) fn words(text: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut word = String::new();
    // "I'm", "don't", "we’re": the apostrophe parts words ("i", "m"), so the parts are function words.
    for character in text.chars() {
        if character.is_alphanumeric() {
            word.extend(character.to_lowercase());
            continue;
        }
        if !word.is_empty() {
            words.push(std::mem::take(&mut word));
        }
        if matches!(character, '-' | '–' | '—') {
            words.push("-".to_owned());
        }
    }
    if !word.is_empty() {
        words.push(word);
    }
    words
}

/// The parts of `word` two forms of it share: Indonesian prefixes and suffixes and English
/// endings taken off, then the first five letters. An Indonesian prefix may have eaten the
/// root's first letter (`mengirim` is `kirim`, `menulis` is `tulis`), so a word may have two.
pub(super) fn stems(word: &str) -> Vec<String> {
    let mut roots = vec![word.to_owned()];
    const PREFIXES: &[(&str, &str)] = &[
        ("meng", "k"),
        ("meny", "s"),
        ("mem", "p"),
        ("men", "t"),
        ("me", ""),
        ("peng", "k"),
        ("peny", "s"),
        ("pem", "p"),
        ("pen", "t"),
        ("pe", ""),
        ("ber", ""),
        ("ter", ""),
        ("di", ""),
        ("ke", ""),
    ];
    for (prefix, eaten) in PREFIXES {
        if let Some(rest) = word.strip_prefix(prefix)
            && rest.chars().count() >= 4
        {
            roots = vec![rest.to_owned()];
            if !eaten.is_empty() && rest.starts_with(['a', 'e', 'i', 'o', 'u']) {
                roots.push(format!("{eaten}{rest}"));
            }
            break;
        }
    }
    roots
        .into_iter()
        .map(|mut root| {
            // At most two endings: `pengirimannya` is `kirim` + `an` + `nya`.
            for _ in 0..2 {
                let ending = ["nya", "kan", "an", "ing", "ies", "es", "ed", "ly", "s", "i"]
                    .into_iter()
                    .find(|suffix| root.strip_suffix(suffix).is_some_and(|rest| rest.chars().count() >= 4));
                match ending {
                    Some(suffix) => root.truncate(root.len() - suffix.len()),
                    None => break,
                }
            }
            root.chars().take(5).collect()
        })
        .collect()
}

fn is_number_like(word: &str) -> bool {
    word.chars().any(|c| c.is_ascii_digit())
}

/// [`FUNCTION_WORDS`] and [`CHAT_WORDS`], read once. The lists are texts, not arrays of
/// texts: a thousand pointers into them would be 16 KiB more of every graphrt binary.
static FUNCTION: LazyLock<HashSet<&'static str>> = LazyLock::new(|| FUNCTION_WORDS.split_whitespace().collect());
static CHAT: LazyLock<HashSet<&'static str>> = LazyLock::new(|| CHAT_WORDS.split_whitespace().collect());

/// The stems of [`CHAT_WORDS`]: "pemesanan" is "pesan", "inquiries" is "inquiry".
static CHAT_STEMS: LazyLock<HashSet<String>> = LazyLock::new(|| CHAT.iter().flat_map(|word| stems(word)).collect());

/// Whether `word` states nothing by itself: a function or chat word (in any form), a day, a
/// number, a currency, a multiplier or a single letter.
pub(super) fn says_nothing(word: &str) -> bool {
    word == "-"
        || word.chars().count() < 3
        || is_number_like(word)
        || FUNCTION.contains(word)
        || CHAT.contains(word)
        || stems(word).iter().any(|stem| CHAT_STEMS.contains(stem))
        || day_of(word).is_some()
        || DAY_GROUPS.iter().any(|(group, _)| *group == word)
        || super::numbers::is_currency_or_multiplier(word)
        || super::numbers::is_number_word(word)
}

/// The words of some texts, by stem.
#[derive(Debug, Default)]
pub(super) struct KnownWords {
    stems: HashSet<String>,
    /// Two words of the sources written as one ("pick up" as `pickup`), exactly: stemming a
    /// joined pair makes words nobody wrote ("menu nasi" would hold "tunai").
    joined: HashSet<String>,
}

impl KnownWords {
    /// Whether `word` (or `two words`, as [`KnownWords::sort`] writes a joined pair) is held.
    pub(super) fn holds(&self, word: &str) -> bool {
        let joined: String = word.split_whitespace().collect();
        self.joined.contains(&joined) || stems(&joined).iter().any(|stem| self.stems.contains(stem))
    }

    pub(super) fn of(text: &str) -> Self {
        let words = words(text);
        let known: HashSet<String> =
            words.iter().filter(|word| !says_nothing(word)).flat_map(|word| stems(word)).collect();
        // "pick-up" and "pick up" are "pickup".
        let mut joined = HashSet::new();
        for pair in words.windows(2) {
            if let [first, second] = pair
                && first != "-"
                && second != "-"
            {
                joined.insert(format!("{first}{second}"));
            }
        }
        for three in words.windows(3) {
            if let [first, joiner, last] = three
                && joiner == "-"
            {
                joined.insert(format!("{first}{last}"));
            }
        }
        Self { stems: known, joined }
    }

    /// The words of `sentence` that state something, split into the ones the sources hold and
    /// the ones they do not.
    pub(super) fn sort(&self, sentence: &str) -> (Vec<String>, Vec<String>) {
        let mut held = Vec::new();
        let mut novel = Vec::new();
        let words = words(sentence);
        let knows = |word: &str| self.joined.contains(word) || stems(word).iter().any(|stem| self.stems.contains(stem));
        let mut index = 0;
        while let Some(word) = words.get(index) {
            index += 1;
            if says_nothing(word) {
                continue;
            }
            // "pick up" for a source's "pickup".
            let next = words.get(index).filter(|next| *next != "-");
            let (written, is_known) = match next {
                Some(next) if !knows(word) && knows(&format!("{word}{next}")) => {
                    index += 1;
                    (format!("{word} {next}"), true)
                }
                _ => (word.clone(), knows(word)),
            };
            let list = if is_known { &mut held } else { &mut novel };
            if !list.contains(&written) {
                list.push(written);
            }
        }
        (held, novel)
    }
}

/// Phrases that say the bot does not know (English and Indonesian), as lowercase word runs.
const UNKNOWN_PHRASES: &[&[&str]] = &[
    &["not", "sure"],
    &["unsure"],
    &["not", "certain"],
    &["don", "t", "know"],
    &["do", "not", "know"],
    // "I don't have that information", not "we don't have red velvet" (that is a claim).
    &["don", "t", "have", "information"],
    &["don", "t", "have", "that", "information"],
    &["don", "t", "have", "any", "information"],
    &["don", "t", "have", "info"],
    &["don", "t", "have", "details"],
    &["do", "not", "have", "information"],
    &["do", "not", "have", "that", "information"],
    &["do", "not", "have", "any", "information"],
    &["no", "information"],
    &["no", "details"],
    &["not", "mentioned"],
    &["not", "mention"],
    &["doesn", "t", "mention"],
    &["does", "not", "mention"],
    &["can", "t", "find"],
    &["cannot", "find"],
    &["couldn", "t", "find"],
    &["unable", "to", "find"],
    &["tidak", "tahu"],
    &["kurang", "tahu"],
    &["belum", "tahu"],
    &["tidak", "yakin"],
    &["kurang", "yakin"],
    &["belum", "punya", "info"],
    &["belum", "punya", "informasi"],
    &["tidak", "punya", "info"],
    &["tidak", "punya", "informasi"],
    &["tidak", "memiliki", "info"],
    &["tidak", "memiliki", "informasi"],
    &["belum", "memiliki", "info"],
    &["belum", "memiliki", "informasi"],
    &["tidak", "ada", "informasi"],
    &["tidak", "ada", "info"],
    &["belum", "ada", "informasi"],
    &["belum", "ada", "info"],
    &["tidak", "disebutkan"],
    &["tidak", "terdapat"],
    &["informasi", "tidak", "tersedia"],
    &["info", "tidak", "tersedia"],
    // A promise that someone else answers: the bot does not.
    &["owner", "will"],
    &["front", "desk", "will"],
    &["will", "reply", "soon"],
    &["will", "get", "back"],
    &["hand", "you", "over"],
    &["hand", "this", "over"],
    &["pass", "your", "question"],
    &["pass", "this", "question"],
    &["pemilik", "akan"],
    &["admin", "akan"],
    &["akan", "segera", "membalas"],
    &["akan", "segera", "menjawab"],
    &["serahkan", "pertanyaan"],
    &["teruskan", "pertanyaan"],
    &["meneruskan", "pertanyaan"],
];

/// Whether `sentence` says the bot does not know ("I'm not sure about…", "saya belum punya info…")
/// or that someone else will answer ("The owner will reply soon").
pub(super) fn admits_unknown(sentence: &str) -> bool {
    let words = words(sentence);
    UNKNOWN_PHRASES
        .iter()
        .any(|phrase| words.windows(phrase.len()).any(|run| run.iter().zip(*phrase).all(|(w, p)| w == p)))
}

/// Whether `sentence` answers yes or no.
pub(super) fn answers_yes_or_no(sentence: &str) -> bool {
    words(sentence).iter().any(|word| ANSWER_WORDS.contains(&word.as_str()))
}

/// The day `word` names (Monday is 0); "Sundays" is Sunday.
fn day_of(word: &str) -> Option<usize> {
    let find = |word: &str| DAYS.iter().position(|names| names.contains(&word));
    find(word).or_else(|| word.strip_suffix('s').and_then(find))
}

/// A day a text names, and whether it says the day is closed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DayMention {
    day: usize,
    closed: bool,
}

/// The days `text` names, with ranges ("Monday to Saturday", "Mon-Sat") spelled out.
fn day_mentions(text: &str) -> Vec<(DayMention, String)> {
    let words = words(text);
    let mut mentions = Vec::new();
    let mut index = 0;
    while let Some(word) = words.get(index) {
        let start = index;
        let previous_is_number = index
            .checked_sub(1)
            .and_then(|before| words.get(before))
            .is_some_and(|before| is_number_like(before) || NUMBER_WORDS.contains(&before.as_str()));
        let days: Vec<usize> = match (day_of(word), DAY_GROUPS.iter().find(|(group, _)| group == word)) {
            // "2 minggu" is two weeks, not two Sundays.
            (Some(_), _) if previous_is_number => Vec::new(),
            (Some(first), _) => {
                let last = words
                    .get(index + 1)
                    .filter(|joiner| RANGE_WORDS.contains(&joiner.as_str()))
                    .and_then(|_| words.get(index + 2))
                    .and_then(|next| day_of(next));
                match last {
                    Some(last) => {
                        index += 2;
                        let span = (last + 7 - first) % 7;
                        (0..=span).map(|step| (first + step) % 7).collect()
                    }
                    None => vec![first],
                }
            }
            (None, Some((_, group))) => group.to_vec(),
            (None, None) => Vec::new(),
        };
        if !days.is_empty() {
            // "closed on Sunday", "tutup hari Minggu", "Sunday: closed".
            let before = words.get(start.saturating_sub(3)..start).unwrap_or_default();
            let after = words.get(index + 1..(index + 3).min(words.len())).unwrap_or_default();
            let closed = before.iter().chain(after).any(|word| CLOSED_WORDS.contains(&word.as_str()));
            for day in days {
                mentions.push((DayMention { day, closed }, word.clone()));
            }
        }
        index += 1;
    }
    mentions
}

/// The days some texts open and close on, one bit per day (Monday is bit 0).
#[derive(Debug, Default)]
pub(super) struct KnownDays {
    open: u8,
    closed: u8,
}

/// The bit of `day` (0 to 6).
fn bit(day: usize) -> u8 {
    u8::try_from(day % 7).map(|day| 1 << day).unwrap_or(0)
}

const EVERY_DAY: u8 = 0b111_1111;

impl KnownDays {
    pub(super) fn of(text: &str) -> Self {
        let mut known = Self::default();
        for (mention, _) in day_mentions(text) {
            if mention.closed {
                known.closed |= bit(mention.day);
            } else {
                known.open |= bit(mention.day);
            }
        }
        known.open &= !known.closed;
        // "Closed on Sunday" alone opens the other days.
        if known.open == 0 && known.closed != 0 {
            known.open = EVERY_DAY & !known.closed;
        }
        known
    }

    fn holds(&self, mention: DayMention) -> bool {
        let day = bit(mention.day);
        if mention.closed {
            self.closed & day != 0 || (self.open != 0 && self.open & day == 0)
        } else {
            self.open & day != 0
        }
    }

    /// The first day `sentence` names that the sources do not hold, as written; and whether
    /// it names a day they do hold.
    pub(super) fn check(&self, sentence: &str) -> (Option<String>, bool) {
        let mut repeats = false;
        for (mention, written) in day_mentions(sentence) {
            if !self.holds(mention) {
                return (Some(written), repeats);
            }
            repeats = true;
        }
        (None, repeats)
    }
}

/// Links, email addresses and `@handles` of `text`, lowercased, without trailing punctuation.
fn addresses(text: &str) -> Vec<String> {
    text.split_whitespace()
        .map(|word| {
            word.trim_matches(|c: char| matches!(c, '.' | ',' | '!' | '?' | ')' | '(' | '"' | '\'' | ':' | ';'))
        })
        .filter(|word| {
            let lower = word.to_lowercase();
            lower.starts_with("http") || lower.starts_with("www.") || word.contains('@')
        })
        .map(str::to_lowercase)
        .collect()
}

/// The addresses some texts hold.
#[derive(Debug, Default)]
pub(super) struct KnownAddresses {
    text: String,
}

impl KnownAddresses {
    pub(super) fn of(text: &str) -> Self {
        Self { text: text.to_lowercase() }
    }

    /// The first address of `sentence` the sources do not hold.
    pub(super) fn first_unknown(&self, sentence: &str) -> Option<String> {
        addresses(sentence).into_iter().find(|address| !self.text.contains(address.as_str()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn forms_of_a_word_share_a_stem() {
        let share = |left: &str, right: &str| stems(left).iter().any(|stem| stems(right).contains(stem));
        assert!(share("delivery", "deliver"));
        assert!(share("delivers", "delivered"));
        assert!(share("pengiriman", "pengirimannya"));
        assert!(share("dikirim", "kirim"));
        assert!(share("pengiriman", "kirim"));
        assert!(share("menulis", "tulis"));
        assert!(!share("parking", "pickup"));
    }

    #[test]
    fn words_the_sources_do_not_hold_are_novel() {
        let known = KnownWords::of("Laundry: 8k per kg, express 15k per kg, pickup between 9 and 18.");
        let (held, novel) = known.sort("Yes, we offer free delivery for express laundry.");
        assert_eq!(held, ["express", "laundry"]);
        assert_eq!(novel, ["free", "delivery"]);
        let (held, novel) = known.sort("Thank you for asking! Our express laundry service costs 15k per kilogram.");
        assert_eq!(held, ["express", "laundry"]);
        assert!(novel.is_empty(), "{novel:?}");
        let (_, novel) =
            KnownWords::of("nasi box 25k, tumpeng 350k").sort("Harga nasi box kami adalah 25.000 per box.");
        assert!(novel.is_empty(), "{novel:?}");
    }

    #[test]
    fn a_joined_pair_of_the_facts_is_no_stem() {
        let (_, novel) =
            KnownWords::of("our catering menu (nasi box 25k)").sort("Kami hanya menerima pembayaran tunai.");
        assert_eq!(novel, ["tunai"]);
        let (held, _) = KnownWords::of("free pick-up").sort("Pickup is free.");
        assert_eq!(held, ["pickup", "free"]);
    }

    #[test]
    fn open_and_closed_days_follow_the_sources() {
        let clinic = KnownDays::of("open Monday to Saturday 9-20");
        assert_eq!(clinic.check("Yes, we are open on Saturday."), (None, true));
        assert_eq!(clinic.check("We are open on Sundays.").0.as_deref(), Some("sundays"));
        assert_eq!(clinic.check("We are closed on Sunday."), (None, true));
        assert_eq!(clinic.check("Kami buka Senin sampai Sabtu."), (None, true));
        let bakery = KnownDays::of("opening hours (8 to 17, closed Sunday)");
        assert_eq!(bakery.check("Yes, we are open on Saturday."), (None, true));
        assert!(bakery.check("We are open on Sunday mornings.").0.is_some());
        assert_eq!(bakery.check("Mon-Sat we bake fresh."), (None, true));
        let nothing = KnownDays::of("prices are 8k per kg");
        assert!(nothing.check("We are open every weekday.").0.is_some());
        assert_eq!(nothing.check("Delivery takes 2 minggu."), (None, false));
        assert_eq!(nothing.check("Pembayaran dalam dua minggu."), (None, false));
    }

    #[test]
    fn addresses_must_be_written_in_the_sources() {
        let known = KnownAddresses::of("Order at https://kue.example/order or mail halo@kue.example");
        assert_eq!(known.first_unknown("Order at https://kue.example/order."), None);
        assert_eq!(known.first_unknown("Write to sales@kue.example!").as_deref(), Some("sales@kue.example"));
        assert_eq!(known.first_unknown("Follow @kue_official").as_deref(), Some("@kue_official"));
    }

    #[test]
    fn a_yes_or_a_no_is_an_answer() {
        assert!(answers_yes_or_no("Yes, we do."));
        assert!(answers_yes_or_no("Tidak, kami tidak menyediakan itu."));
        assert!(!answers_yes_or_no("Our cheesecake costs 120k."));
    }
}