oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1// Package websearch is the instance's web search for lookups (spec
2// 2026-11-26-assistant-abilities §4.2 step 4; plan AD3): one Searcher
3// interface, Kagi first, Mojeek and Brave as optional fallbacks, a chain
4// that tries the fallback once, and a monthly cap per backend counted on
5// the instance. Every request goes through the guarded client
6// (internal/websource/guard) with the backend's key bound to its origin.
7// Nothing here ever carries a URL, a query or a key in an error or a log.
8package websearch
9
10import (
11 "context"
12 "errors"
13 "log/slog"
14 "strconv"
15 "strings"
16 "time"
17 "unicode/utf8"
18
19 "amadan.net/oficina/equipo/internal/websource/guard"
20)
21
22// Result is one search result: an https URL, its title (at most 200
23// bytes), its snippet (at most 300) and its date, if the backend gave one.
24type Result struct {
25 Title, URL, Snippet, Date string
26}
27
28// Bounds on a result (§4.3's frame budget).
29const (
30 MaxTitle = 200
31 MaxSnippet = 300
32 // MaxResults is the most results a query returns.
33 MaxResults = 8
34)
35
36// The failure classes.
37const (
38 ClassLimit = "limit"
39 ClassAuth = "auth"
40 ClassUnavailable = "unavailable"
41 ClassBadResponse = "bad_response"
42)
43
44// Error is a backend's failure, by class only: never a URL, a query or a
45// key. Unsent says the request never went out (refused before sending),
46// so its reservation is returned.
47type Error struct {
48 Backend, Class string
49 Unsent bool
50}
51
52func (e *Error) Error() string { return "websearch: " + e.Backend + ": " + e.Class }
53
54// Searcher is one search backend.
55type Searcher interface {
56 Name() string
57 Search(ctx context.Context, query string, n int) ([]Result, error)
58}
59
60// Reservation is one query reserved against a backend's monthly cap: the
61// backend and the UTC month (2006-01) it counts in.
62type Reservation struct {
63 Backend, Month string
64}
65
66// Usage is the monthly caps' count. Take reserves one query on backend
67// while it is under its cap (ok false when spent); Return refunds that
68// exact reservation.
69type Usage interface {
70 Take(ctx context.Context, backend string) (r Reservation, ok bool, err error)
71 Return(ctx context.Context, r Reservation) error
72}
73
74// Before runs right before each backend request, the fallback's
75// included: an early authorization check. An error stops the chain.
76type Before func(ctx context.Context, backend string) error
77
78// Chain is the primary and an optional fallback, with the caps.
79type Chain struct {
80 Primary, Fallback Searcher
81 Usage Usage
82}
83
84// ErrLimit: every backend's cap is spent.
85var ErrLimit = &Error{Class: ClassLimit}
86
87// Search runs q on the primary and, once, on the fallback when the
88// primary failed, its cap was spent or it found nothing. Before each
89// backend, before runs (its error stops everything), then one query is
90// reserved. A refusal from the context's guard.WithBeforeHop (the final
91// check, right before sending) returns that reservation and stops the
92// chain. backend is the one whose results these are.
93func (c Chain) Search(ctx context.Context, q string, n int, before Before) (results []Result, backend string, err error) {
94 tried, spent := 0, 0
95 var last error
96 for _, s := range []Searcher{c.Primary, c.Fallback} {
97 if s == nil {
98 continue
99 }
100 if before != nil {
101 if err := before(ctx, s.Name()); err != nil {
102 return nil, "", err
103 }
104 }
105 r, ok, err := c.Usage.Take(ctx, s.Name())
106 if err != nil {
107 return nil, "", err
108 }
109 if !ok {
110 spent++
111 last = &Error{Backend: s.Name(), Class: ClassLimit}
112 continue
113 }
114 tried++
115 got, err := s.Search(ctx, q, n)
116 var be *Error
117 switch {
118 case err != nil && !errors.As(err, &be):
119 // Refused before sending (the final check, or the pace ended
120 // by the lookup's end): nothing went out.
121 if rerr := c.refund(ctx, r); rerr != nil {
122 return nil, "", rerr
123 }
124 return nil, "", err
125 case err != nil:
126 if be.Unsent {
127 if rerr := c.refund(ctx, r); rerr != nil {
128 return nil, "", rerr
129 }
130 }
131 last = err
132 continue
133 case len(got) == 0:
134 last, results, backend = nil, []Result{}, s.Name()
135 continue
136 }
137 return got, s.Name(), nil
138 }
139 if results != nil {
140 return results, backend, nil
141 }
142 if tried == 0 && spent > 0 {
143 return nil, "", ErrLimit
144 }
145 if last == nil {
146 last = &Error{Class: ClassUnavailable}
147 }
148 return nil, "", last
149}
150
151// refund returns r on a context of its own: the lookup's may have ended.
152func (c Chain) refund(ctx context.Context, r Reservation) error {
153 cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
154 defer cancel()
155 return c.Usage.Return(cctx, r)
156}
157
158// Config is the operator's search configuration (AD3): the primary and
159// fallback backends by name, each backend's key and monthly cap.
160type Config struct {
161 Primary, Fallback string
162 Keys map[string]string
163 Caps map[string]int
164}
165
166// The backends' names.
167const (
168 Kagi = "kagi"
169 Mojeek = "mojeek"
170 Brave = "brave"
171)
172
173// ParseConfig reads EQUIPO_WEB_SEARCH (default kagi),
174// EQUIPO_WEB_SEARCH_FALLBACK (default none), EQUIPO_<NAME>_KEY and
175// EQUIPO_<NAME>_MONTHLY_CAP for each backend. A cap that isn't an integer
176// above 0 counts as none.
177func ParseConfig(getenv func(string) string) Config {
178 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{}}
179 if c.Primary == "" {
180 c.Primary = Kagi
181 }
182 for _, name := range []string{Kagi, Mojeek, Brave} {
183 env := "EQUIPO_" + strings.ToUpper(name)
184 if k := strings.TrimSpace(getenv(env + "_KEY")); k != "" {
185 c.Keys[name] = k
186 }
187 if n, err := strconv.Atoi(strings.TrimSpace(getenv(env + "_MONTHLY_CAP"))); err == nil && n > 0 {
188 c.Caps[name] = n
189 }
190 }
191 return c
192}
193
194// FromConfig builds the chain: each named backend with its key and cap,
195// its own guarded client from a copy of g. A backend named without a key
196// or a cap is left out, with a log line naming it (never the value). ok
197// is false with no usable backend; err is a constructor refusing its
198// configuration (a code bug: boot fails).
199func FromConfig(cfg Config, g guard.Config, usage Usage) (Chain, bool, error) {
200 logger := g.Logger
201 if logger == nil {
202 logger = slog.Default()
203 }
204 var usable []Searcher
205 for _, name := range []string{cfg.Primary, cfg.Fallback} {
206 if name == "" || (len(usable) == 1 && usable[0].Name() == name) {
207 continue
208 }
209 key, cap := cfg.Keys[name], cfg.Caps[name]
210 build := map[string]func(string, guard.Config) (Searcher, error){Kagi: NewKagi, Mojeek: NewMojeek, Brave: NewBrave}[name]
211 if build == nil || key == "" || cap <= 0 {
212 logger.Warn("web_search.misconfigured", "backend", name)
213 continue
214 }
215 s, err := build(key, g)
216 if err != nil {
217 return Chain{}, false, err
218 }
219 usable = append(usable, s)
220 }
221 c := Chain{Usage: usage}
222 switch len(usable) {
223 case 0:
224 return c, false, nil
225 case 2:
226 c.Fallback = usable[1]
227 }
228 c.Primary = usable[0]
229 return c, true, nil
230}
231
232// clean keeps the https results with a URL and a title, cut to their
233// bounds, at most n.
234func clean(in []Result, n int) []Result {
235 if n <= 0 || n > MaxResults {
236 n = MaxResults
237 }
238 out := []Result{}
239 for _, r := range in {
240 if len(out) == n {
241 break
242 }
243 if !strings.HasPrefix(r.URL, "https://") || len(r.URL) > guard.MaxURL || strings.TrimSpace(r.Title) == "" {
244 continue
245 }
246 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)})
247 }
248 return out
249}
250
251// cut is s at most n bytes, on a rune boundary.
252func cut(s string, n int) string {
253 s = strings.ToValidUTF8(s, "")
254 if len(s) <= n {
255 return s
256 }
257 s = s[:n]
258 for len(s) > 0 && !utf8.ValidString(s) {
259 s = s[:len(s)-1]
260 }
261 return s
262}
263