websearch: Kagi first, optional fallbacks, monthly caps, fakes
Task 3.3: Searcher with Kagi (POST /api/v1/search, bearer key, body of query and limit only), Mojeek and Brave as optional fallbacks, each on its own guarded client with its key bound to its origin and no redirects. Chain tries the fallback once on an error, a spent cap or no results; Before runs before each backend; a refusal at the final check returns its reservation. DBUsage counts per UTC month in chat_web_search_usage (migration 0117, completed by Task 3.6). Config from EQUIPO_WEB_SEARCH and friends; a backend without key or cap is left out and logged by name. Fixtures from Kagi's documented v1 shape; 402 counts as limit (undocumented).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
19 files changed,
+1,159
−1
internal/equipo/chat/lookup_models.go+11 −0internal/equipo/chat/models.go+1 −1internal/equipo/config.go+6 −0internal/equipo/migrations/0117_lookups.sql+3 −0internal/equipo/migrations/schema.sql+1 −0internal/websearch/backends.go+223 −0internal/websearch/testdata/brave_429.json+1 −0internal/websearch/testdata/brave_ok.json+1 −0internal/websearch/testdata/kagi_400.json+1 −0internal/websearch/testdata/kagi_429.json+1 −0internal/websearch/testdata/kagi_empty.json+1 −0internal/websearch/testdata/kagi_ok.json+1 −0internal/websearch/testdata/mojeek_empty.json+1 −0internal/websearch/testdata/mojeek_limit.json+1 −0internal/websearch/testdata/mojeek_ok.json+1 −0internal/websearch/usage.go+50 −0internal/websearch/websearch.go+246 −0internal/websearch/websearch_test.go+522 −0internal/websearch/websearchtest/fake.go+87 −0
diff --git a/internal/equipo/chat/lookup_models.go b/internal/equipo/chat/lookup_models.go| new file mode 100644 |
| index 00000000..13753bd9 |
| --- /dev/null |
| +++ b/internal/equipo/chat/lookup_models.go |
| @@ -0,0 +1,11 @@ |
| +package chat |
| + |
| +// webSearchUsageRecord is one search backend's queries in one UTC month, |
| +// against its cap (websearch.DBUsage reads and writes it). |
| +type webSearchUsageRecord struct { |
| + Backend string `gorm:"primaryKey"` |
| + Month string `gorm:"primaryKey"` |
| + Used int64 `gorm:"not null;default:0"` |
| +} |
| + |
| +func (webSearchUsageRecord) TableName() string { return "chat_web_search_usage" } |
diff --git a/internal/equipo/chat/models.go b/internal/equipo/chat/models.go| index cd38f24f..d18a5504 100644 |
| --- a/internal/equipo/chat/models.go |
| +++ b/internal/equipo/chat/models.go |
| @@ -11,7 +11,7 @@ import ( |
| ) |
| // Models are the tables this package owns, for the migration check. |
| -var Models = append([]any{&changeDiffRecord{}, ¬ificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &instancePrefixRecord{}, &instanceAddressRecord{}, &instanceInventoryCardRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &abilitiesRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}}, push.Models...) |
| +var Models = append([]any{&changeDiffRecord{}, ¬ificationReceipt{}, &projectNameRecord{}, &cardVisibility{}, &cardThreadRecord{}, ©AttemptRecord{}, ©ReviewRecord{}, ©FeedbackRecord{}, &turnRecord{}, &messageRecord{}, &eventRecord{}, &commandRecord{}, &inboxRecord{}, &runnerSessionRecord{}, &projectRecord{}, &cardRecord{}, &toolCallRecord{}, &settingRecord{}, &coordinatorRecord{}, ¬ebookRecord{}, &taskRecord{}, &stepRecord{}, &entryRecord{}, &attachmentRecord{}, &starRecord{}, &questionRecord{}, &connectionRecord{}, &usageRecord{}, &distinctRecord{}, &hkRecord{}, &hkFailureRecord{}, &hkSettingsRecord{}, &fileRecord{}, &fileDataRecord{}, &transferRecord{}, &mergePolicyRecord{}, &mergeAuditRecord{}, &specialistRecord{}, &grantRecord{}, &specialistAuditRecord{}, &researchSourceRecord{}, &researchAddressRecord{}, &researchPrefixRecord{}, &researchInventoryRecord{}, &instancePrefixRecord{}, &instanceAddressRecord{}, &instanceInventoryCardRecord{}, &webSearchUsageRecord{}, &researchRecord{}, &researchFetchRecord{}, &taskFileRecord{}, &taskFileDataRecord{}, &releaseRecord{}, &adviceRecord{}, &assistantHostRecord{}, &abilitiesRecord{}, &handoffRecord{}, &handoffTurnRecord{}, &handoffTaskRecord{}, &handoffActionRecord{}, &connectTurnRecord{}, &carriedRecord{}, &zoneRecord{}, &placeRecord{}, &projectPlaceRecord{}}, push.Models...) |
| type turnRecord struct { |
| CreateRepo string |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index 202f070f..81fb5635 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -2,6 +2,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/websearch" |
| "amadan.net/oficina/equipo/internal/equipo/oficina" |
| "amadan.net/oficina/equipo/internal/equipo/push" |
| "amadan.net/oficina/home/connect" |
| @@ -68,6 +69,10 @@ type Config struct { |
| // (EQUIPO_INSTANCE_PREFIXES, comma-separated prefixes), which no |
| // request to the public web may reach; an owner confirms it. |
| InstancePrefixes string |
| + // WebSearch is the lookups' search backends, keys and monthly caps |
| + // (EQUIPO_WEB_SEARCH, EQUIPO_WEB_SEARCH_FALLBACK, EQUIPO_<NAME>_KEY, |
| + // EQUIPO_<NAME>_MONTHLY_CAP; plan AD3). Keys are never logged. |
| + WebSearch websearch.Config |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| @@ -109,6 +114,7 @@ func LoadConfig(getenv func(string) string) (Config, error) { |
| } |
| cfg.Abilities = fixed |
| cfg.InstancePrefixes = strings.TrimSpace(getenv("EQUIPO_INSTANCE_PREFIXES")) |
| + cfg.WebSearch = websearch.ParseConfig(getenv) |
| if _, err := chat.ParseInstancePrefixes(cfg.InstancePrefixes); err != nil { |
| slog.Default().Error("config", "err", err) |
| //lint:ignore ST1005 User-facing errors preserve the reviewed sentences in copy.go. |
diff --git a/internal/equipo/migrations/0117_lookups.sql b/internal/equipo/migrations/0117_lookups.sql| new file mode 100644 |
| index 00000000..0ed5310b |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0117_lookups.sql |
| @@ -0,0 +1,3 @@ |
| +-- Lookups (spec 2026-11-26-assistant-abilities §4): each search backend's |
| +-- queries per UTC calendar month, against the operator's monthly cap. |
| +CREATE TABLE chat_web_search_usage (backend text, month text, used integer NOT NULL DEFAULT 0, PRIMARY KEY (backend, month)); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index f539eb5e..b5fcf727 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -662,6 +662,7 @@ CREATE INDEX chat_research_inventory_runner ON chat_research_inventory(runner_id |
| CREATE TABLE instance_prefixes (prefix text PRIMARY KEY, confirmed_by text, confirmed_at datetime, card_id text); |
| CREATE TABLE instance_addresses (address text PRIMARY KEY, seen_at datetime); |
| CREATE TABLE chat_instance_inventory (card_id text PRIMARY KEY, prefixes text, addresses text, created_at datetime); |
| +CREATE TABLE chat_web_search_usage (backend text, month text, used integer NOT NULL DEFAULT 0, PRIMARY KEY (backend, month)); |
| CREATE TABLE chat_research (step_id text, attempt integer, task_id text, revision integer, findings text, created_at datetime, PRIMARY KEY (step_id, attempt)); |
| CREATE INDEX chat_research_task ON chat_research(task_id); |
| CREATE TABLE chat_research_fetches (step_id text, attempt integer, idx integer, task_id text, source_id text, origin text, parent text, url text, hops text, address text, status integer, type text, bytes integer, sha256 text, millis integer, reason text, PRIMARY KEY (step_id, attempt, idx)); |
diff --git a/internal/websearch/backends.go b/internal/websearch/backends.go| new file mode 100644 |
| index 00000000..da10a2d3 |
| --- /dev/null |
| +++ b/internal/websearch/backends.go |
| @@ -0,0 +1,223 @@ |
| +package websearch |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/websource/guard" |
| +) |
| + |
| +// The backends' fixed origins: a key goes to nowhere else. |
| +const ( |
| + kagiOrigin = "https://kagi.com" |
| + mojeekOrigin = "https://www.mojeek.com" |
| + braveOrigin = "https://api.search.brave.com" |
| +) |
| + |
| +// backend is one vendor: its name, its guarded client, and how its |
| +// request is made and its answer read. |
| +type backend struct { |
| + name string |
| + client *guard.Client |
| + request func(q string, n int) (*http.Request, error) |
| + parse func(status int, body []byte) ([]Result, string) |
| +} |
| + |
| +func (b *backend) Name() string { return b.name } |
| + |
| +// Search sends one query and reads its results. A guard refusal is |
| +// unavailable (a 3xx, never followed, is bad_response); any other error |
| +// from the guard is the context's final check refusing, and comes back |
| +// as it is, so the chain stops. |
| +func (b *backend) Search(ctx context.Context, q string, n int) ([]Result, error) { |
| + if n <= 0 || n > MaxResults { |
| + n = MaxResults |
| + } |
| + req, err := b.request(q, n) |
| + if err != nil { |
| + return nil, &Error{Backend: b.name, Class: ClassBadResponse} |
| + } |
| + res, err := b.client.Do(ctx, req) |
| + if err != nil { |
| + var r guard.Refusal |
| + if !errors.As(err, &r) { |
| + return nil, err |
| + } |
| + if r.Rule == guard.RuleRedirect { |
| + return nil, &Error{Backend: b.name, Class: ClassBadResponse} |
| + } |
| + return nil, &Error{Backend: b.name, Class: ClassUnavailable} |
| + } |
| + results, class := b.parse(res.Status, res.Body) |
| + if class != "" { |
| + return nil, &Error{Backend: b.name, Class: class} |
| + } |
| + return clean(results, n), nil |
| +} |
| + |
| +// statusClass is a non-200's class: 401 and 403 auth, 402 and 429 limit |
| +// (out of credit, or too many), 5xx unavailable, else bad_response. |
| +func statusClass(status int) string { |
| + switch { |
| + case status == http.StatusOK: |
| + return "" |
| + case status == http.StatusUnauthorized || status == http.StatusForbidden: |
| + return ClassAuth |
| + case status == http.StatusPaymentRequired || status == http.StatusTooManyRequests: |
| + return ClassLimit |
| + case status >= 500: |
| + return ClassUnavailable |
| + } |
| + return ClassBadResponse |
| +} |
| + |
| +// searchClient is a backend's own guarded client: searches' policy, no |
| +// redirects, the key bound to its origin. |
| +func searchClient(g guard.Config, cred guard.Credential) (*guard.Client, error) { |
| + g.Policy, g.Redirects, g.Credential = guard.PolicySearch, 0, &cred |
| + g.Timeouts = guard.Timeouts{} |
| + return guard.New(g) |
| +} |
| + |
| +// NewKagi is Kagi's v1 search: POST https://kagi.com/api/v1/search with |
| +// the key as a bearer and a JSON body of only query and limit. |
| +func NewKagi(key string, g guard.Config) (Searcher, error) { |
| + c, err := searchClient(g, guard.Credential{Origin: kagiOrigin, Header: "Authorization", Value: "Bearer " + key}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &backend{name: Kagi, client: c, |
| + request: func(q string, n int) (*http.Request, error) { |
| + body, err := json.Marshal(struct { |
| + Query string `json:"query"` |
| + Limit int `json:"limit"` |
| + }{q, n}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + req, err := http.NewRequest(http.MethodPost, kagiOrigin+"/api/v1/search", bytes.NewReader(body)) |
| + if err == nil { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + return req, err |
| + }, |
| + parse: func(status int, body []byte) ([]Result, string) { |
| + if c := statusClass(status); c != "" { |
| + return nil, c |
| + } |
| + var out struct { |
| + Data *struct { |
| + Search []struct { |
| + URL string `json:"url"` |
| + Title string `json:"title"` |
| + Snippet string `json:"snippet"` |
| + Time string `json:"time"` |
| + } `json:"search"` |
| + } `json:"data"` |
| + Error []json.RawMessage `json:"error"` |
| + } |
| + if json.Unmarshal(body, &out) != nil || len(out.Error) > 0 || out.Data == nil { |
| + return nil, ClassBadResponse |
| + } |
| + results := make([]Result, 0, len(out.Data.Search)) |
| + for _, r := range out.Data.Search { |
| + results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Snippet, Date: r.Time}) |
| + } |
| + return results, "" |
| + }}, nil |
| +} |
| + |
| +// NewMojeek is Mojeek's search (optional fallback): GET |
| +// https://www.mojeek.com/search with the key as api_key. |
| +func NewMojeek(key string, g guard.Config) (Searcher, error) { |
| + c, err := searchClient(g, guard.Credential{Origin: mojeekOrigin, Param: "api_key", Value: key}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &backend{name: Mojeek, client: c, |
| + request: func(q string, n int) (*http.Request, error) { |
| + v := url.Values{"q": {q}, "fmt": {"json"}, "t": {strconv.Itoa(n)}, "date": {"1"}} |
| + return http.NewRequest(http.MethodGet, mojeekOrigin+"/search?"+v.Encode(), nil) |
| + }, |
| + parse: func(status int, body []byte) ([]Result, string) { |
| + if c := statusClass(status); c != "" { |
| + return nil, c |
| + } |
| + var out struct { |
| + Response struct { |
| + Status string `json:"status"` |
| + Results []struct { |
| + URL string `json:"url"` |
| + Title string `json:"title"` |
| + Desc string `json:"desc"` |
| + Date any `json:"date"` |
| + } `json:"results"` |
| + } `json:"response"` |
| + } |
| + if json.Unmarshal(body, &out) != nil { |
| + return nil, ClassBadResponse |
| + } |
| + if s := out.Response.Status; s != "OK" { |
| + if strings.Contains(strings.ToLower(s), "limit") { |
| + return nil, ClassLimit |
| + } |
| + return nil, ClassBadResponse |
| + } |
| + results := make([]Result, 0, len(out.Response.Results)) |
| + for _, r := range out.Response.Results { |
| + date := "" |
| + switch d := r.Date.(type) { |
| + case string: |
| + date = d |
| + case float64: |
| + date = strconv.FormatInt(int64(d), 10) |
| + } |
| + results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Desc, Date: date}) |
| + } |
| + return results, "" |
| + }}, nil |
| +} |
| + |
| +// NewBrave is Brave's web search (optional fallback): GET |
| +// https://api.search.brave.com/res/v1/web/search with the key as |
| +// X-Subscription-Token. |
| +func NewBrave(key string, g guard.Config) (Searcher, error) { |
| + c, err := searchClient(g, guard.Credential{Origin: braveOrigin, Header: "X-Subscription-Token", Value: key}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &backend{name: Brave, client: c, |
| + request: func(q string, n int) (*http.Request, error) { |
| + v := url.Values{"q": {q}, "count": {strconv.Itoa(n)}} |
| + return http.NewRequest(http.MethodGet, braveOrigin+"/res/v1/web/search?"+v.Encode(), nil) |
| + }, |
| + parse: func(status int, body []byte) ([]Result, string) { |
| + if c := statusClass(status); c != "" { |
| + return nil, c |
| + } |
| + var out struct { |
| + Web struct { |
| + Results []struct { |
| + Title string `json:"title"` |
| + URL string `json:"url"` |
| + Description string `json:"description"` |
| + Age string `json:"age"` |
| + } `json:"results"` |
| + } `json:"web"` |
| + } |
| + if json.Unmarshal(body, &out) != nil { |
| + return nil, ClassBadResponse |
| + } |
| + results := make([]Result, 0, len(out.Web.Results)) |
| + for _, r := range out.Web.Results { |
| + results = append(results, Result{Title: r.Title, URL: r.URL, Snippet: r.Description, Date: r.Age}) |
| + } |
| + return results, "" |
| + }}, nil |
| +} |
diff --git a/internal/websearch/testdata/brave_429.json b/internal/websearch/testdata/brave_429.json| new file mode 100644 |
| index 00000000..5abcb271 |
| --- /dev/null |
| +++ b/internal/websearch/testdata/brave_429.json |
| @@ -0,0 +1 @@ |
| +{"type":"ErrorResponse","error":{"code":"RATE_LIMITED","status":429,"detail":"Request rate limit exceeded"}} |
diff --git a/internal/websearch/testdata/brave_ok.json b/internal/websearch/testdata/brave_ok.json| new file mode 100644 |
| index 00000000..e6af974b |
| --- /dev/null |
| +++ b/internal/websearch/testdata/brave_ok.json |
| @@ -0,0 +1 @@ |
| +{"type":"search","web":{"type":"search","results":[{"title":"Dublin weather","url":"https://www.met.ie/forecasts/dublin","description":"Rain at <strong>first</strong>.","age":"2 hours ago"}]}} |
diff --git a/internal/websearch/testdata/kagi_400.json b/internal/websearch/testdata/kagi_400.json| new file mode 100644 |
| index 00000000..3ede995d |
| --- /dev/null |
| +++ b/internal/websearch/testdata/kagi_400.json |
| @@ -0,0 +1 @@ |
| +{"meta":{"trace":"ghi789"},"data":null,"error":[{"code":"search.invalid_query","url":"https://kagi.com/api/docs/errors/search.invalid_query","message":"Query is invalid","location":"query"}]} |
diff --git a/internal/websearch/testdata/kagi_429.json b/internal/websearch/testdata/kagi_429.json| new file mode 100644 |
| index 00000000..ae495fff |
| --- /dev/null |
| +++ b/internal/websearch/testdata/kagi_429.json |
| @@ -0,0 +1 @@ |
| +{"meta":{"trace":"jkl012"},"data":null,"error":[{"code":"rate_limited","url":"https://kagi.com/api/docs/errors/rate_limited","message":"Too many requests","location":null}]} |
diff --git a/internal/websearch/testdata/kagi_empty.json b/internal/websearch/testdata/kagi_empty.json| new file mode 100644 |
| index 00000000..b9f1ac3b |
| --- /dev/null |
| +++ b/internal/websearch/testdata/kagi_empty.json |
| @@ -0,0 +1 @@ |
| +{"meta":{"trace":"def456","node":"eu-west","ms":120},"data":{"search":[]}} |
diff --git a/internal/websearch/testdata/kagi_ok.json b/internal/websearch/testdata/kagi_ok.json| new file mode 100644 |
| index 00000000..a4e55a26 |
| --- /dev/null |
| +++ b/internal/websearch/testdata/kagi_ok.json |
| @@ -0,0 +1 @@ |
| +{"meta":{"trace":"abc123","node":"eu-west","ms":412},"data":{"search":[{"url":"https://www.met.ie/forecasts/dublin","title":"Dublin forecast - Met Éireann","snippet":"Rain at first, clearing later. Highs of 11°C.","time":"2026-11-28T06:00:00Z"},{"url":"http://insecure.example.org/weather","title":"An http page","snippet":"Dropped: not https."},{"url":"https://www.bbc.com/weather/2964574","title":"Dublin - BBC Weather","snippet":"Light rain and a gentle breeze."}],"direct_answer":[{"props":{"answer":"11"}}],"infobox":[{"title":"Dublin"}],"weather":[{"props":{"temp":11}}]}} |
diff --git a/internal/websearch/testdata/mojeek_empty.json b/internal/websearch/testdata/mojeek_empty.json| new file mode 100644 |
| index 00000000..110b3f3e |
| --- /dev/null |
| +++ b/internal/websearch/testdata/mojeek_empty.json |
| @@ -0,0 +1 @@ |
| +{"response":{"status":"OK","results":[]}} |
diff --git a/internal/websearch/testdata/mojeek_limit.json b/internal/websearch/testdata/mojeek_limit.json| new file mode 100644 |
| index 00000000..824f6b7a |
| --- /dev/null |
| +++ b/internal/websearch/testdata/mojeek_limit.json |
| @@ -0,0 +1 @@ |
| +{"response":{"status":"ERROR: Daily Limit Reached"}} |
diff --git a/internal/websearch/testdata/mojeek_ok.json b/internal/websearch/testdata/mojeek_ok.json| new file mode 100644 |
| index 00000000..75fb43f7 |
| --- /dev/null |
| +++ b/internal/websearch/testdata/mojeek_ok.json |
| @@ -0,0 +1 @@ |
| +{"response":{"status":"OK","head":{"query":"dublin weather"},"results":[{"url":"https://www.met.ie/forecasts/dublin","title":"Dublin forecast","desc":"Rain at first.","date":1795852800}]}} |
diff --git a/internal/websearch/usage.go b/internal/websearch/usage.go| new file mode 100644 |
| index 00000000..2c993d6a |
| --- /dev/null |
| +++ b/internal/websearch/usage.go |
| @@ -0,0 +1,50 @@ |
| +package websearch |
| + |
| +import ( |
| + "context" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| +) |
| + |
| +// DBUsage counts each backend's queries per UTC calendar month in |
| +// chat_web_search_usage(backend, month, used): Take increments only |
| +// while used is below the backend's cap, in one statement, so two |
| +// lookups at once can't both take the last query. |
| +type DBUsage struct { |
| + DB *gorm.DB |
| + Caps map[string]int |
| + // Now is the clock (time.Now when nil). |
| + Now func() time.Time |
| +} |
| + |
| +func (u DBUsage) month() string { |
| + now := time.Now |
| + if u.Now != nil { |
| + now = u.Now |
| + } |
| + return now().UTC().Format("2006-01") |
| +} |
| + |
| +// Take reserves one query on backend this month, while under its cap. |
| +func (u DBUsage) Take(ctx context.Context, backend string) (Reservation, bool, error) { |
| + r := Reservation{Backend: backend, Month: u.month()} |
| + limit := u.Caps[backend] |
| + if limit <= 0 { |
| + return r, false, nil |
| + } |
| + db := u.DB.WithContext(ctx) |
| + if err := db.Exec("INSERT INTO chat_web_search_usage (backend, month, used) VALUES (?, ?, 0) ON CONFLICT DO NOTHING", r.Backend, r.Month).Error; err != nil { |
| + return r, false, err |
| + } |
| + res := db.Exec("UPDATE chat_web_search_usage SET used = used + 1 WHERE backend = ? AND month = ? AND used < ?", r.Backend, r.Month, limit) |
| + if res.Error != nil { |
| + return r, false, res.Error |
| + } |
| + return r, res.RowsAffected == 1, nil |
| +} |
| + |
| +// Return refunds r: its own backend and month, whatever month it is now. |
| +func (u DBUsage) Return(ctx context.Context, r Reservation) error { |
| + return u.DB.WithContext(ctx).Exec("UPDATE chat_web_search_usage SET used = used - 1 WHERE backend = ? AND month = ? AND used > 0", r.Backend, r.Month).Error |
| +} |
diff --git a/internal/websearch/websearch.go b/internal/websearch/websearch.go| new file mode 100644 |
| index 00000000..7e05bba3 |
| --- /dev/null |
| +++ b/internal/websearch/websearch.go |
| @@ -0,0 +1,246 @@ |
| +// 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" |
| + "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. |
| +type Error struct { |
| + Backend, Class string |
| +} |
| + |
| +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): nothing went out. |
| + if rerr := c.Usage.Return(ctx, r); rerr != nil { |
| + return nil, "", rerr |
| + } |
| + return nil, "", err |
| + case err != nil: |
| + 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 |
| +} |
| + |
| +// 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_<NAME>_KEY and |
| +// EQUIPO_<NAME>_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://") || 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 |
| +} |
diff --git a/internal/websearch/websearch_test.go b/internal/websearch/websearch_test.go| new file mode 100644 |
| index 00000000..38bb107d |
| --- /dev/null |
| +++ b/internal/websearch/websearch_test.go |
| @@ -0,0 +1,522 @@ |
| +package websearch_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "math/big" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/websearch" |
| + "amadan.net/oficina/equipo/internal/websearch/websearchtest" |
| + "amadan.net/oficina/equipo/internal/websource/guard" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "amadan.net/rastrillo/rastrillo/db" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +const sentinel = "SENTINEL-KEY-0123456789" |
| + |
| +type ready struct{} |
| + |
| +func (ready) Ready(context.Context) error { return nil } |
| +func (ready) Inside(netip.Addr) bool { return false } |
| + |
| +// vendor is a TLS server answering as kagi.com, www.mojeek.com and |
| +// api.search.brave.com, recording each request. |
| +type vendor struct { |
| + srv *httptest.Server |
| + roots *x509.CertPool |
| + mu sync.Mutex |
| + got []*http.Request |
| + body [][]byte |
| + reply func(r *http.Request) (int, []byte) |
| + logs bytes.Buffer |
| +} |
| + |
| +func newVendor(t *testing.T) *vendor { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "vendor"}, DNSNames: []string{"kagi.com", "www.mojeek.com", "api.search.brave.com", "other.example.org"}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, IsCA: true} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cert, _ := x509.ParseCertificate(der) |
| + v := &vendor{roots: x509.NewCertPool()} |
| + v.roots.AddCert(cert) |
| + v.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + raw, _ := io.ReadAll(r.Body) |
| + v.mu.Lock() |
| + v.got = append(v.got, r) |
| + v.body = append(v.body, raw) |
| + reply := v.reply |
| + v.mu.Unlock() |
| + status, body := 200, []byte(`{}`) |
| + if reply != nil { |
| + status, body = reply(r) |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + if status >= 300 && status < 400 { |
| + w.Header().Set("Location", "https://other.example.org/elsewhere") |
| + } |
| + w.WriteHeader(status) |
| + _, _ = w.Write(body) |
| + })) |
| + v.srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}} |
| + v.srv.StartTLS() |
| + t.Cleanup(v.srv.Close) |
| + return v |
| +} |
| + |
| +func (v *vendor) guard() guard.Config { |
| + return guard.Config{Inventory: ready{}, Logger: slog.New(slog.NewTextHandler(&v.logs, nil)), |
| + Resolve: func(context.Context, string) ([]netip.Addr, error) { |
| + return []netip.Addr{netip.MustParseAddr("93.184.216.34")}, nil |
| + }, |
| + TestDial: func(string) (string, *x509.CertPool) { return v.srv.Listener.Addr().String(), v.roots }} |
| +} |
| + |
| +func (v *vendor) requests() ([]*http.Request, [][]byte) { |
| + v.mu.Lock() |
| + defer v.mu.Unlock() |
| + return append([]*http.Request(nil), v.got...), append([][]byte(nil), v.body...) |
| +} |
| + |
| +func fixture(t *testing.T, name string) []byte { |
| + t.Helper() |
| + raw, err := os.ReadFile(filepath.Join("testdata", name+".json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return raw |
| +} |
| + |
| +func answering(v *vendor, status int, body []byte) { |
| + v.mu.Lock() |
| + v.reply = func(*http.Request) (int, []byte) { return status, body } |
| + v.mu.Unlock() |
| +} |
| + |
| +func newBackend(t *testing.T, name string, v *vendor) websearch.Searcher { |
| + t.Helper() |
| + build := map[string]func(string, guard.Config) (websearch.Searcher, error){websearch.Kagi: websearch.NewKagi, websearch.Mojeek: websearch.NewMojeek, websearch.Brave: websearch.NewBrave}[name] |
| + s, err := build(sentinel, v.guard()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func class(err error) string { |
| + var e *websearch.Error |
| + if errors.As(err, &e) { |
| + return e.Class |
| + } |
| + return fmt.Sprintf("not a websearch error: %v", err) |
| +} |
| + |
| +// Kagi: a POST to /api/v1/search with the key as a bearer and a body of |
| +// only query and limit; url, title, snippet and time map to a result; |
| +// direct_answer, infobox and weather are ignored; an http result is |
| +// dropped. |
| +func TestKagiParsesFixture(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 200, fixture(t, "kagi_ok")) |
| + got, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "dublin weather", 8) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []websearch.Result{ |
| + {Title: "Dublin forecast - Met Éireann", URL: "https://www.met.ie/forecasts/dublin", Snippet: "Rain at first, clearing later. Highs of 11°C.", Date: "2026-11-28T06:00:00Z"}, |
| + {Title: "Dublin - BBC Weather", URL: "https://www.bbc.com/weather/2964574", Snippet: "Light rain and a gentle breeze."}, |
| + } |
| + if fmt.Sprint(got) != fmt.Sprint(want) { |
| + t.Errorf("results %+v", got) |
| + } |
| + reqs, bodies := v.requests() |
| + if len(reqs) != 1 || reqs[0].Method != http.MethodPost || reqs[0].URL.Path != "/api/v1/search" || reqs[0].Host != "kagi.com" || reqs[0].Header.Get("Authorization") != "Bearer "+sentinel || reqs[0].Header.Get("Content-Type") != "application/json" { |
| + t.Fatalf("request %+v", reqs) |
| + } |
| + var body map[string]any |
| + if err := json.Unmarshal(bodies[0], &body); err != nil || len(body) != 2 || body["query"] != "dublin weather" || body["limit"] != float64(8) { |
| + t.Errorf("body %s", bodies[0]) |
| + } |
| +} |
| + |
| +func TestKagi400IsBadResponse(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 400, fixture(t, "kagi_400")) |
| + if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassBadResponse { |
| + t.Errorf("400: %v", err) |
| + } |
| +} |
| + |
| +func TestKagi429IsLimit(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 429, fixture(t, "kagi_429")) |
| + if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassLimit { |
| + t.Errorf("429: %v", err) |
| + } |
| +} |
| + |
| +func TestKagi401IsAuth(t *testing.T) { |
| + v := newVendor(t) |
| + for _, status := range []int{401, 403} { |
| + answering(v, status, []byte(`{"meta":{},"data":null,"error":[{"code":"auth","url":"x"}]}`)) |
| + if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassAuth { |
| + t.Errorf("%d: %v", status, err) |
| + } |
| + } |
| + answering(v, 503, nil) |
| + if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassUnavailable { |
| + t.Errorf("503: %v", err) |
| + } |
| + answering(v, 302, nil) |
| + if _, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassBadResponse { |
| + t.Errorf("302: %v", err) |
| + } |
| + if reqs, _ := v.requests(); len(reqs) != 4 { |
| + t.Errorf("a redirect was followed: %d requests", len(reqs)) |
| + } |
| +} |
| + |
| +func TestKagiEmptyIsNoResults(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 200, fixture(t, "kagi_empty")) |
| + got, err := newBackend(t, websearch.Kagi, v).Search(context.Background(), "q", 8) |
| + if err != nil || len(got) != 0 { |
| + t.Errorf("empty: %+v %v", got, err) |
| + } |
| +} |
| + |
| +func TestMojeekParsesFixture(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 200, fixture(t, "mojeek_ok")) |
| + got, err := newBackend(t, websearch.Mojeek, v).Search(context.Background(), "dublin weather", 8) |
| + if err != nil || len(got) != 1 || got[0].URL != "https://www.met.ie/forecasts/dublin" || got[0].Snippet != "Rain at first." { |
| + t.Fatalf("results %+v %v", got, err) |
| + } |
| + reqs, _ := v.requests() |
| + q := reqs[0].URL.Query() |
| + if reqs[0].Host != "www.mojeek.com" || q.Get("api_key") != sentinel || q.Get("q") != "dublin weather" || q.Get("fmt") != "json" { |
| + t.Errorf("request %s", reqs[0].URL) |
| + } |
| +} |
| + |
| +func TestMojeekStatusErrorIsLimit(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 200, fixture(t, "mojeek_limit")) |
| + if _, err := newBackend(t, websearch.Mojeek, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassLimit { |
| + t.Errorf("daily limit: %v", err) |
| + } |
| +} |
| + |
| +func TestBraveParsesFixture(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 200, fixture(t, "brave_ok")) |
| + got, err := newBackend(t, websearch.Brave, v).Search(context.Background(), "dublin weather", 8) |
| + if err != nil || len(got) != 1 || got[0].Date != "2 hours ago" { |
| + t.Fatalf("results %+v %v", got, err) |
| + } |
| + reqs, _ := v.requests() |
| + if reqs[0].Host != "api.search.brave.com" || reqs[0].Header.Get("X-Subscription-Token") != sentinel || reqs[0].URL.Query().Get("q") != "dublin weather" { |
| + t.Errorf("request %+v", reqs[0]) |
| + } |
| +} |
| + |
| +func TestBrave429IsLimit(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 429, fixture(t, "brave_429")) |
| + if _, err := newBackend(t, websearch.Brave, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassLimit { |
| + t.Errorf("429: %v", err) |
| + } |
| +} |
| + |
| +func TestBrave401IsAuth(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 401, nil) |
| + if _, err := newBackend(t, websearch.Brave, v).Search(context.Background(), "q", 8); class(err) != websearch.ClassAuth { |
| + t.Errorf("401: %v", err) |
| + } |
| +} |
| + |
| +// Every failure, every log line and every request outside the vendor's |
| +// own origin are free of the key. |
| +func TestSearchErrorsNeverCarryKey(t *testing.T) { |
| + v := newVendor(t) |
| + for _, name := range []string{websearch.Kagi, websearch.Mojeek, websearch.Brave} { |
| + for _, status := range []int{302, 400, 401, 429, 500} { |
| + answering(v, status, []byte(`{"error":"`+sentinel+`"}`)) |
| + _, err := newBackend(t, name, v).Search(context.Background(), "q", 8) |
| + if err == nil || strings.Contains(err.Error(), sentinel) || strings.Contains(fmt.Sprintf("%v %+v %#v", err, err, err), sentinel) { |
| + t.Errorf("%s %d: %v", name, status, err) |
| + } |
| + } |
| + } |
| + if strings.Contains(v.logs.String(), sentinel) { |
| + t.Error("a log line holds the key") |
| + } |
| +} |
| + |
| +// What goes out is the query, the count and the key: nothing else. |
| +func TestNoPersonDataInSearchRequest(t *testing.T) { |
| + v := newVendor(t) |
| + answering(v, 200, fixture(t, "kagi_empty")) |
| + for _, name := range []string{websearch.Kagi, websearch.Mojeek, websearch.Brave} { |
| + _, _ = newBackend(t, name, v).Search(context.Background(), "dublin weather", 8) |
| + } |
| + reqs, bodies := v.requests() |
| + allowed := map[string]bool{"User-Agent": true, "Accept": true, "Accept-Encoding": true, "Content-Type": true, "Content-Length": true, "Connection": true, "Authorization": true, "X-Subscription-Token": true} |
| + for i, r := range reqs { |
| + for k := range r.Header { |
| + if !allowed[k] { |
| + t.Errorf("%s sent header %s", r.Host, k) |
| + } |
| + } |
| + if r.Header.Get("Cookie") != "" || r.Header.Get("Referer") != "" { |
| + t.Errorf("%s sent a cookie or referer", r.Host) |
| + } |
| + for k := range r.URL.Query() { |
| + if !map[string]bool{"q": true, "fmt": true, "t": true, "date": true, "api_key": true, "count": true}[k] { |
| + t.Errorf("%s sent parameter %s", r.Host, k) |
| + } |
| + } |
| + if len(bodies[i]) > 0 && r.Host != "kagi.com" { |
| + t.Errorf("%s got a body", r.Host) |
| + } |
| + } |
| +} |
| + |
| +func fakes() (*websearchtest.Fake, *websearchtest.Fake, *websearchtest.MemUsage) { |
| + return &websearchtest.Fake{Backend: "kagi", Results: map[string][]websearch.Result{}}, &websearchtest.Fake{Backend: "mojeek", Results: map[string][]websearch.Result{}}, |
| + &websearchtest.MemUsage{Caps: map[string]int{"kagi": 10, "mojeek": 10}, Month: "2026-11"} |
| +} |
| + |
| +var hit = []websearch.Result{{Title: "Dublin", URL: "https://www.met.ie/"}} |
| + |
| +func TestChainFallsBackOnError(t *testing.T) { |
| + p, f, u := fakes() |
| + p.Fail = map[string]*websearch.Error{"q": {Class: websearch.ClassUnavailable}} |
| + f.Results["q"] = hit |
| + got, backend, err := websearch.Chain{Primary: p, Fallback: f, Usage: u}.Search(context.Background(), "q", 8, nil) |
| + if err != nil || backend != "mojeek" || len(got) != 1 || p.Asked() != 1 || f.Asked() != 1 { |
| + t.Errorf("%+v %q %v", got, backend, err) |
| + } |
| +} |
| + |
| +func TestChainFallsBackOnEmpty(t *testing.T) { |
| + p, f, u := fakes() |
| + f.Results["q"] = hit |
| + got, backend, err := websearch.Chain{Primary: p, Fallback: f, Usage: u}.Search(context.Background(), "q", 8, nil) |
| + if err != nil || backend != "mojeek" || len(got) != 1 { |
| + t.Errorf("%+v %q %v", got, backend, err) |
| + } |
| + f.Results["q"] = nil |
| + if got, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err != nil || len(got) != 0 { |
| + t.Errorf("nothing anywhere: %+v %v", got, err) |
| + } |
| +} |
| + |
| +func TestChainFallsBackOnCap(t *testing.T) { |
| + p, f, u := fakes() |
| + u.Caps["kagi"] = 0 |
| + f.Results["q"] = hit |
| + if _, backend, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err != nil || backend != "mojeek" || p.Asked() != 0 { |
| + t.Errorf("%q %v", backend, err) |
| + } |
| +} |
| + |
| +func TestChainNoFallbackConfigured(t *testing.T) { |
| + p, _, u := fakes() |
| + p.Fail = map[string]*websearch.Error{"q": {Class: websearch.ClassAuth}} |
| + if _, _, err := (websearch.Chain{Primary: p, Usage: u}).Search(context.Background(), "q", 8, nil); class(err) != websearch.ClassAuth { |
| + t.Errorf("%v", err) |
| + } |
| +} |
| + |
| +func TestChainBothCapsSpentIsLimit(t *testing.T) { |
| + p, f, u := fakes() |
| + u.Caps = map[string]int{} |
| + if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); class(err) != websearch.ClassLimit || p.Asked()+f.Asked() != 0 { |
| + t.Errorf("%v", err) |
| + } |
| +} |
| + |
| +// before runs once per backend; its refusal for the fallback means no |
| +// fallback request and no reservation for it. |
| +func TestBeforeRunsForEachBackend(t *testing.T) { |
| + p, f, u := fakes() |
| + f.Results["q"] = hit |
| + var asked []string |
| + before := func(_ context.Context, backend string) error { |
| + asked = append(asked, backend) |
| + if backend == "mojeek" { |
| + return errors.New("web off") |
| + } |
| + return nil |
| + } |
| + if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, before); err == nil || err.Error() != "web off" { |
| + t.Fatalf("%v", err) |
| + } |
| + if strings.Join(asked, ",") != "kagi,mojeek" || f.Asked() != 0 || u.Used[websearch.Reservation{Backend: "mojeek", Month: "2026-11"}] != 0 { |
| + t.Errorf("asked %v, fallback %d, reserved %v", asked, f.Asked(), u.Used) |
| + } |
| +} |
| + |
| +// Each request sent holds one reservation: the primary spent, one |
| +// fallback request and one reservation; a refused before, none; a |
| +// refusal at the final check returns its reservation. |
| +func TestCapReservedOncePerRequest(t *testing.T) { |
| + p, f, u := fakes() |
| + u.Caps["kagi"] = 0 |
| + f.Results["q"] = hit |
| + if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err != nil || u.Taken != 1 || f.Asked() != 1 { |
| + t.Fatalf("%v taken %d", err, u.Taken) |
| + } |
| + p, f, u = fakes() |
| + if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, func(context.Context, string) error { return errors.New("off") }); err == nil || u.Taken != 0 { |
| + t.Errorf("refused before: %v taken %d", err, u.Taken) |
| + } |
| + p, f, u = fakes() |
| + p.Hook = func(context.Context, string) error { return errors.New("refused at the final check") } |
| + if _, _, err := (websearch.Chain{Primary: p, Fallback: f, Usage: u}).Search(context.Background(), "q", 8, nil); err == nil || f.Asked() != 0 || u.Used[websearch.Reservation{Backend: "kagi", Month: "2026-11"}] != 0 { |
| + t.Errorf("final refusal: %v, fallback %d, used %v", err, f.Asked(), u.Used) |
| + } |
| +} |
| + |
| +// usageDB is a database with the usage table. |
| +func usageDB(t *testing.T) *db.DB { |
| + t.Helper() |
| + d, err := db.Open(filepath.Join(t.TempDir(), "usage.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = d.Close() }) |
| + if err := d.G.Exec("CREATE TABLE chat_web_search_usage (backend text, month text, used integer, PRIMARY KEY (backend, month))").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return d |
| +} |
| + |
| +func TestMonthlyCapResetsByUTCMonth(t *testing.T) { |
| + d := usageDB(t) |
| + now := time.Date(2026, 11, 30, 23, 0, 0, 0, time.UTC) |
| + u := websearch.DBUsage{DB: d.G, Caps: map[string]int{"kagi": 2}, Now: func() time.Time { return now }} |
| + ctx := context.Background() |
| + for i, want := range []bool{true, true, false} { |
| + if _, ok, err := u.Take(ctx, "kagi"); err != nil || ok != want { |
| + t.Errorf("take %d: %v %v", i, ok, err) |
| + } |
| + } |
| + now = time.Date(2026, 12, 1, 0, 0, 1, 0, time.UTC) |
| + if _, ok, err := u.Take(ctx, "kagi"); err != nil || !ok { |
| + t.Errorf("a new month: %v %v", ok, err) |
| + } |
| + if _, ok, _ := u.Take(ctx, "brave"); ok { |
| + t.Error("a backend with no cap took one") |
| + } |
| +} |
| + |
| +// A reservation taken just before midnight at the month's end and |
| +// refused after it refunds the old month; concurrent takes in both |
| +// months are counted right. |
| +func TestReturnRefundsItsOwnMonth(t *testing.T) { |
| + d := usageDB(t) |
| + var mu sync.Mutex |
| + now := time.Date(2026, 11, 30, 23, 59, 59, 0, time.UTC) |
| + clock := func() time.Time { mu.Lock(); defer mu.Unlock(); return now } |
| + u := websearch.DBUsage{DB: d.G, Caps: map[string]int{"kagi": 100}, Now: clock} |
| + ctx := context.Background() |
| + r, ok, err := u.Take(ctx, "kagi") |
| + if err != nil || !ok || r.Month != "2026-11" { |
| + t.Fatal(r, ok, err) |
| + } |
| + mu.Lock() |
| + now = time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC) |
| + mu.Unlock() |
| + var wg sync.WaitGroup |
| + for range 5 { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); _, _, _ = u.Take(ctx, "kagi") }() |
| + } |
| + wg.Wait() |
| + if err := u.Return(ctx, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + used := map[string]int{} |
| + rows, err := d.G.Raw("SELECT month, used FROM chat_web_search_usage WHERE backend = 'kagi'").Rows() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var m string |
| + var n int |
| + _ = rows.Scan(&m, &n) |
| + used[m] = n |
| + } |
| + if used["2026-11"] != 0 || used["2026-12"] != 5 { |
| + t.Errorf("used %v", used) |
| + } |
| +} |
| + |
| +func TestBackendSwapByConfig(t *testing.T) { |
| + env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } |
| + c := websearch.ParseConfig(env(nil)) |
| + if c.Primary != "kagi" || c.Fallback != "" { |
| + t.Errorf("defaults %+v", c) |
| + } |
| + v := newVendor(t) |
| + c = websearch.ParseConfig(env(map[string]string{"EQUIPO_WEB_SEARCH": "brave", "EQUIPO_BRAVE_KEY": sentinel, "EQUIPO_BRAVE_MONTHLY_CAP": "500"})) |
| + chain, ok, err := websearch.FromConfig(c, v.guard(), &websearchtest.MemUsage{}) |
| + if err != nil || !ok || chain.Primary.Name() != "brave" || chain.Fallback != nil { |
| + t.Errorf("brave only: %+v %v %v", chain, ok, err) |
| + } |
| + c = websearch.ParseConfig(env(map[string]string{"EQUIPO_KAGI_KEY": sentinel, "EQUIPO_KAGI_MONTHLY_CAP": "1000", "EQUIPO_WEB_SEARCH_FALLBACK": "mojeek", "EQUIPO_MOJEEK_KEY": "m", "EQUIPO_MOJEEK_MONTHLY_CAP": "10"})) |
| + chain, ok, err = websearch.FromConfig(c, v.guard(), &websearchtest.MemUsage{}) |
| + if err != nil || !ok || chain.Primary.Name() != "kagi" || chain.Fallback == nil || chain.Fallback.Name() != "mojeek" { |
| + t.Errorf("kagi then mojeek: %+v %v %v", chain, ok, err) |
| + } |
| +} |
| + |
| +// A backend named without a key or a cap is left out, its name logged, |
| +// never its value. |
| +func TestMisconfiguredBackendLeftOut(t *testing.T) { |
| + v := newVendor(t) |
| + env := map[string]string{"EQUIPO_KAGI_KEY": sentinel, "EQUIPO_KAGI_MONTHLY_CAP": "0"} |
| + _, ok, err := websearch.FromConfig(websearch.ParseConfig(func(k string) string { return env[k] }), v.guard(), &websearchtest.MemUsage{}) |
| + if err != nil || ok { |
| + t.Errorf("no cap: %v %v", ok, err) |
| + } |
| + if !strings.Contains(v.logs.String(), "web_search.misconfigured") || !strings.Contains(v.logs.String(), "backend=kagi") || strings.Contains(v.logs.String(), sentinel) { |
| + t.Errorf("log %q", v.logs.String()) |
| + } |
| + env = map[string]string{"EQUIPO_KAGI_MONTHLY_CAP": "10"} |
| + if _, ok, _ := websearch.FromConfig(websearch.ParseConfig(func(k string) string { return env[k] }), v.guard(), &websearchtest.MemUsage{}); ok { |
| + t.Error("no key: usable") |
| + } |
| +} |
diff --git a/internal/websearch/websearchtest/fake.go b/internal/websearch/websearchtest/fake.go| new file mode 100644 |
| index 00000000..a3472e8e |
| --- /dev/null |
| +++ b/internal/websearch/websearchtest/fake.go |
| @@ -0,0 +1,87 @@ |
| +// Package websearchtest is a fake search backend for tests: no network. |
| +package websearchtest |
| + |
| +import ( |
| + "context" |
| + "sync" |
| + |
| + "amadan.net/oficina/equipo/internal/websearch" |
| +) |
| + |
| +// Fake answers each query from Results, or fails it with Fail, and |
| +// records the queries it was asked, in order. Backend is its name |
| +// (fake when empty). |
| +type Fake struct { |
| + Backend string |
| + Results map[string][]websearch.Result |
| + Fail map[string]*websearch.Error |
| + // Hook, when set, runs first with the query; an error it returns is |
| + // the answer (as a refusal at the final check would be). |
| + Hook func(ctx context.Context, q string) error |
| + |
| + mu sync.Mutex |
| + Calls []string |
| +} |
| + |
| +func (f *Fake) Name() string { |
| + if f.Backend == "" { |
| + return "fake" |
| + } |
| + return f.Backend |
| +} |
| + |
| +func (f *Fake) Search(ctx context.Context, q string, _ int) ([]websearch.Result, error) { |
| + if f.Hook != nil { |
| + if err := f.Hook(ctx, q); err != nil { |
| + return nil, err |
| + } |
| + } |
| + f.mu.Lock() |
| + f.Calls = append(f.Calls, q) |
| + f.mu.Unlock() |
| + if e := f.Fail[q]; e != nil { |
| + return nil, &websearch.Error{Backend: f.Name(), Class: e.Class} |
| + } |
| + return f.Results[q], nil |
| +} |
| + |
| +// Asked is how many queries it was asked. |
| +func (f *Fake) Asked() int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return len(f.Calls) |
| +} |
| + |
| +// MemUsage is an in-memory Usage: caps by backend, counts by backend and |
| +// month, the month set by the test. |
| +type MemUsage struct { |
| + mu sync.Mutex |
| + Caps map[string]int |
| + Month string |
| + Used map[websearch.Reservation]int |
| + Taken int |
| +} |
| + |
| +func (u *MemUsage) Take(_ context.Context, backend string) (websearch.Reservation, bool, error) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + if u.Used == nil { |
| + u.Used = map[websearch.Reservation]int{} |
| + } |
| + r := websearch.Reservation{Backend: backend, Month: u.Month} |
| + if u.Used[r] >= u.Caps[backend] { |
| + return r, false, nil |
| + } |
| + u.Used[r]++ |
| + u.Taken++ |
| + return r, true, nil |
| +} |
| + |
| +func (u *MemUsage) Return(_ context.Context, r websearch.Reservation) error { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + if u.Used[r] > 0 { |
| + u.Used[r]-- |
| + } |
| + return nil |
| +} |