Files
magpie/internal/sessions/said_text.go
T
yetone 64ad53f6c7 sessions: magpie sessions search and show, for agents (yansheng1003 on X)
yansheng1003 asked for a command or skill an agent can call to search
and read its sessions. magpie had the search on the Sessions page and
in the Magpie Sessions MCP server, but not on the command line.

- `magpie sessions search <words…> [--agent] [--days N|today|all]
  [--limit N] [--wait] [--json]`: the Sessions page's search
  (sessions.SearchSaid over said-v1.db; SearchSaidSince adds the --days
  bound), newest first, each hit named agent:id with title, folder,
  time and the words round the match. A one-shot command waits for the
  index (SaidReady, 60s by default, a progress line on a TTY only).
- `magpie sessions show <agent:id|id> [--find] [--from N] [--max-chars N]
  [--json]`: the viewer's reader (TranscriptOf, TranscriptAt) as text,
  from where the words were said; --json is the page's transcript.
- One renderer: the MCP server's search_sessions/read_session text moved
  to sessions.SaidText/SessionText (said_text.go), with how to ask for
  more given by each caller (TextHow). The MCP server's output is
  unchanged (its tests pass as before).
- Consent: neither reads, nor makes the index, until the user has
  answered which agents magpie may read; it prints notAskedLine and
  exits 1. An agent not allowed is ErrNotRead for --agent and show.
- Flags: an unknown flag or a missing value is refused with the usage,
  never taken for words or a session id; `--` ends flags; -h/--help
  prints the subcommand's own usage (help_cli.go).
- Parity: /api/sessions/said and /api/sessions/transcript now map to
  these commands (settings_parity_test.go).
- Library: magpie-sessions is a featured official skill
  (magpie-community/plugins skills/magpie-sessions, pushed as plugins
  cf5b0312), listed after magpie-quota.
- Docs: usage.html "Search what was said" in en, zh and ja; llms-full,
  search indexes and docs-index.sums regenerated (node docs-index.mjs).

