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.
306 lines
8.6 KiB
Go
306 lines
8.6 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/signal"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
)
|
|
|
|
// `magpie sessions search` and `magpie sessions show` (yansheng1003 on
|
|
// X: a command an agent can call to search its sessions): the Sessions
|
|
// page's search over every agent's sessions (sessions.SearchSaid, the
|
|
// index of what was said) and the sessions MCP server's text of a hit
|
|
// and of a session (sessions.SaidText, SessionText), read here without
|
|
// the app running.
|
|
|
|
const sessionsSearchUsage = "usage: magpie sessions search <words…> [--agent <agent>] [--days N|today|all] [--limit N] [--wait <duration>] [--json]"
|
|
|
|
const sessionsShowUsage = "usage: magpie sessions show <agent:id> [--find <words>] [--from N] [--max-chars N] [--json]"
|
|
|
|
// searchWait is how long `magpie sessions search` waits for the index to
|
|
// be brought up to date: the first time on a long history it is made,
|
|
// and what was made is kept for the next run.
|
|
const searchWait = 60 * time.Second
|
|
|
|
// sessionsTextHow is how the command's texts say to ask for more.
|
|
var sessionsTextHow = sessions.TextHow{
|
|
More: "ask with a higher --limit",
|
|
Read: "Read one with: magpie sessions show <agent:id> --find <words>",
|
|
From: func(s sessions.Session, n int) string {
|
|
return fmt.Sprintf("magpie sessions show %s --from %d", sessions.SessionRef(s), n)
|
|
},
|
|
}
|
|
|
|
// errNotAsked: nothing is read until the user allows it.
|
|
var errNotAsked = errors.New(notAskedLine)
|
|
|
|
type searchOpts struct {
|
|
words []string
|
|
agent string
|
|
days int // -1: every day
|
|
limit int
|
|
wait time.Duration
|
|
json bool
|
|
find string
|
|
from int
|
|
most int
|
|
}
|
|
|
|
// parseSearchArgs reads the arguments of search (or show): words, and
|
|
// the flags each takes. A flag it doesn't know is an error, never words
|
|
// to look for; after -- every argument is words.
|
|
func parseSearchArgs(args []string, show bool) (searchOpts, error) {
|
|
o := searchOpts{days: -1, limit: 10, wait: searchWait}
|
|
use := sessionsSearchUsage
|
|
if show {
|
|
use = sessionsShowUsage
|
|
}
|
|
words := true
|
|
for i := 0; i < len(args); i++ {
|
|
a := args[i]
|
|
if !words || !strings.HasPrefix(a, "-") || a == "-" {
|
|
o.words = append(o.words, a)
|
|
continue
|
|
}
|
|
if a == "--" {
|
|
words = false
|
|
continue
|
|
}
|
|
name, v, has := strings.Cut(a, "=")
|
|
takes := map[string]bool{"--agent": !show, "-a": !show, "--days": !show, "-d": !show, "--limit": !show, "-n": !show, "--wait": !show,
|
|
"--find": show, "--from": show, "--max-chars": show}
|
|
switch {
|
|
case name == "--json":
|
|
if has {
|
|
return o, fmt.Errorf("--json takes no value\n%s", use)
|
|
}
|
|
o.json = true
|
|
continue
|
|
case name == "-h" || name == "--help":
|
|
return o, fmt.Errorf("%s", use)
|
|
case !takes[name]:
|
|
return o, fmt.Errorf("unknown flag %q\n%s", a, use)
|
|
}
|
|
if !has {
|
|
if i+1 >= len(args) || (strings.HasPrefix(args[i+1], "-") && name != "--find") {
|
|
return o, fmt.Errorf("%s takes a value\n%s", name, use)
|
|
}
|
|
i++
|
|
v = args[i]
|
|
}
|
|
num := func() (int, error) {
|
|
n, err := strconv.Atoi(v)
|
|
if err != nil || n < 0 {
|
|
return 0, fmt.Errorf("%s takes a number\n%s", name, use)
|
|
}
|
|
return n, nil
|
|
}
|
|
var err error
|
|
switch name {
|
|
case "--agent", "-a":
|
|
o.agent = v
|
|
case "--days", "-d":
|
|
switch strings.ToLower(v) {
|
|
case "today", "1d":
|
|
o.days = 1
|
|
case "all", "0":
|
|
o.days = -1
|
|
default:
|
|
n, e := strconv.Atoi(strings.TrimSuffix(strings.ToLower(v), "d"))
|
|
if e != nil || n < 0 {
|
|
return o, fmt.Errorf("--days takes a number of days, today or all\n%s", use)
|
|
}
|
|
o.days = n
|
|
}
|
|
case "--limit", "-n":
|
|
if o.limit, err = num(); err == nil && (o.limit < 1 || o.limit > 100) {
|
|
err = fmt.Errorf("--limit takes a number from 1 to 100\n%s", use)
|
|
}
|
|
case "--wait":
|
|
if o.wait, err = time.ParseDuration(v); err != nil || o.wait < 0 {
|
|
err = fmt.Errorf("--wait takes a duration (30s, 2m)\n%s", use)
|
|
}
|
|
case "--find":
|
|
o.find = v
|
|
case "--from":
|
|
o.from, err = num()
|
|
case "--max-chars":
|
|
o.most, err = num()
|
|
}
|
|
if err != nil {
|
|
return o, err
|
|
}
|
|
}
|
|
if len(o.words) == 0 {
|
|
return o, fmt.Errorf("%s", use)
|
|
}
|
|
if show && len(o.words) != 1 {
|
|
return o, fmt.Errorf("one session at a time\n%s", use)
|
|
}
|
|
return o, nil
|
|
}
|
|
|
|
// signalContext ends on Ctrl+C, so a long first index stops cleanly
|
|
// (what was indexed is kept).
|
|
func signalContext() (context.Context, func()) {
|
|
return signal.NotifyContext(context.Background(), os.Interrupt)
|
|
}
|
|
|
|
// sessionsSearchTo: `magpie sessions search <words…>`.
|
|
func sessionsSearchTo(w io.Writer, args []string) error {
|
|
o, err := parseSearchArgs(args, false)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !sessions.SettleReads().Asked {
|
|
return errNotAsked
|
|
}
|
|
needle := sessions.NeedleOf(strings.Join(o.words, " "))
|
|
if o.agent != "" {
|
|
if o.agent, err = searchAgent(o.agent); err != nil {
|
|
return err
|
|
}
|
|
if !sessions.Reads(o.agent) {
|
|
return fmt.Errorf("%w: magpie sessions read on %s allows it", sessions.ErrNotRead, o.agent)
|
|
}
|
|
}
|
|
ctx, stop := signalContext()
|
|
defer stop()
|
|
var progress func(int, int)
|
|
if isTerminal(os.Stderr) && !o.json {
|
|
shown := false
|
|
progress = func(n, of int) {
|
|
if n < of {
|
|
fmt.Fprintf(os.Stderr, "\rIndexing %d of %d sessions…", n, of)
|
|
shown = true
|
|
}
|
|
}
|
|
defer func() {
|
|
if shown {
|
|
fmt.Fprint(os.Stderr, "\r\033[K")
|
|
}
|
|
}()
|
|
}
|
|
if err := sessions.SaidReady(ctx, o.wait, progress); err != nil {
|
|
return err
|
|
}
|
|
var since time.Time
|
|
if o.days > 0 {
|
|
y, m, d := time.Now().Date()
|
|
since = time.Date(y, m, d-(o.days-1), 0, 0, 0, 0, time.Local)
|
|
}
|
|
found, err := sessions.SearchSaidSince(ctx, needle, o.agent, since, o.limit)
|
|
if errors.Is(err, sessions.ErrNoWords) {
|
|
return fmt.Errorf("nothing to search for: the words need a letter or digit\n%s", sessionsSearchUsage)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if o.json {
|
|
for i := range found.Hits {
|
|
found.Hits[i].Session.Path = tildePath(found.Hits[i].Session.Path)
|
|
}
|
|
return writeJSON(w, found)
|
|
}
|
|
fmt.Fprintln(w, sessions.SaidText(found, needle, sessionsTextHow))
|
|
return nil
|
|
}
|
|
|
|
// sessionsShowTo: `magpie sessions show <agent:id>`.
|
|
func sessionsShowTo(w io.Writer, args []string) error {
|
|
o, err := parseSearchArgs(args, true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !sessions.SettleReads().Asked {
|
|
return errNotAsked
|
|
}
|
|
s, err := findSession(o.words[0])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if o.json {
|
|
var tr sessions.Transcript
|
|
if needle := sessions.NeedleOf(o.find); needle != "" {
|
|
tr, err = sessions.TranscriptAt(s, needle)
|
|
} else {
|
|
tr, err = sessions.TranscriptOf(s)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.Path = tildePath(s.Path)
|
|
return writeJSON(w, struct {
|
|
Session sessions.Session `json:"session"`
|
|
Transcript sessions.Transcript `json:"transcript"`
|
|
}{s, tr})
|
|
}
|
|
text, err := sessions.SessionText(s, sessions.ReadAsk{Find: o.find, From: o.from, MaxChars: o.most}, sessionsTextHow)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Fprintln(w, text)
|
|
return nil
|
|
}
|
|
|
|
// findSession is the session ref names: agent:id as search prints it,
|
|
// or an id alone when one agent has it.
|
|
func findSession(ref string) (sessions.Session, error) {
|
|
agent, id, ok := strings.Cut(ref, ":")
|
|
if ok && agent != "" && id != "" {
|
|
if !sessions.Reads(agent) {
|
|
return sessions.Session{}, fmt.Errorf("%w: magpie sessions read on %s allows it", sessions.ErrNotRead, agent)
|
|
}
|
|
if s, found := sessions.Find(agent, id); found {
|
|
return s, nil
|
|
}
|
|
return sessions.Session{}, fmt.Errorf("no session %s (magpie sessions search finds them)", ref)
|
|
}
|
|
var have []sessions.Session
|
|
for _, s := range sessions.List(sessions.All) {
|
|
if s.ID == ref && !slices.ContainsFunc(have, func(h sessions.Session) bool { return h.Agent == s.Agent }) {
|
|
have = append(have, s)
|
|
}
|
|
}
|
|
switch len(have) {
|
|
case 0:
|
|
return sessions.Session{}, fmt.Errorf("no session %s (magpie sessions search finds them; name one as agent:id)", ref)
|
|
case 1:
|
|
if !sessions.Reads(have[0].Agent) {
|
|
return sessions.Session{}, sessions.ErrNotRead
|
|
}
|
|
if s, found := sessions.Find(have[0].Agent, have[0].ID); found {
|
|
return s, nil
|
|
}
|
|
return have[0], nil
|
|
}
|
|
var refs []string
|
|
for _, s := range have {
|
|
refs = append(refs, sessions.SessionRef(s))
|
|
}
|
|
return sessions.Session{}, fmt.Errorf("%s is more than one session: %s", ref, strings.Join(refs, ", "))
|
|
}
|
|
|
|
// searchAgent is the agent typed, by id or name.
|
|
func searchAgent(typed string) (string, error) {
|
|
names := agentNames()
|
|
if _, ok := names[typed]; ok || slices.Contains(sessions.Found(), typed) {
|
|
return typed, nil
|
|
}
|
|
for id, name := range names {
|
|
if strings.EqualFold(id, typed) || strings.EqualFold(name, typed) {
|
|
return id, nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("unknown agent %q (magpie sessions read lists them)\n%s", typed, sessionsSearchUsage)
|
|
}
|