sessions: read LiveAgent's sessions (#6741)

Usage › Sessions and the Sessions page now list LiveAgent's sessions
with their title, time, model, tokens and cost, and show their
conversation.

- Where: K-brain keeps each session at
  <root>/sessions/<project>/<id>/session.jsonl (older ones right under
  sessions/). sessions/.runs and sessions/.deleted-history are skipped.
- Root: $LIVEAGENT_HOME, then $K_BRAIN_HOME, then
  ~/.liveagent/data-dir.json, then ~/.liveagent. The rule now lives in
  sessions.LiveAgentDirIn, and agent.liveAgentDir calls it, so it has
  one owner.
- Reading: K-brain rewrites the file whole, so it is parsed whole. The
  first line is session_meta (id, title, cwd, running totals).
- Tokens:
  - Each reply's own usage counts on the day it came back.
  - What the totals (model_usage, else usage_in/usage_cached/usage_out)
    hold beyond those replies, such as a compaction's call or a rewound
    reply, counts on the last message's day, together with sub_usage.
  - Cache reads and writes are taken out of prompt_tokens.
- Forks: a fork's copies of its source's messages (seq <= fork_seq) are
  the source's, and count in neither the fork's messages nor its totals.
- Subagents: a subagent's own session (task-<parent>-<task>, task_id
  set) is filed under its parent with its activity, but no tokens,
  because its spend is the parent's sub_usage already.
- Not added:
  - a Calls reader: the gateway's own record of LiveAgent's calls
    carries no session id, so it would count them twice;
  - resume and delete: LiveAgent has no resume command.
