Documentation
¶
Overview ¶
Package research is the harness's one-call research lane: fetch public web pages DELEGATOR-side, strip them to text, and fan the digests out to the free local seats through the ordinary delegation path.
Why it exists (2026-08-30, operator directive): every "web research" leg was being handed to a cloud subagent because the seats have no network, while the digest work — the expensive part — is exactly what the seats do all day. The fetch here is the same act as the operator's own WebFetch: the CALLER names the URLs, the harness reads them, and the seats only ever see inline text. The seats never gain network access; the agent loop's egress cage is untouched.
Index ¶
- Constants
- Variables
- func Anchor(text, goal string) string
- func AnchorCheck(text, goal string) string
- func Anchors(text, goal string, n int) []string
- func AnnotateWire(wire *delegate.ResponseWire, resultSources []int, fetched []Fetched)
- func DocName(i int, finalURL, rawURL string) string
- func FeedToText(body []byte) (title, text string, err error)
- func HTMLToText(src string) (title, text string)
- func ResultSources(sources []Source) []int
- func SRV3ToText(data []byte) (string, error)
- func SniffFeed(body []byte) bool
- func VTTToText(src string) string
- func ValidateURL(ctx context.Context, raw string) (*url.URL, error)
- func VerifyQuotes(page string, structured json.RawMessage) (json.RawMessage, *delegate.QuoteCheck)
- func WrapLongLines(text string, max int) string
- type Fetched
- type Options
- type Request
- type Source
- type SourceKind
Constants ¶
const ( MaxFeedItems = 50 MaxFeedSummaryChars = 1000 )
Feed bounds. A feed past MaxFeedItems is cut and says so, and a summary past MaxFeedSummaryChars is cut at a rune boundary; the response body was already bounded by MaxFetchBytes before it reached the parser.
const ( MaxFetchBytes = 2 << 20 TextCap = 96 << 10 DefaultTimeout = 30 * time.Second MaxRedirects = 5 MaxURLsPerCall = maxURLsPerCall )
Limits. MaxFetchBytes bounds what is read off the wire (a page past it is truncated and flagged, never refused); TextCap bounds what a seat is handed (well under the 128 KiB per-doc contract cap so the goal and schema fit).
const ( // ErrKindYtDlpPath: the configured binary is not an absolute path, is missing, does not match the pinned // ytdlp_sha256 (or that value is not a sha256), or will not start. ErrKindYtDlpPath = "ytdlp_path" // ErrKindBadLangs: the sub_langs value is not a plain language list. ErrKindBadLangs = "bad_sub_langs" // ErrKindSiteBreak: the binary ran and exited non-zero (the site changed, asked for a login, or refused). ErrKindSiteBreak = "subtitle_site_break" // ErrKindNoSubtitles: the binary exited zero and wrote no subtitle file in the asked languages. ErrKindNoSubtitles = "no_subtitles" // ErrKindUnsupportedSubs: a subtitle file came back in a format this adapter does not read. ErrKindUnsupportedSubs = "unsupported_subtitle_format" // ErrKindEmptySubtitles: a subtitle file was read and held no speech text (blank cues only). ErrKindEmptySubtitles = "empty_subtitles" // ErrKindTimeout: the caller's deadline (or the per-fetch timeout) ended the run. ErrKindTimeout = "subtitle_timeout" // ErrKindURLRefused: the canonical URL the binary would be given did not pass the public-web guard. ErrKindURLRefused = "url_refused" )
Error kinds a source can fail with. They ride on Fetched.ErrKind so a caller can tell a broken site from an absent track without parsing prose.
const DefaultSubLangs = "en.*"
DefaultSubLangs is the subtitle language selection when the caller gives none.
const MaxLineChars = 1800
MaxLineChars is the longest line a context document is handed to a seat with. The agent's read_file cuts every line at 2,000 characters and pages by line, so the rest of a longer line is out of the seat's reach; a page that arrives as one 98,304-character line gave it 2,020 of them. 1,800 leaves the line number and the tool's own framing room under that cap (a cross-package test pins the two).
Variables ¶
var DefaultSchema = json.RawMessage(`{"type":"object","properties":{` +
`"key_facts":{"type":"array","items":{"type":"string"}},` +
`"numbers":{"type":"array","items":{"type":"string"}},` +
`"quotes":{"type":"array","items":{"type":"string"}},` +
`"verdict":{"type":"string"}},` +
`"required":["key_facts","numbers","quotes","verdict"]}`)
DefaultSchema is what a digest comes back as when the caller gives no output_schema: the fields a research reader actually needs to merge across sources. Every field is a string or string list so the small seats' re-pack path (grammar-guided, scalar-coerced) handles it.
All four fields are required, in declaration order (the gbnf builder reads `required` first for field order). Without it a seat's direct JSON answer that left one out validated, skipped the structured re-pack and reached the delegator with the field missing, and vLLM's structured_outputs was free to leave an optional field out of its own answer (register C-74). Required is presence only: an empty list is a complete answer for a page with nothing to say, so no minItems is declared here (see nonEmptyChecks for who asks for items).
Functions ¶
func AnchorCheck ¶
AnchorCheck is the ONE acceptance line the research lane emits for a page: a case-insensitive alternation of the page's top prose words, tagged with the named group `docanchor` (delegate.strikeOnFingerprint keys on it, so a contract-caused failure never quarantines a node). A faithful digest passes by restating ANY of them (in the singular, so an inflection does not fail it); an answer about another document, or an echo of the goal (no goal word is ever included, nor its singular), does not. The line holds the page's words and NOTHING ELSE, on purpose: a phrase that is not a page word can only be one the goal also contains (the goal's own instruction for an absence), and then the goal echoed back satisfies the check, the delegator's lint rightly calls the contract parrot-passable, and a stock phrase anywhere in a digest about the wrong document passes it. An honest "nothing on this page" digest, which can restate no page word, is excused by delegate.EvalAcceptance instead, from the structure of what it says (delegate.HonestAbsence) and not from a phrase in the text. It is a wrong-document tripwire, not a quality gate: lexical overlap is a poor faithfulness metric (Maynez et al. 2020; Cao et al. 2022), so the bar is one word of twenty-four. A page with fewer than minAnchorWords usable words yields "" — nothing trustworthy to check.
func Anchors ¶
Anchors returns up to n distinctive prose words of the page that do NOT occur in the goal, most central first: weight (prose and heading occurrences, capped so one repeated word cannot crowd the rest out), then length, then alphabetical for determinism.
func AnnotateWire ¶
func AnnotateWire(wire *delegate.ResponseWire, resultSources []int, fetched []Fetched)
AnnotateWire checks the quotes of every finished digest in wire against the page it was written from (resultSources[i] is result i's source index), replaces quotes found only after folding with the page's own span, and attaches the report as the result's QuoteCheck. A deferred or failed result, one with no digest, and one with no mapped page are left alone.
func DocName ¶
DocName is the flat context-doc filename for source i: "<i>-<host>.txt", host sanitized to the flat-filename shape core.ContextDoc.Validate demands (no separators, no traversal).
func FeedToText ¶
FeedToText turns an RSS 2.0, RSS 1.0 or Atom document into the text a seat is handed, and returns the feed's own title. It is a pure function of the bytes: no link in the document is fetched. A document cut off mid-way (the fetch bound) yields the items read so far. A document with no item or entry is an error, so an empty feed or an RDF file that is not RSS stays an ordinary document.
func HTMLToText ¶
HTMLToText is a deterministic, dependency-free stripper: drops scripts, styles and page chrome, turns block boundaries into newlines, removes the remaining tags, unescapes entities, and collapses whitespace. It is meant to hand a seat readable prose and code blocks, not to render a page.
func ResultSources ¶
ResultSources maps a research call's results to the pages they came from: one result per usable source, in source order, so a skipped (failed or refused) page has none.
func SRV3ToText ¶
SRV3ToText converts YouTube's srv3 timed-text XML (<timedtext><body><p><s>word</s>...</p>) to plain text with the same rolling-caption handling as VTTToText. A file that ends inside an element (the read bound cut it) yields the cues read before the cut; one with no complete cue, or no timedtext root, is an error.
func SniffFeed ¶
SniffFeed reports whether the body is a feed document: after an optional BOM, whitespace, XML declaration, comments and a doctype, the root element is rss, an RDF root (RSS 1.0) or an Atom feed. A page that merely mentions a feed element, or one that holds it below an html root, is not.
func VTTToText ¶
VTTToText converts WebVTT (or SubRip) to plain speech text: the header, NOTE, STYLE and REGION blocks, cue identifiers, timing lines and settings, inline timestamps and tags are dropped, entities are decoded, and the rolling repetition automatic captions carry is removed (a line equal to the one before it is dropped, and a line that only extends the one before it replaces it).
func ValidateURL ¶
ValidateURL is the SSRF guard's NAME half: only http(s), only public hosts. Loopback, private (RFC 1918 / ULA), link-local, `.local`, `localhost`, and the operator's tailnet zone are refused — the research lane must never become a way to read a fleet node's admin endpoints or a box's local services through the harness. DNS is resolved here (through netguard's single seam) and every returned address is judged by netguard.CheckPublicIP, so a public name that resolves to a private address is refused too.
It is NOT sufficient on its own and never was: between this lookup and the socket, the name can resolve again to something else (DNS rebinding). The load-bearing half is netguard.PublicTransport in Fetch below, which resolves once more at DIAL time and connects to the vetted IP LITERAL. Keep both: this one refuses by NAME (scheme, `.local`, the tailnet zone) where an address check has nothing to look at, and it refuses without spending a connection.
func VerifyQuotes ¶
func VerifyQuotes(page string, structured json.RawMessage) (json.RawMessage, *delegate.QuoteCheck)
VerifyQuotes looks every item of the digest's `quotes` list up in page. It returns the digest with each tolerantly-found quote replaced by the page's own span, and the report; a digest with nothing to look up (no `quotes` list, an empty one, a field of another shape, not JSON) comes back byte for byte with a nil report, and so does one whose quotes were all already the page's bytes.
func WrapLongLines ¶
WrapLongLines breaks every line of text that is longer than max runes into lines of at most max, at the last space in the final quarter of the window (in the middle of the run when that quarter holds no space at all), never inside a rune. The space it breaks at becomes the newline and nothing else is added or removed, so the words are the same words in the same order; text whose lines all fit is returned as it came.
Types ¶
type Fetched ¶
type Fetched struct {
URL string `json:"url"`
FinalURL string `json:"final_url,omitempty"`
Title string `json:"title,omitempty"`
Status int `json:"status,omitempty"`
ContentType string `json:"content_type,omitempty"`
Bytes int `json:"bytes"`
TextBytes int `json:"text_bytes"`
Truncated bool `json:"truncated,omitempty"`
Err string `json:"error,omitempty"`
// ErrKind names the failure of a text-source adapter (the ErrKind constants); empty for a page.
ErrKind string `json:"error_kind,omitempty"`
// CleanupErr is set when the adapter could not remove its per-call scratch directory; it is a note beside a
// result that may itself have succeeded, never a reason to drop the text.
CleanupErr string `json:"cleanup_error,omitempty"`
Elapsed time.Duration `json:"-"`
Text string `json:"-"`
}
Fetched is one URL's outcome. Err is set (and Text empty) when the page could not be used; the caller reports it as a skipped source, never as a digest.
type Options ¶
type Options struct {
Timeout time.Duration
MaxBytes int
UserAgent string
// Client overrides the HTTP client (tests). Its Transport is used as-is;
// the redirect policy is always ours.
Client *http.Client
// YtDlpPath is the absolute path of the yt-dlp executable the subtitle adapter runs; empty = the adapter is
// off and a YouTube URL is an ordinary page. SubLangs is the subtitle language selection (default en.*).
// ScratchRoot is where the adapter makes its per-call directory (default: a directory under the OS temp dir).
YtDlpPath string
SubLangs string
ScratchRoot string
// YtDlpSHA256, when set, is the sha256 the file at YtDlpPath must have: it is hashed before every run and a
// mismatch refuses to run it. Empty = the path is trusted as written and nothing is hashed.
YtDlpSHA256 string
}
Options tunes one Fetch. Zero values take the package defaults.
type Request ¶
type Request struct {
Goal string
URLs []string
Questions []string // optional extra asks, appended to the goal for every source
OutputSchema json.RawMessage // optional; DefaultSchema when empty
Acceptance []string // optional caller checks, appended to the grounded default
TimeoutSec int
MaxSteps int
Profile string
}
Request is one research call: a goal applied to every fetched source.
type Source ¶
type Source struct {
Index int `json:"index"`
Fetched
DocName string `json:"doc_name,omitempty"`
Anchor string `json:"anchor,omitempty"`
// Fingerprinted says whether DocFingerprint produced the wrong-document
// tripwire for this page; false = the page was too thin (< 6 distinctive
// tokens) and an off-document answer cannot be caught by it.
Fingerprinted bool `json:"fingerprinted"`
Skipped string `json:"skipped,omitempty"`
}
Source is what the caller sees about each URL — with the text withheld: the point of the lane is that the calling context never pays for the page.
func Build ¶
func Build(req Request, fetched []Fetched) (specs []delegate.SubtaskSpec, sources []Source)
Build turns fetched pages into one delegation contract per usable page. The contract is written the way the seats were measured to pass (2026-08-28/30): context docs are MATERIALIZED as files in the seat's read root (see pipeline.RunAgentContract), so the goal names the file and tells the seat to read it with its file tool — a goal that says "do not open anything" made every seat report the document missing, and one that says "read the document" without naming the file sent a small seat hunting. Acceptance is an alternation of prose content words that appear in the page and never in the goal (see AnchorCheck) — one any-of check, so an echoed question cannot pass as verified and a faithful digest needs to restate only one of them.
type SourceKind ¶
type SourceKind int
SourceKind is the class a URL is routed to.
const ( // SourceKindPage is everything else: the ordinary fetch (and the feed parser when the response is a feed). SourceKindPage SourceKind = iota // SourceKindYouTube is a watch, youtu.be, shorts, live or embed URL on youtube.com (www, m or music) or an // embed URL on youtube-nocookie.com. SourceKindYouTube )
func ClassifyURL ¶
func ClassifyURL(u *url.URL) (SourceKind, string)
ClassifyURL is the explicit matcher for a video: youtube.com/watch?v=, and /shorts/<id>, /live/<id> and /embed/<id>, on exactly youtube.com, www.youtube.com, m.youtube.com and music.youtube.com; /embed/<id> on youtube-nocookie.com and www.youtube-nocookie.com; and youtu.be/<id> (also www.youtu.be). Over http or https, on the default port, with no userinfo and a video id of the real shape. Anything else, a lookalike host or a trailing-dot name included, is a page. It returns the video id for a YouTube URL. The binary is always given the canonical www.youtube.com/watch?v=<id>, whichever of these the caller wrote.