oficina / equipo Public

Lookups: web_lookup, run by the instance from the person's words

Task 3.7: the web provider's one read-only operation, with an empty
input, listed only for a person turn, a usable backend, a confirmed
inventory, a primary at protocol 36 and a Base that draws answers. The
run: the pack; typed addresses read, or a query step, its queries
refused when they look secret, and a search; the top 3 results read by
rank through the guarded page client, every hop paced per host, denied
the instance's and the person's app hosts (base_apps on a gate of its
own, cached 60 s, kept 10 min, failing closed) and gated right before
sending; an answer step cut to the frame budget; the lookup stored with
numbers only and audited by domains. The Assistant gets fixed text.
Caps: 2 per turn, 100 a day, 40 s. Registered after the team's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 00a865146c20726fbdf6a85a1b26db5123ccabc2 parent 67986c4
8 files changed, +1,206 −4
  • internal/equipo/app.go +3 −0
  • internal/equipo/chat/lookup.go +465 −0
  • internal/equipo/chat/lookup_test.go +516 −0
  • internal/equipo/chat/store.go +4 −2
  • internal/equipo/chat/web_provider.go +173 −0
  • internal/equipo/chat_wiring.go +1 −1
  • internal/equipo/config.go +1 −1
  • internal/equipo/lookups_wiring.go +43 −0
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index c33a854d..ebcced5c 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -226,6 +226,9 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
}
// What the Assistant's provider calls could not do, by call id only.
store.Chat().SetLogger(logger)
+ if err := store.setupLookups(cfg, logger); err != nil {
+ return nil, err
+ }
if cfg.OficinaConnectOrigin != "" {
// The Oficina apps, through oficina-connect.
if store.oficina, err = oficina.New(cfg.oficinaConfig(), oficinaStore{store}, oficinaSealer{store}); err != nil {
diff --git a/internal/equipo/chat/lookup.go b/internal/equipo/chat/lookup.go
new file mode 100644
index 00000000..3ebd0f39
--- /dev/null
+++ b/internal/equipo/chat/lookup.go
@@ -0,0 +1,465 @@
+package chat
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/url"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/assist"
+ "amadan.net/oficina/equipo/internal/websearch"
+ "amadan.net/oficina/equipo/internal/websource"
+ "amadan.net/oficina/equipo/internal/websource/guard"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// A lookup, step by step (spec 2026-11-26-assistant-abilities §4.2): the
+// pack from the person's words; the addresses they typed, or a query
+// step and a search; reads of the top results, picked by rank in this
+// code; an answer step; the answer stored and shown under the reply,
+// never handed back. Every search and read goes through the guarded
+// client, paced per host and gated right before it is sent.
+
+// Lookup bounds.
+const (
+ lookupLimit = 40 * time.Second
+ lookupsPerTurn = 2
+ lookupsPerDay = 100
+ lookupReads = 3
+ lookupTries = 6
+ lookupPageText = 16 << 10
+ lookupDenyFresh = 60 * time.Second
+ lookupDenyKeep = 10 * time.Minute
+ auditLookup = "assistant.lookup"
+)
+
+// What the Assistant gets back: fixed instance text, never page text or
+// the answer (§4.2 step 8). Reviewed as code.
+const (
+ toolLookupShown = "Looked up and shown to the person under your reply, with its sources. You can't see it. Don't guess or repeat what it says. If they want something done with it, they'll tell you in their own words: ask for what you need, for example \"Want me to put a visit in your calendar? Tell me the day and time.\""
+ toolLookupFailed = "The lookup didn't work. Tell the person in one line, for example \"I couldn't find that just now.\""
+ toolNothingFound = "Nothing was found for that. Tell the person in one line, for example \"I couldn't find that just now.\""
+ toolLookupLimit = "No more lookups can run for now. Tell the person in one line that you can't look that up just now."
+ toolLookupUnsupported = "A lookup can't run for this message. Tell the person in one line that you can't look that up here."
+ toolLookupInput = "web_lookup takes no input: it works from what the person asked."
+)
+
+var lookupTexts = map[string]string{wire.CodeLookupFailed: toolLookupFailed, wire.CodeNothingFound: toolNothingFound, wire.CodeLookupLimit: toolLookupLimit, wire.CodeLookupUnsupported: toolLookupUnsupported}
+
+// lookupQuery is one query and the backend that answered it.
+type lookupQuery struct {
+ Q string `json:"q"`
+ Backend string `json:"backend"`
+}
+
+// lookupRead is one page read, by its numbers only.
+type lookupRead struct {
+ URL string `json:"url"`
+ FinalURL string `json:"final_url,omitempty"`
+ Status int `json:"status,omitempty"`
+ Bytes int `json:"bytes,omitempty"`
+ SHA256 string `json:"sha256,omitempty"`
+ Code string `json:"code,omitempty"`
+}
+
+// lookupRun is one lookup's state while it runs.
+type lookupRun struct {
+ s *Store
+ cfg *LookupConfig
+ call toolCallRecord
+ row lookupRecord
+ deny []string
+ queries []lookupQuery
+ reads []lookupRead
+ domains []string
+}
+
+// webLookup runs the call's lookup and is the Assistant's result: the
+// fixed shown result, or a code with fixed text. A delivery retry of the
+// same call id answers as the first did.
+func (s *Store) webLookup(ctx context.Context, call toolCallRecord) (json.RawMessage, error) {
+ if why := s.lookupUnsupported(ctx, call.Person); why != "" {
+ return nil, lookupFailure(wire.CodeLookupUnsupported)
+ }
+ if kind, err := s.turnKind(ctx, call); err != nil || kind != wire.TurnPerson {
+ return nil, lookupFailure(wire.CodeLookupUnsupported)
+ }
+ cfg := s.lookups.cfg.Load()
+ ctx, cancel := context.WithTimeout(ctx, lookupLimit)
+ defer cancel()
+ run := &lookupRun{s: s, cfg: cfg, call: call}
+ var pack wire.LookupPack
+ var replay *lookupRecord
+ err := s.tx(ctx, func(t *txn) error {
+ var prior lookupRecord
+ if err := t.db.Where("call_id = ? AND person = ?", call.CallID, call.Person).Limit(1).Find(&prior).Error; err != nil || prior.ID != "" {
+ replay = &prior
+ return err
+ }
+ var turn turnRecord
+ if err := t.db.Where("id = ? AND person = ?", call.TurnID, call.Person).First(&turn).Error; err != nil {
+ return err
+ }
+ var inTurn, today int64
+ if err := t.db.Model(&lookupRecord{}).Where("turn_id = ? AND attempt = ?", call.TurnID, call.Attempt).Count(&inTurn).Error; err != nil {
+ return err
+ }
+ if err := t.db.Model(&lookupRecord{}).Where("person = ? AND created_at > ?", call.Person, t.now().Add(-24*time.Hour)).Count(&today).Error; err != nil {
+ return err
+ }
+ run.row = lookupRecord{ID: newID("lk"), Person: call.Person, TurnID: call.TurnID, Attempt: call.Attempt, Seq: inTurn + 1, CallID: call.CallID, State: lookupRunning, CreatedAt: t.now()}
+ if inTurn >= lookupsPerTurn || today >= lookupsPerDay {
+ run.row.State, run.row.Code = lookupFailed, wire.CodeLookupLimit
+ return t.db.Create(&run.row).Error
+ }
+ var ok bool
+ var err error
+ if pack, ok, err = t.lookupPack(call.Person, turn, t.now()); err != nil {
+ return err
+ }
+ if !ok {
+ run.row.State, run.row.Code = lookupFailed, wire.CodeLookupUnsupported
+ }
+ return t.db.Create(&run.row).Error
+ })
+ if err != nil {
+ return nil, err
+ }
+ if replay != nil {
+ return lookupResult(*replay)
+ }
+ if run.row.State == lookupFailed {
+ return lookupResult(run.row)
+ }
+ answer, sources, code, err := run.do(ctx, pack)
+ var refusal assist.Refusal
+ if errors.As(err, &refusal) {
+ // The gate refused (web turned off meanwhile): nothing more was
+ // sent. The refusal is the Assistant's answer.
+ run.finish(context.WithoutCancel(ctx), "", nil, refusal.Code)
+ return nil, refusal
+ }
+ if err != nil {
+ code = wire.CodeLookupFailed
+ }
+ run.finish(context.WithoutCancel(ctx), answer, sources, code)
+ return lookupResult(run.row)
+}
+
+func lookupFailure(code string) error {
+ return assist.Refusal{Code: code, Message: lookupTexts[code]}
+}
+
+// lookupResult is a stored lookup as the Assistant's result.
+func lookupResult(r lookupRecord) (json.RawMessage, error) {
+ if r.State != lookupShown {
+ code := r.Code
+ if lookupTexts[code] == "" {
+ if code == "" || code == wire.CodeLookupShown {
+ code = wire.CodeLookupFailed
+ } else {
+ return nil, assist.Refusal{Code: code, Message: toolOpUnavailable}
+ }
+ }
+ return nil, lookupFailure(code)
+ }
+ var sources []wire.LookupSource
+ _ = json.Unmarshal([]byte(r.Sources), &sources)
+ out, _ := json.Marshal(map[string]any{"code": wire.CodeLookupShown, "sources": len(sources), "text": toolLookupShown})
+ return out, nil
+}
+
+// do runs steps 2 to 6: what to read, the reads, the answer.
+func (r *lookupRun) do(ctx context.Context, pack wire.LookupPack) (answer string, sources []wire.LookupSource, code string, err error) {
+ deny, err := r.s.lookupDeny(ctx, r.call.Person)
+ if err != nil {
+ return "", nil, wire.CodeLookupFailed, nil
+ }
+ r.deny = append(slices.Clone(r.cfg.Deny), deny...)
+ var results []wire.SearchResult
+ var candidates []string
+ if typed := websource.Mentions(pack.Question); len(typed) > 0 {
+ for i, u := range typed {
+ if i == lookupReads {
+ break
+ }
+ candidates = append(candidates, u.String())
+ }
+ } else {
+ q, err := r.s.lookupStep(ctx, r.call.Person, wire.LookupStep{Lookup: r.row.ID, Attempt: int(r.row.Attempt), Stage: wire.LookupStageQuery, Pack: pack})
+ if err != nil || q.Code != "" || wire.ValidQueryResult(q) != nil {
+ return "", nil, wire.CodeLookupFailed, err
+ }
+ for _, query := range q.Queries {
+ if websource.LooksSecret(query) {
+ return "", nil, wire.CodeLookupFailed, nil
+ }
+ }
+ for _, query := range q.Queries {
+ got, backend, err := r.cfg.Search.Search(r.searchCtx(ctx), query, websearch.MaxResults, func(ctx context.Context, _ string) error { return assist.Gate(ctx, webLookupOp) })
+ var refusal assist.Refusal
+ if errors.As(err, &refusal) {
+ return "", nil, "", refusal
+ }
+ var be *websearch.Error
+ if errors.As(err, &be) && be.Class == websearch.ClassLimit {
+ return "", nil, wire.CodeLookupLimit, nil
+ }
+ if err != nil {
+ continue
+ }
+ r.queries = append(r.queries, lookupQuery{Q: query, Backend: backend})
+ for _, g := range got {
+ if !slices.ContainsFunc(results, func(x wire.SearchResult) bool { return x.URL == g.URL }) {
+ results = append(results, wire.SearchResult{Title: g.Title, URL: g.URL, Snippet: g.Snippet, Date: g.Date})
+ }
+ }
+ }
+ if len(r.queries) == 0 {
+ return "", nil, wire.CodeLookupFailed, nil
+ }
+ if len(results) == 0 {
+ return "", nil, wire.CodeNothingFound, nil
+ }
+ results = results[:min(len(results), websearch.MaxResults)]
+ for _, res := range results {
+ candidates = append(candidates, res.URL)
+ }
+ }
+ var pages []wire.LookupPage
+ for i, u := range candidates {
+ if len(pages) == lookupReads || i == lookupTries {
+ break
+ }
+ page, err := r.read(ctx, u)
+ if err != nil {
+ return "", nil, "", err
+ }
+ if page != nil {
+ pages = append(pages, *page)
+ }
+ }
+ if len(pages) == 0 && len(results) == 0 {
+ return "", nil, wire.CodeNothingFound, nil
+ }
+ step, truncated := fitAnswerStep(wire.LookupStep{Lookup: r.row.ID, Attempt: int(r.row.Attempt), Stage: wire.LookupStageAnswer, Pack: pack, Results: results, Pages: pages})
+ step.Truncated = truncated
+ a, err := r.s.lookupStep(ctx, r.call.Person, step)
+ if err != nil || a.Code != "" || wire.ValidAnswerResult(a, len(results)) != nil {
+ return "", nil, wire.CodeLookupFailed, err
+ }
+ return a.Answer, lookupSources(pages, results, a.Used), wire.CodeLookupShown, nil
+}
+
+// searchCtx carries the final check for each search request: the pace
+// for the actual host, then the gate, right before it is sent.
+func (r *lookupRun) searchCtx(ctx context.Context) context.Context {
+ return guard.WithBeforeHop(ctx, func(ctx context.Context, host string) error {
+ if err := r.s.lookups.pace.wait(ctx, host); err != nil {
+ return err
+ }
+ return assist.Gate(ctx, webLookupOp)
+ })
+}
+
+// read reads one page through the guarded client, every hop denied the
+// lookup's hosts, paced and gated. A page that can't be read is skipped
+// (nil), its rule noted; the gate refusing is the error.
+func (r *lookupRun) read(ctx context.Context, raw string) (*wire.LookupPage, error) {
+ rd := lookupRead{URL: raw}
+ defer func() { r.reads = append(r.reads, rd) }()
+ u, err := url.Parse(raw)
+ if err != nil || len(raw) > guard.MaxURL {
+ rd.Code = guard.RuleURL
+ return nil, nil
+ }
+ if d := guard.Registrable(u.Hostname()); !slices.Contains(r.domains, d) {
+ r.domains = append(r.domains, d)
+ }
+ req, err := http.NewRequest(http.MethodGet, u.String(), nil)
+ if err != nil {
+ rd.Code = guard.RuleURL
+ return nil, nil
+ }
+ hctx := guard.WithBeforeHop(guard.WithDeny(ctx, r.deny), func(ctx context.Context, host string) error {
+ if err := r.s.lookups.pace.wait(ctx, host); err != nil {
+ return err
+ }
+ return assist.Gate(ctx, webLookupOp)
+ })
+ res, err := r.cfg.Pages.Do(hctx, req)
+ if err != nil {
+ var refusal assist.Refusal
+ if errors.As(err, &refusal) {
+ rd.Code = refusal.Code
+ return nil, refusal
+ }
+ rd.Code = guard.RuleOf(err)
+ if rd.Code == "" {
+ rd.Code = guard.RuleUnavailable
+ }
+ return nil, nil
+ }
+ sum := sha256.Sum256(res.Body)
+ rd.FinalURL, rd.Status, rd.Bytes, rd.SHA256 = res.FinalURL, res.Status, len(res.Body), hex.EncodeToString(sum[:])
+ if res.Status != http.StatusOK {
+ rd.Code = "status"
+ return nil, nil
+ }
+ base, err := websource.Parse(res.FinalURL)
+ if err != nil {
+ rd.Code = guard.RuleURL
+ return nil, nil
+ }
+ title, text := websource.Readable(res.Body, res.Type, base)
+ if strings.TrimSpace(text) == "" {
+ rd.Code = "unsupported_type"
+ return nil, nil
+ }
+ return &wire.LookupPage{URL: res.FinalURL, Title: title, Text: cutRunes(text, lookupPageText)}, nil
+}
+
+// fitAnswerStep cuts the answer step to the runner's frame budget (§4.3):
+// each page at most 16 KiB, then the lowest-ranked page's text first
+// until the whole fits. truncated says it was cut.
+func fitAnswerStep(s wire.LookupStep) (wire.LookupStep, bool) {
+ truncated := false
+ size := func() int { raw, _ := json.Marshal(s); return len(raw) }
+ for i := len(s.Pages) - 1; i >= 0 && size() > wire.MaxLookupStepBytes; i-- {
+ over := size() - wire.MaxLookupStepBytes
+ text := s.Pages[i].Text
+ s.Pages[i].Text = cutRunes(text, len(text)-over-64)
+ truncated = true
+ }
+ for size() > wire.MaxLookupStepBytes && len(s.Results) > 1 {
+ s.Results = s.Results[:len(s.Results)-1]
+ truncated = true
+ }
+ return s, truncated
+}
+
+// lookupSources are the pages read, or else the results the answer used:
+// https only, at most 5.
+func lookupSources(pages []wire.LookupPage, results []wire.SearchResult, used []int) []wire.LookupSource {
+ var out []wire.LookupSource
+ add := func(u, title string) {
+ if len(out) < wire.MaxLookupSources && strings.HasPrefix(u, "https://") && !slices.ContainsFunc(out, func(s wire.LookupSource) bool { return s.URL == u }) {
+ out = append(out, wire.LookupSource{URL: u, Title: cutRunes(strings.TrimSpace(title), 200)})
+ }
+ }
+ for _, p := range pages {
+ add(p.URL, p.Title)
+ }
+ if len(out) == 0 {
+ for _, i := range used {
+ if i >= 0 && i < len(results) {
+ add(results[i].URL, results[i].Title)
+ }
+ }
+ }
+ return out
+}
+
+// finish stores the lookup's outcome and audits it: the person, the
+// numbers of queries and reads, the hosts' registrable domains, the code.
+// Never a query, a path or the answer.
+func (r *lookupRun) finish(ctx context.Context, answer string, sources []wire.LookupSource, code string) {
+ queries, _ := json.Marshal(r.queries)
+ reads, _ := json.Marshal(r.reads)
+ src, _ := json.Marshal(sources)
+ r.row.Queries, r.row.Reads, r.row.Code = string(queries), string(reads), code
+ r.row.State = lookupFailed
+ if code == wire.CodeLookupShown && answer != "" && len(sources) > 0 {
+ r.row.State, r.row.Answer, r.row.Sources = lookupShown, answer, string(src)
+ } else if code == wire.CodeLookupShown {
+ r.row.Code = wire.CodeNothingFound
+ }
+ err := r.s.tx(ctx, func(t *txn) error {
+ if err := t.db.Model(&lookupRecord{}).Where("id = ?", r.row.ID).Select("state", "queries", "reads", "answer", "sources", "code").Updates(&r.row).Error; err != nil {
+ return err
+ }
+ if t.s.authority.Audit == nil {
+ return nil
+ }
+ return t.s.authority.Audit(t.db, r.call.Person, auditLookup, "queries="+strconv.Itoa(len(r.queries))+" reads="+strconv.Itoa(len(r.reads))+" domains="+strings.Join(r.domains, ",")+" code="+r.row.Code)
+ })
+ if err != nil {
+ if l := r.s.logger.Load(); l != nil {
+ l.Warn("lookup not stored", "call", r.call.CallID, "err", err)
+ }
+ }
+}
+
+// lookupDeny is the person's own hosts no lookup may reach: the
+// addresses of their Base's apps and Oficina apps (base_apps, read on a
+// gate of its own), cached for 60 s and kept for at most 10 minutes. With
+// none to be had, the lookup fails.
+func (s *Store) lookupDeny(ctx context.Context, person string) ([]string, error) {
+ now := time.Now()
+ s.lookups.mu.Lock()
+ cached, ok := s.lookups.deny[person]
+ s.lookups.mu.Unlock()
+ if ok && now.Sub(cached.at) < lookupDenyFresh {
+ return cached.hosts, nil
+ }
+ hosts, err := s.baseAppOrigins(ctx, person)
+ if err != nil {
+ if ok && now.Sub(cached.at) < lookupDenyKeep {
+ return cached.hosts, nil
+ }
+ return nil, err
+ }
+ s.lookups.mu.Lock()
+ if s.lookups.deny == nil {
+ s.lookups.deny = map[string]denyEntry{}
+ }
+ s.lookups.deny[person] = denyEntry{hosts: hosts, at: now}
+ s.lookups.mu.Unlock()
+ return hosts, nil
+}
+
+// baseAppOrigins are the hosts of the person's apps as their Base reports
+// them (base_apps): an instance-owned read on its own gate.
+func (s *Store) baseAppOrigins(ctx context.Context, person string) ([]string, error) {
+ ops := s.operations()
+ if ops == nil {
+ return nil, errors.New("lookup: no operations")
+ }
+ op, err := ops.Describe(ctx, person, "base_apps")
+ if err != nil {
+ return nil, err
+ }
+ raw, err := ops.Invoke(assist.WithGate(ctx, s.sendGate(ctx, person, op)), person, "base_apps", json.RawMessage(`{}`), "")
+ if err != nil {
+ return nil, err
+ }
+ var apps struct {
+ Installed []struct {
+ Address string `json:"address"`
+ } `json:"installed"`
+ Oficina []struct {
+ Address string `json:"address"`
+ } `json:"oficina"`
+ }
+ if err := json.Unmarshal(raw, &apps); err != nil {
+ return nil, err
+ }
+ var hosts []string
+ for _, a := range append(apps.Installed, apps.Oficina...) {
+ u, err := url.Parse(strings.TrimSpace(a.Address))
+ if err != nil || u.Hostname() == "" {
+ continue
+ }
+ if h := strings.ToLower(u.Hostname()); !slices.Contains(hosts, h) {
+ hosts = append(hosts, h)
+ }
+ }
+ return hosts, nil
+}
diff --git a/internal/equipo/chat/lookup_test.go b/internal/equipo/chat/lookup_test.go
new file mode 100644
index 00000000..d844e49c
--- /dev/null
+++ b/internal/equipo/chat/lookup_test.go
@@ -0,0 +1,516 @@
+package chat
+
+import (
+ "context"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/json"
+ "errors"
+ "math/big"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/assist"
+ "amadan.net/oficina/equipo/internal/websearch"
+ "amadan.net/oficina/equipo/internal/websearch/websearchtest"
+ "amadan.net/oficina/equipo/internal/websource/guard"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+const pageSentinel = "SENTINEL-WEB-TEXT-991"
+
+type readyInv struct{ ready bool }
+
+func (i readyInv) Ready(context.Context) error {
+ if !i.ready {
+ return guard.ErrInventoryUnconfirmed
+ }
+ return nil
+}
+func (readyInv) Inside(netip.Addr) bool { return false }
+
+// fakeBase is Base's base_apps as the registry reaches it.
+type fakeBase struct {
+ apps string
+ fail bool
+}
+
+func (fakeBase) Name() string { return "base" }
+func (fakeBase) List(context.Context, string) ([]assist.Operation, error) {
+ return []assist.Operation{{Provider: "base", Name: "base_apps", App: "Base", Scope: "base.read", ReadOnly: true, Idempotent: true, Input: json.RawMessage(`{"type":"object"}`)}}, nil
+}
+func (b fakeBase) Invoke(ctx context.Context, _, op string, _ json.RawMessage, _ string) (json.RawMessage, error) {
+ if err := assist.Gate(ctx, assist.Operation{Provider: "base", Name: op, App: "Base", Scope: "base.read", ReadOnly: true, Idempotent: true, Input: json.RawMessage(`{"type":"object"}`)}); err != nil {
+ return nil, err
+ }
+ if b.fail {
+ return nil, assist.Failure{Code: "unavailable"}
+ }
+ return json.RawMessage(b.apps), nil
+}
+
+// web is the public web the lookup reads: one TLS server answering as
+// every host, recording each request by host and path.
+type web struct {
+ srv *httptest.Server
+ roots *x509.CertPool
+ mu sync.Mutex
+ got []string
+ pages map[string]func(w http.ResponseWriter, r *http.Request)
+}
+
+func newWeb(t *testing.T) *web {
+ t.Helper()
+ key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ hosts := []string{"www.met.ie", "news.example.org", "shop.paul.example.org", "cal.oficina.works", "other.example.org", "www.bbc.com"}
+ tmpl := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "web"}, DNSNames: hosts, 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, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
+ cert, _ := x509.ParseCertificate(der)
+ w := &web{roots: x509.NewCertPool(), pages: map[string]func(http.ResponseWriter, *http.Request){}}
+ w.roots.AddCert(cert)
+ w.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+ w.mu.Lock()
+ w.got = append(w.got, r.Host+r.URL.Path)
+ h := w.pages[r.Host+r.URL.Path]
+ w.mu.Unlock()
+ if h == nil {
+ rw.Header().Set("Content-Type", "text/html")
+ _, _ = rw.Write([]byte("<html><title>" + r.Host + "</title><body><p>Rain at first, 11 degrees. " + pageSentinel + "</p></body></html>"))
+ return
+ }
+ h(rw, r)
+ }))
+ w.srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}
+ w.srv.StartTLS()
+ t.Cleanup(w.srv.Close)
+ return w
+}
+
+func (w *web) requests() []string {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return append([]string(nil), w.got...)
+}
+
+// lookupRig is a person with web on, a Base drawing answers, a primary
+// at protocol 36 whose model answers the two steps, a search backend and
+// the web.
+type lookupRig struct {
+ t *testing.T
+ h *abilitiesHarness
+ base *fakeBoardBase
+ web *web
+ search *websearchtest.Fake
+ usage *websearchtest.MemUsage
+ apps *fakeBase
+ steps []wire.LookupStep
+ mu sync.Mutex
+ queries []string
+ answer string
+ n int
+ detach func()
+}
+
+func newLookupRig(t *testing.T) *lookupRig {
+ t.Helper()
+ h, base := boardBase(t)
+ refresh(t, h)
+ ctx := context.Background()
+ if err := h.s.SetCapabilities(ctx, abPerson, wire.CapLookupAnswers); err != nil {
+ t.Fatal(err)
+ }
+ r := &lookupRig{t: t, h: h, base: base, web: newWeb(t), search: &websearchtest.Fake{Backend: "kagi", Results: map[string][]websearch.Result{}},
+ usage: &websearchtest.MemUsage{Caps: map[string]int{"kagi": 1000}, Month: "2026-11"}, apps: &fakeBase{apps: `{"installed":[{"address":"https://shop.paul.example.org"}],"oficina":[{"address":"https://cal.oficina.works"}]}`},
+ queries: []string{"dublin weather"}, answer: "Rain at first, 11 degrees."}
+ g := guard.Config{Inventory: readyInv{true}, 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 r.web.srv.Listener.Addr().String(), r.web.roots }}
+ pageCfg := g
+ pageCfg.Policy, pageCfg.Redirects = guard.PolicyLookupPage, guard.MaxRedirects
+ pages, err := guard.New(pageCfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.s.SetLookups(&LookupConfig{Search: websearch.Chain{Primary: r.search, Usage: r.usage}, Pages: pages, Inventory: g.Inventory, Deny: []string{"equipo.example.org"}})
+ h.s.SetOperations(assist.NewRegistry(r.apps, h.s.WebProvider()))
+ r.detach = h.s.attachLive("RUNNER1", wire.ProtocolLookup, func(_ context.Context, f wire.Frame) error {
+ body, err := f.Decode()
+ if err != nil {
+ return err
+ }
+ s := *body.(*wire.LookupStep)
+ r.mu.Lock()
+ r.steps = append(r.steps, s)
+ res := wire.LookupResult{Lookup: s.Lookup, Attempt: s.Attempt, Nonce: s.Nonce, Stage: s.Stage}
+ if s.Stage == wire.LookupStageQuery {
+ res.Queries = r.queries
+ } else {
+ res.Answer, res.Used = r.answer, []int{}
+ if len(s.Results) > 0 {
+ res.Used = []int{0}
+ }
+ }
+ r.mu.Unlock()
+ h.s.deliverLookup("RUNNER1", res)
+ return nil
+ })
+ return r
+}
+
+// ask is a person turn with words as its composer message, and the call
+// in it; kind is the turn's kind.
+func (r *lookupRig) ask(words, kind string) toolCallRecord {
+ r.t.Helper()
+ r.n++
+ id := "lt" + itoa64(int64(r.n))
+ now := r.h.now()
+ turn := turnRecord{ID: id, Person: abPerson, State: wire.TurnRunning, Kind: kind, Lane: wire.LaneAssistant, Attempt: 1, CreatedAt: now, UpdatedAt: now}
+ m := messageRecord{ID: "lm" + id, Person: abPerson, IdempotencyKey: "lk" + id, Role: wire.RolePerson, Origin: originComposer, Text: words, TurnID: id, Lane: wire.LaneAssistant, CreatedAt: now}
+ call := toolCallRecord{CallID: "lc" + id, Person: abPerson, TurnID: id, Attempt: 1, Name: wire.ToolUse, CreatedAt: now}
+ for _, row := range []any{&turn, &m, &call} {
+ if err := r.h.s.db.G.Create(row).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ }
+ return call
+}
+
+// lookup runs web_lookup for call as the Assistant's use does.
+func (r *lookupRig) lookup(call toolCallRecord, input string) (json.RawMessage, error) {
+ r.t.Helper()
+ ctx := context.Background()
+ gated := assist.WithGate(withCall(ctx, call), r.h.s.sendGate(ctx, abPerson, webLookupOp))
+ return r.h.s.WebProvider().Invoke(gated, abPerson, opWebLookup, json.RawMessage(input), call.CallID)
+}
+
+func codeOf(err error) string {
+ var ref assist.Refusal
+ if errors.As(err, &ref) {
+ return ref.Code
+ }
+ var f assist.Failure
+ if errors.As(err, &f) {
+ return f.Code
+ }
+ return ""
+}
+
+func (r *lookupRig) row(call toolCallRecord) lookupRecord {
+ r.t.Helper()
+ var row lookupRecord
+ if err := r.h.s.db.G.Where("call_id = ?", call.CallID).First(&row).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ return row
+}
+
+func (r *lookupRig) webOff() {
+ r.base.set(func(f *fakeBoardBase) { f.board.Abilities["web"], f.board.Revision = false, f.board.Revision+1 })
+ if _, _, err := r.h.s.RefreshAbilities(context.Background(), abPerson); err != nil {
+ r.t.Fatal(err)
+ }
+}
+
+func TestLookupInputIsEmpty(t *testing.T) {
+ r := newLookupRig(t)
+ if _, err := r.lookup(r.ask("Weather in Dublin?", wire.TurnPerson), `{"q":"dublin"}`); codeOf(err) != "invalid_input" {
+ t.Errorf("an input: %v", err)
+ }
+ if string(webLookupOp.Input) != `{"type":"object","additionalProperties":false}` || !webLookupOp.ReadOnly {
+ t.Errorf("op %+v", webLookupOp)
+ }
+}
+
+// Only in a turn the person started: a team_update (a connect's resume
+// turn included) is refused, and doesn't list it.
+func TestLookupsOnlyInPersonTurns(t *testing.T) {
+ r := newLookupRig(t)
+ call := r.ask("Weather in Dublin?", wire.TurnTeamUpdate)
+ if _, err := r.lookup(call, `{}`); codeOf(err) != wire.CodeLookupUnsupported {
+ t.Errorf("in a team_update: %v", err)
+ }
+ if ops, _ := r.h.s.WebProvider().List(withCall(context.Background(), call), abPerson); len(ops) != 0 {
+ t.Errorf("listed in a team_update: %v", ops)
+ }
+ if ops, _ := r.h.s.WebProvider().List(withCall(context.Background(), r.ask("Weather?", wire.TurnPerson)), abPerson); len(ops) != 1 {
+ t.Errorf("not listed in a person turn: %v", ops)
+ }
+}
+
+// The top results are read, in rank order, at most 3; the answer is
+// shown with its sources; the Assistant gets the fixed result only.
+func TestReadsPickedByRank(t *testing.T) {
+ r := newLookupRig(t)
+ r.search.Results["dublin weather"] = []websearch.Result{
+ {Title: "Met", URL: "https://www.met.ie/dublin"}, {Title: "BBC", URL: "https://www.bbc.com/weather"},
+ {Title: "News", URL: "https://news.example.org/weather"}, {Title: "Other", URL: "https://other.example.org/x"},
+ }
+ out, err := r.lookup(r.ask("What's the weather in Dublin?", wire.TurnPerson), `{}`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(r.web.requests(), " "); got != "www.met.ie/dublin www.bbc.com/weather news.example.org/weather" {
+ t.Errorf("read %s", got)
+ }
+ var res struct {
+ Code string `json:"code"`
+ Sources int `json:"sources"`
+ Text string `json:"text"`
+ }
+ if json.Unmarshal(out, &res) != nil || res.Code != wire.CodeLookupShown || res.Sources != 3 || res.Text != toolLookupShown {
+ t.Errorf("result %s", out)
+ }
+}
+
+// What the Assistant gets back never holds the page's text or the answer.
+func TestAssistantNeverSeesWebText(t *testing.T) {
+ r := newLookupRig(t)
+ r.answer = "Rain. " + pageSentinel
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met " + pageSentinel, URL: "https://www.met.ie/dublin", Snippet: pageSentinel}}
+ out, err := r.lookup(r.ask("Weather in Dublin?", wire.TurnPerson), `{}`)
+ if err != nil || strings.Contains(string(out), pageSentinel) || strings.Contains(string(out), "Rain") {
+ t.Errorf("%s %v", out, err)
+ }
+}
+
+// Addresses the person typed are read instead of searching; one of
+// their own Oficina or Base apps is refused, typed or reached by a
+// redirect.
+func TestTypedAddressesRefusedOrSkipped(t *testing.T) {
+ r := newLookupRig(t)
+ r.web.pages["news.example.org/jump"] = func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Location", "https://cal.oficina.works/events")
+ w.WriteHeader(http.StatusFound)
+ }
+ call := r.ask("What does https://shop.paul.example.org/menu and https://news.example.org/jump and https://www.met.ie/today say?", wire.TurnPerson)
+ if _, err := r.lookup(call, `{}`); err != nil {
+ t.Fatal(err)
+ }
+ if r.search.Asked() != 0 {
+ t.Error("searched though addresses were typed")
+ }
+ got := strings.Join(r.web.requests(), " ")
+ if strings.Contains(got, "shop.paul") || strings.Contains(got, "cal.oficina") || !strings.Contains(got, "news.example.org/jump") || !strings.Contains(got, "www.met.ie/today") {
+ t.Errorf("read %s", got)
+ }
+ if reads := r.row(call).Reads; !strings.Contains(reads, guard.RuleDenied) {
+ t.Errorf("reads %s", reads)
+ }
+}
+
+func TestOficinaAppOriginRefused(t *testing.T) {
+ r := newLookupRig(t)
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Calendar", URL: "https://cal.oficina.works/today"}}
+ call := r.ask("Weather?", wire.TurnPerson)
+ if _, err := r.lookup(call, `{}`); err != nil && codeOf(err) != wire.CodeNothingFound && codeOf(err) != wire.CodeLookupFailed {
+ t.Fatal(err)
+ }
+ if len(r.web.requests()) != 0 {
+ t.Errorf("an app was read: %v", r.web.requests())
+ }
+}
+
+// With the person's app addresses not to be had, the lookup fails and
+// nothing is read.
+func TestDenyUnavailableFailsClosed(t *testing.T) {
+ r := newLookupRig(t)
+ r.apps.fail = true
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}}
+ if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupFailed || len(r.web.requests()) != 0 || r.search.Asked() != 0 {
+ t.Errorf("%v, read %v", err, r.web.requests())
+ }
+}
+
+// Two lookups in a turn; a third is refused; so is the 101st in a day.
+func TestLookupCaps(t *testing.T) {
+ r := newLookupRig(t)
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}}
+ call := r.ask("Weather?", wire.TurnPerson)
+ for i := range 3 {
+ call.CallID = "cap" + itoa64(int64(i))
+ _, err := r.lookup(call, `{}`)
+ if want := i == 2; (codeOf(err) == wire.CodeLookupLimit) != want {
+ t.Errorf("lookup %d: %v", i+1, err)
+ }
+ }
+ r = newLookupRig(t)
+ for i := range 100 {
+ if err := r.h.s.db.G.Create(&lookupRecord{ID: "old" + itoa64(int64(i)), Person: abPerson, TurnID: "x", Attempt: 1, Seq: int64(i), CallID: "o" + itoa64(int64(i)), State: lookupShown, CreatedAt: r.h.now().Add(-time.Hour)}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupLimit {
+ t.Errorf("the 101st: %v", err)
+ }
+}
+
+func TestSecretLookingQueryRefused(t *testing.T) {
+ r := newLookupRig(t)
+ r.queries = []string{"sk-proj-abcdefghijklmnopqrstuvwxyz0123456789ABCD"}
+ if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeLookupFailed || r.search.Asked() != 0 {
+ t.Errorf("%v, searched %d", err, r.search.Asked())
+ }
+}
+
+// Page text is never stored: the lookup's row holds numbers, the answer
+// and its sources.
+func TestLookupPageTextNotStored(t *testing.T) {
+ r := newLookupRig(t)
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin", Snippet: "snippet " + pageSentinel}}
+ call := r.ask("Weather?", wire.TurnPerson)
+ if _, err := r.lookup(call, `{}`); err != nil {
+ t.Fatal(err)
+ }
+ row := r.row(call)
+ raw, _ := json.Marshal(row)
+ if strings.Contains(string(raw), pageSentinel) || row.State != lookupShown || !strings.Contains(row.Reads, "sha256") || !strings.Contains(row.Queries, `"backend":"kagi"`) {
+ t.Errorf("row %s", raw)
+ }
+}
+
+// The audit names the person, the numbers and the domains: never the
+// query or the answer.
+func TestLookupAuditNoQuery(t *testing.T) {
+ r := newLookupRig(t)
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}}
+ if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); err != nil {
+ t.Fatal(err)
+ }
+ var line string
+ for _, a := range r.h.audits {
+ if strings.HasPrefix(a, auditLookup+" ") {
+ line = a
+ }
+ }
+ if line == "" || strings.Contains(line, "dublin weather") || strings.Contains(line, "Rain") || !strings.Contains(line, "domains=met.ie") || !strings.Contains(line, "code=shown") {
+ t.Errorf("audit %q", line)
+ }
+}
+
+// The answer step fits the runner's frame, the lowest-ranked page cut
+// first, and says it was cut.
+func TestAnswerStepBudget(t *testing.T) {
+ big := strings.Repeat("é", 8<<10)
+ s := wire.LookupStep{Stage: wire.LookupStageAnswer, Pages: []wire.LookupPage{{Text: big}, {Text: big}, {Text: big}, {Text: big}}}
+ out, cut := fitAnswerStep(s)
+ raw, _ := json.Marshal(out)
+ if !cut || len(raw) > wire.MaxLookupStepBytes || out.Pages[0].Text != big || len(out.Pages[3].Text) >= len(big) {
+ t.Errorf("%d bytes, cut %v", len(raw), cut)
+ }
+}
+
+// web turned off after the search: the page reads that would follow are
+// refused before anything is sent, and the refusal is the answer.
+func TestRevokedMidLookupStopsNextRequest(t *testing.T) {
+ r := newLookupRig(t)
+ r.search.Results["dublin weather"] = []websearch.Result{{Title: "Met", URL: "https://www.met.ie/dublin"}}
+ r.search.Hook = func(context.Context, string) error { r.webOff(); return nil }
+ if _, err := r.lookup(r.ask("Weather?", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeAbilityOff || len(r.web.requests()) != 0 {
+ t.Errorf("%v, read %v", err, r.web.requests())
+ }
+}
+
+// web turned off while the first hop's 302 comes back: its target
+// receives nothing.
+func TestRevokedDuringRedirectStops(t *testing.T) {
+ r := newLookupRig(t)
+ r.web.pages["news.example.org/jump"] = func(w http.ResponseWriter, _ *http.Request) {
+ r.webOff()
+ w.Header().Set("Location", "https://other.example.org/next")
+ w.WriteHeader(http.StatusFound)
+ }
+ if _, err := r.lookup(r.ask("Read https://news.example.org/jump please", wire.TurnPerson), `{}`); codeOf(err) != wire.CodeAbilityOff {
+ t.Errorf("%v", err)
+ }
+ for _, got := range r.web.requests() {
+ if strings.HasPrefix(got, "other.example.org") {
+ t.Errorf("the redirect's target was read")
+ }
+ }
+}
+
+// A request to a host waits for a second after the last one to it.
+func TestSearchPacedAfterDNS(t *testing.T) {
+ var p hostPacer
+ start := time.Now()
+ var wg sync.WaitGroup
+ for range 2 {
+ wg.Add(1)
+ go func() { defer wg.Done(); _ = p.wait(context.Background(), "kagi.com") }()
+ }
+ wg.Wait()
+ if time.Since(start) < time.Second {
+ t.Errorf("two requests to one host within %s", time.Since(start))
+ }
+ start = time.Now()
+ _ = p.wait(context.Background(), "www.mojeek.com")
+ if time.Since(start) > 200*time.Millisecond {
+ t.Error("another host waited")
+ }
+}
+
+func TestSameHostRedirectPaced(t *testing.T) {
+ r := newLookupRig(t)
+ r.web.pages["news.example.org/jump"] = func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Location", "https://news.example.org/landed")
+ w.WriteHeader(http.StatusFound)
+ }
+ start := time.Now()
+ if _, err := r.lookup(r.ask("Read https://news.example.org/jump", wire.TurnPerson), `{}`); err != nil {
+ t.Fatal(err)
+ }
+ if time.Since(start) < time.Second {
+ t.Errorf("the same host's redirect wasn't paced: %s", time.Since(start))
+ }
+}
+
+// web_lookup isn't listed for an older runner, a Base that can't draw
+// answers, an unconfirmed inventory, or no backend.
+func TestLookupUnsupported(t *testing.T) {
+ ctx := context.Background()
+ listed := func(r *lookupRig) bool {
+ ops, _ := r.h.s.WebProvider().List(ctx, abPerson)
+ return len(ops) == 1
+ }
+ r := newLookupRig(t)
+ if !listed(r) {
+ t.Fatal("not listed when it can run")
+ }
+ r.detach()
+ defer r.h.s.attachLive("RUNNER1", wire.Protocol35, func(context.Context, wire.Frame) error { return nil })()
+ if listed(r) {
+ t.Error("listed on protocol 35")
+ }
+ r = newLookupRig(t)
+ if err := r.h.s.SetCapabilities(ctx, abPerson, ""); err != nil {
+ t.Fatal(err)
+ }
+ if listed(r) {
+ t.Error("listed for a Base that can't draw answers")
+ }
+ r = newLookupRig(t)
+ cfg := *r.h.s.lookups.cfg.Load()
+ cfg.Inventory = readyInv{false}
+ r.h.s.SetLookups(&cfg)
+ if listed(r) {
+ t.Error("listed with the inventory unconfirmed")
+ }
+ r.h.s.SetLookups(nil)
+ if listed(r) {
+ t.Error("listed with no backend")
+ }
+}
+
+func TestLookupExemptFromOutboundRule(t *testing.T) {
+ t.Skip("MCP Task 27 (the outbound rule) has not landed")
+}
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index ab7558e8..9abbe0bc 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -120,8 +120,10 @@ type Store struct {
// scan; ifaceAddrs replaces net.InterfaceAddrs in tests.
instance instanceNet
ifaceAddrs func() ([]net.Addr, error)
- // live is the lookups' live channel to each runner (lookup_live.go).
- live lookupLive
+ // live is the lookups' live channel to each runner (lookup_live.go);
+ // lookups their configuration, pace and deny lists (web_provider.go).
+ live lookupLive
+ lookups lookupState
// ops is the Assistant's registry (SetOperations); remote wakes
// ServeRemoteCalls after a commit that stored a pending call.
ops atomic.Pointer[Operations]
diff --git a/internal/equipo/chat/web_provider.go b/internal/equipo/chat/web_provider.go
new file mode 100644
index 00000000..f6d50a5e
--- /dev/null
+++ b/internal/equipo/chat/web_provider.go
@@ -0,0 +1,173 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/assist"
+ "amadan.net/oficina/equipo/internal/websearch"
+ "amadan.net/oficina/equipo/internal/websource/guard"
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// The web provider (spec 2026-11-26-assistant-abilities §4.1): one
+// read-only operation, web_lookup, with an empty input. The Assistant
+// says that something should be looked up, never what: the lookup works
+// from the person's own words, and its answer is shown to them, never
+// handed back.
+
+const (
+ webProviderName = "web"
+ opWebLookup = "web_lookup"
+)
+
+// webLookupOp is the one operation. Its description is for the model.
+var webLookupOp = assist.Operation{Provider: webProviderName, Name: opWebLookup, App: "Web", Scope: "web", ReadOnly: true, Idempotent: true,
+ Description: "Look something up on the public web for the person: weather, opening hours, news, prices, facts. Takes no input: it works from what the person asked. The answer is shown to them under your reply.",
+ Input: json.RawMessage(`{"type":"object","additionalProperties":false}`),
+ Output: json.RawMessage(`{"type":"object","properties":{"code":{"type":"string"},"sources":{"type":"integer"},"text":{"type":"string"}}}`)}
+
+// LookupConfig is what lookups run on: the search chain (FromConfig's,
+// usable), the page client (PolicyLookupPage, 5 redirects), the
+// inventory, and the hosts no lookup may reach whoever the person is (the
+// instance, every Assistant host, oficina-connect, the forge).
+type LookupConfig struct {
+ Search websearch.Chain
+ Pages *guard.Client
+ Inventory guard.Inventory
+ Deny []string
+}
+
+// lookupState is the store's lookup configuration and its in-memory
+// state: the per-host pace and the deny lists per person.
+type lookupState struct {
+ cfg atomic.Pointer[LookupConfig]
+ pace hostPacer
+ mu sync.Mutex
+ deny map[string]denyEntry
+}
+
+type denyEntry struct {
+ hosts []string
+ at time.Time
+}
+
+// SetLookups configures lookups; nil (no usable backend) leaves
+// web_lookup unlisted.
+func (s *Store) SetLookups(c *LookupConfig) { s.lookups.cfg.Store(c) }
+
+// WebProvider is the web provider, registered after the team's.
+func (s *Store) WebProvider() assist.Provider { return webProvider{s} }
+
+type webProvider struct{ s *Store }
+
+func (webProvider) Name() string { return webProviderName }
+
+// List offers web_lookup only when a lookup can run for the person now
+// (§4.2): a usable backend, the inventory ready, their primary at
+// protocol 36 or later, their Base drawing answers (lookup_answers), and,
+// for a call, a turn they started.
+func (p webProvider) List(ctx context.Context, person string) ([]assist.Operation, error) {
+ if p.s.lookupUnsupported(ctx, person) != "" {
+ return nil, nil
+ }
+ if call, ok := callFrom(ctx); ok {
+ if kind, err := p.s.turnKind(ctx, call); err != nil || kind != wire.TurnPerson {
+ return nil, err
+ }
+ }
+ return []assist.Operation{webLookupOp}, nil
+}
+
+func (p webProvider) Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error) {
+ call, ok := callFrom(ctx)
+ if !ok || call.Person != person {
+ return nil, assist.Failure{Code: "unavailable"}
+ }
+ if operation != opWebLookup {
+ return nil, assist.Failure{Code: "unknown_operation"}
+ }
+ if in := strings.TrimSpace(string(input)); in != "" && in != "{}" && in != "null" {
+ return nil, assist.Failure{Code: "invalid_input", Message: toolLookupInput}
+ }
+ return p.s.webLookup(ctx, call)
+}
+
+// lookupUnsupported is why a lookup can't run for person now, "" when it
+// can.
+func (s *Store) lookupUnsupported(ctx context.Context, person string) string {
+ cfg := s.lookups.cfg.Load()
+ if cfg == nil || cfg.Pages == nil || cfg.Search.Primary == nil || cfg.Inventory == nil {
+ return "no_backend"
+ }
+ if cfg.Inventory.Ready(ctx) != nil {
+ return "inventory"
+ }
+ sw, err := s.switchesNow(ctx, person)
+ if err != nil || !sw.Draws(wire.CapLookupAnswers) {
+ return "client"
+ }
+ var runner string
+ if err := s.read(ctx, func(tx *gorm.DB) error {
+ var err error
+ runner, err = s.authority.PrimaryRunner(tx, person)
+ return err
+ }); err != nil || runner == "" {
+ return "runner"
+ }
+ s.live.mu.Lock()
+ c := s.live.conns[runner]
+ s.live.mu.Unlock()
+ if c == nil || c.protocol < wire.ProtocolLookup {
+ return "runner"
+ }
+ return ""
+}
+
+// turnKind is the call's turn's kind.
+func (s *Store) turnKind(ctx context.Context, call toolCallRecord) (string, error) {
+ var kinds []string
+ err := s.read(ctx, func(tx *gorm.DB) error {
+ return tx.Model(&turnRecord{}).Where("id = ? AND person = ?", call.TurnID, call.Person).Pluck("coalesce(kind, '')", &kinds).Error
+ })
+ if err != nil || len(kinds) != 1 {
+ return "", err
+ }
+ return kinds[0], nil
+}
+
+// hostPacer keeps requests to any one host at least a second apart.
+type hostPacer struct {
+ mu sync.Mutex
+ next map[string]time.Time
+}
+
+// wait is host's next slot, taken, then waited for (or ctx's end).
+func (p *hostPacer) wait(ctx context.Context, host string) error {
+ p.mu.Lock()
+ if p.next == nil {
+ p.next = map[string]time.Time{}
+ }
+ now := time.Now()
+ at := p.next[host]
+ if at.Before(now) {
+ at = now
+ }
+ p.next[host] = at.Add(time.Second)
+ p.mu.Unlock()
+ if d := time.Until(at); d > 0 {
+ t := time.NewTimer(d)
+ defer t.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-t.C:
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/chat_wiring.go b/internal/equipo/chat_wiring.go
index 2a61bfaa..b07fba15 100644
--- a/internal/equipo/chat_wiring.go
+++ b/internal/equipo/chat_wiring.go
@@ -89,7 +89,7 @@ func (s *Store) Chat() *chat.Store {
// they do by a person not connected raises the connect card.
func (s *Store) assistRegistry(logger *slog.Logger) *assist.Registry {
c := s.chat.store
- providers := []assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider()}
+ providers := []assist.Provider{assist.NewHTTPProvider("base", c.Host, nil), c.TeamProvider(), c.WebProvider()}
if s.oficina != nil {
s.oficina.SetAllowed(c.AllowedFor(wire.AbilityAppsRead))
providers = append(providers, assist.NewOficinaProvider(oficinaProvider, s.oficina, nil, c.AllowedFor(wire.AbilityAppsRead)))
diff --git a/internal/equipo/config.go b/internal/equipo/config.go
index 81fb5635..62e851f8 100644
--- a/internal/equipo/config.go
+++ b/internal/equipo/config.go
@@ -2,9 +2,9 @@ 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/equipo/internal/websearch"
"amadan.net/oficina/home/connect"
"errors"
"log/slog"
diff --git a/internal/equipo/lookups_wiring.go b/internal/equipo/lookups_wiring.go
new file mode 100644
index 00000000..55969168
--- /dev/null
+++ b/internal/equipo/lookups_wiring.go
@@ -0,0 +1,43 @@
+package equipo
+
+import (
+ "log/slog"
+ "net/url"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/chat"
+ "amadan.net/oficina/equipo/internal/websearch"
+ "amadan.net/oficina/equipo/internal/websource/guard"
+)
+
+// forgeHost is the forge the instance pushes to: never a lookup's.
+const forgeHost = "amadan.net"
+
+// setupLookups configures the Assistant's lookups (spec 2026-11-26-
+// assistant-abilities §4): the search chain from EQUIPO_WEB_SEARCH and
+// friends, the page client, both guarded by the instance inventory and
+// denied the instance's own hosts. With no usable backend web_lookup
+// stays unlisted; a constructor refusing its configuration is an error.
+func (s *Store) setupLookups(cfg Config, logger *slog.Logger) error {
+ deny := []string{forgeHost}
+ for _, origin := range append([]string{cfg.Origin, cfg.OficinaConnectOrigin}, cfg.AssistantHosts...) {
+ if u, err := url.Parse(strings.TrimSpace(origin)); err == nil && u.Hostname() != "" {
+ deny = append(deny, strings.ToLower(u.Hostname()))
+ }
+ }
+ c := s.Chat()
+ g := guard.Config{Inventory: c.InstanceInventory(), Deny: deny, Logger: logger}
+ chain, ok, err := websearch.FromConfig(cfg.WebSearch, g, websearch.DBUsage{DB: s.db.G, Caps: cfg.WebSearch.Caps})
+ if err != nil || !ok {
+ c.SetLookups(nil)
+ return err
+ }
+ pageCfg := g
+ pageCfg.Policy, pageCfg.Redirects = guard.PolicyLookupPage, guard.MaxRedirects
+ pages, err := guard.New(pageCfg)
+ if err != nil {
+ return err
+ }
+ c.SetLookups(&chat.LookupConfig{Search: chain, Pages: pages, Inventory: g.Inventory, Deny: deny})
+ return nil
+}