- Skills: SkillsManager read (skill://<name>/SKILL.md) and Read of a
  skill path are counted.

Run (mote, mote-run, at d67ccbd3c plus this change before the rebase):
- go test -count=1 -timeout 45m ./internal/sessions ./internal/agent
  ./internal/library ./internal/agentenv ./internal/gui: all ok.
- go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./...: clean. gofmt -l: clean.
- TestEveryAgentSaysItsSkills has liveagent →
  TestLiveAgentSessions.

Again after the rebase on 3be322fe4 (mote): ./internal/sessions,
./internal/agent, ./internal/library ok; GOOS=linux -tags nogui and
GOOS=windows go vet ./... clean.

Broken by hand (mote), each red:
- Without parserFor's liveagent case: TestLiveAgentSessions (0 listed)
  and TestLiveAgentTranscript.
- Without subtracting a fork's copies: fork1 tokens 600/140/1000 for
  want 400/40.
- Without subtracting the replies already counted: abc123
  3500/550/2000 for want 2500/350/1000.

Fixtures: the issue's literal session_meta, with its placeholders
filled in (12786068 in, 12455808 cached, 103572 out →
330260/103572/12455808). The message, snapshot and compaction lines
follow K-brain's record types as its source writes them.

Not tried: no real LiveAgent install. The files were not written by
LiveAgent itself, and no real session was read. Imported sessions
(ImportHistory) are listed as they are. No GUI file changed, so no
GUI tests were run.
This commit is contained in:
yetone
2026-11-17 20:56:30 +08:00
parent 5622149331
commit 8e1534f5f9
8 changed files with 698 additions and 21 deletions
+20
View File
@@ -505,6 +505,26 @@ Codex's newest rollout's last line before magpie restarts Codex
`TestSettleReadsKeepsWhatWasThere`, `TestSessionReadsRoutes`,
`sessions-reads.test.cjs`.
LiveAgent's sessions (#6741,
[`liveagent.go`](../../internal/sessions/liveagent.go)) are K-brain's
`<root>/sessions/<project>/<id>/session.jsonl` (older ones right under
`sessions`; `.runs` and `.deleted-history` are skipped), the root found by
the rule `agent.liveAgentDir` uses (`sessions.LiveAgentDirIn`:
`$LIVEAGENT_HOME`, `$K_BRAIN_HOME`, `~/.liveagent/data-dir.json`,
`~/.liveagent`). K-brain rewrites the whole file, so it is parsed whole.
Its first line, `session_meta`, gives the id, title, cwd and the running
totals (`usage_in` with cache reads and writes in it, `usage_cached`,
`usage_out`, `model_usage` by `"<model> @ <provider>"`); each reply's own
`usage` counts on its day, and what the totals hold beyond those replies
(a compaction's call, a rewound reply) plus `sub_usage` counts on the last
message's day. A fork's copies (`seq` up to `fork_seq`) are its source's
and count in neither. A subagent's session (`task-<parent>-<task>`,
`task_id` set) is filed under its parent with its tools but no tokens:
they are the parent's `sub_usage`. There is no Calls reader, as the
gateway's own record of LiveAgent's calls carries no session, and no
resume command or delete. Tests: `TestLiveAgentSessions` (the issue's
literal `session_meta`), `TestLiveAgentTranscript`, `TestLiveAgentRoot`.
## Local Gateway Conversation Recording
The Sessions page offers an explicit, default-off recording switch. Confirmation
+3 -18
View File
@@ -69,6 +69,7 @@ import (
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
)
// liveAgentApp is LiveAgent's macOS bundle (tauri.conf.json's identifier).
@@ -152,24 +153,8 @@ var liveAgentRunning = func() bool {
// liveAgentDir is the folder of K-brain's config.json as LiveAgent hands it
// over: $LIVEAGENT_HOME, else $K_BRAIN_HOME (each only an absolute path,
// here), else the folder ~/.liveagent/data-dir.json points to, else
// ~/.liveagent.
func liveAgentDir(home string) string {
for _, v := range []string{"LIVEAGENT_HOME", "K_BRAIN_HOME"} {
if d := strings.TrimSpace(appdir.Getenv(v)); d != "" && filepath.IsAbs(d) {
return d
}
}
def := filepath.Join(home, ".liveagent")
if b, err := os.ReadFile(filepath.Join(def, "data-dir.json")); err == nil {
var p struct {
Path string `json:"path"`
}
if json.Unmarshal(b, &p) == nil && filepath.IsAbs(p.Path) && filepath.Clean(p.Path) != filepath.Clean(def) {
return p.Path
}
}
return def
}
// ~/.liveagent. The rule is sessions', which reads its sessions there.
func liveAgentDir(home string) string { return sessions.LiveAgentDirIn(home) }
// liveAgentWindowsApp says LiveAgent's installer has put it where it
// installs it: per user under %LOCALAPPDATA%\LiveAgent, or for everyone
+1
View File
@@ -245,6 +245,7 @@ func Found() []string {
add("hermes", HermesDirs()...)
add("alma", almaDB())
add("openmausbot", ombDB())
add("liveagent", liveagentSessions())
add("minimax-code", minimaxSessions())
kimi := []string{kimiSessions()}
for _, sh := range kimiWorkShares() {
+436
View File
@@ -0,0 +1,436 @@
package sessions
import (
"bytes"
"cmp"
"encoding/json"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/appdir"
)
// LiveAgent's engine, K-brain, keeps a session in a folder of its own
// under sessions in its data folder (LiveAgentDir), in a folder per
// project: <root>/sessions/<project>/<id>/session.jsonl (older ones right
// in sessions: <root>/sessions/<id>/session.jsonl). sessions/.runs and
// sessions/.deleted-history are its own, not sessions. Read in K-brain
// ac94873 (internal/session/transcript.go, location.go).
//
// K-brain writes the whole file again on every save, through a temp file
// renamed over it, so a read finds it whole. Each line is
// {"type", "payload"}. The first is session_meta: the id, title (the
// first prompt, cut at 64, until renamed), model and provider, cwd,
// created_at and updated_at, the session it was forked from (forked_from,
// with fork_seq the last message it copied) and, for a subagent's, task_id.
// It holds what the session spent so far: usage_in (prompt tokens, cache
// reads and writes in them), usage_cached, usage_out, usage_cache_write,
// and the same by "<model> @ <provider>" in model_usage; what its
// subagents spent is in sub_usage, by the same key, and in neither total.
// "message" lines follow, by seq: {"seq", "message"}, an OpenAI-shaped
// message with id, role (user, assistant, tool, system), content (a string
// or parts), reasoning, tool_calls, tool_call_id and name, sent_at, and on
// an assistant's reply the call's usage and its "<model> @ <provider>".
// A user message the user typed is authored; one with origin "background"
// is a runtime notice. compaction, task, snapshot and schedule lines come
// after.
//
// A reply's usage counts on the day it came back. What the meta's totals
// hold beyond the replies in the file — a compaction's summary call, a
// reply rewound and dropped, a subagent's (sub_usage) — counts on the day
// of the last message, as Droid's total does. A fork starts with copies of
// its source's messages up to fork_seq, and once it runs its totals start
// from what those copies spent, so neither counts in it. A subagent's own
// session (task-<parent>-<task>, task_id set) is filed under its parent's:
// its spend is the parent's sub_usage already, so only its activity counts.
// The gateway's own record of LiveAgent's calls carries no session, so
// nothing here is counted twice. LiveAgent has no resume command.
// LiveAgentDir is LiveAgent's data folder: $LIVEAGENT_HOME, else
// $K_BRAIN_HOME (each only an absolute path), else the folder
// ~/.liveagent/data-dir.json points to, else ~/.liveagent.
func LiveAgentDir() string {
home, _ := os.UserHomeDir()
return LiveAgentDirIn(home)
}
// LiveAgentDirIn is LiveAgentDir for the home folder given. It is the one
// rule agent.liveAgentDir uses too.
func LiveAgentDirIn(home string) string {
for _, v := range []string{"LIVEAGENT_HOME", "K_BRAIN_HOME"} {
if d := strings.TrimSpace(appdir.Getenv(v)); d != "" && filepath.IsAbs(d) {
return d
}
}
def := filepath.Join(home, ".liveagent")
if b, err := os.ReadFile(filepath.Join(def, "data-dir.json")); err == nil {
var p struct {
Path string `json:"path"`
}
if json.Unmarshal(b, &p) == nil && filepath.IsAbs(p.Path) && filepath.Clean(p.Path) != filepath.Clean(def) {
return p.Path
}
}
return def
}
func liveagentSessions() string { return filepath.Join(LiveAgentDir(), "sessions") }
type liveagentUsage struct {
Prompt int `json:"prompt_tokens"`
Completion int `json:"completion_tokens"`
Details *struct {
Cached int `json:"cached_tokens"`
} `json:"prompt_tokens_details"`
CacheHit int `json:"prompt_cache_hit_tokens"`
CacheWrite int `json:"prompt_cache_write_tokens"`
}
// tokens are K-brain's counts as magpie keeps them: input without what
// was read from or written to the cache (ai.Usage's Cached, CacheWrite).
func (u liveagentUsage) tokens() Tokens {
read := u.CacheHit
if u.Details != nil && u.Details.Cached > 0 {
read = u.Details.Cached
}
return Tokens{Input: max(0, u.Prompt-read-u.CacheWrite), Output: u.Completion, CacheRead: read, CacheWrite: u.CacheWrite}
}
type liveagentMeta struct {
ID string `json:"id"`
Title string `json:"title"`
Model string `json:"model"`
Provider string `json:"provider"`
Cwd string `json:"cwd"`
ForkedFrom string `json:"forked_from"`
ForkSeq int `json:"fork_seq"`
TaskID string `json:"task_id"`
In int `json:"usage_in"`
Cached int `json:"usage_cached"`
Out int `json:"usage_out"`
CacheWrite int `json:"usage_cache_write"`
Models map[string]liveagentUsage `json:"model_usage"`
Subs map[string]liveagentUsage `json:"sub_usage"`
Created time.Time `json:"created_at"`
Updated time.Time `json:"updated_at"`
}
type liveagentToolCall struct {
ID string `json:"id"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
type liveagentMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
Reasoning string `json:"reasoning"`
ToolCalls []liveagentToolCall `json:"tool_calls"`
ToolCallID string `json:"tool_call_id"`
Name string `json:"name"`
Authored bool `json:"authored"`
Origin string `json:"origin"`
SentAt *time.Time `json:"sent_at"`
Usage *liveagentUsage `json:"usage"`
Model string `json:"model"`
}
type liveagentLine struct {
Type string `json:"type"`
Payload struct {
liveagentMeta
Seq int `json:"seq"`
Message liveagentMessage `json:"message"`
} `json:"payload"`
}
// readLiveAgentMeta is a session's session_meta line.
func readLiveAgentMeta(path string) (liveagentMeta, bool) {
var l liveagentLine
ok := false
scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
ok = json.Unmarshal(b, &l) == nil && l.Type == "session_meta"
return false
})
return l.Payload.liveagentMeta, ok
}
// liveagentParents is whose subagent each task-* session is, as its meta
// said when the listing last read it.
var liveagentParents listMemo[string]
func liveagentFiles() []file {
if !Reads("liveagent") {
return nil
}
root := liveagentSessions()
a, _ := filepath.Glob(filepath.Join(root, "*", "*", "session.jsonl"))
b, _ := filepath.Glob(filepath.Join(root, "*", "session.jsonl"))
parents := liveagentParents.round()
defer parents.done()
var out []file
for _, p := range append(a, b...) {
dir := filepath.Dir(p)
id := filepath.Base(dir)
rel, err := filepath.Rel(root, dir)
if err != nil || strings.HasPrefix(rel, ".") || !safeID.MatchString(id) {
continue // .runs, .deleted-history
}
f := file{agent: "liveagent", key: "liveagent:" + id, path: p, main: true}
if !stat(&f) {
continue
}
if strings.HasPrefix(id, "task-") {
parent, _ := parents.get(p, f.size, f.mod.Time(), func() (string, bool) {
m, ok := readLiveAgentMeta(p)
if m.TaskID == "" {
return "", ok
}
return m.ForkedFrom, ok
})
if parent != "" && parent != id && safeID.MatchString(parent) {
f.key, f.main = "liveagent:"+parent, false
}
}
out = append(out, f)
}
return out
}
// liveagentModel is the model a "<model> @ <provider>" key names.
func liveagentModel(label string) string {
if i := strings.LastIndex(label, " @ "); i >= 0 {
label = label[:i]
}
return strings.TrimSpace(label)
}
// parseLiveAgent reads a session's file whole: K-brain writes it whole.
func parseLiveAgent(f file) *state {
s := &state{Size: f.size, Mod: f.mod.UnixNano()}
var m liveagentMeta
started := false
var said time.Time // the last message's time
counted := map[string]Tokens{} // what replies counted, by key
copied := map[string]Tokens{} // what a fork's copies spent, by key
scanAt(f.path, 0, nil, func(b []byte, _, _ int64) bool {
var l liveagentLine
if json.Unmarshal(b, &l) != nil {
return true
}
if !started {
started = true
if l.Type != "session_meta" {
return false
}
m = l.Payload.liveagentMeta
if f.main {
s.ID, s.Cwd, s.own().Named = m.ID, m.Cwd, title(m.Title)
}
s.saw(m.Created, f.main)
return true
}
if l.Type != "message" {
return true
}
msg := l.Payload.Message
var at time.Time
if msg.SentAt != nil {
at = *msg.SentAt
}
label := msg.Model
if label == "" {
label = m.Model + " @ " + m.Provider
}
if m.ForkedFrom != "" && m.TaskID == "" && l.Payload.Seq <= m.ForkSeq {
// a copy of the source's: counted there
if msg.Usage != nil {
t := copied[label]
t.add(msg.Usage.tokens())
copied[label] = t
}
return true
}
s.saw(at, f.main)
if at.After(said) {
said = at
}
date := dateOf(at)
switch msg.Role {
case "user":
text := liveagentText(msg.Content)
if !f.main || !msg.Authored || msg.Origin == "background" || strings.TrimSpace(text) == "" {
return true
}
s.day(date).Prompts++
if s.Title == "" {
s.Title = title(text)
}
case "assistant":
if f.main {
s.day(date).Replies++
}
for _, c := range msg.ToolCalls {
s.tool(at, c.Function.Name, liveagentSkill(c.Function.Name, c.Function.Arguments))
}
if msg.Usage != nil && f.main && date != "" {
t := msg.Usage.tokens()
s.use(date, liveagentModel(label), t)
c := counted[label]
c.add(t)
counted[label] = c
}
}
return true
})
if !started || !f.main {
return s
}
// what the totals hold beyond the replies counted: on the last day
totals := map[string]Tokens{}
for k, u := range m.Models {
totals[k] = u.tokens()
}
if len(m.Models) == 0 && (m.In != 0 || m.Out != 0) {
u := liveagentUsage{Prompt: m.In, Completion: m.Out, CacheHit: m.Cached, CacheWrite: m.CacheWrite}
totals[m.Model+" @ "+m.Provider] = u.tokens()
}
for k := range totals {
t := totals[k]
t.sub(copied[k])
t.sub(counted[k])
totals[k] = t
}
for k, u := range m.Subs {
t := totals[k]
t.add(u.tokens())
totals[k] = t
}
if said.IsZero() {
s.saw(m.Updated, true)
}
when := said
if when.IsZero() {
when = s.Last
}
if when.IsZero() {
when = time.Unix(0, s.Mod)
}
for k, t := range totals {
t = Tokens{Input: max(0, t.Input), Output: max(0, t.Output), CacheRead: max(0, t.CacheRead), CacheWrite: max(0, t.CacheWrite)}
s.use(dateOf(when), liveagentModel(k), t)
}
return s
}
// liveagentText is a message's words: its content as a string, or its
// text parts.
func liveagentText(raw json.RawMessage) string {
var s string
if json.Unmarshal(raw, &s) == nil {
return s
}
var parts []struct {
Type string `json:"type"`
Text string `json:"text"`
}
json.Unmarshal(raw, &parts)
var out []string
for _, p := range parts {
if p.Type == "text" && strings.TrimSpace(p.Text) != "" {
out = append(out, p.Text)
}
}
return strings.Join(out, "\n")
}
// liveagentSkill is the skill a tool call calls up: one whose SKILL.md it
// reads, by Read or SkillsManager's read, at skill://<name>/SKILL.md (or
// <name>/SKILL.md to SkillsManager; K-brain's internal/agent/skills.go),
// or through magpie's skill router.
func liveagentSkill(name, args string) string {
var a struct {
Action string `json:"action"`
Path string `json:"path"`
}
if json.Unmarshal([]byte(args), &a) != nil || a.Path == "" {
return ""
}
switch {
case name == "SkillsManager" && a.Action == "read":
case name == "Read" && strings.HasPrefix(a.Path, "skill:"):
case name == "Read":
return routedSkill(a.Path)
default:
return ""
}
p := strings.TrimPrefix(strings.TrimPrefix(a.Path, "skill://"), "skill:")
rest, ok := strings.CutSuffix(p, "/SKILL.md")
if !ok {
return ""
}
return filepath.Base(filepath.FromSlash(rest))
}
var liveagentSaid = []byte(`{"type":"message"`)
// liveagentTranscript tells add what a LiveAgent session said, by its
// message lines; a fork's copies of its source's are read too, as the
// conversation it goes on from.
func liveagentTranscript(path string, add func(bool, Part) bool) error {
names := map[string]string{} // a tool call's name, by its id
_, err := scanAt(path, 0, nil, func(b []byte, _, _ int64) bool {
if !bytes.HasPrefix(b, liveagentSaid) {
return true
}
var l liveagentLine
if json.Unmarshal(b, &l) != nil || l.Type != "message" {
return true
}
for _, p := range liveagentParts(l.Payload.Message, names) {
if !add(p.Role != "assistant", p) {
return false
}
}
return true
})
return err
}
// liveagentParts are what one message said.
func liveagentParts(m liveagentMessage, names map[string]string) []Part {
text := liveagentText(m.Content)
var parts []Part
switch m.Role {
case "user":
if strings.TrimSpace(text) == "" {
return nil
}
if m.Authored && m.Origin != "background" {
return []Part{textPart("user", text)}
}
// what LiveAgent put in itself: a notice, a task's report
return []Part{{Role: "user", Kind: "context", Text: text}}
case "assistant":
model := liveagentModel(m.Model)
if strings.TrimSpace(m.Reasoning) != "" {
parts = append(parts, Part{Role: "assistant", Kind: "thinking", Text: m.Reasoning, Model: model})
}
if strings.TrimSpace(text) != "" {
p := textPart("assistant", text)
p.Model = model
parts = append(parts, p)
}
for _, c := range m.ToolCalls {
names[c.ID] = c.Function.Name
parts = append(parts, Part{Role: "assistant", Kind: "tool_use", Name: c.Function.Name, Text: pretty(json.RawMessage(c.Function.Arguments)), Model: model})
}
case "tool":
parts = append(parts, Part{Role: "tool", Kind: "tool_result", Name: cmp.Or(names[m.ToolCallID], m.Name), Text: text})
}
return parts
}
+229
View File
@@ -0,0 +1,229 @@
package sessions
import (
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"time"
)
// putLiveAgent writes a K-brain session.jsonl under root's sessions, at
// rel (<project>/<id>), its lines as they are.
func putLiveAgent(t *testing.T, root, rel string, lines ...string) string {
t.Helper()
p := filepath.Join(root, "sessions", filepath.FromSlash(rel), "session.jsonl")
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
t.Fatal(err)
}
return p
}
// laIssueMeta is #6741's session_meta, word for word but for its
// placeholders: a session that ran on through magpie, its messages
// compacted away, so the totals are all there is.
const laIssueMeta = `{"type":"session_meta","payload":{"id":"67e678d0","title":"Port the reader","model":"glm-5.1","provider":"magpie","cwd":"/work/kb","usage_in":12786068,"usage_cached":12455808,"usage_out":103572,"model_usage":{"glm-5.1 @ magpie":{"prompt_tokens":12786068,"completion_tokens":103572,"prompt_tokens_details":{"cached_tokens":12455808}}},"created_at":"2026-11-01T10:00:00Z","updated_at":"2026-11-02T12:00:00Z","forked_from":"","fork_seq":0,"effort":""}}`
// laParser is a session that ran: a prompt, a reply that read a skill
// through SkillsManager, its result, a runtime notice and a reply to it.
// Its totals hold the replies, a compaction's call (prompt 1000,
// completion 100) and, in sub_usage, its subagent's.
var laParser = []string{
`{"type":"session_meta","payload":{"id":"abc123","title":"Parser fix","model":"glm-5.1","provider":"magpie","cwd":"/work/parser","usage_in":3000,"usage_cached":1000,"usage_out":300,"model_usage":{"glm-5.1 @ magpie":{"prompt_tokens":3000,"completion_tokens":300,"prompt_tokens_details":{"cached_tokens":1000}}},"sub_usage":{"glm-5.1 @ magpie":{"prompt_tokens":500,"completion_tokens":50}},"created_at":"2026-11-01T08:59:00Z","updated_at":"2026-11-02T08:00:06Z","forked_from":"","fork_seq":0,"effort":"","version":3}}`,
`{"type":"message","payload":{"seq":1,"message":{"id":"m1","role":"user","content":"Fix the parser","authored":true,"sent_at":"2026-11-01T09:00:00Z"}}}`,
`{"type":"message","payload":{"seq":2,"message":{"id":"m2","role":"assistant","content":"Reading the skill.","reasoning":"Need the skill.","tool_calls":[{"id":"c1","type":"function","function":{"name":"SkillsManager","arguments":"{\"action\":\"read\",\"path\":\"skill://greet-user/SKILL.md\"}"}}],"sent_at":"2026-11-01T09:00:10Z","model":"glm-5.1 @ magpie","usage":{"prompt_tokens":1200,"completion_tokens":100,"prompt_tokens_details":{"cached_tokens":1000}}}}}`,
`{"type":"message","payload":{"seq":3,"message":{"id":"m3","role":"tool","content":"# greet-user","tool_call_id":"c1","sent_at":"2026-11-01T09:00:11Z"}}}`,
`{"type":"snapshot","payload":{"seq":3,"ref":"s1"}}`,
`{"type":"message","payload":{"seq":4,"message":{"id":"m4","role":"user","content":[{"type":"text","text":"Task t1 finished"}],"origin":"background","sent_at":"2026-11-02T08:00:00Z"}}}`,
`{"type":"message","payload":{"seq":5,"message":{"id":"m5","role":"assistant","content":"Done.","sent_at":"2026-11-02T08:00:05Z","model":"glm-5.1 @ magpie","usage":{"prompt_tokens":800,"completion_tokens":100}}}}`,
`{"type":"compaction","payload":{"seq":5,"summary":"…"}}`,
}
// TestLiveAgentSessions lists LiveAgent's sessions as K-brain keeps them
// (#6741): each project's, an older one right under sessions, and not
// .runs or .deleted-history; a reply's usage on its own day, what else
// the totals hold on the last; a fork without its source's copies, and a
// subagent's session under its parent's, its spend there already.
func TestLiveAgentSessions(t *testing.T) {
inZone(t, 0)
home := setupAgents(t)
t.Setenv("LIVEAGENT_HOME", "")
t.Setenv("K_BRAIN_HOME", "")
root := filepath.Join(home, ".liveagent")
if LiveAgentDir() != root {
t.Fatalf("LiveAgentDir() = %q, want %q", LiveAgentDir(), root)
}
issue := putLiveAgent(t, root, "kb/67e678d0", laIssueMeta)
putLiveAgent(t, root, "parser/abc123", laParser...)
putLiveAgent(t, root, "parser/task-abc123-t1",
`{"type":"session_meta","payload":{"id":"task-abc123-t1","title":"Check the tests","model":"glm-5.1","provider":"magpie","cwd":"/work/parser","usage_in":500,"usage_out":50,"model_usage":{"glm-5.1 @ magpie":{"prompt_tokens":500,"completion_tokens":50}},"created_at":"2026-11-01T09:05:00Z","updated_at":"2026-11-01T09:06:00Z","forked_from":"abc123","fork_seq":0,"task_id":"t1"}}`,
`{"type":"message","payload":{"seq":1,"message":{"id":"t1","role":"user","content":"Check the tests","authored":true,"sent_at":"2026-11-01T09:05:00Z"}}}`,
`{"type":"message","payload":{"seq":2,"message":{"id":"t2","role":"assistant","tool_calls":[{"id":"r1","type":"function","function":{"name":"Read","arguments":"{\"path\":\"parser_test.go\"}"}}],"sent_at":"2026-11-01T09:06:00Z","model":"glm-5.1 @ magpie","usage":{"prompt_tokens":500,"completion_tokens":50}}}}`,
)
// a fork of abc123 after its first reply: the copies' spend is its
// source's, in its totals too
putLiveAgent(t, root, "parser/fork1",
`{"type":"session_meta","payload":{"id":"fork1","title":"Parser fix (fork)","model":"glm-5.1","provider":"magpie","cwd":"/work/parser","usage_in":1600,"usage_cached":1000,"usage_out":140,"model_usage":{"glm-5.1 @ magpie":{"prompt_tokens":1600,"completion_tokens":140,"prompt_tokens_details":{"cached_tokens":1000}}},"created_at":"2026-11-03T10:00:00Z","updated_at":"2026-11-03T10:00:05Z","forked_from":"abc123","fork_seq":2,"effort":""}}`,
laParser[1], laParser[2],
`{"type":"message","payload":{"seq":3,"message":{"id":"f3","role":"user","content":"Try another way","authored":true,"sent_at":"2026-11-03T10:00:00Z"}}}`,
`{"type":"message","payload":{"seq":4,"message":{"id":"f4","role":"assistant","content":"OK.","sent_at":"2026-11-03T10:00:05Z","model":"glm-5.1 @ magpie","usage":{"prompt_tokens":400,"completion_tokens":40}}}}`,
)
putLiveAgent(t, root, "old1",
`{"type":"session_meta","payload":{"id":"old1","title":"","model":"glm-5.1","provider":"magpie","cwd":"/work/old","created_at":"2026-10-20T10:00:00Z","updated_at":"2026-10-20T10:00:09Z"}}`,
`{"type":"message","payload":{"seq":1,"message":{"id":"o1","role":"user","content":"An older one","authored":true,"sent_at":"2026-10-20T10:00:00Z"}}}`,
)
putLiveAgent(t, root, ".runs/r1", laIssueMeta)
putLiveAgent(t, root, ".deleted-history/gone1", laIssueMeta)
Reset()
ss := List(0)
if n := count(ss, "liveagent"); n != 4 {
t.Fatalf("want 4 LiveAgent sessions (not .runs, .deleted-history or the subagent's), got %d", n)
}
a := find(t, ss, "liveagent", "67e678d0")
if a.Title != "Port the reader" || a.Cwd != "/work/kb" || a.Resume != "" || a.Path != issue {
t.Errorf("the issue's session: %+v", a)
}
if !a.Start.Equal(at("2026-11-01T10:00:00Z")) || !a.Last.Equal(at("2026-11-02T12:00:00Z")) {
t.Errorf("the issue's session ran %v to %v", a.Start, a.Last)
}
if got := model(a, "glm-5.1").Tokens; got != (Tokens{Input: 12786068 - 12455808, Output: 103572, CacheRead: 12455808}) {
t.Errorf("the issue's tokens = %+v", got)
}
if !a.Transcript {
t.Errorf("the issue's session has no transcript")
}
b := find(t, ss, "liveagent", "abc123")
if b.Title != "Parser fix" || b.Cwd != "/work/parser" || b.Resume != "" {
t.Errorf("abc123: %+v", b)
}
if !b.Start.Equal(at("2026-11-01T08:59:00Z")) || !b.Last.Equal(at("2026-11-02T08:00:05Z")) {
t.Errorf("abc123 ran %v to %v", b.Start, b.Last)
}
// replies 200+800 in, 100+100 out, 1000 read; the compaction's call
// 1000/100 and the subagent's 500/50 on top
if got := model(b, "glm-5.1").Tokens; got != (Tokens{Input: 2500, Output: 350, CacheRead: 1000}) {
t.Errorf("abc123 tokens = %+v", got)
}
f := find(t, ss, "liveagent", "fork1")
if f.Title != "Parser fix (fork)" || !f.Start.Equal(at("2026-11-03T10:00:00Z")) {
t.Errorf("fork1: %+v", f)
}
if got := model(f, "glm-5.1").Tokens; got != (Tokens{Input: 400, Output: 40}) {
t.Errorf("fork1 tokens = %+v, want only its own reply's", got)
}
o := find(t, ss, "liveagent", "old1")
if o.Title != "An older one" || len(o.Models) != 0 {
t.Errorf("old1: %+v", o)
}
// each reply on its day, the rest on the last message's
st := statsAt(0, time.Date(2026, 11, 4, 0, 0, 0, 0, time.UTC))
var sum *Summary
for i := range st.Sessions {
if st.Sessions[i].Agent == "liveagent" && st.Sessions[i].ID == "abc123" {
sum = &st.Sessions[i]
}
}
if sum == nil {
t.Fatal("abc123 not in the stats")
}
if sum.Prompts != 1 || sum.Replies != 2 {
t.Errorf("abc123 prompts %d replies %d, want 1 and 2 (the notice isn't a prompt, the subagent's aren't its)", sum.Prompts, sum.Replies)
}
if sum.ToolCalls != 2 || sum.tools.of("SkillsManager") != 1 || sum.tools.of("Read") != 1 {
t.Errorf("abc123 tools %d %v, want its SkillsManager and its subagent's Read", sum.ToolCalls, sum.tools)
}
if sum.skills.of("greet-user") != 1 || len(sum.skills) != 1 {
t.Errorf("abc123 skills %v", sum.skills)
}
if len(sum.Days) != 2 {
t.Errorf("abc123 days %v, want 11-01 and 11-02", sum.Days)
}
if sum.Tokens != (Tokens{Input: 2500, Output: 350, CacheRead: 1000}) {
t.Errorf("abc123 stats tokens %+v", sum.Tokens)
}
day1 := statsAt(1, time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC))
for _, x := range day1.Sessions {
if x.Agent == "liveagent" && x.ID == "abc123" && x.Tokens != (Tokens{Input: 200, Output: 100, CacheRead: 1000}) {
t.Errorf("abc123 on 11-01: %+v, want its first reply's", x.Tokens)
}
}
}
// TestLiveAgentTranscript reads a session as it went: the prompt, the
// reply's thinking, words and tool call, the tool's answer, LiveAgent's
// own notice as context.
func TestLiveAgentTranscript(t *testing.T) {
inZone(t, 0)
home := setupAgents(t)
t.Setenv("LIVEAGENT_HOME", "")
t.Setenv("K_BRAIN_HOME", "")
putLiveAgent(t, filepath.Join(home, ".liveagent"), "parser/abc123", laParser...)
Reset()
s := find(t, List(0), "liveagent", "abc123")
tr, err := TranscriptOf(s)
if err != nil {
t.Fatal(err)
}
var got []string
for _, p := range tr.Parts {
got = append(got, p.Role+"/"+p.Kind+"/"+p.Name+": "+p.Text)
}
want := []string{
"user/text/: Fix the parser",
"assistant/thinking/: Need the skill.",
"assistant/text/: Reading the skill.",
"assistant/tool_use/SkillsManager: {\n \"action\": \"read\",\n \"path\": \"skill://greet-user/SKILL.md\"\n}",
"tool/tool_result/SkillsManager: # greet-user",
"user/context/: Task t1 finished",
"assistant/text/: Done.",
}
if !slices.Equal(got, want) {
t.Errorf("transcript:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}
// LiveAgent's root is K-brain's: $LIVEAGENT_HOME, then $K_BRAIN_HOME
// (absolute only), then the folder ~/.liveagent/data-dir.json names.
func TestLiveAgentRoot(t *testing.T) {
home := setupAgents(t)
moved := filepath.Join(home, "elsewhere")
t.Setenv("LIVEAGENT_HOME", "")
t.Setenv("K_BRAIN_HOME", "")
os.MkdirAll(filepath.Join(home, ".liveagent"), 0o755)
if err := os.WriteFile(filepath.Join(home, ".liveagent", "data-dir.json"), []byte(`{"path":`+strconv.Quote(moved)+`}`), 0o644); err != nil {
t.Fatal(err)
}
if LiveAgentDir() != moved {
t.Errorf("data-dir.json: %q", LiveAgentDir())
}
putLiveAgent(t, moved, "kb/67e678d0", laIssueMeta)
Reset()
if s := find(t, List(0), "liveagent", "67e678d0"); s.Path != filepath.Join(moved, "sessions", "kb", "67e678d0", "session.jsonl") {
t.Errorf("read from %q", s.Path)
}
kb := filepath.Join(home, "kb")
t.Setenv("K_BRAIN_HOME", kb)
if LiveAgentDir() != kb {
t.Errorf("$K_BRAIN_HOME: %q", LiveAgentDir())
}
live := filepath.Join(home, "live")
t.Setenv("LIVEAGENT_HOME", live)
if LiveAgentDir() != live {
t.Errorf("$LIVEAGENT_HOME: %q", LiveAgentDir())
}
t.Setenv("LIVEAGENT_HOME", "relative/dir")
if LiveAgentDir() != kb {
t.Errorf("a relative $LIVEAGENT_HOME is taken: %q", LiveAgentDir())
}
}
+5 -2
View File
@@ -122,7 +122,7 @@ type Session struct {
// Gateway: seen only through magpie's gateway, with no file of the
// agent's on this computer (external.go)
Gateway bool `json:"gateway,omitempty"`
Agent string `json:"agent"` // magpie agent id: claude, codex, opencode, pi, omp, zcode, dsh, cline, qoder, qoder-cn, grok, workbuddy, workbuddy-ai, codebuddy, droid, cursor, hermes, alma, openmausbot, kimi, agy
Agent string `json:"agent"` // magpie agent id: claude, codex, opencode, pi, omp, zcode, dsh, cline, qoder, qoder-cn, grok, workbuddy, workbuddy-ai, codebuddy, droid, cursor, hermes, alma, openmausbot, liveagent, kimi, agy
ID string `json:"id"`
Cwd string `json:"cwd"`
Title string `json:"title"` // the name it was given, else the agent's own title, else the first prompt
@@ -1005,7 +1005,7 @@ func allFilesWith(kept *filesKept, zcode func() []file) []file {
lists := callFileLists(codexFiles())
lists = append(lists, openCodeFiles(), piFiles(), raftFiles(), cindyFiles(), wslFiles("pi", "raft", "omp", "kimi", "antigravity", "agy"), zcode())
lists = append(lists, dshFiles(), clineFiles(), ccFiles("qoder", QoderDir("qoder")), ccFiles("qoder-cn", QoderDir("qoder-cn")),
grokFiles(), workbuddyFiles(), workbuddyAIFiles(), codebuddyFiles(), droidFiles(), ompFiles(), cursorFiles(), hermesFiles(), almaFiles(), openmausbotFiles(), kimiFiles(), agyFiles(),
grokFiles(), workbuddyFiles(), workbuddyAIFiles(), codebuddyFiles(), droidFiles(), ompFiles(), cursorFiles(), hermesFiles(), almaFiles(), openmausbotFiles(), liveagentFiles(), kimiFiles(), agyFiles(),
antigravityFiles()) // #2190
// each lister asked Reads already; a file listed under another
// agent's name is held to that agent too
@@ -1120,6 +1120,7 @@ func Dirs() []string {
{filepath.Dir(cursorEditorDB()), cursorEditorDB()},
{AlmaDir(), almaDB()},
{OpenMausBotDir(), ombDB()},
{LiveAgentDir(), liveagentSessions()},
{MiniMaxDir(), minimaxSessions()},
{KimiCodeDir(), kimiSessions()},
{AntigravityAppDir(), antigravityConversations()},
@@ -2312,6 +2313,8 @@ func parserFor(agent string) sessionParser {
return sessionParser{whole: parseAlma}
case "openmausbot":
return sessionParser{whole: parseOpenMausBot}
case "liveagent":
return sessionParser{whole: parseLiveAgent}
case "opencode", "zcode":
return sessionParser{whole: parseOpenCode}
case "dsh":
@@ -36,6 +36,7 @@ var skillsCounted = map[string]struct {
"grok": {test: "TestGrokToolsAndSkills"},
"alma": {test: "TestAlmaSessions"},
"droid": {test: "TestDroidToolsAndSkills"},
"liveagent": {test: "TestLiveAgentSessions"},
"opencode": {test: "TestOpenCodeToolsAndSkills"},
"cline": {test: "TestClineToolsAndSkills"},
+3 -1
View File
@@ -35,7 +35,7 @@ var ErrNoTranscript = errors.New("this agent's conversations can't be shown")
// transcript.
func HasTranscript(agent string) bool {
switch agent {
case "claude", "qoder", "qoder-cn", "codex", "pi", "raft", "cindy", "omp", "cursor", "opencode", "kimi", "agy", "openmausbot":
case "claude", "qoder", "qoder-cn", "codex", "pi", "raft", "cindy", "omp", "cursor", "opencode", "kimi", "agy", "openmausbot", "liveagent":
return true
}
return false
@@ -164,6 +164,8 @@ func readTranscriptOf(s Session, keep func([]byte) bool, add func(bool, Part) bo
return agyTranscript(s.Path, keep, add)
case "openmausbot":
return ombTranscript(s, add)
case "liveagent":
return liveagentTranscript(s.Path, add)
default:
if s.BranchOf != "" && keep == nil {
return branchTranscript(s, add)