| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "net/url" |
| 6 | "regexp" |
| 7 | "strings" |
| 8 | "unicode" |
| 9 | "unicode/utf8" |
| 10 | ) |
| 11 | |
| 12 | // Lookup is one thing the Assistant looked up on the web for a reply: a |
| 13 | // short answer, and the pages it came from. Equipo sends a message's |
| 14 | // lookups only to a Base that said it draws them (CapLookupAnswers). |
| 15 | type Lookup struct { |
| 16 | Answer string `json:"answer"` |
| 17 | Sources []Source `json:"sources"` |
| 18 | } |
| 19 | |
| 20 | // Source is a page a lookup's answer came from. |
| 21 | type Source struct { |
| 22 | URL string `json:"url"` |
| 23 | Title string `json:"title"` |
| 24 | } |
| 25 | |
| 26 | // The bounds Clean keeps a message's lookups to: an answer of at most |
| 27 | // MaxLookupAnswer characters (a longer one is dropped with its lookup), at |
| 28 | // most MaxLookupSources sources each, titles cut to MaxLookupTitle |
| 29 | // characters, and at most MaxLookups lookups. |
| 30 | const ( |
| 31 | MaxLookupAnswer = 1200 |
| 32 | MaxLookupSources = 5 |
| 33 | MaxLookupTitle = 120 |
| 34 | MaxLookups = 2 |
| 35 | // maxSourceURL bounds a source's address, in bytes. |
| 36 | maxSourceURL = 2 << 10 |
| 37 | ) |
| 38 | |
| 39 | // fallbackSources heads a lookup's addresses in the plain text a client |
| 40 | // that can't draw lookups gets (copy ask.fallback_sources, approved by |
| 41 | // Paul, 2026-11-28, copy review mi3kgi7nubnsf7kxn235tqwrbu). |
| 42 | const fallbackSources = "Sources:" |
| 43 | |
| 44 | // cleanLookups is lookups as Base passes them on (Message.Clean): only an |
| 45 | // assistant's message has any; each answer is valid UTF-8, not blank and |
| 46 | // at most MaxLookupAnswer characters; each source an absolute https |
| 47 | // address (sourceURL) with its title cut to MaxLookupTitle characters; a |
| 48 | // lookup left without a source is dropped. Nil when none are left. |
| 49 | func cleanLookups(role string, lookups []Lookup) []Lookup { |
| 50 | if role != "assistant" { |
| 51 | return nil |
| 52 | } |
| 53 | var out []Lookup |
| 54 | for _, l := range lookups { |
| 55 | if len(out) == MaxLookups { |
| 56 | break |
| 57 | } |
| 58 | answer := strings.ToValidUTF8(l.Answer, "") |
| 59 | if strings.TrimSpace(answer) == "" || utf8.RuneCountInString(answer) > MaxLookupAnswer { |
| 60 | continue |
| 61 | } |
| 62 | var sources []Source |
| 63 | for _, s := range l.Sources { |
| 64 | if len(sources) == MaxLookupSources { |
| 65 | break |
| 66 | } |
| 67 | u := sourceURL(s.URL) |
| 68 | if u == "" { |
| 69 | continue |
| 70 | } |
| 71 | title := []rune(strings.Map(func(r rune) rune { |
| 72 | if unicode.IsControl(r) { |
| 73 | return ' ' |
| 74 | } |
| 75 | return r |
| 76 | }, strings.ToValidUTF8(s.Title, ""))) |
| 77 | if len(title) > MaxLookupTitle { |
| 78 | title = title[:MaxLookupTitle] |
| 79 | } |
| 80 | sources = append(sources, Source{URL: u, Title: string(title)}) |
| 81 | } |
| 82 | if len(sources) > 0 { |
| 83 | out = append(out, Lookup{Answer: answer, Sources: sources}) |
| 84 | } |
| 85 | } |
| 86 | return out |
| 87 | } |
| 88 | |
| 89 | // sourceURL is raw if it is an absolute https address with a DNS name |
| 90 | // for its host (sourceHostRE), no port and no user info, of at most |
| 91 | // maxSourceURL bytes, else "". |
| 92 | func sourceURL(raw string) string { |
| 93 | if len(raw) > maxSourceURL { |
| 94 | return "" |
| 95 | } |
| 96 | u := WebURL(raw) |
| 97 | p, err := url.Parse(u) |
| 98 | if u == "" || err != nil || p.Scheme != "https" || p.Port() != "" || !sourceHostRE.MatchString(strings.ToLower(p.Host)) { |
| 99 | return "" |
| 100 | } |
| 101 | return normalizeURL(u) |
| 102 | } |
| 103 | |
| 104 | // normalizeURL percent-encodes every byte of u that Go's html/template |
| 105 | // would encode in an href (all but letters, digits, -._~, the reserved |
| 106 | // !#$&*+,/:;=?@[] and %), so the address the server draws and the one |
| 107 | // ask.js and the app are handed are the same. |
| 108 | func normalizeURL(u string) string { |
| 109 | var b strings.Builder |
| 110 | for i := 0; i < len(u); i++ { |
| 111 | c := u[i] |
| 112 | switch { |
| 113 | case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9', strings.IndexByte("-._~!#$&*+,/:;=?@[]%", c) >= 0: |
| 114 | b.WriteByte(c) |
| 115 | default: |
| 116 | fmt.Fprintf(&b, "%%%02X", c) |
| 117 | } |
| 118 | } |
| 119 | return b.String() |
| 120 | } |
| 121 | |
| 122 | // sourceHostRE is a source's host: a DNS name of two labels or more in |
| 123 | // ASCII letters, digits and inner hyphens, the last with a letter, and |
| 124 | // no port. So it is no IP literal in any form, and every client (Go's |
| 125 | // url, a browser's URL, Foundation's URL) reads the same host from it. |
| 126 | var sourceHostRE = regexp.MustCompile(`^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]*[a-z][a-z0-9-]*$`) |
| 127 | |
| 128 | // The addresses plainAnswer takes out of an answer's text: a Markdown |
| 129 | // link, an autolink, a bare http(s) address, and a www. name; then |
| 130 | // markdownEscaper. Whitespace |
| 131 | // is spelled out, so every engine reads it alike. |
| 132 | var ( |
| 133 | foldMarkdownLink = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\t\n\f\r ]{1,1000})\)`) |
| 134 | foldAddress = regexp.MustCompile(`<?(?:https?://|www\.)[^\t\n\f\r <>()\[\]"']+>?`) |
| 135 | ) |
| 136 | |
| 137 | // plainAnswer is a lookup's answer as a client that draws ordinary |
| 138 | // Markdown may show it with no link of its own (spec §4.6): a Markdown |
| 139 | // link is its words, and an address (bare, an autolink, or a www. name) |
| 140 | // is its host alone, without "www.", which no Markdown links; and what |
| 141 | // Markdown could still read as a link is escaped. Trailing punctuation |
| 142 | // stays as text. |
| 143 | func plainAnswer(answer string) string { |
| 144 | answer = foldMarkdownLink.ReplaceAllString(answer, "$1") |
| 145 | answer = foldAddress.ReplaceAllStringFunc(answer, func(m string) string { |
| 146 | raw := strings.TrimSuffix(strings.TrimPrefix(m, "<"), ">") |
| 147 | trail := "" |
| 148 | if !strings.HasSuffix(m, ">") { |
| 149 | cut := strings.TrimRight(raw, ".,;:!?") |
| 150 | trail, raw = raw[len(cut):], cut |
| 151 | } |
| 152 | if strings.HasPrefix(raw, "www.") { |
| 153 | raw = "https://" + raw |
| 154 | } |
| 155 | u, err := url.Parse(raw) |
| 156 | if err != nil { |
| 157 | return trail |
| 158 | } |
| 159 | return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + trail |
| 160 | }) |
| 161 | return markdownEscaper.Replace(answer) |
| 162 | } |
| 163 | |
| 164 | // markdownEscaper escapes what CommonMark could still read as a link: a |
| 165 | // reference link or its definition, an image, an autolink, raw HTML or |
| 166 | // an entity in a destination. Escaped, each shows as written. |
| 167 | var markdownEscaper = strings.NewReplacer(`\`, `\\`, `[`, `\[`, `]`, `\]`, `<`, `\<`, `>`, `\>`, `&`, `\&`) |
| 168 | |
| 169 | // PlainLookups is m for a client that can't draw lookups: each answer |
| 170 | // folded into the text after the message's own words, followed by |
| 171 | // "Sources:" and its sources' addresses, one per line; the answer's own |
| 172 | // addresses are taken out (plainAnswer). Lookups is nil. |
| 173 | func (m Message) PlainLookups() Message { |
| 174 | parts := []string{} |
| 175 | if m.Text != "" { |
| 176 | parts = append(parts, m.Text) |
| 177 | } |
| 178 | for _, l := range m.Lookups { |
| 179 | urls := make([]string, 0, len(l.Sources)) |
| 180 | for _, s := range l.Sources { |
| 181 | urls = append(urls, s.URL) |
| 182 | } |
| 183 | parts = append(parts, plainAnswer(l.Answer), fallbackSources+"\n"+strings.Join(urls, "\n")) |
| 184 | } |
| 185 | m.Text, m.Lookups = strings.Join(parts, "\n\n"), nil |
| 186 | return m |
| 187 | } |
| 188 | |