// Package websearch is the instance's web search for lookups (spec // 2026-11-26-assistant-abilities §4.2 step 4; plan AD3): one Searcher // interface, Kagi first, Mojeek and Brave as optional fallbacks, a chain // that tries the fallback once, and a monthly cap per backend counted on // the instance. Every request goes through the guarded client // (internal/websource/guard) with the backend's key bound to its origin. // Nothing here ever carries a URL, a query or a key in an error or a log. package websearch import ( "context" "errors" "log/slog" "strconv" "strings" "time" "unicode/utf8" "amadan.net/oficina/equipo/internal/websource/guard" ) // Result is one search result: an https URL, its title (at most 200 // bytes), its snippet (at most 300) and its date, if the backend gave one. type Result struct { Title, URL, Snippet, Date string } // Bounds on a result (§4.3's frame budget). const ( MaxTitle = 200 MaxSnippet = 300 // MaxResults is the most results a query returns. MaxResults = 8 ) // The failure classes. const ( ClassLimit = "limit" ClassAuth = "auth" ClassUnavailable = "unavailable" ClassBadResponse = "bad_response" ) // Error is a backend's failure, by class only: never a URL, a query or a // key. Unsent says the request never went out (refused before sending), // so its reservation is returned. type Error struct { Backend, Class string Unsent bool } func (e *Error) Error() string { return "websearch: " + e.Backend + ": " + e.Class } // Searcher is one search backend. type Searcher interface { Name() string Search(ctx context.Context, query string, n int) ([]Result, error) } // Reservation is one query reserved against a backend's monthly cap: the // backend and the UTC month (2006-01) it counts in. type Reservation struct { Backend, Month string } // Usage is the monthly caps' count. Take reserves one query on backend // while it is under its cap (ok false when spent); Return refunds that // exact reservation. type Usage interface { Take(ctx context.Context, backend string) (r Reservation, ok bool, err error) Return(ctx context.Context, r Reservation) error } // Before runs right before each backend request, the fallback's // included: an early authorization check. An error stops the chain. type Before func(ctx context.Context, backend string) error // Chain is the primary and an optional fallback, with the caps. type Chain struct { Primary, Fallback Searcher Usage Usage } // ErrLimit: every backend's cap is spent. var ErrLimit = &Error{Class: ClassLimit} // Search runs q on the primary and, once, on the fallback when the // primary failed, its cap was spent or it found nothing. Before each // backend, before runs (its error stops everything), then one query is // reserved. A refusal from the context's guard.WithBeforeHop (the final // check, right before sending) returns that reservation and stops the // chain. backend is the one whose results these are. func (c Chain) Search(ctx context.Context, q string, n int, before Before) (results []Result, backend string, err error) { tried, spent := 0, 0 var last error for _, s := range []Searcher{c.Primary, c.Fallback} { if s == nil { continue } if before != nil { if err := before(ctx, s.Name()); err != nil { return nil, "", err } } r, ok, err := c.Usage.Take(ctx, s.Name()) if err != nil { return nil, "", err } if !ok { spent++ last = &Error{Backend: s.Name(), Class: ClassLimit} continue } tried++ got, err := s.Search(ctx, q, n) var be *Error switch { case err != nil && !errors.As(err, &be): // Refused before sending (the final check, or the pace ended // by the lookup's end): nothing went out. if rerr := c.refund(ctx, r); rerr != nil { return nil, "", rerr } return nil, "", err case err != nil: if be.Unsent { if rerr := c.refund(ctx, r); rerr != nil { return nil, "", rerr } } last = err continue case len(got) == 0: last, results, backend = nil, []Result{}, s.Name() continue } return got, s.Name(), nil } if results != nil { return results, backend, nil } if tried == 0 && spent > 0 { return nil, "", ErrLimit } if last == nil { last = &Error{Class: ClassUnavailable} } return nil, "", last } // refund returns r on a context of its own: the lookup's may have ended. func (c Chain) refund(ctx context.Context, r Reservation) error { cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() return c.Usage.Return(cctx, r) } // Config is the operator's search configuration (AD3): the primary and // fallback backends by name, each backend's key and monthly cap. type Config struct { Primary, Fallback string Keys map[string]string Caps map[string]int } // The backends' names. const ( Kagi = "kagi" Mojeek = "mojeek" Brave = "brave" ) // ParseConfig reads EQUIPO_WEB_SEARCH (default kagi), // EQUIPO_WEB_SEARCH_FALLBACK (default none), EQUIPO__KEY and // EQUIPO__MONTHLY_CAP for each backend. A cap that isn't an integer // above 0 counts as none. func ParseConfig(getenv func(string) string) Config { c := Config{Primary: strings.ToLower(strings.TrimSpace(getenv("EQUIPO_WEB_SEARCH"))), Fallback: strings.ToLower(strings.TrimSpace(getenv("EQUIPO_WEB_SEARCH_FALLBACK"))), Keys: map[string]string{}, Caps: map[string]int{}} if c.Primary == "" { c.Primary = Kagi } for _, name := range []string{Kagi, Mojeek, Brave} { env := "EQUIPO_" + strings.ToUpper(name) if k := strings.TrimSpace(getenv(env + "_KEY")); k != "" { c.Keys[name] = k } if n, err := strconv.Atoi(strings.TrimSpace(getenv(env + "_MONTHLY_CAP"))); err == nil && n > 0 { c.Caps[name] = n } } return c } // FromConfig builds the chain: each named backend with its key and cap, // its own guarded client from a copy of g. A backend named without a key // or a cap is left out, with a log line naming it (never the value). ok // is false with no usable backend; err is a constructor refusing its // configuration (a code bug: boot fails). func FromConfig(cfg Config, g guard.Config, usage Usage) (Chain, bool, error) { logger := g.Logger if logger == nil { logger = slog.Default() } var usable []Searcher for _, name := range []string{cfg.Primary, cfg.Fallback} { if name == "" || (len(usable) == 1 && usable[0].Name() == name) { continue } key, cap := cfg.Keys[name], cfg.Caps[name] build := map[string]func(string, guard.Config) (Searcher, error){Kagi: NewKagi, Mojeek: NewMojeek, Brave: NewBrave}[name] if build == nil || key == "" || cap <= 0 { logger.Warn("web_search.misconfigured", "backend", name) continue } s, err := build(key, g) if err != nil { return Chain{}, false, err } usable = append(usable, s) } c := Chain{Usage: usage} switch len(usable) { case 0: return c, false, nil case 2: c.Fallback = usable[1] } c.Primary = usable[0] return c, true, nil } // clean keeps the https results with a URL and a title, cut to their // bounds, at most n. func clean(in []Result, n int) []Result { if n <= 0 || n > MaxResults { n = MaxResults } out := []Result{} for _, r := range in { if len(out) == n { break } if !strings.HasPrefix(r.URL, "https://") || len(r.URL) > guard.MaxURL || strings.TrimSpace(r.Title) == "" { continue } out = append(out, Result{Title: cut(strings.TrimSpace(r.Title), MaxTitle), URL: r.URL, Snippet: cut(strings.TrimSpace(r.Snippet), MaxSnippet), Date: cut(strings.TrimSpace(r.Date), 40)}) } return out } // cut is s at most n bytes, on a rune boundary. func cut(s string, n int) string { s = strings.ToValidUTF8(s, "") if len(s) <= n { return s } s = s[:n] for len(s) > 0 && !utf8.ValidString(s) { s = s[:len(s)-1] } return s }