Files
magpie/internal/sessions/cline.go
T
yetone 4eba5c37a8 sessions: ZCode, DeepSeek Harness, Cline and Qoder's sessions are listed too (lml: 希望会话里也能看到 ZCode、Qoder CN、Cline、DeepSeek Harness 的) — ZCode's are OpenCode's tables in ~/.zcode/cli/db/db.sqlite, read as OpenCode's database is (opened read-only), its tokens the AI SDK's (input less the cache, output as it is), its model modelId, a title_source of default no title, a prompt typed a real_user's; dsh's are ~/.dsh/sessions ($DSH_HOME), a folder a session, the latest format's session[.vN].jsonl[.zstd] read whole, zstd frames and all, a subagent's (parentSession) in its parent's, a fork's seeded events (seedLength, or up to an inherited session/end-seed) counted where they were first written; Cline's are ~/.cline/data/sessions ($CLINE_SESSION_DATA_DIR, $CLINE_DATA_DIR, $CLINE_DIR), <id>.messages.json with its manifest <id>.json for the cwd, the prompt and the title, a subagent's other messages file beside it, a fork's messages before its forkedAt not counted, cline --id <id> to pick it up; Qoder's and Qoder CN's are Claude Code's lines in ~/.qoder/projects and ~/.qoder-cn/projects ($QODER_CONFIG_DIR, $QODERCN_CONFIG_DIR), qodercli --resume / qoderclicn --resume. Each folder is watched when it's there (Dirs). Tests keep HOME in their sandbox now. Tested with made-up fixtures for each (a ZCode database made in the test, dsh plain and zstd, forks of both formats, a Cline fork and subagent, both Qoder builds), and read-only against copies of this machine's ZCode database and dsh sessions: 2 and 13 sessions, their token totals the same as a separate tally of the raw rows
2026-09-28 22:45:50 +08:00

159 lines
4.8 KiB
Go

package sessions
import (
"encoding/json"
"os"
"path/filepath"
"regexp"
"strings"
"time"
)
// Cline's CLI (3, on the Cline SDK) keeps a session in a folder of its own
// under its sessions folder (~/.cline/data/sessions): <id>.json, the
// manifest — the cwd, the time started, the first prompt, the title in its
// metadata — and <id>.messages.json, the conversation, written anew whole
// as it goes on. A subagent's is <agent id>.messages.json in the folder of
// the session it ran in. An assistant message carries its model
// (modelInfo.id), its time (ts, milliseconds) and its usage (metrics): the
// AI SDK's counts, input with the cache in it, output with the reasoning.
// A session forked from another (metadata.fork) starts with a copy of that
// one's messages, which count where they were first written: only those
// from its forkedAt on count in it. `cline --id <id>` picks one up again.
// ClineSessionDir is Cline's sessions folder: $CLINE_SESSION_DATA_DIR, else
// sessions in $CLINE_DATA_DIR, else in data in $CLINE_DIR, else in
// ~/.cline/data.
func ClineSessionDir() string {
if d := strings.TrimSpace(os.Getenv("CLINE_SESSION_DATA_DIR")); d != "" {
return d
}
data := strings.TrimSpace(os.Getenv("CLINE_DATA_DIR"))
if data == "" {
dir := strings.TrimSpace(os.Getenv("CLINE_DIR"))
if dir == "" {
home, _ := os.UserHomeDir()
dir = filepath.Join(home, ".cline")
}
data = filepath.Join(dir, "data")
}
return filepath.Join(data, "sessions")
}
func clineFiles() []file {
paths, _ := filepath.Glob(filepath.Join(ClineSessionDir(), "*", "*.messages.json"))
var out []file
for _, p := range paths {
id := filepath.Base(filepath.Dir(p))
f := file{agent: "cline", key: "cline:" + id, path: p, main: filepath.Base(p) == id+".messages.json"}
if !stat(&f) {
continue
}
if f.main {
// its title and its fork are in the manifest, beside it
m := file{path: filepath.Join(filepath.Dir(p), id+".json")}
if stat(&m) {
f.manifest = m.path
f.size += m.size
if m.mod.After(f.mod) {
f.mod = m.mod
}
}
}
out = append(out, f)
}
return out
}
type clineManifest struct {
SessionID string `json:"session_id"`
StartedAt string `json:"started_at"`
Cwd string `json:"cwd"`
Prompt string `json:"prompt"`
Metadata struct {
Title string `json:"title"`
Fork *struct {
ForkedAt string `json:"forkedAt"`
} `json:"fork"`
} `json:"metadata"`
}
type clineMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
TS int64 `json:"ts"`
ModelInfo *struct {
ID string `json:"id"`
} `json:"modelInfo"`
Metrics *struct {
Input int `json:"inputTokens"`
Output int `json:"outputTokens"`
CacheRead int `json:"cacheReadTokens"`
CacheWrite int `json:"cacheWriteTokens"`
} `json:"metrics"`
}
// parseCline reads a session's messages whole, as they are written.
func parseCline(f file) *state {
s := &state{Size: f.size, Mod: f.mod.UnixNano()}
var since time.Time
if f.manifest != "" {
var m clineManifest
if b, err := os.ReadFile(f.manifest); err == nil && json.Unmarshal(b, &m) == nil {
s.ID, s.Cwd = m.SessionID, m.Cwd
s.Named = title(m.Metadata.Title)
if m.Metadata.Fork != nil {
since, _ = time.Parse(time.RFC3339Nano, m.Metadata.Fork.ForkedAt)
}
start, _ := time.Parse(time.RFC3339Nano, m.StartedAt)
if since.IsZero() || !start.Before(since) {
s.saw(start, f.main)
}
clineTitle(s, m.Prompt)
}
}
b, err := os.ReadFile(f.path)
if err != nil {
return s
}
var doc struct {
Messages []clineMessage `json:"messages"`
}
if json.Unmarshal(b, &doc) != nil {
return s
}
for _, m := range doc.Messages {
if f.main && m.Role == "user" && s.Title == "" && s.First == "" {
clineTitle(s, ccText(m.Content))
}
at := ms(m.TS)
if !since.IsZero() && at.Before(since) {
continue // the copy of the session it was forked from
}
s.saw(at, f.main)
if u := m.Metrics; m.Role == "assistant" && u != nil && m.ModelInfo != nil && m.ModelInfo.ID != "" {
s.use(dateOf(at), m.ModelInfo.ID, Tokens{Input: max(0, u.Input-u.CacheRead-u.CacheWrite), Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite})
}
}
return s
}
var (
clineNotice = regexp.MustCompile(`(?s)<mode_notice\b[^>]*>.*?</mode_notice>`)
clineInput = regexp.MustCompile(`</?(?:user_input|user_command)\b[^>]*>`)
)
// clineTitle takes a session's title from a prompt: the words typed, out of
// the tags Cline wraps them in (<user_input mode="act">) and its notices.
func clineTitle(s *state, prompt string) {
if s.Title != "" || s.First != "" {
return
}
t := strings.TrimSpace(clineInput.ReplaceAllString(clineNotice.ReplaceAllString(prompt, " "), " "))
if strings.HasPrefix(t, "<") {
s.First = untagged(t)
} else {
s.Title = title(t)
}
}