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.
This commit is contained in:
yetone
2026-11-17 17:33:23 +08:00
parent a2213b1b67
commit 64ad53f6c7
19 changed files with 861 additions and 193 deletions
+6
View File
@@ -72,6 +72,12 @@ func helpFor(args []string) string {
case "log", "logs":
return logUsage
case "sessions":
if len(args) > 1 && args[1] == "search" {
return sessionsSearchUsage
}
if len(args) > 1 && args[1] == "show" {
return sessionsShowUsage
}
return sessionsUsage
case "search":
return searchUsage
+4
View File
@@ -173,6 +173,10 @@ const usage = `magpie — one place to pick every agent's model
magpie sessions --days N|today|all [--model <m>] [--folder <f>] [--json]
what every session spent, day by day, with the top models and folders (7 days)
magpie sessions read [on|off all|<agent>…] which agents' session history magpie may read (none until allowed)
magpie sessions search <words…> [--agent <a>] [--days N|today|all] [--limit N] [--json]
every agent's sessions that said those words, newest first, with where
magpie sessions show <agent:id> [--find <words>] [--from N] [--max-chars N] [--json]
one session's conversation as text, from where the words were said
magpie quota [<provider>] [--json] what is left of every subscription, plan and key balance
magpie quota wait <provider|account> [--timeout <d>] [--quiet]
block until that subscription (any of its accounts) or account has allowance again
+6
View File
@@ -28,6 +28,12 @@ func sessionsCmd(args []string) error {
if len(args) > 1 && args[1] == "read" {
return sessionReadsTo(os.Stdout, args[2:])
}
if len(args) > 1 && args[1] == "search" {
return sessionsSearchTo(os.Stdout, args[2:])
}
if len(args) > 1 && args[1] == "show" {
return sessionsShowTo(os.Stdout, args[2:])
}
if r := sessions.SettleReads(); !r.Asked {
fmt.Fprintln(os.Stderr, notAskedLine)
}
+305
View File
@@ -0,0 +1,305 @@
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)
}
+192
View File
@@ -0,0 +1,192 @@
package cli
import (
"bytes"
"encoding/json"
"errors"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/settings"
)
const fixClaude = "claude:11111111-2222-3333-4444-555555555555"
func runSearch(t *testing.T, show bool, args ...string) (string, error) {
t.Helper()
var b bytes.Buffer
var err error
if show {
err = sessionsShowTo(&b, args)
} else {
err = sessionsSearchTo(&b, args)
}
return b.String(), err
}
// magpie sessions search (yansheng1003 on X): the Sessions page's search
// over every agent's sessions, from the command line, as the sessions
// MCP server writes it, each hit named so that show reads it.
func TestSessionsSearch(t *testing.T) {
sessionsHome(t)
out, err := runSearch(t, false, "login", "bug")
if err != nil {
t.Fatal(err)
}
wantAll(t, out, `1 session says "login bug":`, "1. "+fixClaude, "/work/app · ", "user: Fix the [login bug] in auth.go", "magpie sessions show <agent:id> --find")
if strings.Contains(out, "codex:") {
t.Errorf("a Codex session doesn't say it:\n%s", out)
}
if out, err = runSearch(t, false, "readme", "--agent", "Codex"); err != nil {
t.Fatal(err)
}
wantAll(t, out, "1. codex:01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd", "user: Add a [README]")
if out, _ = runSearch(t, false, "login", "--agent", "codex"); !strings.Contains(out, `No session says "login".`) {
t.Errorf("--agent codex found Claude Code's:\n%s", out)
}
// the fixtures are from September 2026: none was used today
if out, _ = runSearch(t, false, "login", "--days", "today"); !strings.Contains(out, "No session says") {
t.Errorf("--days today found an old session:\n%s", out)
}
if out, _ = runSearch(t, false, "login", "--days", "all"); !strings.Contains(out, fixClaude) {
t.Errorf("--days all left it out:\n%s", out)
}
if out, err = runSearch(t, false, "--json", "login"); err != nil {
t.Fatal(err)
}
var found sessions.SaidFound
if err := json.Unmarshal([]byte(out), &found); err != nil {
t.Fatalf("%v\n%s", err, out)
}
if len(found.Hits) != 1 || found.Hits[0].Session.Agent != "claude" || found.Hits[0].Hit.Match == "" || found.Listing || found.Indexed != found.Total {
t.Fatalf("json: %+v", found)
}
if strings.Contains(found.Hits[0].Session.Path, os.Getenv("HOME")) {
t.Errorf("the path isn't under ~: %s", found.Hits[0].Session.Path)
}
// words that start with a dash, after --
if _, err := runSearch(t, false, "--", "--login"); err != nil {
t.Errorf("after -- every argument is words: %v", err)
}
}
// magpie sessions show reads one session as text, from where the words
// were said, or as the page's transcript in --json; an id alone is
// enough when one agent has it.
func TestSessionsShow(t *testing.T) {
sessionsHome(t)
out, err := runSearch(t, true, fixClaude)
if err != nil {
t.Fatal(err)
}
wantAll(t, out, fixClaude, "/work/app · ", "user:\nFix the login\nbug in auth.go", "called Read")
if out, err = runSearch(t, true, "11111111-2222-3333-4444-555555555555", "--find", "login"); err != nil {
t.Fatal(err)
}
wantAll(t, out, fixClaude, "Fix the login")
if out, err = runSearch(t, true, fixClaude, "--json"); err != nil {
t.Fatal(err)
}
var j struct {
Session sessions.Session `json:"session"`
Transcript sessions.Transcript `json:"transcript"`
}
if err := json.Unmarshal([]byte(out), &j); err != nil || j.Session.ID == "" || len(j.Transcript.Parts) == 0 {
t.Fatalf("json %v: %s", err, out)
}
if _, err := runSearch(t, true, "claude:nope"); err == nil || !strings.Contains(err.Error(), "no session claude:nope") {
t.Errorf("a session that isn't there: %v", err)
}
// reading on from where a read stopped
if out, err = runSearch(t, true, fixClaude, "--from", "2"); err != nil || !strings.Contains(out, "(messages before 2 left out)") || strings.Contains(out, "[0]") {
t.Errorf("--from 2: %v\n%s", err, out)
}
}
// A flag either command doesn't know, or one missing its value, is
// refused with the usage, never taken for words or a session (LESSONS:
// magpie snow --help wrote "--help" into a profile); --help prints the
// command's own usage.
func TestSessionsSearchFlags(t *testing.T) {
sessionsHome(t)
for _, c := range []struct {
show bool
args []string
want string
}{
{false, []string{"login", "--bogus"}, `unknown flag "--bogus"`},
{false, []string{"login", "--find", "x"}, `unknown flag "--find"`},
{false, []string{"login", "--limit"}, "--limit takes a value"},
{false, []string{"login", "--limit", "0"}, "--limit takes a number from 1 to 100"},
{false, []string{"login", "--days", "soon"}, "--days takes a number"},
{false, []string{"login", "--json=1"}, "--json takes no value"},
{false, []string{"--agent", "nobody", "login"}, `unknown agent "nobody"`},
{false, []string{}, sessionsSearchUsage},
{false, []string{"?!"}, "nothing to search for"},
{true, []string{fixClaude, "--agent", "claude"}, `unknown flag "--agent"`},
{true, []string{fixClaude, "--from", "x"}, "--from takes a number"},
{true, []string{fixClaude, "other"}, "one session at a time"},
{true, []string{"--help"}, sessionsShowUsage},
{true, []string{}, sessionsShowUsage},
} {
_, err := runSearch(t, c.show, c.args...)
if err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%v: %v, want %q", c.args, err, c.want)
}
}
for args, want := range map[string]string{
"sessions search --help": sessionsSearchUsage,
"sessions show -h": sessionsShowUsage,
"sessions search login -h": sessionsSearchUsage,
"sessions --help": sessionsUsage,
} {
a := strings.Fields(args)
if !helpAsked(a) || helpFor(a) != want {
t.Errorf("%s: %q", args, helpFor(a))
}
}
}
// Until the user answers which agents' sessions magpie may read, search
// and show read nothing, not even to index, and say how to allow it.
func TestSessionsSearchNotAsked(t *testing.T) {
sessionsHome(t)
if err := settings.SetSessionReads(func(*settings.SessionReads) *settings.SessionReads {
return &settings.SessionReads{}
}); err != nil {
t.Fatal(err)
}
for _, show := range []bool{false, true} {
arg := "login"
if show {
arg = fixClaude
}
out, err := runSearch(t, show, arg)
if !errors.Is(err, errNotAsked) || out != "" {
t.Errorf("show %v: %v\n%s", show, err, out)
}
}
if _, err := os.Stat(sessions.SaidPath()); !os.IsNotExist(err) {
t.Errorf("the index was made before reads were allowed: %v", err)
}
// allowed for Codex alone: Claude Code's session is neither found nor read
if err := settings.SetSessionReads(func(*settings.SessionReads) *settings.SessionReads {
return &settings.SessionReads{Asked: true, Agents: map[string]bool{"codex": true}}
}); err != nil {
t.Fatal(err)
}
if out, err := runSearch(t, false, "login"); err != nil || strings.Contains(out, fixClaude) {
t.Errorf("Claude Code isn't read: %v\n%s", err, out)
}
if _, err := runSearch(t, true, fixClaude); !errors.Is(err, sessions.ErrNotRead) {
t.Errorf("show of an agent not read: %v", err)
}
if _, err := runSearch(t, false, "login", "--agent", "claude"); !errors.Is(err, sessions.ErrNotRead) {
t.Errorf("--agent of an agent not read: %v", err)
}
}
+2 -2
View File
@@ -222,6 +222,8 @@ var cliForRoute = map[string]string{
"GET /api/sessions/reads": "magpie sessions read",
"POST /api/sessions/reads": "magpie sessions read",
"GET /api/sessions": "magpie sessions",
"GET /api/sessions/said": "magpie sessions search",
"GET /api/sessions/transcript": "magpie sessions show",
"POST /api/uninstall": "magpie uninstall",
"GET /api/usage": "magpie usage",
"GET /api/usage/quotas": "magpie quota",
@@ -500,7 +502,6 @@ var notYet = map[string]string{
"GET /api/speeds": U, // sessions_manage.go: the Sessions row's speed curve
"GET /api/sessions/manage": U, // sessions_manage.go
"GET /api/sessions/search": U, // sessions_manage.go
"GET /api/sessions/said": U, // sessions_manage.go: every agent's sessions; agents have the sessions MCP server
"POST /api/sessions/codex-provider": U, // sessions_manage.go
"POST /api/sessions/delete": U, // sessions_manage.go
"POST /api/sessions/purge": U, // sessions_manage.go
@@ -512,7 +513,6 @@ var notYet = map[string]string{
"GET /api/sessions/overview": U, // sessions.go
"GET /api/sessions/progress": U, // sessions.go
"GET /api/sessions/stats": U, // sessions.go
"GET /api/sessions/transcript": U, // sessions.go
"POST /api/agents/open": W, // sessions.go
"POST /api/sessions/carry": U, // sessions.go
"POST /api/sessions/export": U, // sessions.go
+10 -181
View File
@@ -6,7 +6,6 @@ import (
"fmt"
"net/http"
"strings"
"unicode"
"github.com/yetone/magpie/internal/sessions"
)
@@ -28,15 +27,6 @@ const (
sessionsReadTool = "read_session"
)
const (
// sessionsReadChars is how much of a session read_session gives when
// not told, and sessionsReadMost the most it gives
sessionsReadChars = 20_000
sessionsReadMost = 100_000
// sessionsToolChars is what is shown of a tool's call or answer
sessionsToolChars = 400
)
func (s *Server) sessionsMCP(w http.ResponseWriter, r *http.Request) {
// what was said in this computer's agents' sessions: only an agent on
// this computer reads it. Another computer's gateway key and a web
@@ -77,7 +67,7 @@ func sessionsMCPTools() []any {
"session": map[string]any{"type": "string", "description": "The session, as " + sessionsSearchTool + " names it (agent:id)"},
"find": map[string]any{"type": "string", "description": "Start a few messages before where these words were said"},
"from": map[string]any{"type": "integer", "minimum": 0, "description": "Start at this message, as a read before says"},
"max_chars": map[string]any{"type": "integer", "minimum": 1000, "maximum": sessionsReadMost, "default": sessionsReadChars},
"max_chars": map[string]any{"type": "integer", "minimum": 1000, "maximum": sessions.TextReadMost, "default": sessions.TextReadChars},
},
"required": []string{"session"},
},
@@ -144,6 +134,13 @@ func (s *Server) sessionsMCPCall(r *http.Request, m mcpMessage) (any, map[string
// searchSaid is sessions.SearchSaid; a variable for tests.
var searchSaid = sessions.SearchSaid
// sessionsHow is how the MCP server's texts say to ask for more.
var sessionsHow = sessions.TextHow{
More: "ask for a higher limit",
Read: "Read one with " + sessionsReadTool + "(session, find).",
From: func(_ sessions.Session, n int) string { return fmt.Sprintf("%s with from=%d", sessionsReadTool, n) },
}
func sessionsSearch(r *http.Request, a sessionsArgs) (string, error) {
needle := sessions.NeedleOf(a.Query)
if needle == "" {
@@ -160,42 +157,7 @@ func sessionsSearch(r *http.Request, a sessionsArgs) (string, error) {
if err != nil {
return "", err
}
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:%s", i+1, ss.Agent, ss.ID)
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 {
b.WriteString("\nThere may be more: ask for a higher limit, or more words.")
}
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 {
b.WriteString("\nRead one with " + sessionsReadTool + "(session, find).")
}
return b.String(), nil
return sessions.SaidText(found, needle, sessionsHow), nil
}
func sessionsRead(a sessionsArgs) (string, error) {
@@ -210,138 +172,5 @@ func sessionsRead(a sessionsArgs) (string, error) {
if !found {
return "", fmt.Errorf("no session %s", a.Session)
}
var tr sessions.Transcript
var err error
from := max(int(a.From), 0)
if needle := sessions.NeedleOf(a.Find); needle != "" && from == 0 {
tr, err = sessions.TranscriptAt(s, needle)
if err == nil {
from = max(tr.From, sessionsNear(tr, needle)-sessionsLead)
}
} else {
tr, err = sessions.TranscriptOf(s)
}
if err != nil {
return "", err
}
most := int(a.MaxChars)
if most <= 0 {
most = sessionsReadChars
}
most = min(max(most, 1000), sessionsReadMost)
var b strings.Builder
fmt.Fprintf(&b, "%s:%s", s.Agent, s.ID)
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 := sessionsPart(n, p)
if line == "" {
end = n + 1
continue
}
if b.Len()+len(line) > most && end > from {
fmt.Fprintf(&b, "\n(more: %s with from=%d)", sessionsReadTool, 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 with from=%d)", sessionsReadTool, end)
}
return b.String(), nil
}
// sessionsLead is how many messages before the found one a read with
// find starts.
const sessionsLead = 3
// sessionsNear is the number of the first part that says needle, or 0.
func sessionsNear(tr sessions.Transcript, needle string) int {
for i, p := range tr.Parts {
if (p.Kind == "text" || p.Kind == "context") && strings.Contains(sessions.NeedleOf(p.Text), needle) {
return tr.From + i
}
}
return 0
}
// sessionsPart is one part as read_session shows it.
func sessionsPart(n int, p sessions.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, sessionsToolChars))
case "tool_result":
return fmt.Sprintf("[%d] tool answered: %s\n", n, cutLine(text, sessionsToolChars))
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
return sessions.SessionText(s, sessions.ReadAsk{Find: a.Find, From: int(a.From), MaxChars: int(a.MaxChars)}, sessionsHow)
}
+6 -1
View File
@@ -977,13 +977,18 @@ type MarketSkill struct {
// magpie-community/plugins, beside its plugins. magpie-setup has an agent
// set magpie up as the user asks, through its commands (Leyuu_5 on X: so
// many features that an AI could do the setting up); magpie-quota reads
// what magpie quota tells (ttmouse on X).
// what magpie quota tells (ttmouse on X); magpie-sessions searches and
// reads every agent's sessions through magpie sessions search and show
// (yansheng1003 on X).
var featuredSkills = []MarketSkill{{
Source: "magpie-community/plugins", SkillID: "magpie-setup", Name: "magpie-setup", Official: true, Featured: true,
Description: "Set magpie up as you ask, through its own commands: add keys and subscriptions, point agents at models, build routing groups with fallbacks and time-of-day rules, give devices gateway keys with budgets, and share MCP servers and instructions with every agent.",
}, {
Source: "magpie-community/plugins", SkillID: "magpie-quota", Name: "magpie-quota", Official: true, Featured: true,
Description: "Check how much is left of the user's AI subscriptions, coding plans and API key balances through magpie: each usage window's percent used and when it resets, each key's balance, and wait until a subscription has allowance again.",
}, {
Source: "magpie-community/plugins", SkillID: "magpie-sessions", Name: "magpie-sessions", Official: true, Featured: true,
Description: "Search what was said in every coding agent's sessions on this computer through magpie, Claude Code's, Codex's and the others', and read the session a hit is in: find an earlier conversation, decision or fix.",
}}
type skillsShEntry struct {
+8 -2
View File
@@ -233,10 +233,10 @@ func TestFeaturedSkills(t *testing.T) {
t.Cleanup(func() { popular.Lock(); popular.list = nil; popular.Unlock() })
list, _ := MarketSkills("")
if len(list) != 3 || list[0].ID != "magpie-community/plugins/magpie-setup" || list[1].ID != "magpie-community/plugins/magpie-quota" || list[2].ID != "o/r/pdf" {
if len(list) != 4 || list[0].ID != "magpie-community/plugins/magpie-setup" || list[1].ID != "magpie-community/plugins/magpie-quota" || list[2].ID != "magpie-community/plugins/magpie-sessions" || list[3].ID != "o/r/pdf" {
t.Fatalf("market: %+v", list)
}
for _, m := range list[:2] {
for _, m := range list[:3] {
if !m.Official || !m.Featured || m.Description == "" || m.Icon != gh("magpie-community") || !offered(m.Icon) {
t.Fatalf("magpie's own: %+v", m)
}
@@ -244,6 +244,12 @@ func TestFeaturedSkills(t *testing.T) {
if list, _ := MarketSkills("quota"); len(list) == 0 || list[0].SkillID != "magpie-quota" || slices.ContainsFunc(list, func(m MarketSkill) bool { return m.SkillID == "magpie-setup" }) {
t.Fatalf("quota: %+v", list)
}
// yansheng1003 on X: an agent searches every agent's sessions
for _, q := range []string{"sessions", "conversation"} {
if list, _ := MarketSkills(q); len(list) == 0 || list[0].SkillID != "magpie-sessions" {
t.Fatalf("%s: %+v", q, list)
}
}
// Leyuu_5 on X: an agent sets magpie up; found by what a user searches
for _, q := range []string{"setup", "routing", "gateway key"} {
if list, _ := MarketSkills(q); len(list) == 0 || list[0].SkillID != "magpie-setup" {
+51 -1
View File
@@ -121,6 +121,52 @@ func SearchSaid(ctx context.Context, needle, agent string, limit int) (SaidFound
return saidIdx.search(ctx, needle, agent, limit)
}
// SearchSaidSince is SearchSaid of the sessions last used at since or
// after (`magpie sessions search --days`).
func SearchSaidSince(ctx context.Context, needle, agent string, since time.Time, limit int) (SaidFound, error) {
return saidIdx.searchSince(ctx, needle, agent, since, limit)
}
// SaidReady brings the index up to date as a search does, but waits for
// it at most wait, not saidWait: a command run once (`magpie sessions
// search`) has no next search to find the rest by. progress, when
// given, is told every second how far it got.
func SaidReady(ctx context.Context, wait time.Duration, progress func(indexed, total int)) error {
return saidIdx.ready(ctx, wait, progress)
}
func (x *saidIndex) ready(ctx context.Context, wait time.Duration, progress func(indexed, total int)) error {
db, err := x.open()
if err != nil {
return err
}
if progress != nil {
done, gone := make(chan struct{}), make(chan struct{})
// progress is not told anything once this returns
defer func() { close(done); <-gone }()
go func() {
defer close(gone)
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-done:
return
case <-t.C:
x.mu.Lock()
n, of, listed := x.indexed, x.total, x.listed
x.mu.Unlock()
if listed {
progress(n, of)
}
}
}
}()
}
x.fresh(ctx, db, wait)
return nil
}
// ForgetSaid closes the index, so a test's HOME can go: a refresh
// running stops after the session it is reading.
func ForgetSaid() {
@@ -539,6 +585,10 @@ func saidKeys(ctx context.Context, db *sql.DB, terms []string) (map[string]bool,
const saidReadMost = 6 * time.Second
func (x *saidIndex) search(ctx context.Context, needle, agent string, limit int) (SaidFound, error) {
return x.searchSince(ctx, needle, agent, time.Time{}, limit)
}
func (x *saidIndex) searchSince(ctx context.Context, needle, agent string, since time.Time, limit int) (SaidFound, error) {
out := SaidFound{Hits: []SaidHit{}}
terms := saidTerms(needle)
if len(terms) == 0 {
@@ -559,7 +609,7 @@ func (x *saidIndex) search(ctx context.Context, needle, agent string, limit int)
x.mu.Lock()
var found []saidSession
for k := range keys {
if ss, ok := x.sessions[k]; ok && (agent == "" || ss.s.Agent == agent) && Reads(ss.s.Agent) {
if ss, ok := x.sessions[k]; ok && (agent == "" || ss.s.Agent == agent) && !ss.s.Last.Before(since) && Reads(ss.s.Agent) {
found = append(found, ss)
}
}
+224
View File
@@ -0,0 +1,224 @@
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
}
+3 -3
View File
@@ -164,7 +164,7 @@ cfab436ba62869c63471dbce5355f88737230e50f3c916b9b7bf79ac8434c465 docs/ja/t3-cod
0309b9d5310b23a80bd11981b2f13c77e0f6bf9ebba12d2fd0c747bdeb0895ce docs/ja/tencent-cloud.html
7d0235fa7af13cba72826dc17f1e4bd08e5b4c115998e1c5db67879dcb890009 docs/ja/troubleshooting.html
2e4df362f721892b504a4730e57faedcd4712f01ec4b93e924fc29b1ec09339a docs/ja/tuanjie-cowork.html
e4738358c0ff8e641d7691af493f47a50ae38e1bb2e4b52423a989a91424e231 docs/ja/usage.html
afd43a767def8db51ce75ea9ff80634dc06759f566b908db229a0a419dc2ca90 docs/ja/usage.html
81cbff4dea3c3f33812ec96f870acba37f47492f8bfd4f8a4c0677e1336bc649 docs/ja/vercel.html
7979bf06c0908e2c2d7c8d7c7f002b9faf3428729c479cbe3c01d8e535b484f5 docs/ja/vertex.html
e0892b83ad5eb94129bf1455995b247fe135168a78e879709ebf910cf4839679 docs/ja/volcengine.html
@@ -239,7 +239,7 @@ cbf3a16eee9a07f5c1f5dda30b26787d574a79189fbe8a26ed6088aa9c962d88 docs/routing-g
d14ec7a227d30a6f79037ec591a164a518d148894cdceb98b7ad6f6322b50430 docs/tencent-cloud.html
067c04117d9cc32474087b6a813d6ed475923f3bdb12022aeaba79dcd3ef65da docs/troubleshooting.html
c9629843c3f9698c9e471db1c47eb1eafee6aa30d5b49212f9028b06fe2a4a97 docs/tuanjie-cowork.html
83cee74efb30ea123d9971b7c5467d0ad06a7068855aa47928733c12a3e02342 docs/usage.html
8770d03bad9e7c2799153bf11f5dc829a7d01bc4eb65caf23ec7bedc3fb3ac3c docs/usage.html
bedde3b80362e29f7525e5dc0d7efabfc6bf1a086f8b2a650e161632330b4721 docs/vercel.html
4947d6620bf521820c5c8c5d37ac9453c0212d9331950e6379490d1fa0fb5d98 docs/vertex.html
b56b0f4c59cc3fd2297b82acff05bc090ab0af61a3b7a926c4168b8f08b4728b docs/volcengine.html
@@ -364,7 +364,7 @@ b98fe5e40042853057e726642fae823183b85b27ead65de68705a13e0ab4a318 docs/zh/subscr
afcdb46194424409ced78a15df7beb5bc9b29da51e406e3518f24e6f1445e673 docs/zh/tencent-cloud.html
1ac57d96e52c645303c2ed6840179b540987e0d724d4ab3354549d10b09b45b3 docs/zh/troubleshooting.html
893cbeb3159e0a2e18121f50256e082508ef174a8c2abc36d675550eb2ccb94e docs/zh/tuanjie-cowork.html
d5ccae9b37f97199f1484f8e30a00163b013b24a30df8f3483639c7de1bf6d87 docs/zh/usage.html
d648c6f31284cb465077032ee720ed4a319534e88701067a96c35101553edbfe docs/zh/usage.html
f8566d876fc113894ba990c09dd901b3a228d71bfe57c4ce5be87984cfd9309a docs/zh/vercel.html
c278929b5322a8b70de45d291ac3df0e9b787255dc3e4b73baa8d943c8118b19 docs/zh/vertex.html
ca7f32f2d6d2b097d24950097b68bef395668e30f237d2e3b5d3417cb0c56528 docs/zh/volcengine.html
+9
View File
@@ -171,6 +171,7 @@
<a href="#overview">記録される内容</a>
<a href="#cli">コマンドラインで見る</a>
<a href="#sessions">セッションごとの費用</a>
<a href="#search-sessions">話した内容を検索</a>
<a href="#price">価格の出どころ</a>
<a href="#unpriced">価格のないリクエスト</a>
<a href="#statusline">Claude Code のステータスライン</a>
@@ -196,6 +197,14 @@ magpie sessions --days 7 # what every session spent, day by day
magpie sessions --model <m> --folder <f> --json
magpie sessions read # which agents' history magpie may read</pre></div>
<p>エージェント自身のセッションファイルは、そのエージェントを許可するまで読みません。既定ではどれも読みません。許可すると、magpie を通らなかったリクエスト(Claude Code が claude.ai に直接サインインしている場合など)も、それらのファイルから使用量に入ります。</p>
<h2 id="search-sessions"><a class="anchor" href="#search-sessions">話した内容を検索</a></h2>
<p><span class="ui">セッション</span> ページの検索、<code>magpie sessions search</code>、Magpie Sessions MCP サーバー(ライブラリ → MCP)は、プロンプトや返答でその言葉を言ったすべてのエージェントのセッションを新しい順に見つけ、前後の文を添えて示します。<code>magpie sessions show</code> はセッションをテキストで表示し、その言葉が出た場所から始めます。エージェントが以前の会話・決定・修正を自分で調べられます:</p>
<div class="code"><span class="lang">ターミナル</span><button class="copy" data-copy="use-said">コピー</button><pre id="use-said">magpie sessions search login bug # every agent's sessions that said it
magpie sessions search "rate limit" --agent codex --days 7 --limit 5
magpie sessions search login --json
magpie sessions show claude:&lt;id&gt; --find login # that session, from where it was said
magpie sessions show claude:&lt;id&gt; --from 40 --json</pre></div>
<p>読み取りを許可したエージェントだけを読みます。履歴が長いと最初の検索で話した内容の索引を作り、次からはそれを使います。</p>
<h2 id="price"><a class="anchor" href="#price">価格の出どころ</a></h2>
<p>リクエストは実効価格で数えられます。そのプロバイダーとモデルにあなたが設定した価格、なければプロバイダー自身のカタログの価格、それもなければ models.dev にあるモデル提供元の価格です。</p>
<p>割引や倍率で再販する中継サービスは、提供元の価格では請求しません。実際の価格を設定すれば、使用量とセッションの合計はそれで計算されます。</p>
+9
View File
@@ -171,6 +171,7 @@
<a href="#overview">What is recorded</a>
<a href="#cli">On the command line</a>
<a href="#sessions">What each session cost</a>
<a href="#search-sessions">Search what was said</a>
<a href="#price">Where a price comes from</a>
<a href="#unpriced">Calls with no price</a>
<a href="#statusline">Claude Code's status line</a>
@@ -196,6 +197,14 @@ magpie sessions --days 7 # what every session spent, day by day
magpie sessions --model <m> --folder <f> --json
magpie sessions read # which agents' history magpie may read</pre></div>
<p>An agent's own session files are read only once you allow that agent; none are read until then. Once allowed, calls that didn't go through magpie (Claude Code signed in to claude.ai directly, say) reach Usage from those files too.</p>
<h2 id="search-sessions"><a class="anchor" href="#search-sessions">Search what was said</a></h2>
<p>The <span class="ui">Sessions</span> page's search, <code>magpie sessions search</code> and the Magpie Sessions MCP server (Library → MCP) find the sessions of every agent whose prompts or replies say the words, newest first, each with a snippet. <code>magpie sessions show</code> prints one as text, from where the words were said, so an agent can look up an earlier conversation, decision or fix by itself:</p>
<div class="code"><span class="lang">Terminal</span><button class="copy" data-copy="use-said">Copy</button><pre id="use-said">magpie sessions search login bug # every agent's sessions that said it
magpie sessions search "rate limit" --agent codex --days 7 --limit 5
magpie sessions search login --json
magpie sessions show claude:&lt;id&gt; --find login # that session, from where it was said
magpie sessions show claude:&lt;id&gt; --from 40 --json</pre></div>
<p>They read only the agents you allow magpie to read. The first search on a long history builds an index of what was said, kept for the next one.</p>
<h2 id="price"><a class="anchor" href="#price">Where a price comes from</a></h2>
<p>A call is counted at its effective price: what you set for that provider and model if you did, otherwise what the provider's own catalogue lists, otherwise what models.dev lists for the model's maker.</p>
<p>A relay that resells at a discount or a multiplier isn't charging the maker's price. Say what it actually charges, and Usage and the session totals use that:</p>
+9
View File
@@ -171,6 +171,7 @@
<a href="#overview">记了什么</a>
<a href="#cli">命令行查看</a>
<a href="#sessions">每个会话花了多少</a>
<a href="#search-sessions">搜索说过的话</a>
<a href="#price">价格从哪来</a>
<a href="#unpriced">没有价格的请求</a>
<a href="#statusline">Claude Code 状态栏</a>
@@ -196,6 +197,14 @@ magpie sessions --days 7 # what every session spent, day by day
magpie sessions --model <m> --folder <f> --json
magpie sessions read # which agents' history magpie may read</pre></div>
<p>Agent 自己的会话文件,要你允许该 Agent 后 magpie 才会读取,默认一个都不读。允许后,没经过 magpie 的请求(比如 Claude Code 直接登录 claude.ai 时)也能从这些文件计入用量。</p>
<h2 id="search-sessions"><a class="anchor" href="#search-sessions">搜索说过的话</a></h2>
<p><span class="ui">会话</span> 页的搜索、<code>magpie sessions search</code> 和 Magpie Sessions MCP 服务器(资源库 → MCP)都能在所有 Agent 的会话里,找出提示词或回复里说过这些词的会话,最新的在前,每条带一段上下文。<code>magpie sessions show</code> 把一个会话以文本打印出来,从说到这些词的地方开始,Agent 自己就能查到之前的对话、决定或修复:</p>
<div class="code"><span class="lang">终端</span><button class="copy" data-copy="use-said">复制</button><pre id="use-said">magpie sessions search login bug # every agent's sessions that said it
magpie sessions search "rate limit" --agent codex --days 7 --limit 5
magpie sessions search login --json
magpie sessions show claude:&lt;id&gt; --find login # that session, from where it was said
magpie sessions show claude:&lt;id&gt; --from 40 --json</pre></div>
<p>只读取你允许 magpie 读取的 Agent。长历史上第一次搜索会建立一份索引,之后的搜索接着用。</p>
<h2 id="price"><a class="anchor" href="#price">价格从哪来</a></h2>
<p>每次请求按“实际价格”计费:你给该供应商和模型设了价格就用你的;没设就用供应商自己目录里的价格;再没有就用 models.dev 上模型厂商的价格。</p>
<p>中转站打折或按倍率卖时,厂商的价格就不对了。告诉 magpie 它实际收多少,用量和会话的合计就会按这个算:</p>
+14
View File
@@ -9312,6 +9312,20 @@ magpie sessions read # which agents' history magpie may read
An agent's own session files are read only once you allow that agent; none are read until then. Once allowed, calls that didn't go through magpie (Claude Code signed in to claude.ai directly, say) reach Usage from those files too.
## Search what was said
The Sessions page's search, `magpie sessions search` and the Magpie Sessions MCP server (Library → MCP) find the sessions of every agent whose prompts or replies say the words, newest first, each with a snippet. `magpie sessions show` prints one as text, from where the words were said, so an agent can look up an earlier conversation, decision or fix by itself:
```
magpie sessions search login bug # every agent's sessions that said it
magpie sessions search "rate limit" --agent codex --days 7 --limit 5
magpie sessions search login --json
magpie sessions show claude:<id> --find login # that session, from where it was said
magpie sessions show claude:<id> --from 40 --json
```
They read only the agents you allow magpie to read. The first search on a long history builds an index of what was said, kept for the next one.
## Where a price comes from
A call is counted at its effective price: what you set for that provider and model if you did, otherwise what the provider's own catalogue lists, otherwise what models.dev lists for the model's maker.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long