use std::collections::HashMap;
use std::sync::OnceLock;
use fancy_regex::{Regex, RegexBuilder};
use serde_json::Value;
use super::Turn;
use super::message::text_of;
use crate::text::is_space;
pub const LINK_CHARS: usize = 48;
const SPACE: &str = r"\s\x1c-\x1f";
const HANDLE_OPEN: &str = "[link ";
fn atom() -> &'static Regex {
static ATOM: OnceLock<Regex> = OnceLock::new();
ATOM.get_or_init(|| {
let handle = r"\[link [^\]]*\]";
let character = format!(r#"[^{SPACE}"'<>|\[\]`\\()]"#);
let unit = format!(r"(?:{character}|\({character}*\))");
let end = format!(r#"(?=[.,;:!?)]*(?:[{SPACE}"'<>|\[\]`\\)]|$))"#);
let url = format!("[A-Za-z][A-Za-z0-9+.-]*://{unit}+?{end}");
let path = format!("{unit}*?/{unit}*?{end}");
let id =
format!(r"(?=[A-Za-z0-9_.-]*\d)[A-Za-z0-9_-](?:[A-Za-z0-9_.-]*[A-Za-z0-9_-])?{end}");
RegexBuilder::new(&format!("{handle}|(?<!{character})(?:{url}|{path}|{id})"))
.backtrack_limit(usize::MAX)
.build()
.expect("the atom grammar compiles")
})
}
fn delimiter(ch: char) -> bool {
is_space(ch) || "\"'<>|[]`\\".contains(ch)
}
fn runs(text: &str) -> Vec<(usize, usize)> {
let mut runs = Vec::new();
let mut start = None;
for (at, ch) in text.char_indices() {
match (delimiter(ch), start) {
(true, Some(from)) => {
runs.push((from, at));
start = None;
}
(false, None) => start = Some(at),
_ => {}
}
}
if let Some(from) = start {
runs.push((from, text.len()));
}
runs
}
fn handle_open_at(text: &str, at: usize) -> bool {
text.match_indices(HANDLE_OPEN)
.take_while(|(open, _)| *open < at)
.last()
.is_some_and(|(open, _)| !text[(open + HANDLE_OPEN.len()).min(at)..at].contains(']'))
}
fn run_around(text: &str, at: usize) -> (usize, usize) {
let from = text[..at]
.char_indices()
.rev()
.find(|(_, ch)| delimiter(*ch))
.map_or(0, |(index, ch)| index + ch.len_utf8());
let until = text[at..]
.char_indices()
.find(|(_, ch)| delimiter(*ch))
.map_or(text.len(), |(index, _)| at + index);
(from, until)
}
fn scan(text: &str, from: usize, until: usize) -> Vec<(usize, usize)> {
let window = &text[..until];
let mut found = Vec::new();
let mut pos = from;
while let Ok(Some(matched)) = atom().find_from_pos(window, pos) {
found.push((matched.start(), matched.end()));
pos = matched.end();
}
found
}
struct Cursor<'a> {
text: &'a str,
byte: usize,
chars: usize,
}
impl Cursor<'_> {
fn at(&mut self, byte: usize) -> usize {
self.chars += self.text[self.byte..byte].chars().count();
self.byte = byte;
self.chars
}
}
pub fn boundary(text: &str, at: usize) -> (usize, usize) {
let at_byte = text
.char_indices()
.nth(at)
.map_or(text.len(), |(byte, _)| byte);
let (from, until) = if handle_open_at(text, at_byte) {
(0, text.len())
} else {
run_around(text, at_byte)
};
let mut cursor = Cursor {
text,
byte: 0,
chars: 0,
};
for (first, last) in scan(text, from, until) {
let start = cursor.at(first);
let end = cursor.at(last);
if start < at && at < end {
return (start, end);
}
if start >= at {
break;
}
}
(at, at)
}
fn registrable(token: &str) -> bool {
token.chars().count() >= LINK_CHARS && !token.starts_with(HANDLE_OPEN)
}
fn long_runs(text: &str) -> Vec<(usize, usize)> {
if text.contains(HANDLE_OPEN) {
return vec![(0, text.len())];
}
let long = |(from, until): &(usize, usize)| text[*from..*until].chars().count() >= LINK_CHARS;
runs(text).into_iter().filter(long).collect()
}
fn links(text: &str) -> Vec<&str> {
long_runs(text)
.into_iter()
.flat_map(|(from, until)| scan(text, from, until))
.map(|(first, last)| &text[first..last])
.filter(|token| registrable(token))
.collect()
}
pub fn whole_tokens<'a>(head: &'a str, tail: &'a str) -> (&'a str, &'a str) {
let front = head
.char_indices()
.rev()
.find(|(_, ch)| delimiter(*ch))
.map_or("", |(at, _)| &head[..at]);
let back = tail
.char_indices()
.find(|(_, ch)| delimiter(*ch))
.map_or("", |(at, ch)| &tail[at + ch.len_utf8()..]);
(front, back)
}
fn strings<'a>(value: &'a Value, found: &mut Vec<&'a str>) {
match value {
Value::String(text) => found.push(text),
Value::Object(map) => map.values().for_each(|item| strings(item, found)),
Value::Array(items) => items.iter().for_each(|item| strings(item, found)),
_ => {}
}
}
pub struct LinkRegistry {
numbers: HashMap<String, usize>,
label: String,
}
impl LinkRegistry {
pub fn of(turns: &[Turn], source: Option<&str>) -> Self {
let mut registry = Self {
numbers: HashMap::new(),
label: source.map_or_else(String::new, |source| format!("{source}:")),
};
for turn in turns {
for message in &turn.messages {
registry.register(&text_of(message));
for call in &message.tool_calls {
registry.register_strings(&call.arguments);
}
}
}
registry
}
pub fn register(&mut self, text: &str) {
for token in links(text) {
let next = self.numbers.len() + 1;
self.numbers.entry(token.to_string()).or_insert(next);
}
}
pub fn register_strings(&mut self, value: &Value) {
let mut found = Vec::new();
strings(value, &mut found);
found.into_iter().for_each(|text| self.register(text));
}
pub fn handle(&self, number: usize) -> String {
format!("[link {}{number}]", self.label)
}
pub fn contract(&self, text: &str) -> String {
if self.numbers.is_empty() {
return text.to_string();
}
let mut out = String::with_capacity(text.len());
let mut done = 0;
for (from, until) in long_runs(text) {
out.push_str(&text[done..from]);
let mut pos = from;
for (first, last) in scan(text, from, until) {
out.push_str(&text[pos..first]);
let token = &text[first..last];
match self.numbers.get(token) {
Some(number) => out.push_str(&self.handle(*number)),
None => out.push_str(token),
}
pos = last;
}
out.push_str(&text[pos..until]);
done = until;
}
out.push_str(&text[done..]);
out
}
}
#[cfg(test)]
mod tests;