Usage counts the gateway's calls and the calls the agents' own session files record (sessions.Calls). Kimi Code had no reader, so its calls straight to api.kimi.com on Kimi's own sign-in never showed (the reporter's 47 k3 calls of one session on 2026-10-11). The reader (calls_kimi.go) is built from the redacted real wire files infinitr0us shared from two machines (protocols 1.0, 1.4, 1.5; text replaced, every id, model and number kept) and their notes from Kimi Code's source. It reads every agents/*/wire.jsonl under $KIMI_CODE_HOME/sessions, else ~/.kimi-code/sessions (as agent.KimiDir finds the new Kimi Code), main and subagents, ses_* folders included. One call per usage.record: inputOther, inputCacheRead and inputCacheCreation go to Input, CacheRead and CacheWrite, output as is, the record's own model and time. Nothing is paired with step.end, since 1.4 and 1.5 write them in opposite orders and the June 1.4 build has no messageId or llm.request. A model beginning "magpie/" (magpie's own entry in Kimi's config) is skipped: the gateway counted it. kimi fork copies the parent's records unchanged, so a call is keyed by agent (agentId, else its agents/<id> folder), time, model and usage, and Calls counts a key once. It is a whole-file call source (callSources, wholeCallReaders) and the folder is watched (Dirs). The subsystem page gets the list of call readers. Fixtures (testdata/kimi-code) are the reporter's files cut to the lines a call is read from, each line verbatim (50 KB; one of the July session's eight agents kept). Run: the reader over the reporter's whole, untrimmed files gives exactly their README's totals (32/2,841,972/12,283; 151/7,025,587/122,782; 6/147,822/2,009; 10/338,328/2,176; 0 for the four others). TestKimiCodeCalls (both homes), TestKimiCodeSkipsCallsThroughMagpie, TestKimiCodeForkCountsOnce, TestKimiCodeBrokenFiles (cut mid-record, empty, junk, null/negative/timeless usage) pass. Broken by hand, each goes red: no magpie skip, no key, key without agent, no negative or time guard, main only, KIMI_CODE_HOME ignored, cache read dropped. go test -tags nogui ./internal/sessions ./internal/usage ./internal/cli ./internal/gui under a sandbox HOME, gofmt -l, go vet (darwin), GOOS=linux go vet -tags nogui, GOOS=windows go vet. Not tried: a live Kimi Code run (fixtures are the reporter's real files, not a sandbox capture), a successful call through magpie (the magpie-routed record in the test is the reporter's quoted 1.5 line with a magpie/ model), a compaction record (usageScope "session", none in the files), Kimi Code in WSL (not read), Windows paths at runtime. A subagent's calls carry the session but no Subagent field. Thanks to infinitr0us for the write-up from Kimi's source and the redacted wire files. Reported-by: infinitr0us
169 lines
5.9 KiB
Go
169 lines
5.9 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 {
|
|
paths, _ := SessionGlob(filepath.Join(kimiSessions(), "*", "*", "agents", "*", "wire.jsonl"))
|
|
var out []file
|
|
for _, p := range paths {
|
|
agentDir := filepath.Dir(p)
|
|
session := filepath.Base(filepath.Dir(filepath.Dir(agentDir)))
|
|
f := file{agent: "kimi", key: "kimi:" + session, path: p, main: filepath.Base(agentDir) == "main"}
|
|
if stat(&f) {
|
|
out = append(out, f)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
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)
|
|
}
|