Run at 114eb4592 (rebased on a2213b1b6), on mote:
- gofmt -l internal: clean. go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows of internal/cli, sessions, gateway, library: ok (before
  the rebase; upstream's one commit touches none of these).
- go test -count=1: internal/cli -run 'TestSessions|TestEveryRoute|TestHelp'
  ok; internal/library -run TestFeaturedSkills ok; internal/gui -run
  TestEveryRouteIsNamedForTheCLI ok; internal/sessions (whole package)
  ok; internal/gateway -run 'SessionsMCP|Sessions' ok.
- site: node --test search.test.mjs worker.test.mjs, 47 pass.
- Real binary, sandbox HOME holding internal/sessions/testdata's Claude
  and Codex sessions: search before `sessions read on all` printed the
  not-asked line, exit 1; --help printed usage, exit 0; --bogus refused,
  exit 1; then search "login bug" found the Claude session, --json gave
  the Codex hit, show --find and a bare Codex id read their sessions.

Broken by hand: without the consent check TestSessionsSearchNotAsked is
red; without the since filter the --days today case is red.

Not run before the push: the full suite. Both mote (load 31 on 18
cores) and mica (21 to 30 on 12, another session's gateway run) were
over their limits; it runs at this head after the push. Not tried: real
agents' long histories (the index on a large history is the GUI's, as
before), Windows and Linux runs of the command.
2026-11-17 17:33:23 +08:00

225 lines
6.4 KiB
Go

package sessions
import (
"fmt"
"strings"
"unicode"
)
// A search over every agent's sessions, and a session read, as text an
// agent reads: the sessions MCP server's search_sessions and
// read_session (cryingLiu on X) and `magpie sessions search` / `show`
// (yansheng1003 on X) both write it, each saying how to ask it for more
// in its own words (TextHow).
// TextHow is how the reader of a text asks for more, in the words of
// the tool or command that wrote it.
type TextHow struct {
// More: how to ask for more hits ("ask for a higher limit")
More string
// Read: how to read a hit's session, a sentence
Read string
// From: how to read s on from message n
From func(s Session, n int) string
}
const (
// TextReadChars is how much of a session SessionText gives when not
// told, and TextReadMost the most it gives
TextReadChars = 20_000
TextReadMost = 100_000
// textToolChars is what is shown of a tool's call or answer
textToolChars = 400
// textLead is how many messages before the found one a read with
// find starts
textLead = 3
)
// SessionRef is how a session is named in these texts: agent:id.
func SessionRef(s Session) string { return s.Agent + ":" + s.ID }
// SaidText is what a search found, as text: each session (agent:id,
// title, folder, when) and the words round where it said needle.
func SaidText(found SaidFound, needle string, how TextHow) string {
var b strings.Builder
still := found.Listing || found.Indexed < found.Total
if len(found.Hits) == 0 && still {
fmt.Fprintf(&b, "No session searched so far says %q.", needle)
} else if len(found.Hits) == 0 {
fmt.Fprintf(&b, "No session says %q.", needle)
} else if len(found.Hits) == 1 {
fmt.Fprintf(&b, "1 session says %q:\n", needle)
} else {
fmt.Fprintf(&b, "%d sessions say %q, the newest first:\n", len(found.Hits), needle)
}
for i, h := range found.Hits {
ss := h.Session
fmt.Fprintf(&b, "\n%d. %s", i+1, SessionRef(ss))
if t := cutLine(ss.Title, 120); t != "" {
fmt.Fprintf(&b, " · %s", t)
}
b.WriteString("\n ")
if ss.Cwd != "" {
b.WriteString(ss.Cwd + " · ")
}
b.WriteString(ss.Last.Local().Format("2006-01-02 15:04"))
fmt.Fprintf(&b, "\n %s: %s[%s]%s\n", h.Hit.Role, strings.TrimLeft(snipTail(flat(h.Hit.Before), 200), " "), flat(h.Hit.Match), strings.TrimRight(snipHead(flat(h.Hit.After), 300), " "))
}
if found.Cut {
fmt.Fprintf(&b, "\nThere may be more: %s, or more words.", how.More)
}
if found.Listing {
b.WriteString("\nStill indexing: the sessions to search are still being found; ask again in a minute.")
} else if found.Total > 0 && found.Indexed < found.Total {
fmt.Fprintf(&b, "\nStill indexing: %d of %d sessions searched so far; ask again in a minute for the rest.", found.Indexed, found.Total)
}
if len(found.Hits) > 0 && how.Read != "" {
b.WriteString("\n" + how.Read)
}
return b.String()
}
// ReadAsk is what part of a session SessionText gives: from message
// From on, or, with Find, from a few messages before where those words
// were said; MaxChars of it at most.
type ReadAsk struct {
Find string
From int
MaxChars int
}
// SessionText is s's conversation as text: the prompts, the replies and
// the tools called, shortened, each message numbered.
func SessionText(s Session, ask ReadAsk, how TextHow) (string, error) {
var tr Transcript
var err error
from := max(ask.From, 0)
if needle := NeedleOf(ask.Find); needle != "" && from == 0 {
tr, err = TranscriptAt(s, needle)
if err == nil {
from = max(tr.From, textNear(tr, needle)-textLead)
}
} else {
tr, err = TranscriptOf(s)
}
if err != nil {
return "", err
}
most := ask.MaxChars
if most <= 0 {
most = TextReadChars
}
most = min(max(most, 1000), TextReadMost)
var b strings.Builder
b.WriteString(SessionRef(s))
if t := cutLine(s.Title, 200); t != "" {
b.WriteString(" · " + t)
}
b.WriteString("\n")
if s.Cwd != "" {
b.WriteString(s.Cwd + " · ")
}
fmt.Fprintf(&b, "%s to %s\n", s.Start.Local().Format("2006-01-02 15:04"), s.Last.Local().Format("2006-01-02 15:04"))
if from > tr.From {
fmt.Fprintf(&b, "(messages before %d left out)\n", from)
} else if tr.From > 0 {
fmt.Fprintf(&b, "(messages before %d left out)\n", tr.From)
}
end := tr.From
for i, p := range tr.Parts {
n := tr.From + i
if n < from {
continue
}
line := partText(n, p)
if line == "" {
end = n + 1
continue
}
if b.Len()+len(line) > most && end > from {
fmt.Fprintf(&b, "\n(more: %s)", how.From(s, n))
return b.String(), nil
}
b.WriteString(line)
end = n + 1
}
if tr.Cut {
fmt.Fprintf(&b, "\n(the rest is longer than is read at once: %s)", how.From(s, end))
}
return b.String(), nil
}
// textNear is the number of the first part that says needle, or 0.
func textNear(tr Transcript, needle string) int {
for i, p := range tr.Parts {
if (p.Kind == "text" || p.Kind == "context") && strings.Contains(NeedleOf(p.Text), needle) {
return tr.From + i
}
}
return 0
}
// partText is one part as SessionText shows it.
func partText(n int, p Part) string {
text := strings.TrimSpace(p.Text)
switch p.Kind {
case "text", "context":
if text == "" {
return ""
}
return fmt.Sprintf("\n[%d] %s:\n%s\n", n, p.Role, text)
case "thinking":
return ""
case "tool_use":
return fmt.Sprintf("\n[%d] %s called %s: %s\n", n, p.Role, p.Name, cutLine(text, textToolChars))
case "tool_result":
return fmt.Sprintf("[%d] tool answered: %s\n", n, cutLine(text, textToolChars))
case "image":
return fmt.Sprintf("\n[%d] %s: (an image)\n", n, p.Role)
}
return ""
}
// cutLine is text on one line, cut to most runes.
func cutLine(text string, most int) string {
return snipHead(strings.Join(strings.Fields(text), " "), most)
}
// flat is text on one line, each run of white space one space, its ends
// kept: the words round a match stay apart from it.
func flat(text string) string {
var b strings.Builder
space := false
for _, r := range text {
if unicode.IsSpace(r) {
space = true
continue
}
if space {
b.WriteByte(' ')
space = false
}
b.WriteRune(r)
}
if space {
b.WriteByte(' ')
}
return b.String()
}
// snipHead is text's first most runes; snipTail its last.
func snipHead(text string, most int) string {
if r := []rune(text); len(r) > most {
return string(r[:most]) + "…"
}
return text
}
func snipTail(text string, most int) string {
if r := []rune(text); len(r) > most {
return "…" + string(r[len(r)-most:])
}
return text
}