oficina / equipo Public

websource: readable text shared by Research and lookups

Task 3.2: the runner's HTML reader moves to websource.ExtractHTML
(webread keeps a thin adapter, so its fetcher and tests are unchanged),
and websource.Readable gives a fetched body's title and text by type:
HTML without scripts or styles, a feed's items, JSON pretty-printed,
XML's text, plain text; at most 16 KiB.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 75f8b5f73f2f5a1c5289e74259862f34055be814 parent 8bca44f
4 files changed, +582 −328
  • internal/runner/webread/extract.go +15 −328
  • internal/websource/html.go +382 −0
  • internal/websource/readable.go +120 −0
  • internal/websource/readable_test.go +65 −0
diff --git a/internal/runner/webread/extract.go b/internal/runner/webread/extract.go
index 83fd8453..f7d59555 100644
--- a/internal/runner/webread/extract.go
+++ b/internal/runner/webread/extract.go
@@ -1,26 +1,20 @@
package webread
import (
- "bytes"
- "html"
- "net/url"
- "strings"
-
"amadan.net/oficina/equipo/internal/websource"
)
-// A small HTML reader: enough for a page's title, meta, readable text and
-// the URLs it names, with every loop bounded by the input. It never
-// builds a tree and never runs anything a page carries.
+// The page reader is websource.ExtractHTML, shared with the instance's
+// lookups; webread keeps its own view of what it read.
-type refKind int
+type refKind = websource.HTMLRefKind
const (
- refLink refKind = iota
- refStylesheet
- refIcon
- refOG
- refImage
+ refLink = websource.RefLink
+ refStylesheet = websource.RefStylesheet
+ refIcon = websource.RefIcon
+ refOG = websource.RefOG
+ refImage = websource.RefImage
)
var kindName = map[refKind]string{refLink: "link", refStylesheet: "stylesheet", refIcon: "icon", refOG: "og", refImage: "img"}
@@ -47,328 +41,21 @@ type page struct {
refs []ref
}
-// Bounds on what one page contributes.
-const (
- maxMetas = 32
- maxMetaValue = 1024
- maxStyles = 32 << 10
- maxAttributes = 64
- maxAttrValue = 4096
- // maxRawText bounds a page's text before whitespace collapses.
- maxRawText = 4 * MaxPageText
-)
-
-// rawText elements hold text that is not markup; their content runs to
-// the matching end tag.
-var rawText = map[string]bool{"script": true, "style": true, "title": true, "textarea": true, "noscript": true, "xmp": true, "template": true, "iframe": true, "noembed": true, "noframes": true, "plaintext": true}
-
-var blockTags = map[string]bool{"p": true, "div": true, "br": true, "li": true, "ul": true, "ol": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "tr": true, "td": true, "th": true, "table": true, "section": true, "article": true, "header": true, "footer": true, "nav": true, "main": true, "aside": true, "blockquote": true, "pre": true, "hr": true, "dt": true, "dd": true, "figcaption": true, "address": true}
-
-func asciiLower(b []byte) []byte {
- out := make([]byte, len(b))
- for i, c := range b {
- if c >= 'A' && c <= 'Z' {
- c += 'a' - 'A'
- }
- out[i] = c
- }
- return out
-}
-
-func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' }
-func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' }
-
-type extractor struct {
- page
- base websource.URL
- based bool
- buf bytes.Buffer
-}
-
// extractHTML reads src, an HTML page fetched from base.
func extractHTML(src []byte, base websource.URL) page {
- x := &extractor{base: base}
- lower := asciiLower(src)
- n := len(src)
- for i := 0; i < n; {
- if src[i] != '<' {
- j := bytes.IndexByte(src[i:], '<')
- if j < 0 {
- j = n - i
- }
- x.addText(src[i : i+j])
- i += j
- continue
- }
- switch {
- case bytes.HasPrefix(lower[i:], []byte("<!--")):
- end := bytes.Index(lower[i+4:], []byte("-->"))
- if end < 0 {
- return x.finish()
- }
- i += 4 + end + 3
- case i+1 < n && (src[i+1] == '!' || src[i+1] == '?'):
- end := bytes.IndexByte(src[i:], '>')
- if end < 0 {
- return x.finish()
- }
- i += end + 1
- case i+1 < n && src[i+1] == '/':
- j := i + 2
- for j < n && (isLetter(src[j]) || src[j] >= '0' && src[j] <= '9') {
- j++
- }
- if blockTags[string(lower[i+2:j])] {
- x.buf.WriteByte('\n')
- }
- end := bytes.IndexByte(src[j:], '>')
- if end < 0 {
- return x.finish()
- }
- i = j + end + 1
- case i+1 < n && isLetter(src[i+1]):
- name, attrs, next, ok := parseTag(src, lower, i+1)
- if !ok {
- return x.finish()
- }
- i = next
- x.start(name, attrs)
- if rawText[name] {
- end := bytes.Index(lower[i:], []byte("</"+name))
- if end < 0 {
- end = n - i
- }
- x.raw(name, src[i:i+end])
- i += end
- if close := bytes.IndexByte(src[i:], '>'); close >= 0 {
- i += close + 1
- } else {
- i = n
- }
- }
- default:
- x.addText(src[i : i+1])
- i++
- }
- }
- return x.finish()
-}
-
-type attr struct{ name, value string }
-
-// parseTag reads a start tag from its name at i to its closing '>'.
-func parseTag(src, lower []byte, i int) (name string, attrs []attr, next int, ok bool) {
- n := len(src)
- j := i
- for j < n && !isSpace(src[j]) && src[j] != '>' && src[j] != '/' {
- j++
- }
- name = string(lower[i:j])
- for {
- for j < n && (isSpace(src[j]) || src[j] == '/') {
- j++
- }
- if j >= n {
- return "", nil, n, false
- }
- if src[j] == '>' {
- return name, attrs, j + 1, true
- }
- k := j
- for k < n && !isSpace(src[k]) && src[k] != '=' && src[k] != '>' && src[k] != '/' {
- k++
- }
- key := string(lower[j:k])
- if k == j {
- k++ // a stray '=' with no name
- }
- j = k
- for j < n && isSpace(src[j]) {
- j++
- }
- var value []byte
- if j < n && src[j] == '=' {
- j++
- for j < n && isSpace(src[j]) {
- j++
- }
- if j < n && (src[j] == '"' || src[j] == '\'') {
- q := src[j]
- end := bytes.IndexByte(src[j+1:], q)
- if end < 0 {
- return "", nil, n, false
- }
- value = src[j+1 : j+1+end]
- j += end + 2
- } else {
- k = j
- for k < n && !isSpace(src[k]) && src[k] != '>' {
- k++
- }
- value = src[j:k]
- j = k
- }
- }
- if key != "" && len(attrs) < maxAttributes {
- if len(value) > maxAttrValue {
- value = value[:maxAttrValue]
- }
- attrs = append(attrs, attr{key, html.UnescapeString(string(value))})
- }
- }
-}
-
-func get(attrs []attr, name string) (string, bool) {
- for _, a := range attrs {
- if a.name == name {
- return a.value, true
- }
- }
- return "", false
-}
-
-func (x *extractor) addText(b []byte) {
- room := maxRawText - x.buf.Len()
- if room <= 0 {
- return
- }
- if len(b) > room {
- b = b[:room]
- }
- // A text node's own line breaks are layout; block tags make lines.
- space := false
- for _, r := range html.UnescapeString(string(b)) {
- if r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\f' || r == '\u00a0' {
- if !space {
- x.buf.WriteByte(' ')
- }
- space = true
- continue
- }
- space = false
- x.buf.WriteRune(r)
- }
-}
-
-func (x *extractor) addRef(kind refKind, raw string, logo bool, alt string) {
- if len(x.refs) >= MaxLinks {
- return
- }
- raw = strings.TrimSpace(raw)
- if raw == "" {
- return
+ h := websource.ExtractHTML(src, base, MaxPageText, MaxLinks)
+ p := page{title: h.Title, text: h.Text, styles: h.Styles}
+ for _, m := range h.Metas {
+ p.metas = append(p.metas, meta{m.Name, m.Content})
}
- if p, err := url.Parse(raw); err == nil && p.Scheme != "" && p.Scheme != "http" && p.Scheme != "https" {
- return // data:, javascript:, mailto: name nothing to fetch
- }
- u, err := websource.Resolve(x.base, raw)
- x.refs = append(x.refs, ref{kind: kind, url: u, raw: raw, err: err, logo: logo, alt: alt})
-}
-
-func (x *extractor) start(name string, attrs []attr) {
- if blockTags[name] {
- x.buf.WriteByte('\n')
+ for _, r := range h.Refs {
+ p.refs = append(p.refs, ref{kind: r.Kind, url: r.URL, raw: r.Raw, err: r.Err, logo: r.Logo, alt: r.Alt})
}
- switch name {
- case "base":
- if href, ok := get(attrs, "href"); ok && !x.based {
- x.based = true
- if u, err := websource.Resolve(x.base, strings.TrimSpace(href)); err == nil {
- x.base = u
- }
- }
- case "meta":
- key, ok := get(attrs, "name")
- if !ok {
- key, _ = get(attrs, "property")
- }
- key = strings.ToLower(strings.TrimSpace(key))
- content, _ := get(attrs, "content")
- if key == "description" || key == "theme-color" || strings.HasPrefix(key, "og:") {
- if len(x.metas) < maxMetas {
- x.metas = append(x.metas, meta{key, clip(oneLine(content), maxMetaValue)})
- }
- if key == "og:image" || key == "og:image:url" || key == "og:image:secure_url" {
- x.addRef(refOG, content, false, "")
- }
- }
- case "link":
- href, _ := get(attrs, "href")
- rel, _ := get(attrs, "rel")
- for _, r := range strings.Fields(strings.ToLower(rel)) {
- switch r {
- case "stylesheet":
- x.addRef(refStylesheet, href, false, "")
- return
- case "icon", "apple-touch-icon", "apple-touch-icon-precomposed", "mask-icon":
- x.addRef(refIcon, href, false, "")
- return
- }
- }
- case "img":
- src, _ := get(attrs, "src")
- alt, _ := get(attrs, "alt")
- id, _ := get(attrs, "id")
- class, _ := get(attrs, "class")
- logo := strings.Contains(strings.ToLower(src+" "+alt+" "+id+" "+class), "logo")
- x.addRef(refImage, src, logo, clip(oneLine(alt), 200))
- if alt = oneLine(alt); alt != "" && x.buf.Len() < maxRawText {
- x.buf.WriteString(" [image: " + clip(alt, 200) + "] ")
- }
- case "a":
- if href, ok := get(attrs, "href"); ok {
- x.addRef(refLink, href, false, "")
- }
- }
-}
-
-func (x *extractor) raw(name string, content []byte) {
- switch name {
- case "title":
- if x.title == "" {
- x.title = clip(oneLine(html.UnescapeString(string(content))), maxMetaValue)
- }
- case "style":
- if room := maxStyles - len(x.styles); room > 0 {
- x.styles += clip(string(content), room)
- }
- case "textarea":
- x.addText(content)
- }
-}
-
-func (x *extractor) finish() page {
- p := x.page
- var lines []string
- for _, line := range strings.Split(x.buf.String(), "\n") {
- if line = oneLine(line); line != "" {
- lines = append(lines, line)
- }
- }
- p.text = clip(strings.Join(lines, "\n"), MaxPageText)
- p.styles = strings.TrimSpace(p.styles)
return p
}
-// oneLine collapses whitespace, including line breaks, to single spaces.
-func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") }
-
// clip cuts s to at most n bytes on a UTF-8 boundary.
-func clip(s string, n int) string {
- if len(s) <= n {
- return s
- }
- s = s[:n]
- for len(s) > 0 && !utf8Start(s[len(s)-1]) {
- s = s[:len(s)-1]
- }
- if len(s) > 0 && s[len(s)-1] >= 0x80 {
- s = s[:len(s)-1] // a lead byte whose continuation was cut
- }
- return s
-}
-
-func utf8Start(b byte) bool { return b < 0x80 || b >= 0xc0 }
+func clip(s string, n int) string { return websource.Clip(s, n) }
// Expansion caps per approved page (spec §3.2).
const (
diff --git a/internal/websource/html.go b/internal/websource/html.go
new file mode 100644
index 00000000..0a588416
--- /dev/null
+++ b/internal/websource/html.go
@@ -0,0 +1,382 @@
+package websource
+
+import (
+ "bytes"
+ "html"
+ "net/url"
+ "strings"
+)
+
+// A small HTML reader, shared by Research's fetcher (internal/runner/
+// webread) and the instance's lookups (Readable): enough for a page's
+// title, meta, readable text and the URLs it names, with every loop
+// bounded by the input. It never builds a tree and never runs anything a
+// page carries.
+
+// HTMLRefKind is what a URL a page names is for.
+type HTMLRefKind int
+
+// The kinds of URL a page names.
+const (
+ RefLink HTMLRefKind = iota
+ RefStylesheet
+ RefIcon
+ RefOG
+ RefImage
+)
+
+// HTMLRef is a URL a page names, resolved against the page (or its base), or
+// the refusal resolving it met. logo marks an img whose src, alt, id or
+// class says "logo".
+type HTMLRef struct {
+ Kind HTMLRefKind
+ URL URL
+ Raw string
+ Err error
+ Logo bool
+ Alt string
+}
+
+// HTMLMeta is one of a page's meta tags.
+type HTMLMeta struct{ Name, Content string }
+
+// HTMLPage is what ExtractHTML read from a page.
+type HTMLPage struct {
+ Title string
+ Metas []HTMLMeta
+ Text string
+ Styles string
+ Refs []HTMLRef
+}
+
+// Bounds on what one page contributes.
+const (
+ maxMetas = 32
+ maxMetaValue = 1024
+ maxStyles = 32 << 10
+ maxAttributes = 64
+ maxAttrValue = 4096
+)
+
+// rawText elements hold text that is not markup; their content runs to
+// the matching end tag.
+var rawText = map[string]bool{"script": true, "style": true, "title": true, "textarea": true, "noscript": true, "xmp": true, "template": true, "iframe": true, "noembed": true, "noframes": true, "plaintext": true}
+
+var blockTags = map[string]bool{"p": true, "div": true, "br": true, "li": true, "ul": true, "ol": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "tr": true, "td": true, "th": true, "table": true, "section": true, "article": true, "header": true, "footer": true, "nav": true, "main": true, "aside": true, "blockquote": true, "pre": true, "hr": true, "dt": true, "dd": true, "figcaption": true, "address": true}
+
+func asciiLower(b []byte) []byte {
+ out := make([]byte, len(b))
+ for i, c := range b {
+ if c >= 'A' && c <= 'Z' {
+ c += 'a' - 'A'
+ }
+ out[i] = c
+ }
+ return out
+}
+
+func isLetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' }
+func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' }
+
+type extractor struct {
+ HTMLPage
+ base URL
+ based bool
+ buf bytes.Buffer
+ // maxText bounds the text, maxRefs the URLs named.
+ maxText, maxRefs int
+}
+
+// maxRawText bounds a page's text before whitespace collapses.
+func (x *extractor) maxRawText() int { return 4 * x.maxText }
+
+// ExtractHTML reads src, an HTML page fetched from base: its title,
+// meta, readable text (at most maxText bytes) and up to maxRefs of the
+// URLs it names. Every loop is bounded by the input; it never builds a
+// tree and never runs anything a page carries. Scripts' and styles'
+// contents are never text.
+func ExtractHTML(src []byte, base URL, maxText, maxRefs int) HTMLPage {
+ x := &extractor{base: base, maxText: maxText, maxRefs: maxRefs}
+ lower := asciiLower(src)
+ n := len(src)
+ for i := 0; i < n; {
+ if src[i] != '<' {
+ j := bytes.IndexByte(src[i:], '<')
+ if j < 0 {
+ j = n - i
+ }
+ x.addText(src[i : i+j])
+ i += j
+ continue
+ }
+ switch {
+ case bytes.HasPrefix(lower[i:], []byte("<!--")):
+ end := bytes.Index(lower[i+4:], []byte("-->"))
+ if end < 0 {
+ return x.finish()
+ }
+ i += 4 + end + 3
+ case i+1 < n && (src[i+1] == '!' || src[i+1] == '?'):
+ end := bytes.IndexByte(src[i:], '>')
+ if end < 0 {
+ return x.finish()
+ }
+ i += end + 1
+ case i+1 < n && src[i+1] == '/':
+ j := i + 2
+ for j < n && (isLetter(src[j]) || src[j] >= '0' && src[j] <= '9') {
+ j++
+ }
+ if blockTags[string(lower[i+2:j])] {
+ x.buf.WriteByte('\n')
+ }
+ end := bytes.IndexByte(src[j:], '>')
+ if end < 0 {
+ return x.finish()
+ }
+ i = j + end + 1
+ case i+1 < n && isLetter(src[i+1]):
+ name, attrs, next, ok := parseTag(src, lower, i+1)
+ if !ok {
+ return x.finish()
+ }
+ i = next
+ x.start(name, attrs)
+ if rawText[name] {
+ end := bytes.Index(lower[i:], []byte("</"+name))
+ if end < 0 {
+ end = n - i
+ }
+ x.raw(name, src[i:i+end])
+ i += end
+ if close := bytes.IndexByte(src[i:], '>'); close >= 0 {
+ i += close + 1
+ } else {
+ i = n
+ }
+ }
+ default:
+ x.addText(src[i : i+1])
+ i++
+ }
+ }
+ return x.finish()
+}
+
+type attr struct{ name, value string }
+
+// parseTag reads a start tag from its name at i to its closing '>'.
+func parseTag(src, lower []byte, i int) (name string, attrs []attr, next int, ok bool) {
+ n := len(src)
+ j := i
+ for j < n && !isSpace(src[j]) && src[j] != '>' && src[j] != '/' {
+ j++
+ }
+ name = string(lower[i:j])
+ for {
+ for j < n && (isSpace(src[j]) || src[j] == '/') {
+ j++
+ }
+ if j >= n {
+ return "", nil, n, false
+ }
+ if src[j] == '>' {
+ return name, attrs, j + 1, true
+ }
+ k := j
+ for k < n && !isSpace(src[k]) && src[k] != '=' && src[k] != '>' && src[k] != '/' {
+ k++
+ }
+ key := string(lower[j:k])
+ if k == j {
+ k++ // a stray '=' with no name
+ }
+ j = k
+ for j < n && isSpace(src[j]) {
+ j++
+ }
+ var value []byte
+ if j < n && src[j] == '=' {
+ j++
+ for j < n && isSpace(src[j]) {
+ j++
+ }
+ if j < n && (src[j] == '"' || src[j] == '\'') {
+ q := src[j]
+ end := bytes.IndexByte(src[j+1:], q)
+ if end < 0 {
+ return "", nil, n, false
+ }
+ value = src[j+1 : j+1+end]
+ j += end + 2
+ } else {
+ k = j
+ for k < n && !isSpace(src[k]) && src[k] != '>' {
+ k++
+ }
+ value = src[j:k]
+ j = k
+ }
+ }
+ if key != "" && len(attrs) < maxAttributes {
+ if len(value) > maxAttrValue {
+ value = value[:maxAttrValue]
+ }
+ attrs = append(attrs, attr{key, html.UnescapeString(string(value))})
+ }
+ }
+}
+
+func get(attrs []attr, name string) (string, bool) {
+ for _, a := range attrs {
+ if a.name == name {
+ return a.value, true
+ }
+ }
+ return "", false
+}
+
+func (x *extractor) addText(b []byte) {
+ room := x.maxRawText() - x.buf.Len()
+ if room <= 0 {
+ return
+ }
+ if len(b) > room {
+ b = b[:room]
+ }
+ // A text node's own line breaks are layout; block tags make lines.
+ space := false
+ for _, r := range html.UnescapeString(string(b)) {
+ if r == ' ' || r == '\t' || r == '\n' || r == '\r' || r == '\f' || r == '\u00a0' {
+ if !space {
+ x.buf.WriteByte(' ')
+ }
+ space = true
+ continue
+ }
+ space = false
+ x.buf.WriteRune(r)
+ }
+}
+
+func (x *extractor) addRef(kind HTMLRefKind, raw string, logo bool, alt string) {
+ if len(x.Refs) >= x.maxRefs {
+ return
+ }
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return
+ }
+ if p, err := url.Parse(raw); err == nil && p.Scheme != "" && p.Scheme != "http" && p.Scheme != "https" {
+ return // data:, javascript:, mailto: name nothing to fetch
+ }
+ u, err := Resolve(x.base, raw)
+ x.Refs = append(x.Refs, HTMLRef{Kind: kind, URL: u, Raw: raw, Err: err, Logo: logo, Alt: alt})
+}
+
+func (x *extractor) start(name string, attrs []attr) {
+ if blockTags[name] {
+ x.buf.WriteByte('\n')
+ }
+ switch name {
+ case "base":
+ if href, ok := get(attrs, "href"); ok && !x.based {
+ x.based = true
+ if u, err := Resolve(x.base, strings.TrimSpace(href)); err == nil {
+ x.base = u
+ }
+ }
+ case "meta":
+ key, ok := get(attrs, "name")
+ if !ok {
+ key, _ = get(attrs, "property")
+ }
+ key = strings.ToLower(strings.TrimSpace(key))
+ content, _ := get(attrs, "content")
+ if key == "description" || key == "theme-color" || strings.HasPrefix(key, "og:") {
+ if len(x.Metas) < maxMetas {
+ x.Metas = append(x.Metas, HTMLMeta{key, clip(oneLine(content), maxMetaValue)})
+ }
+ if key == "og:image" || key == "og:image:url" || key == "og:image:secure_url" {
+ x.addRef(RefOG, content, false, "")
+ }
+ }
+ case "link":
+ href, _ := get(attrs, "href")
+ rel, _ := get(attrs, "rel")
+ for _, r := range strings.Fields(strings.ToLower(rel)) {
+ switch r {
+ case "stylesheet":
+ x.addRef(RefStylesheet, href, false, "")
+ return
+ case "icon", "apple-touch-icon", "apple-touch-icon-precomposed", "mask-icon":
+ x.addRef(RefIcon, href, false, "")
+ return
+ }
+ }
+ case "img":
+ src, _ := get(attrs, "src")
+ alt, _ := get(attrs, "alt")
+ id, _ := get(attrs, "id")
+ class, _ := get(attrs, "class")
+ logo := strings.Contains(strings.ToLower(src+" "+alt+" "+id+" "+class), "logo")
+ x.addRef(RefImage, src, logo, clip(oneLine(alt), 200))
+ if alt = oneLine(alt); alt != "" && x.buf.Len() < x.maxRawText() {
+ x.buf.WriteString(" [image: " + clip(alt, 200) + "] ")
+ }
+ case "a":
+ if href, ok := get(attrs, "href"); ok {
+ x.addRef(RefLink, href, false, "")
+ }
+ }
+}
+
+func (x *extractor) raw(name string, content []byte) {
+ switch name {
+ case "title":
+ if x.Title == "" {
+ x.Title = clip(oneLine(html.UnescapeString(string(content))), maxMetaValue)
+ }
+ case "style":
+ if room := maxStyles - len(x.Styles); room > 0 {
+ x.Styles += clip(string(content), room)
+ }
+ case "textarea":
+ x.addText(content)
+ }
+}
+
+func (x *extractor) finish() HTMLPage {
+ p := x.HTMLPage
+ var lines []string
+ for _, line := range strings.Split(x.buf.String(), "\n") {
+ if line = oneLine(line); line != "" {
+ lines = append(lines, line)
+ }
+ }
+ p.Text = clip(strings.Join(lines, "\n"), x.maxText)
+ p.Styles = strings.TrimSpace(p.Styles)
+ return p
+}
+
+// oneLine collapses whitespace, including line breaks, to single spaces.
+func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") }
+
+// Clip cuts s to at most n bytes on a UTF-8 boundary.
+func Clip(s string, n int) string { return clip(s, n) }
+
+func clip(s string, n int) string {
+ if len(s) <= n {
+ return s
+ }
+ s = s[:n]
+ for len(s) > 0 && !utf8Start(s[len(s)-1]) {
+ s = s[:len(s)-1]
+ }
+ if len(s) > 0 && s[len(s)-1] >= 0x80 {
+ s = s[:len(s)-1] // a lead byte whose continuation was cut
+ }
+ return s
+}
+
+func utf8Start(b byte) bool { return b < 0x80 || b >= 0xc0 }
diff --git a/internal/websource/readable.go b/internal/websource/readable.go
new file mode 100644
index 00000000..a06f2d0c
--- /dev/null
+++ b/internal/websource/readable.go
@@ -0,0 +1,120 @@
+package websource
+
+import (
+ "bytes"
+ "encoding/json"
+ "encoding/xml"
+ "errors"
+ "io"
+ "strings"
+)
+
+// MaxReadable bounds a page's readable text (spec 2026-11-26-assistant-
+// abilities §4.3: each page at most 16 KiB before the answer step's
+// budget cuts it further).
+const MaxReadable = 16 << 10
+
+// Readable is a fetched body's title and readable text, by its sniffed
+// type (guard.Response.Type): HTML through ExtractHTML (scripts and
+// styles dropped), a feed's channel title and each item's title and
+// summary (their markup reduced to text), JSON pretty-printed, XML's
+// text nodes, plain text as it is. Anything else gives nothing. The text
+// is at most MaxReadable bytes, cut on a character boundary.
+func Readable(body []byte, typ string, base URL) (title, text string) {
+ switch typ {
+ case "html":
+ p := ExtractHTML(body, base, MaxReadable, 0)
+ return p.Title, p.Text
+ case "feed":
+ return readFeed(body, base)
+ case "json":
+ var v any
+ if json.Unmarshal(body, &v) != nil {
+ return "", ""
+ }
+ out, err := json.MarshalIndent(v, "", " ")
+ if err != nil {
+ return "", ""
+ }
+ return "", clip(string(out), MaxReadable)
+ case "xml":
+ return "", clip(strings.Join(xmlText(body), "\n"), MaxReadable)
+ case "text":
+ return "", clip(strings.ToValidUTF8(string(body), ""), MaxReadable)
+ }
+ return "", ""
+}
+
+// readFeed reads an RSS or Atom feed: its title, then each item's title
+// and summary (RSS description, Atom summary or content), a blank line
+// between items.
+func readFeed(body []byte, base URL) (string, string) {
+ d := xml.NewDecoder(bytes.NewReader(body))
+ d.Strict = false
+ d.CharsetReader = func(_ string, r io.Reader) (io.Reader, error) { return r, nil }
+ var title string
+ var items []string
+ var cur []string
+ var buf strings.Builder
+ inItem := false
+ for {
+ tok, err := d.Token()
+ if err != nil {
+ if !errors.Is(err, io.EOF) && len(items) == 0 && title == "" {
+ return "", ""
+ }
+ break
+ }
+ switch t := tok.(type) {
+ case xml.StartElement:
+ name := strings.ToLower(t.Name.Local)
+ if name == "item" || name == "entry" {
+ inItem, cur = true, nil
+ }
+ buf.Reset()
+ case xml.CharData:
+ buf.Write(t)
+ case xml.EndElement:
+ name := strings.ToLower(t.Name.Local)
+ value := strings.TrimSpace(buf.String())
+ buf.Reset()
+ switch {
+ case name == "item" || name == "entry":
+ if len(cur) > 0 {
+ items = append(items, strings.Join(cur, "\n"))
+ }
+ inItem = false
+ case inItem && (name == "title" || name == "description" || name == "summary" || name == "content"):
+ // A summary may carry escaped markup: its text only.
+ if v := ExtractHTML([]byte(value), base, MaxReadable, 0).Text; v != "" {
+ cur = append(cur, oneLine(v))
+ }
+ case !inItem && name == "title" && title == "":
+ title = clip(oneLine(value), maxMetaValue)
+ }
+ }
+ }
+ return title, clip(strings.Join(items, "\n\n"), MaxReadable)
+}
+
+// xmlText is a document's text nodes, each trimmed, in order.
+func xmlText(body []byte) []string {
+ d := xml.NewDecoder(bytes.NewReader(body))
+ d.Strict = false
+ d.CharsetReader = func(_ string, r io.Reader) (io.Reader, error) { return r, nil }
+ var out []string
+ size := 0
+ for size < MaxReadable {
+ tok, err := d.Token()
+ if err != nil {
+ break
+ }
+ if c, ok := tok.(xml.CharData); ok {
+ if s := oneLine(string(c)); s != "" {
+ out = append(out, s)
+ size += len(s) + 1
+ }
+ }
+ }
+ return out
+}
diff --git a/internal/websource/readable_test.go b/internal/websource/readable_test.go
new file mode 100644
index 00000000..9aa61af8
--- /dev/null
+++ b/internal/websource/readable_test.go
@@ -0,0 +1,65 @@
+package websource
+
+import (
+ "strings"
+ "testing"
+)
+
+func readableBase(t *testing.T) URL {
+ t.Helper()
+ u, err := Parse("https://news.example.org/today")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return u
+}
+
+// A page's scripts and styles are never its text; its title is.
+func TestReadableDropsScript(t *testing.T) {
+ page := `<html><head><title>Dublin weather</title><style>body{color:red}</style>
+<script>alert("steal")</script></head><body><h1>Today</h1><p>Rain, 11&deg;C.</p>
+<script type="text/javascript">document.write("injected")</script><noscript>no js</noscript></body></html>`
+ title, text := Readable([]byte(page), "html", readableBase(t))
+ if title != "Dublin weather" {
+ t.Errorf("title %q", title)
+ }
+ for _, bad := range []string{"alert", "steal", "injected", "color:red", "no js"} {
+ if strings.Contains(text, bad) {
+ t.Errorf("text holds %q: %q", bad, text)
+ }
+ }
+ if !strings.Contains(text, "Today") || !strings.Contains(text, "Rain, 11°C.") {
+ t.Errorf("text %q", text)
+ }
+}
+
+// A feed gives its items' titles and summaries; JSON is pretty-printed;
+// XML gives its text; plain text is itself; anything else gives nothing.
+func TestReadableFeedItems(t *testing.T) {
+ rss := `<?xml version="1.0"?><rss><channel><title>Met news</title>
+<item><title>Storm warning</title><description>Winds up to &lt;b&gt;90 km/h&lt;/b&gt;.</description><link>https://x.example.org/1</link></item>
+<item><title>Calm weekend</title><description>Sun on Saturday.</description></item></channel></rss>`
+ title, text := Readable([]byte(rss), "feed", readableBase(t))
+ if title != "Met news" || !strings.Contains(text, "Storm warning\nWinds up to 90 km/h.") || !strings.Contains(text, "Calm weekend\nSun on Saturday.") || strings.Contains(text, "<b>") {
+ t.Errorf("rss: %q %q", title, text)
+ }
+ atom := `<feed xmlns="http://www.w3.org/2005/Atom"><title>Club</title><entry><title>Open late</title><summary>Until 22:00 on Fridays.</summary></entry></feed>`
+ if title, text := Readable([]byte(atom), "feed", readableBase(t)); title != "Club" || !strings.Contains(text, "Open late\nUntil 22:00 on Fridays.") {
+ t.Errorf("atom: %q %q", title, text)
+ }
+ if _, text := Readable([]byte(`{"temp":11,"sky":"rain"}`), "json", readableBase(t)); text != "{\n \"sky\": \"rain\",\n \"temp\": 11\n}" && text != "{\n \"temp\": 11,\n \"sky\": \"rain\"\n}" {
+ t.Errorf("json: %q", text)
+ }
+ if _, text := Readable([]byte(`<forecast><day>Monday</day><sky>Rain</sky></forecast>`), "xml", readableBase(t)); text != "Monday\nRain" {
+ t.Errorf("xml: %q", text)
+ }
+ if _, text := Readable([]byte("Open 9 to 5."), "text", readableBase(t)); text != "Open 9 to 5." {
+ t.Errorf("text: %q", text)
+ }
+ if title, text := Readable([]byte{0x89, 'P', 'N', 'G'}, "unsupported", readableBase(t)); title != "" || text != "" {
+ t.Errorf("unsupported: %q %q", title, text)
+ }
+ if _, text := Readable([]byte(strings.Repeat("a", 2*MaxReadable)), "text", readableBase(t)); len(text) != MaxReadable {
+ t.Errorf("text not cut: %d", len(text))
+ }
+}