Kimi Code's calls reached the usage ledger in #1607, but no session reader was ever written for it: allFiles had no Kimi entry, so its sessions were missing from Sessions and from Usage > Sessions (both read sessions.List). kimi.go reads a session folder, sessions/<workdir slug>/<id>/, as Kimi Code itself does (packages/agent-core-v2, checked at MoonshotAI/kimi-code afd95f6): - state.json: the title, custom or Kimi's own (isCustomTitle, titleKind, an old customTitle, as normalizeSessionTitle decides), cwd or 1.4's workDir, createdAt as epoch ms or an RFC 3339 string. Its size and mtime join the main file's, so a rename reads the session again. - each agent's wire.jsonl: usage.record tokens (a magpie/ model counted under its own name: here it is the session's spend), turn.prompt typed by the user (a subagent's system_trigger and a skill_activation aren't), step.end end_turn as replies, tool.call names. - a fork counts only what follows its last {"type":"forked"} marker (copyAgentWire + appendForkedMarker); one without a marker is cut at its createdAt. - resume: kimi --session <id>. The same files feed the calls reader (kimiCallFiles now shares kimiFilesIn). Siblings: Kimi's ~/.kimi-code in a WSL distro is listed (wslAgents) and its calls are counted (callSources); the Usage page's Sessions tab reads the same List. ggbdpq described a reader on the issue; the patch they mentioned didn't come through as an attachment, so this is written from their notes and Kimi's source. Co-authored for the design. Tests (testdata/kimi-code-sessions: the #1607 reporter's whole real files, 6 sessions, totals equal to their README's): TestKimiCodeSessions, TestKimiCodeSessionCounts, TestKimiCodeSessionFork, TestWSLKimiCode. Broken by hand, each goes red: no kimiFiles in allFiles, no marker cut (the clock-set-back fork), no createdAt cut, no WSL entry, any origin as a prompt, no workDir, no resume case. Run: go test -tags nogui ./internal/sessions/ ./internal/gui/ in a sandbox HOME, gofmt -l, GOOS=linux and windows go vet. Not tried with a live Kimi Code install (the fixtures are real files from one). Co-authored-by: ggbdpq <ggbdpq@gmail.com>
157 lines
5.5 KiB
Go
157 lines
5.5 KiB
Go
package sessions
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"cmp"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/yetone/magpie/internal/appdir"
|
|
)
|
|
|
|
// Kimi Code's calls (#1607, infinitr0us: its direct calls to api.kimi.com
|
|
// never reached Usage). Read from the wire files the reporter shared from
|
|
// two machines (protocols 1.0, 1.4 and 1.5, redacted, every number kept)
|
|
// and Kimi Code's own source as they quoted it. Each session is a folder
|
|
// sessions/<workdir slug>/<session id>/ of Kimi's home, each of its agents
|
|
// (main, and agent-N for a subagent, whose calls are written only in its
|
|
// own file) writing agents/<agent>/wire.jsonl. Every model response that
|
|
// came back with usage writes one usage.record:
|
|
//
|
|
// {"type":"usage.record","agentId":"main","model":"kimi-code/k3",
|
|
// "usage":{"inputOther":20257,"output":230,"inputCacheRead":0,
|
|
// "inputCacheCreation":0},"usageScope":"turn","time":1791696952640}
|
|
//
|
|
// model is the key of the [models."<key>"] table the call used. Input is
|
|
// inputOther plus the cache's read and creation, kept apart here as the
|
|
// ledger keeps them; output includes the thinking. usageScope "session" is
|
|
// a call outside a turn (compaction), counted all the same. A failed or
|
|
// interrupted call writes none, only a step.end with usage null.
|
|
//
|
|
// What changed between versions, and why nothing here pairs a record with
|
|
// its step.end: 1.4 writes the step.end first and the usage.record after
|
|
// it, 1.5 the other way round; the June 1.4 build writes no messageId and no
|
|
// llm.request; 1.4 and the 1.5 builds before late August write no agentId.
|
|
// The record alone carries everything a call needs.
|
|
//
|
|
// A call Kimi made through magpie's own entry (internal/agent's kimi.go
|
|
// writes it as the provider "magpie", its model tables keyed
|
|
// "magpie/<provider>/<model>") is the gateway's to count: it logged the
|
|
// call itself, with the provider and account that answered.
|
|
//
|
|
// kimi fork copies the parent's records into the new session unchanged,
|
|
// times included, so a call is keyed by its agent, time, model and usage
|
|
// (kimiCallKey), and Calls counts each key once. Among the reporter's
|
|
// 5,190 records no two calls share one.
|
|
|
|
// KimiCodeDir is Kimi Code's folder: $KIMI_CODE_HOME, else ~/.kimi-code, as
|
|
// internal/agent's KimiDir finds the new Kimi Code's (which this package
|
|
// cannot import). The old Python kimi-cli's ~/.kimi has no usage records.
|
|
func KimiCodeDir() string {
|
|
if d := strings.TrimSpace(appdir.Getenv("KIMI_CODE_HOME")); d != "" {
|
|
return expandHome(d)
|
|
}
|
|
home, _ := os.UserHomeDir()
|
|
return filepath.Join(home, ".kimi-code")
|
|
}
|
|
|
|
func kimiSessions() string { return filepath.Join(KimiCodeDir(), "sessions") }
|
|
|
|
// kimiGateway is how the model of a call to magpie's entry begins.
|
|
const kimiGateway = "magpie/"
|
|
|
|
// kimiCallFiles are every agent's wire.jsonl of every session. A session
|
|
// migrated from the Python kimi-cli (a ses_* folder) is read too: one Kimi
|
|
// Code opened again writes its own records there.
|
|
func kimiCallFiles() []file { return kimiFilesIn(kimiSessions()) }
|
|
|
|
type kimiUsage struct {
|
|
InputOther int `json:"inputOther"`
|
|
Output int `json:"output"`
|
|
InputCacheRead int `json:"inputCacheRead"`
|
|
InputCacheCreation int `json:"inputCacheCreation"`
|
|
}
|
|
|
|
type kimiRecord struct {
|
|
Type string `json:"type"`
|
|
AgentID string `json:"agentId"`
|
|
Model string `json:"model"`
|
|
Usage *kimiUsage `json:"usage"`
|
|
Time int64 `json:"time"`
|
|
}
|
|
|
|
var kimiUsageRecord = []byte(`"usage.record"`)
|
|
|
|
// readKimiCalls reads one agent's wire file whole.
|
|
func readKimiCalls(f file) (*callFile, bool) {
|
|
r, err := os.Open(f.path)
|
|
if err != nil {
|
|
return &callFile{Path: f.path, Agent: "kimi"}, false
|
|
}
|
|
defer r.Close()
|
|
agentDir := filepath.Base(filepath.Dir(f.path))
|
|
st := &callFile{Agent: "kimi", Path: f.path, Session: strings.TrimPrefix(f.key, "kimi:")}
|
|
br := bufio.NewReaderSize(r, 1<<20)
|
|
for {
|
|
b, err := br.ReadBytes('\n')
|
|
if err != nil && (!errors.Is(err, io.EOF) || len(bytes.TrimSpace(b)) == 0) {
|
|
break
|
|
}
|
|
b = bytes.TrimSpace(b)
|
|
if len(b) > 0 && len(b) <= maxLine && bytes.Contains(b, kimiUsageRecord) {
|
|
var rec kimiRecord
|
|
if json.Unmarshal(b, &rec) == nil {
|
|
if c, ok := kimiCall(st, agentDir, rec); ok {
|
|
st.Calls = append(st.Calls, c)
|
|
}
|
|
}
|
|
}
|
|
if err != nil {
|
|
break
|
|
}
|
|
}
|
|
return st, true
|
|
}
|
|
|
|
// kimiCall is a usage.record as a call.
|
|
func kimiCall(st *callFile, agentDir string, rec kimiRecord) (Call, bool) {
|
|
u := rec.Usage
|
|
if rec.Type != "usage.record" || u == nil || strings.HasPrefix(rec.Model, kimiGateway) {
|
|
return Call{}, false
|
|
}
|
|
if u.InputOther < 0 || u.Output < 0 || u.InputCacheRead < 0 || u.InputCacheCreation < 0 {
|
|
return Call{}, false
|
|
}
|
|
at := ms(rec.Time)
|
|
if at.IsZero() {
|
|
return Call{}, false
|
|
}
|
|
c := Call{
|
|
Agent: "kimi",
|
|
Time: at,
|
|
Session: st.Session,
|
|
Model: st.str(rec.Model),
|
|
Tokens: Tokens{Input: u.InputOther, Output: u.Output, CacheRead: u.InputCacheRead, CacheWrite: u.InputCacheCreation},
|
|
}
|
|
if c.Tokens.zero() {
|
|
return Call{}, false
|
|
}
|
|
agent := cmp.Or(rec.AgentID, agentDir)
|
|
c.Msg = st.str(kimiCallKey(agent, rec.Time, rec.Model, *u))
|
|
return c, true
|
|
}
|
|
|
|
// kimiCallKey is what tells one call from another across sessions: a fork
|
|
// repeats its parent's records byte for byte.
|
|
func kimiCallKey(agent string, t int64, model string, u kimiUsage) string {
|
|
return "kimi:" + agent + ":" + strconv.FormatInt(t, 10) + ":" + model + ":" +
|
|
strconv.Itoa(u.InputOther) + "/" + strconv.Itoa(u.Output) + "/" +
|
|
strconv.Itoa(u.InputCacheRead) + "/" + strconv.Itoa(u.InputCacheCreation)
|
|
}
|