package equipo import ( "fmt" "net/url" "regexp" "strings" "unicode" "unicode/utf8" ) // Lookup is one thing the Assistant looked up on the web for a reply: a // short answer, and the pages it came from. Equipo sends a message's // lookups only to a Base that said it draws them (CapLookupAnswers). type Lookup struct { Answer string `json:"answer"` Sources []Source `json:"sources"` } // Source is a page a lookup's answer came from. type Source struct { URL string `json:"url"` Title string `json:"title"` } // The bounds Clean keeps a message's lookups to: an answer of at most // MaxLookupAnswer characters (a longer one is dropped with its lookup), at // most MaxLookupSources sources each, titles cut to MaxLookupTitle // characters, and at most MaxLookups lookups. const ( MaxLookupAnswer = 1200 MaxLookupSources = 5 MaxLookupTitle = 120 MaxLookups = 2 // maxSourceURL bounds a source's address, in bytes. maxSourceURL = 2 << 10 ) // fallbackSources heads a lookup's addresses in the plain text a client // that can't draw lookups gets (copy ask.fallback_sources, approved by // Paul, 2026-11-28, copy review mi3kgi7nubnsf7kxn235tqwrbu). const fallbackSources = "Sources:" // cleanLookups is lookups as Base passes them on (Message.Clean): only an // assistant's message has any; each answer is valid UTF-8, not blank and // at most MaxLookupAnswer characters; each source an absolute https // address (sourceURL) with its title cut to MaxLookupTitle characters; a // lookup left without a source is dropped. Nil when none are left. func cleanLookups(role string, lookups []Lookup) []Lookup { if role != "assistant" { return nil } var out []Lookup for _, l := range lookups { if len(out) == MaxLookups { break } answer := strings.ToValidUTF8(l.Answer, "") if strings.TrimSpace(answer) == "" || utf8.RuneCountInString(answer) > MaxLookupAnswer { continue } var sources []Source for _, s := range l.Sources { if len(sources) == MaxLookupSources { break } u := sourceURL(s.URL) if u == "" { continue } title := []rune(strings.Map(func(r rune) rune { if unicode.IsControl(r) { return ' ' } return r }, strings.ToValidUTF8(s.Title, ""))) if len(title) > MaxLookupTitle { title = title[:MaxLookupTitle] } sources = append(sources, Source{URL: u, Title: string(title)}) } if len(sources) > 0 { out = append(out, Lookup{Answer: answer, Sources: sources}) } } return out } // sourceURL is raw if it is an absolute https address with a DNS name // for its host (sourceHostRE), no port and no user info, of at most // maxSourceURL bytes, else "". func sourceURL(raw string) string { if len(raw) > maxSourceURL { return "" } u := WebURL(raw) p, err := url.Parse(u) if u == "" || err != nil || p.Scheme != "https" || p.Port() != "" || !sourceHostRE.MatchString(strings.ToLower(p.Host)) { return "" } return normalizeURL(u) } // normalizeURL percent-encodes every byte of u that Go's html/template // would encode in an href (all but letters, digits, -._~, the reserved // !#$&*+,/:;=?@[] and %), so the address the server draws and the one // ask.js and the app are handed are the same. func normalizeURL(u string) string { var b strings.Builder for i := 0; i < len(u); i++ { c := u[i] switch { case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9', strings.IndexByte("-._~!#$&*+,/:;=?@[]%", c) >= 0: b.WriteByte(c) default: fmt.Fprintf(&b, "%%%02X", c) } } return b.String() } // sourceHostRE is a source's host: a DNS name of two labels or more in // ASCII letters, digits and inner hyphens, the last with a letter, and // no port. So it is no IP literal in any form, and every client (Go's // url, a browser's URL, Foundation's URL) reads the same host from it. var sourceHostRE = regexp.MustCompile(`^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]*[a-z][a-z0-9-]*$`) // The addresses plainAnswer takes out of an answer's text: a Markdown // link, an autolink, a bare http(s) address, and a www. name; then // markdownEscaper. Whitespace // is spelled out, so every engine reads it alike. var ( foldMarkdownLink = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\t\n\f\r ]{1,1000})\)`) foldAddress = regexp.MustCompile(`()\[\]"']+>?`) ) // plainAnswer is a lookup's answer as a client that draws ordinary // Markdown may show it with no link of its own (spec ยง4.6): a Markdown // link is its words, and an address (bare, an autolink, or a www. name) // is its host alone, without "www.", which no Markdown links; and what // Markdown could still read as a link is escaped. Trailing punctuation // stays as text. func plainAnswer(answer string) string { answer = foldMarkdownLink.ReplaceAllString(answer, "$1") answer = foldAddress.ReplaceAllStringFunc(answer, func(m string) string { raw := strings.TrimSuffix(strings.TrimPrefix(m, "<"), ">") trail := "" if !strings.HasSuffix(m, ">") { cut := strings.TrimRight(raw, ".,;:!?") trail, raw = raw[len(cut):], cut } if strings.HasPrefix(raw, "www.") { raw = "https://" + raw } u, err := url.Parse(raw) if err != nil { return trail } return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + trail }) return markdownEscaper.Replace(answer) } // markdownEscaper escapes what CommonMark could still read as a link: a // reference link or its definition, an image, an autolink, raw HTML or // an entity in a destination. Escaped, each shows as written. var markdownEscaper = strings.NewReplacer(`\`, `\\`, `[`, `\[`, `]`, `\]`, `<`, `\<`, `>`, `\>`, `&`, `\&`) // PlainLookups is m for a client that can't draw lookups: each answer // folded into the text after the message's own words, followed by // "Sources:" and its sources' addresses, one per line; the answer's own // addresses are taken out (plainAnswer). Lookups is nil. func (m Message) PlainLookups() Message { parts := []string{} if m.Text != "" { parts = append(parts, m.Text) } for _, l := range m.Lookups { urls := make([]string, 0, len(l.Sources)) for _, s := range l.Sources { urls = append(urls, s.URL) } parts = append(parts, plainAnswer(l.Answer), fallbackSources+"\n"+strings.Join(urls, "\n")) } m.Text, m.Lookups = strings.Join(parts, "\n\n"), nil return m }