cryingLiu on X asked to search the chat history of every agent magpie
reads sessions from: prompts and replies, from one place.
What the user gets:
- The Sessions page's search also lists, under the agent's own list,
the other agents' sessions whose conversation says the words, each
with a snippet. A hit opens the conversation in the sheet at the
message that said it (transcript?find=), with "N earlier messages
not shown"; the page itself never scrolls. While the index is still
being built the head says "Indexing sessions…" or "Indexing N of M
sessions…", and the page asks again every 3s until it is done.
- Magpie Sessions, a built-in MCP server in Library → MCP (Discover),
opt in per agent like the other magpie servers. Its tools are
search_sessions(query, agent?, limit) and read_session(id, around?),
both returning text. It runs as `magpie mcp sessions` over stdio and
reaches the gateway's /mcp/magpie/sessions, which serves only local
callers that are not browsers.
How it works:
- internal/sessions/said_index.go keeps said-v1.db beside sessions.json:
a contentless SQLite FTS5 index (detail=none) of the words each
session says. It is built from the sessions list sessions already
caches and refreshed at most every 10s: a new or rewritten file is
read once, a grown Claude Code or Codex file only from where it ended,
and a gone one is forgotten. A query asks the index which sessions
have every word, then reads only those files for the snippet, for at
most 6s. A search waits up to 2s for a refresh. While the first
listing is still running the answer says `listing`, so an empty first
answer is not read as "no session says it".
- Privacy: only agents sessions.Reads allows are indexed or searched;
nothing is read until the user has answered the sessions question,
and in gateway mode no agent's own files are read (the page doesn't
ask). Reset forgets the index.
- /api/sessions/said for the page; the CLI parity list names it.
Run, at this tree (rebased on origin/main 256910f17):
- gofmt -l clean; go vet on mote for darwin, GOOS=linux -tags nogui
and GOOS=windows: ok.
- go test -tags nogui ./... -timeout 45m on the WSL Linux box:
every package ok at c8e445c4b (the tree before the one-hit wording,
whose gateway tests ran again on mote: ok).
- GUI: the whole suite on mica at this head was still running when
this was pushed (owner: never hold a verified change behind a full
suite). Under mica's load, beside another session's full suite, 90
tests had failed so far, all in files this change doesn't touch
(accounts, Details, keys, plugins, providers); none in sessions,
library or i18n. The files this change reaches passed on their own
(below).
- Focused, green: internal/sessions (Said*, TranscriptAt),
internal/gateway (SessionsMCP*, own MCP, read-only, key slots),
internal/library (market, opt in), internal/gui (Said, Sessions,
gateway mode); GUI sessions-said, sessions-search, library-sessions-mcp,
vision-mcp-library, library-browser-setup and i18n-keys in chromium
and webkit, every language, wide and narrow.
- Broken by hand, one at a time, each red and green restored: the
index's Listing left out (TestSearchSaidWhileTheSessionsAreFound red
in 2.5s); the page ignoring `listing` (sessions-said 6 of 7 red); the
MCP's local/browser guard (TestSessionsMCPOnlyForAgentsHere red); the
server's opt in (TestSessionsServerInDiscover red); every Reads check
on the search path, the index's and SearchSession's together
(TestSearchSaidLeavesOutAgentsNotRead red). With those gone the
gateway-mode GUI test stays green, because the sessions listing
leaves an unread agent out before the index sees it.
- Real use, in a sandbox HOME with GOPATH, GOMODCACHE and GOCACHE
pinned, over the real history through symlinks (29 GB Claude Code,
60 GB Codex, 14,102 sessions), sessions reads set to all in the
sandbox: first listing ~60s cold (answers say still being found),
whole index built in 9m50s while queries answered in ~6s each, index
38 MB, a common word 4.9s and a rare word 1.0s warm, read_session at
the words of a huge session 1.8s, peak footprint 442 MB for the whole
process with the sessions cache. Nothing was written under the real
~/.claude or ~/.codex.
- The real binary end to end on mote, in a sandbox HOME: `magpie serve`
on a free port and `magpie mcp sessions` over stdio with
MAGPIE_GATEWAY, against a Claude Code session written there:
initialize, tools/list, search_sessions found it with its snippet,
read_session at the words started 3 messages before them, a word
nowhere said "No session says", and a POST with a web page's Origin
was refused 403. That run is how "1 sessions say" was found and
made "1 session says" (TestSessionsMCPSearch red before, green after).
Not tried: a real agent (Claude Code, Codex) calling the server it was
given from the Library, and the page against a real backend (the GUI
tests fake the API). The index on Windows and Linux ran only through
the Go suite.
343 lines
10 KiB
Go
343 lines
10 KiB
Go
package sessions
|
|
|
|
// A session's whole conversation, read from the agent's own file when it is
|
|
// asked for: what was said, in order, by the user, the model and its tools.
|
|
// The file is only read; magpie keeps no copy.
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"math"
|
|
|
|
"github.com/tidwall/gjson"
|
|
)
|
|
|
|
// Transcript is what was said in a session, in the order it was said.
|
|
type Transcript struct {
|
|
Parts []Part `json:"parts"`
|
|
Cut bool `json:"cut,omitempty"` // there was more than is kept here
|
|
// From is the parts before the first one kept, left out so that the
|
|
// part a search found is shown (TranscriptAt)
|
|
From int `json:"from,omitempty"`
|
|
Source string `json:"source,omitempty"`
|
|
Captured int `json:"captured,omitempty"`
|
|
}
|
|
|
|
// transcriptMax is the characters of all of a transcript's parts.
|
|
const transcriptMax = 400_000
|
|
|
|
// ErrNoTranscript is a session whose conversation magpie can't read: an
|
|
// agent that keeps it in a database, or in a form not read here.
|
|
var ErrNoTranscript = errors.New("this agent's conversations can't be shown")
|
|
|
|
// HasTranscript says whether an agent's sessions can be read as a
|
|
// transcript.
|
|
func HasTranscript(agent string) bool {
|
|
switch agent {
|
|
case "claude", "qoder", "qoder-cn", "codex", "pi", "raft", "cindy", "omp", "cursor", "opencode", "kimi", "agy", "openmausbot":
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// readable says whether a session's conversation can be read: its agent's
|
|
// can, and its file is the one they are read from (an agy conversation
|
|
// listed from its row alone has none).
|
|
func readable(s Session) bool {
|
|
return HasTranscript(s.Agent) && !(s.Agent == "agy" && agyRowOnly(s.Path))
|
|
}
|
|
|
|
func (t *Transcript) add(_ bool, p Part) bool {
|
|
size := 0
|
|
for _, x := range t.Parts {
|
|
size += len(x.Text)
|
|
}
|
|
if size >= transcriptMax {
|
|
t.Cut = true
|
|
return false
|
|
}
|
|
if p, ok := keep(p); ok {
|
|
t.Parts = append(t.Parts, p)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// TranscriptOf reads a session's conversation from its (main) file.
|
|
func TranscriptOf(s Session) (Transcript, error) {
|
|
if !Reads(s.Agent) {
|
|
return Transcript{Parts: []Part{}}, ErrNotRead
|
|
}
|
|
out := Transcript{Parts: []Part{}}
|
|
if !HasTranscript(s.Agent) || s.Path == "" {
|
|
return out, ErrNoTranscript
|
|
}
|
|
return out, readTranscript(s, out.add)
|
|
}
|
|
|
|
// transcriptLead is the parts kept before the one TranscriptAt finds,
|
|
// when the ones before it are left out.
|
|
const transcriptLead = 6
|
|
|
|
// TranscriptAt is TranscriptOf for a reader brought to the part that
|
|
// holds needle (NeedleOf), the first said one, else the first anywhere,
|
|
// as SearchSession's hit: when TranscriptOf would be cut before that
|
|
// part, the parts before it are left out (but a few) and From says how
|
|
// many were.
|
|
func TranscriptAt(s Session, needle string) (Transcript, error) {
|
|
if needle == "" {
|
|
return TranscriptOf(s)
|
|
}
|
|
if !Reads(s.Agent) {
|
|
return Transcript{Parts: []Part{}}, ErrNotRead
|
|
}
|
|
if !HasTranscript(s.Agent) || s.Path == "" {
|
|
return Transcript{Parts: []Part{}}, ErrNoTranscript
|
|
}
|
|
// the parts TranscriptOf keeps are counted as it keeps them, and the
|
|
// found one's place among them noted, and the characters before it
|
|
at, saidAt, n, size, sizeAt, saidSize := -1, -1, 0, 0, 0, 0
|
|
if err := readTranscript(s, func(_ bool, p Part) bool {
|
|
p, ok := keep(p)
|
|
if !ok {
|
|
return true
|
|
}
|
|
if searched(p) {
|
|
if _, hit := hitIn(p, needle); hit {
|
|
if at < 0 {
|
|
at, sizeAt = n, size
|
|
}
|
|
if said(p) && saidAt < 0 {
|
|
saidAt, saidSize = n, size
|
|
}
|
|
}
|
|
}
|
|
n++
|
|
size += len(p.Text)
|
|
return saidAt < 0
|
|
}); err != nil {
|
|
return Transcript{Parts: []Part{}}, err
|
|
}
|
|
if saidAt >= 0 {
|
|
at, sizeAt = saidAt, saidSize
|
|
}
|
|
if at < 0 || sizeAt < transcriptMax {
|
|
return TranscriptOf(s)
|
|
}
|
|
out := Transcript{Parts: []Part{}, From: max(0, at-transcriptLead)}
|
|
i := 0
|
|
return out, readTranscript(s, func(in bool, p Part) bool {
|
|
if _, ok := keep(p); !ok {
|
|
return true
|
|
}
|
|
i++
|
|
if i <= out.From {
|
|
return true
|
|
}
|
|
return out.add(in, p)
|
|
})
|
|
}
|
|
|
|
// readTranscript tells add each part of a session's conversation, in order,
|
|
// as its agent's file has it.
|
|
func readTranscript(s Session, add func(bool, Part) bool) error {
|
|
return readTranscriptOf(s, nil, add)
|
|
}
|
|
|
|
// readTranscriptOf is readTranscript decoding only the lines keep says yes
|
|
// to, where a line stands alone (Claude's, Codex's, Kimi's); Pi's lines are a tree,
|
|
// read whole.
|
|
func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bool) error {
|
|
whole := Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}
|
|
switch s.Agent {
|
|
case "opencode":
|
|
return openCodeTranscript(s, add)
|
|
case "cursor":
|
|
return cursorTranscript(s.Path, add)
|
|
case "codex":
|
|
return codexContentOf(whole, keep, add)
|
|
case "pi", "raft", "cindy", "omp":
|
|
return piTranscript(s.Path, add)
|
|
case "kimi":
|
|
return kimiTranscript(s.Path, keep, add)
|
|
case "agy":
|
|
return agyTranscript(s.Path, keep, add)
|
|
case "openmausbot":
|
|
return ombTranscript(s, add)
|
|
default:
|
|
if s.BranchOf != "" && keep == nil {
|
|
return branchTranscript(s, add)
|
|
}
|
|
return claudeContentOf(whole, keep, add)
|
|
}
|
|
}
|
|
|
|
// branchTranscript reads a branch (ccFamily) as its conversation went: the
|
|
// session it is a branch of from its start up to the last message the two
|
|
// share, then what the branch said on its own. A fork made after a
|
|
// compaction holds only the summary and what follows it, and opened on
|
|
// that summary and one turn (Neo, #feedback). A search reads the branch's
|
|
// own file only, so a hit in the shared part is the head's, not each
|
|
// branch's again.
|
|
func branchTranscript(s Session, add func(bool, Part) bool) error {
|
|
ends := map[string]int64{}
|
|
if _, err := scanThin(s.BranchOf, 0, nil, thinClaude, func(b []byte, _, end int64) bool {
|
|
if u := ccMessageUUID(b); u != "" {
|
|
ends[u] = end
|
|
}
|
|
return true
|
|
}); err != nil {
|
|
// the head unread: the branch alone, as before it was known to be one
|
|
return claudeContentOf(Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}, nil, add)
|
|
}
|
|
fork := int64(-1)
|
|
if _, err := scanThin(s.Path, 0, nil, thinClaude, func(b []byte, _, _ int64) bool {
|
|
if e, ok := ends[ccMessageUUID(b)]; ok && e > fork {
|
|
fork = e
|
|
}
|
|
return true
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
if fork < 0 {
|
|
return claudeContentOf(Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}, nil, add)
|
|
}
|
|
more := true
|
|
if err := claudeContentOf(Call{Agent: s.Agent, File: s.BranchOf, To: fork}, nil, func(in bool, p Part) bool {
|
|
more = add(in, p) && more
|
|
return more
|
|
}); err != nil || !more {
|
|
return err
|
|
}
|
|
return claudeContentOf(Call{Agent: s.Agent, File: s.Path, To: math.MaxInt64}, func(b []byte) bool {
|
|
_, shared := ends[ccMessageUUID(b)]
|
|
return !shared
|
|
}, add)
|
|
}
|
|
|
|
// ccMessageUUID is the uuid of a Claude-format user or assistant line, ""
|
|
// for any other line.
|
|
func ccMessageUUID(b []byte) string {
|
|
if !bytes.Contains(b, ccUser) && !bytes.Contains(b, ccAssistant) {
|
|
return ""
|
|
}
|
|
r := gjson.GetManyBytes(b, "type", "uuid")
|
|
if t := r[0].String(); (t == "user" || t == "assistant") && r[1].Type == gjson.String {
|
|
return r[1].String()
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// piEntry is a line of a Pi (or oh-my-pi) session: an entry of its tree.
|
|
type piEntry struct {
|
|
Type string `json:"type"`
|
|
ID string `json:"id"`
|
|
ParentID string `json:"parentId"`
|
|
Summary string `json:"summary"` // compaction, branch_summary
|
|
Message *struct {
|
|
Role string `json:"role"`
|
|
ToolName string `json:"toolName"`
|
|
Model string `json:"model"` // an assistant's: the one it was answered by (#2253)
|
|
Content json.RawMessage `json:"content"`
|
|
} `json:"message"`
|
|
}
|
|
|
|
var piMessage = []byte(`"type":"message"`)
|
|
|
|
// piTranscript reads the branch the session is on: a Pi session is a tree,
|
|
// each entry naming its parent, and the last entry written is where it
|
|
// stands (an earlier branch, left by /tree or a retry, isn't said again).
|
|
func piTranscript(path string, add func(bool, Part) bool) error {
|
|
byID := map[string]piEntry{}
|
|
last := ""
|
|
_, err := scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
|
|
var e piEntry
|
|
if json.Unmarshal(b, &e) != nil || e.ID == "" || e.Type == "session" || e.Type == "title" {
|
|
return true
|
|
}
|
|
if !bytes.Contains(b, piMessage) && e.Type != "compaction" && e.Type != "branch_summary" {
|
|
// keep the tree whole without holding what isn't shown
|
|
e = piEntry{Type: e.Type, ID: e.ID, ParentID: e.ParentID}
|
|
}
|
|
byID[e.ID], last = e, e.ID
|
|
return true
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var branch []piEntry
|
|
for id, n := last, 0; id != "" && n <= len(byID); n++ {
|
|
e, ok := byID[id]
|
|
if !ok {
|
|
break
|
|
}
|
|
branch = append(branch, e)
|
|
id = e.ParentID
|
|
}
|
|
for i := len(branch) - 1; i >= 0; i-- {
|
|
for _, p := range piParts(branch[i]) {
|
|
if p.Role == "assistant" && branch[i].Message != nil {
|
|
p.Model = branch[i].Message.Model
|
|
}
|
|
if !add(p.Role != "assistant", p) {
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// piParts are what an entry said.
|
|
func piParts(e piEntry) []Part {
|
|
switch e.Type {
|
|
case "compaction", "branch_summary":
|
|
return []Part{{Role: "user", Kind: "context", Text: e.Summary}}
|
|
case "message":
|
|
default:
|
|
return nil
|
|
}
|
|
if e.Message == nil {
|
|
return nil
|
|
}
|
|
m := e.Message
|
|
var role string
|
|
switch m.Role {
|
|
case "user":
|
|
role = "user"
|
|
case "assistant":
|
|
role = "assistant"
|
|
case "toolResult":
|
|
return []Part{{Role: "tool", Kind: "tool_result", Name: m.ToolName, Text: resultText(m.Content)}}
|
|
default:
|
|
return nil
|
|
}
|
|
var s string
|
|
if json.Unmarshal(m.Content, &s) == nil {
|
|
return []Part{textPart(role, s)}
|
|
}
|
|
var blocks []struct {
|
|
Type string `json:"type"`
|
|
Text string `json:"text"`
|
|
Thinking string `json:"thinking"`
|
|
Name string `json:"name"`
|
|
Arguments json.RawMessage `json:"arguments"`
|
|
}
|
|
if json.Unmarshal(m.Content, &blocks) != nil {
|
|
return nil
|
|
}
|
|
var parts []Part
|
|
for _, b := range blocks {
|
|
switch b.Type {
|
|
case "text":
|
|
parts = append(parts, textPart(role, b.Text))
|
|
case "thinking":
|
|
parts = append(parts, Part{Role: role, Kind: "thinking", Text: b.Thinking})
|
|
case "toolCall":
|
|
parts = append(parts, Part{Role: role, Kind: "tool_use", Name: b.Name, Text: pretty(b.Arguments)})
|
|
case "image":
|
|
parts = append(parts, Part{Role: role, Kind: "image", Text: "[image]"})
|
|
}
|
|
}
|
|
return parts
|
|
}
|