oficina / equipo Public

Lookups: answers and sources on the reply, plain text for older clients

Tasks 3.8 and 3.9 (one file holds both): every message view carries its
Assistant reply's lookups, those the turn's final attempt showed, in
call order, at most 2, links taken out of the answer; the activity line
reads assistant.activity.lookup while one runs. A snapshot, message
page or event read whose request lacks lookup_answers gets each answer
folded into the text with a "Sources:" line, at read time only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev fbccfb245f93baf443a38e7be5821f7736fb7600 parent 00a8651
5 files changed, +294 −3
  • internal/equipo/chat/assistant_http.go +74 −1
  • internal/equipo/chat/attachments.go +2 −1
  • internal/equipo/chat/lookup.go +9 −1
  • internal/equipo/chat/lookup_view.go +93 −0
  • internal/equipo/chat/lookup_view_test.go +116 −0
diff --git a/internal/equipo/chat/assistant_http.go b/internal/equipo/chat/assistant_http.go
index 6f375cb4..52d8ed2a 100644
--- a/internal/equipo/chat/assistant_http.go
+++ b/internal/equipo/chat/assistant_http.go
@@ -33,10 +33,19 @@ func (h *HTTP) MountAssistant(r chi.Router) {
out.Cards[i] = olderJobCard(out.Cards[i])
}
}
+ if !drawsLookups(r) {
+ for i := range out.Messages {
+ out.Messages[i] = plainLookups(out.Messages[i], h.sourcesLine())
+ }
+ }
writeJSON(w, 200, out)
}))
r.Get("/messages", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
- h.messagesWith(w, r, p, lane.Messages)
+ page := lane.Messages
+ if !drawsLookups(r) {
+ page = h.plainPage(lane.Messages)
+ }
+ h.messagesWith(w, r, p, page)
}))
r.Post("/messages", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
h.turnStartRefresh(r, p)
@@ -58,6 +67,9 @@ func (h *HTTP) MountAssistant(r chi.Router) {
if !knowsPaused(r) {
read = olderJobEvents(lane.Events)
}
+ if !drawsLookups(r) {
+ read = h.plainEvents(read)
+ }
h.stream(w, r, p, lane.lane, read)
}))
r.Put("/host", h.assistantBearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
@@ -294,3 +306,64 @@ func (h *HTTP) carryOn(w http.ResponseWriter, r *http.Request, p personapi.Perso
h.fail(w, r, err)
}
}
+
+// drawsLookups: the request's Base draws lookups' answers (its
+// Base-Capabilities say lookup_answers). Without it a read gets each
+// answer folded into its message's text (plainLookups).
+func drawsLookups(r *http.Request) bool {
+ for _, v := range r.Header.Values("Base-Capabilities") {
+ for _, c := range strings.Split(v, ",") {
+ if strings.TrimSpace(c) == wire.CapLookupAnswers {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// sourcesLine is the fallback's sources label (approved copy).
+func (h *HTTP) sourcesLine() string {
+ if h.Store.authority.Copy != nil {
+ if s := h.Store.authority.Copy("assistant.lookup.fallback_sources"); s != "" {
+ return s
+ }
+ }
+ return "Sources:"
+}
+
+// plainPage is a message page with each answer folded into its text.
+func (h *HTTP) plainPage(page func(context.Context, string, string, int) (wire.MessagePage, error)) func(context.Context, string, string, int) (wire.MessagePage, error) {
+ return func(ctx context.Context, person, before string, limit int) (wire.MessagePage, error) {
+ out, err := page(ctx, person, before, limit)
+ for i := range out.Items {
+ out.Items[i] = plainLookups(out.Items[i], h.sourcesLine())
+ }
+ return out, err
+ }
+}
+
+// plainEvents reads the lane's events with each message's answers folded
+// into its text.
+func (h *HTTP) plainEvents(read func(context.Context, string, int64, int) ([]wire.Event, error)) func(context.Context, string, int64, int) ([]wire.Event, error) {
+ return func(ctx context.Context, person string, after int64, limit int) ([]wire.Event, error) {
+ events, err := read(ctx, person, after, limit)
+ if err != nil {
+ return nil, err
+ }
+ for i, e := range events {
+ if e.Type != wire.EventMessage {
+ continue
+ }
+ var m wire.Message
+ if json.Unmarshal(e.Data, &m) != nil || len(m.Lookups) == 0 {
+ continue
+ }
+ raw, err := json.Marshal(plainLookups(m, h.sourcesLine()))
+ if err != nil {
+ return nil, err
+ }
+ events[i].Data = raw
+ }
+ return events, nil
+ }
+}
diff --git a/internal/equipo/chat/attachments.go b/internal/equipo/chat/attachments.go
index 197eb575..4d412e4c 100644
--- a/internal/equipo/chat/attachments.go
+++ b/internal/equipo/chat/attachments.go
@@ -250,7 +250,8 @@ func withFiles(tx *gorm.DB, views []wire.Message) error {
for i := range views {
views[i].Attachments = files[views[i].ID]
}
- return nil
+ // An Assistant reply shows its turn's lookups.
+ return withLookups(tx, views)
}
// AttachmentData is one attachment's bytes for its person: the original,
diff --git a/internal/equipo/chat/lookup.go b/internal/equipo/chat/lookup.go
index 3ebd0f39..964bc1f0 100644
--- a/internal/equipo/chat/lookup.go
+++ b/internal/equipo/chat/lookup.go
@@ -38,6 +38,8 @@ const (
lookupDenyFresh = 60 * time.Second
lookupDenyKeep = 10 * time.Minute
auditLookup = "assistant.lookup"
+ // lookupActivityKey is the activity line's copy while a lookup runs.
+ lookupActivityKey = "assistant.activity.lookup"
)
// What the Assistant gets back: fixed instance text, never page text or
@@ -126,8 +128,14 @@ func (s *Store) webLookup(ctx context.Context, call toolCallRecord) (json.RawMes
}
if !ok {
run.row.State, run.row.Code = lookupFailed, wire.CodeLookupUnsupported
+ return t.db.Create(&run.row).Error
+ }
+ if err := t.db.Create(&run.row).Error; err != nil {
+ return err
}
- return t.db.Create(&run.row).Error
+ // The reply's activity line while it runs.
+ a := wire.Activity{TurnID: turn.ID, Attempt: turn.Attempt, Kind: wire.ActivityTool, Tool: wire.ToolUse, Label: t.words(lookupActivityKey)}
+ return t.event(turn.Lane, turn.Person, wire.EventActivity, "turn", turn.ID, 0, turn.ID, "", turn.Attempt, a)
})
if err != nil {
return nil, err
diff --git a/internal/equipo/chat/lookup_view.go b/internal/equipo/chat/lookup_view.go
new file mode 100644
index 00000000..57968bd8
--- /dev/null
+++ b/internal/equipo/chat/lookup_view.go
@@ -0,0 +1,93 @@
+package chat
+
+import (
+ "encoding/json"
+ "regexp"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "gorm.io/gorm"
+)
+
+// What a reply shows of its turn's lookups (spec 2026-11-26-assistant-
+// abilities §4.6): every lookup the turn's final attempt showed, in call
+// order, at most 2, each its answer (links taken out) and its sources. A
+// lookup from an earlier attempt is never shown.
+
+// withLookups sets each Assistant reply's lookups.
+func withLookups(tx *gorm.DB, views []wire.Message) error {
+ for i := range views {
+ if views[i].Role != wire.RoleAssistant || views[i].TurnID == "" {
+ continue
+ }
+ var attempt []int64
+ if err := tx.Model(&turnRecord{}).Where("id = ?", views[i].TurnID).Pluck("attempt", &attempt).Error; err != nil {
+ return err
+ }
+ if len(attempt) != 1 {
+ continue
+ }
+ got, err := lookupsFor(tx, views[i].TurnID, attempt[0])
+ if err != nil {
+ return err
+ }
+ views[i].Lookups = got
+ }
+ return nil
+}
+
+// lookupsFor are the lookups turn's attempt showed, in call order, at
+// most MaxLookupsPerReply.
+func lookupsFor(tx *gorm.DB, turn string, attempt int64) ([]wire.AssistantLookup, error) {
+ var rows []lookupRecord
+ if err := tx.Where("turn_id = ? AND attempt = ? AND state = ?", turn, attempt, lookupShown).Order("seq").Limit(wire.MaxLookupsPerReply).Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ var out []wire.AssistantLookup
+ for _, r := range rows {
+ var sources []wire.LookupSource
+ if json.Unmarshal([]byte(r.Sources), &sources) != nil || len(sources) == 0 {
+ continue
+ }
+ out = append(out, wire.AssistantLookup{Answer: stripLinks(r.Answer), Sources: sources})
+ }
+ return out, nil
+}
+
+var (
+ mdLink = regexp.MustCompile(`!?\[([^\]\n]*)\]\([^)\n]*\)`)
+ autoLink = regexp.MustCompile(`<(?:https?|ftp|mailto):[^>\s]*>`)
+ bareLink = regexp.MustCompile(`(?i)\b(?:https?|ftp)://[^\s<>()]+`)
+)
+
+// stripLinks takes the links out of an answer: a Markdown link becomes
+// its text; an address goes. The only links under a reply are the
+// sources the instance recorded.
+func stripLinks(s string) string {
+ s = mdLink.ReplaceAllString(s, "$1")
+ s = autoLink.ReplaceAllString(s, "")
+ s = bareLink.ReplaceAllString(s, "")
+ return strings.TrimSpace(s)
+}
+
+// plainLookups is m for a client that can't draw answers (§4.6): each
+// answer after the text, then a "Sources:" line with the addresses.
+// Presentation only, at read time: never stored, never the Assistant's.
+func plainLookups(m wire.Message, sourcesLine string) wire.Message {
+ if len(m.Lookups) == 0 {
+ return m
+ }
+ parts := []string{}
+ if t := strings.TrimSpace(m.Text); t != "" {
+ parts = append(parts, t)
+ }
+ for _, l := range m.Lookups {
+ var urls []string
+ for _, s := range l.Sources {
+ urls = append(urls, s.URL)
+ }
+ parts = append(parts, l.Answer+"\n\n"+sourcesLine+" "+strings.Join(urls, " "))
+ }
+ m.Text, m.Lookups = strings.Join(parts, "\n\n"), nil
+ return m
+}
diff --git a/internal/equipo/chat/lookup_view_test.go b/internal/equipo/chat/lookup_view_test.go
new file mode 100644
index 00000000..6c048eb7
--- /dev/null
+++ b/internal/equipo/chat/lookup_view_test.go
@@ -0,0 +1,116 @@
+package chat
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/websearch"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// replyTo is the Assistant's reply in call's turn, as a reader gets it.
+func (r *lookupRig) replyTo(call toolCallRecord) wire.Message {
+ r.t.Helper()
+ m := messageRecord{ID: "reply" + call.TurnID, Person: abPerson, IdempotencyKey: "rk" + call.TurnID, Role: wire.RoleAssistant, Text: "Here you go.", TurnID: call.TurnID, Lane: wire.LaneAssistant, CreatedAt: r.h.now()}
+ if err := r.h.s.db.G.Create(&m).Error; err != nil {
+ r.t.Fatal(err)
+ }
+ views := []wire.Message{messageView(m)}
+ if err := withFiles(r.h.s.db.G, views); err != nil {
+ r.t.Fatal(err)
+ }
+ return views[0]
+}
+
+// A reply shows its turn's two lookups in call order; one from an earlier
+// attempt isn't shown.
+func TestTwoLookupsOneReply(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 in Dublin and Cork?", wire.TurnPerson)
+ if err := r.h.s.db.G.Create(&lookupRecord{ID: "early", Person: abPerson, TurnID: call.TurnID, Attempt: 0, Seq: 1, CallID: "early", State: lookupShown, Answer: "Old.", Sources: `[{"url":"https://www.met.ie/","title":"Met"}]`, CreatedAt: r.h.now()}).Error; err != nil {
+ t.Fatal(err)
+ }
+ for i, answer := range []string{"Dublin: rain.", "Cork: sun."} {
+ r.answer = answer
+ call.CallID = "two" + itoa64(int64(i))
+ if _, err := r.lookup(call, `{}`); err != nil {
+ t.Fatal(err)
+ }
+ }
+ got := r.replyTo(call).Lookups
+ if len(got) != 2 || got[0].Answer != "Dublin: rain." || got[1].Answer != "Cork: sun." || got[0].Sources[0].URL != "https://www.met.ie/dublin" {
+ t.Errorf("lookups %+v", got)
+ }
+}
+
+func TestAnswerLinksStripped(t *testing.T) {
+ for in, want := range map[string]string{
+ "See [the forecast](https://evil.example.org/x) for **rain**.": "See the forecast for **rain**.",
+ "Open <https://evil.example.org/> now": "Open now",
+ "Rain. https://evil.example.org/track?id=1 Sun later.": "Rain. Sun later.",
+ "![pixel](https://evil.example.org/p.png)Rain.": "pixelRain.",
+ } {
+ if got := stripLinks(in); got != want {
+ t.Errorf("%q: %q", in, got)
+ }
+ }
+}
+
+// While a lookup runs, the reply's activity line is the lookup's.
+func TestLookupActivityLabel(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)
+ if _, err := r.lookup(call, `{}`); err != nil {
+ t.Fatal(err)
+ }
+ var events []eventRecord
+ if err := r.h.s.db.G.Where("person = ? AND type = ?", abPerson, wire.EventActivity).Find(&events).Error; err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for _, e := range events {
+ var ev struct {
+ Data wire.Activity `json:"data"`
+ }
+ _ = json.Unmarshal([]byte(e.Body), &ev)
+ a := ev.Data
+ found = found || a.TurnID == call.TurnID && a.Label == lookupActivityKey && e.Lane == wire.LaneAssistant
+ }
+ if !found {
+ t.Errorf("no lookup activity in %d events: %+v", len(events), events)
+ }
+}
+
+// A read without lookup_answers gets each answer folded into the text
+// with its sources; the stored message, and what the Assistant reads of
+// it, are unchanged.
+func TestLookupFallbackForOldClients(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)
+ if _, err := r.lookup(call, `{}`); err != nil {
+ t.Fatal(err)
+ }
+ reply := r.replyTo(call)
+ plain := plainLookups(reply, "Sources:")
+ if plain.Lookups != nil || plain.Text != "Here you go.\n\nRain at first, 11 degrees.\n\nSources: https://www.met.ie/dublin" {
+ t.Errorf("plain %q %v", plain.Text, plain.Lookups)
+ }
+ h := &HTTP{Store: r.h.s}
+ raw, _ := json.Marshal(reply)
+ read := h.plainEvents(func(context.Context, string, int64, int) ([]wire.Event, error) {
+ return []wire.Event{{Type: wire.EventMessage, Data: raw}}, nil
+ })
+ events, err := read(context.Background(), abPerson, 0, 10)
+ if err != nil || !strings.Contains(string(events[0].Data), "https://www.met.ie/dublin") || strings.Contains(string(events[0].Data), `"lookups"`) {
+ t.Errorf("event %s %v", events[0].Data, err)
+ }
+ var stored messageRecord
+ if err := r.h.s.db.G.Where("id = ?", reply.ID).First(&stored).Error; err != nil || stored.Text != "Here you go." {
+ t.Errorf("stored %q %v", stored.Text, err)
+ }
+}