Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5773 fix(agent): report kimi token usage from its session wire log (#6495)

Bohan Jiang7a7de4fa5651
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index aaebff1c39..87b3d73479 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -1,10 +1,14 @@
package agent
import (
+ "bytes"
"context"
+ "encoding/json"
"fmt"
"io"
+ "os"
"os/exec"
+ "path/filepath"
"strings"
"sync/atomic"
"time"
@@ -374,6 +378,13 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
c.usageMu.Lock()
c.usage.InputTokens += pr.usage.InputTokens
c.usage.OutputTokens += pr.usage.OutputTokens
+ // kimi-code 0.33.0 sends no usage at all on this path,
+ // so these two are inert today; they exist so a future
+ // kimi that does populate the ACP result is billed
+ // correctly instead of silently dropping its cache
+ // split. scanKimiSessionUsage below is the live path.
+ c.usage.CacheReadTokens += pr.usage.CacheReadTokens
+ c.usage.CacheWriteTokens += pr.usage.CacheWriteTokens
c.usageMu.Unlock()
default:
}
@@ -408,13 +419,36 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
u := c.usage
c.usageMu.Unlock()
+ // Fallback: kimi-code 0.33.0 exports no token counters over ACP.
+ // Its session/prompt result carries only stopReason, and its
+ // `usage_update` notification carries only {used,size} — context
+ // window occupancy, not billing. Verified against the CLI Multica's
+ // own onboarding installs. Without this scan every kimi task lands
+ // on the usage dashboard with no row at all (MUL-5773 / #6448).
+ //
+ // The counters do exist in kimi's per-session wire log, so read
+ // them from there, the same way codex.go falls back to Codex
+ // rollouts. Bound by sessionID so a concurrent kimi session is
+ // never billed to this task.
+ fallbackModel := opts.Model
+ if fallbackModel == "" {
+ fallbackModel = "unknown"
+ }
+
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
- model := opts.Model
- if model == "" {
- model = "unknown"
- }
- usageMap = map[string]TokenUsage{model: u}
+ if acpTokenUsagePresent(u) {
+ usageMap = map[string]TokenUsage{fallbackModel: u}
+ } else {
+ // Keyed per model by the scan itself: a task whose subagent
+ // or compaction step ran on a different model must not have
+ // that model's tokens priced at the main model's rate.
+ usageMap = scanKimiSessionUsage(kimiUsageScan{
+ startTime: startTime,
+ kimiHome: b.cfg.Env["KIMI_CODE_HOME"],
+ sessionID: sessionID,
+ resumed: opts.ResumeSessionID != "",
+ fallbackModel: fallbackModel,
+ })
}
resCh <- Result{
@@ -477,3 +511,209 @@ func kimiToolNameFromTitle(title string) string {
// Fallback: snake_case the title so the UI gets a stable identifier.
return strings.ReplaceAll(lower, " ", "_")
}
+
+// kimiUsageRecordType is the wire-log entry kimi-code writes after every LLM
+// call. Its sibling `step.end` loop event repeats the same numbers, so only
+// this type may be summed — counting both double-bills every turn.
+const kimiUsageRecordType = "usage.record"
+
+// kimiWireUsage is one `usage.record` entry from a kimi session wire log.
+//
+// The buckets are mutually exclusive: on a verified two-turn session the
+// records read {inputOther:4844, inputCacheRead:17664, output:22} and
+// {inputOther:272, inputCacheRead:22272, output:22}, and each turn's three
+// fields sum exactly to the `used` figure kimi reports over ACP (22530 and
+// 22566). So `inputOther` is uncached input only and maps straight onto
+// TokenUsage.InputTokens with no cached-prefix subtraction — unlike the ACP
+// `inputTokens` case excludeACPCachedInput exists to correct.
+type kimiWireUsage struct {
+ Type string `json:"type"`
+ // Time is the record's epoch-millisecond write time. It is what keeps a
+ // resumed session from being billed twice: kimi appends to the same wire
+ // log across resumes, so the file still holds the previous task's
+ // records.
+ Time int64 `json:"time"`
+ Model string `json:"model"`
+ Usage struct {
+ InputOther int64 `json:"inputOther"`
+ Output int64 `json:"output"`
+ InputCacheRead int64 `json:"inputCacheRead"`
+ InputCacheCreation int64 `json:"inputCacheCreation"`
+ } `json:"usage"`
+}
+
+// kimiUsageScan parameterises a wire-log scan.
+type kimiUsageScan struct {
+ startTime time.Time
+ kimiHome string
+ sessionID string
+ // resumed marks a turn that continued an existing kimi session. Those
+ // append to the wire log the previous task already billed, so records are
+ // filtered by their own timestamp, not just by the file's mtime.
+ resumed bool
+ // fallbackModel keys records that carry no model of their own.
+ fallbackModel string
+}
+
+// scanKimiSessionUsage returns the usage kimi-code recorded for this session,
+// bucketed by the model that produced each record.
+//
+// Records are per-LLM-call and incremental, never cumulative: a verified
+// two-step turn logged one record per `llm.request`, with the second call's
+// uncached input far below the first's as the prefix moved into cache. So the
+// total for a task is the plain sum over every record in the session.
+//
+// Subagent turns get their own `agents/<name>/wire.jsonl` and may run a
+// different model, which is why the result is a map rather than one total:
+// billing only `agents/main` would drop delegated work, and folding every
+// agent into one model name would price it wrong.
+func scanKimiSessionUsage(scan kimiUsageScan) map[string]TokenUsage {
+ root := kimiSessionRoot(scan.kimiHome)
+ if root == "" {
+ return nil
+ }
+
+ usage := make(map[string]TokenUsage)
+ for _, path := range kimiSessionWireLogs(root, scan.sessionID) {
+ // A wire log untouched since before the turn began belongs to an
+ // earlier run of a resumed session; billing it would re-charge
+ // tokens the previous task already reported.
+ if info, err := os.Stat(path); err != nil || info.ModTime().Before(scan.startTime) {
+ continue
+ }
+ accumulateKimiWireUsage(usage, path, scan)
+ }
+ if len(usage) == 0 {
+ return nil
+ }
+ return usage
+}
+
+// kimiSessionWireLogs returns the wire logs belonging to sessionID.
+//
+// kimi names the session directory with the ACP session id verbatim
+// (`<root>/<workspace>/<sessionID>/agents/<name>/wire.jsonl`), so the session
+// is addressed by exact path rather than by globbing every session and
+// filtering after: session history only grows, and this runs on the billing
+// path at the end of every task. Building the path also keeps the agent's
+// session id out of a glob pattern, where a `*` or `[` would be read as a
+// wildcard — as would one in a custom KIMI_CODE_HOME.
+func kimiSessionWireLogs(root, sessionID string) []string {
+ sessionID = strings.TrimSpace(sessionID)
+ // Guard the path join: the id comes from the agent.
+ if sessionID == "" || sessionID == "." || sessionID == ".." ||
+ strings.ContainsRune(sessionID, '/') || strings.ContainsRune(sessionID, os.PathSeparator) {
+ return nil
+ }
+
+ workspaces, err := os.ReadDir(root)
+ if err != nil {
+ return nil
+ }
+ var paths []string
+ for _, workspace := range workspaces {
+ if !workspace.IsDir() {
+ continue
+ }
+ agentsDir := filepath.Join(root, workspace.Name(), sessionID, "agents")
+ agents, err := os.ReadDir(agentsDir)
+ if err != nil {
+ continue
+ }
+ for _, agent := range agents {
+ if !agent.IsDir() {
+ continue
+ }
+ paths = append(paths, filepath.Join(agentsDir, agent.Name(), "wire.jsonl"))
+ }
+ }
+ return paths
+}
+
+// accumulateKimiWireUsage adds one wire log's records into usage, keyed by the
+// model each record names. A malformed or truncated line is skipped rather
+// than failing the scan: the log is appended to live, so the tail can be a
+// partial write, and reporting the records we could read beats reporting
+// nothing.
+func accumulateKimiWireUsage(usage map[string]TokenUsage, path string, scan kimiUsageScan) {
+ file, err := os.Open(path)
+ if err != nil {
+ return
+ }
+ defer file.Close()
+
+ scanner := newAgentStreamScanner(file)
+ for scanner.Scan() {
+ line := scanner.Bytes()
+ if !bytes.Contains(line, []byte(kimiUsageRecordType)) {
+ continue
+ }
+ var record kimiWireUsage
+ if err := json.Unmarshal(line, &record); err != nil || record.Type != kimiUsageRecordType {
+ continue
+ }
+ if !kimiWireRecordInTurn(record.Time, scan.startTime, scan.resumed) {
+ continue
+ }
+ model := record.Model
+ if model == "" {
+ model = scan.fallbackModel
+ }
+ total := usage[model]
+ total.InputTokens += record.Usage.InputOther
+ total.OutputTokens += record.Usage.Output
+ total.CacheReadTokens += record.Usage.InputCacheRead
+ total.CacheWriteTokens += record.Usage.InputCacheCreation
+ usage[model] = total
+ }
+}
+
+// kimiWireRecordInTurn reports whether a usage record belongs to the turn that
+// started at startTime.
+//
+// kimi-code 0.33.0 stamps every usage record, so the untimed case is only a
+// guard against a future format change. There it errs toward billing on a
+// fresh session (whose records are all ours anyway) and toward dropping on a
+// resume, where counting an untimed record risks charging a user twice for
+// tokens the earlier task already reported.
+func kimiWireRecordInTurn(recordTimeMillis int64, startTime time.Time, resumed bool) bool {
+ if recordTimeMillis <= 0 {
+ return !resumed
+ }
+ if startTime.IsZero() {
+ return true
+ }
+ return recordTimeMillis >= startTime.UnixMilli()
+}
+
+// kimiSessionRoot resolves kimi's session directory: an explicitly configured
+// home first, then the ambient KIMI_CODE_HOME, then ~/.kimi-code. Mirrors
+// codexSessionRoot.
+//
+// The env lookup is not redundant with cfg.Env: the kimi subprocess inherits
+// os.Environ() via buildEnv, so a KIMI_CODE_HOME exported to the daemon
+// relocates kimi's sessions without ever appearing in cfg.Env. Reading only
+// cfg.Env would leave the scan looking in ~/.kimi-code while kimi wrote
+// somewhere else. The stat check keeps a home without a sessions directory
+// from disabling the scan.
+func kimiSessionRoot(kimiHome string) string {
+ if kimiHome = strings.TrimSpace(kimiHome); kimiHome == "" {
+ kimiHome = strings.TrimSpace(os.Getenv("KIMI_CODE_HOME"))
+ }
+ if kimiHome != "" {
+ dir := filepath.Join(kimiHome, "sessions")
+ if info, err := os.Stat(dir); err == nil && info.IsDir() {
+ return dir
+ }
+ }
+
+ home, err := os.UserHomeDir()
+ if err != nil {
+ return ""
+ }
+ dir := filepath.Join(home, ".kimi-code", "sessions")
+ if info, err := os.Stat(dir); err == nil && info.IsDir() {
+ return dir
+ }
+ return ""
+}
diff --git a/server/pkg/agent/kimi_integration_test.go b/server/pkg/agent/kimi_integration_test.go
new file mode 100644
index 0000000000..bb91529acf
--- /dev/null
+++ b/server/pkg/agent/kimi_integration_test.go
@@ -0,0 +1,90 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestKimiRealACPUsageSmoke drives the real `kimi acp` binary end-to-end and
+// asserts the task comes back with a token split.
+//
+// This is the test that would have caught #6448 before it shipped: kimi-code
+// 0.33.0 reports no usage over ACP at all, so any fix validated only against a
+// hand-written ACP fixture passes while the real runtime still reports nothing.
+//
+// The model matters: the CLI rejects thinking=off on some models with
+// `400 invalid thinking`, and a turn that dies there writes no usage record.
+// KIMI_SMOKE_MODEL overrides the default when the account's default model has
+// that constraint.
+func TestKimiRealACPUsageSmoke(t *testing.T) {
+ requireRealAgentSmoke(t)
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+ path, err := exec.LookPath("kimi")
+ if err != nil {
+ t.Skip("kimi not on PATH; skipping real-binary smoke test")
+ }
+ if version, err := exec.Command(path, "--version").CombinedOutput(); err == nil {
+ t.Logf("kimi CLI version: %s", strings.TrimSpace(string(version)))
+ }
+
+ backend, err := New("kimi", Config{ExecutablePath: path, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "Reply with exactly one word: alpha", ExecOptions{
+ Timeout: 150 * time.Second,
+ Model: kimiSmokeModel(),
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ t.Logf("status=%q error=%q output=%q", result.Status, result.Error, result.Output)
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got %q (%s)", result.Status, result.Error)
+ }
+
+ if len(result.Usage) == 0 {
+ t.Fatal("no usage reported: the wire-log fallback did not fire")
+ }
+ var total TokenUsage
+ for model, u := range result.Usage {
+ t.Logf("usage[%s] = input:%d output:%d cacheRead:%d cacheWrite:%d",
+ model, u.InputTokens, u.OutputTokens, u.CacheReadTokens, u.CacheWriteTokens)
+ total.InputTokens += u.InputTokens
+ total.OutputTokens += u.OutputTokens
+ total.CacheReadTokens += u.CacheReadTokens
+ total.CacheWriteTokens += u.CacheWriteTokens
+ }
+ if total.InputTokens <= 0 {
+ t.Errorf("input tokens = %d, want > 0", total.InputTokens)
+ }
+ if total.OutputTokens <= 0 {
+ t.Errorf("output tokens = %d, want > 0", total.OutputTokens)
+ }
+}
+
+func kimiSmokeModel() string {
+ if model := strings.TrimSpace(os.Getenv("KIMI_SMOKE_MODEL")); model != "" {
+ return model
+ }
+ return ""
+}
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index cdf3eef3e9..87b8892399 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -3,9 +3,11 @@ package agent
import (
"context"
"encoding/json"
+ "fmt"
"log/slog"
"os"
"path/filepath"
+ "strconv"
"strings"
"testing"
"time"
@@ -495,3 +497,407 @@ func TestKimiBackendDropsHistoryReplayOnResume(t *testing.T) {
}
}
}
+
+// kimiScanTotal folds a per-model scan result into one total, for assertions
+// that do not care about model attribution.
+func kimiScanTotal(scan kimiUsageScan) TokenUsage {
+ var total TokenUsage
+ for _, u := range scanKimiSessionUsage(scan) {
+ total.InputTokens += u.InputTokens
+ total.OutputTokens += u.OutputTokens
+ total.CacheReadTokens += u.CacheReadTokens
+ total.CacheWriteTokens += u.CacheWriteTokens
+ }
+ return total
+}
+
+// kimiScanSingle asserts the scan produced exactly one model bucket and
+// returns it with its model name.
+func kimiScanSingle(tb testing.TB, scan kimiUsageScan) (TokenUsage, string) {
+ tb.Helper()
+ byModel := scanKimiSessionUsage(scan)
+ if len(byModel) != 1 {
+ tb.Fatalf("expected exactly one model bucket, got %v", byModel)
+ }
+ for model, u := range byModel {
+ return u, model
+ }
+ return TokenUsage{}, ""
+}
+
+// kimiWireRecordLine is a verbatim `usage.record` line as kimi-code 0.33.0
+// writes it, captured from a real session.
+func kimiWireRecordLine(inputOther, output, cacheRead, cacheCreate int64) string {
+ return kimiWireRecordLineAt(time.Now(), inputOther, output, cacheRead, cacheCreate)
+}
+
+// kimiWireRecordLineAt stamps the record, so resume tests can place records on
+// either side of a turn boundary.
+func kimiWireRecordLineAt(at time.Time, inputOther, output, cacheRead, cacheCreate int64) string {
+ return kimiWireRecordLineFor("moonshot-cn/kimi-k2.7-code", at, inputOther, output, cacheRead, cacheCreate)
+}
+
+// kimiWireRecordLineFor names the model on the record, the way kimi does.
+func kimiWireRecordLineFor(model string, at time.Time, inputOther, output, cacheRead, cacheCreate int64) string {
+ return fmt.Sprintf(`{"type":"usage.record","model":%q,"usage":{"inputOther":%d,"output":%d,"inputCacheRead":%d,"inputCacheCreation":%d},"usageScope":"turn","time":%d}`,
+ model, inputOther, output, cacheRead, cacheCreate, at.UnixMilli())
+}
+
+// kimiWireStepEndLine is the `step.end` loop event kimi writes alongside the
+// usage record, repeating the same counters. Summing both double-bills.
+func kimiWireStepEndLine(inputOther, output, cacheRead, cacheCreate int64) string {
+ return fmt.Sprintf(`{"type":"context.append_loop_event","event":{"type":"step.end","uuid":"a3799b31","turnId":"0","step":1,"finishReason":"end_turn","usage":{"inputOther":%d,"output":%d,"inputCacheRead":%d,"inputCacheCreation":%d}},"time":1785997224849}`,
+ inputOther, output, cacheRead, cacheCreate)
+}
+
+// writeKimiWireLog lays out a wire log at the path kimi uses:
+// <root>/sessions/<workspace>/<sessionID>/agents/<agent>/wire.jsonl
+func writeKimiWireLog(tb testing.TB, kimiHome, sessionID, agentName string, lines ...string) string {
+ tb.Helper()
+ dir := filepath.Join(kimiHome, "sessions", "wd_test_abc123", sessionID, "agents", agentName)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ tb.Fatalf("mkdir wire log dir: %v", err)
+ }
+ path := filepath.Join(dir, "wire.jsonl")
+ body := strings.Join(lines, "\n") + "\n"
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ tb.Fatalf("write wire log: %v", err)
+ }
+ return path
+}
+
+// TestScanKimiSessionUsageSumsRecordsIgnoringStepEnd is the core guard for
+// MUL-5773: kimi logs each LLM call's usage twice — once as `usage.record`
+// and once inside the `step.end` loop event. Counting both doubles every
+// number on the dashboard.
+func TestScanKimiSessionUsageSumsRecordsIgnoringStepEnd(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ // A real two-step turn: the second call's uncached input collapses as
+ // the prefix moves into cache.
+ writeKimiWireLog(t, home, "session_abc", "main",
+ `{"type":"metadata","protocol_version":"1"}`,
+ kimiWireRecordLine(4883, 200, 17664, 0),
+ kimiWireStepEndLine(4883, 200, 17664, 0),
+ kimiWireRecordLine(244, 8, 22528, 0),
+ )
+
+ usage, model := kimiScanSingle(t, kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_abc", fallbackModel: "unknown"})
+
+ if usage.InputTokens != 5127 {
+ t.Errorf("InputTokens = %d, want 5127 (4883+244)", usage.InputTokens)
+ }
+ if usage.OutputTokens != 208 {
+ t.Errorf("OutputTokens = %d, want 208 (200+8)", usage.OutputTokens)
+ }
+ if usage.CacheReadTokens != 40192 {
+ t.Errorf("CacheReadTokens = %d, want 40192 (17664+22528)", usage.CacheReadTokens)
+ }
+ if usage.CacheWriteTokens != 0 {
+ t.Errorf("CacheWriteTokens = %d, want 0", usage.CacheWriteTokens)
+ }
+ if model != "moonshot-cn/kimi-k2.7-code" {
+ t.Errorf("model = %q, want moonshot-cn/kimi-k2.7-code", model)
+ }
+}
+
+// TestScanKimiSessionUsageMapsCacheCreation pins inputCacheCreation onto the
+// cache-write bucket, the half of #6448 that stayed unfixed.
+func TestScanKimiSessionUsageMapsCacheCreation(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ writeKimiWireLog(t, home, "session_w", "main", kimiWireRecordLine(100, 20, 300, 400))
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_w", fallbackModel: "unknown"})
+ if usage.CacheWriteTokens != 400 {
+ t.Errorf("CacheWriteTokens = %d, want 400", usage.CacheWriteTokens)
+ }
+ if usage.CacheReadTokens != 300 {
+ t.Errorf("CacheReadTokens = %d, want 300", usage.CacheReadTokens)
+ }
+}
+
+// TestScanKimiSessionUsageBindsToSessionID: a concurrent kimi session must
+// never be billed to this task.
+func TestScanKimiSessionUsageBindsToSessionID(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ writeKimiWireLog(t, home, "session_mine", "main", kimiWireRecordLine(10, 1, 0, 0))
+ writeKimiWireLog(t, home, "session_theirs", "main", kimiWireRecordLine(9999, 9999, 9999, 9999))
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_mine", fallbackModel: "unknown"})
+ if usage.InputTokens != 10 || usage.OutputTokens != 1 {
+ t.Fatalf("billed the wrong session: %+v", usage)
+ }
+}
+
+// TestScanKimiSessionUsageCountsSubagents: kimi's Agent tool gives each
+// subagent its own wire log; delegated work must not vanish from the bill.
+func TestScanKimiSessionUsageCountsSubagents(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ writeKimiWireLog(t, home, "session_s", "main", kimiWireRecordLine(100, 10, 0, 0))
+ writeKimiWireLog(t, home, "session_s", "subagent-1", kimiWireRecordLine(50, 5, 0, 0))
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_s", fallbackModel: "unknown"})
+ if usage.InputTokens != 150 || usage.OutputTokens != 15 {
+ t.Fatalf("subagent usage not counted: %+v", usage)
+ }
+}
+
+// TestScanKimiSessionUsageSkipsLogsUntouchedSinceStart: on a resumed session
+// the previous run's log is still on disk and was already billed.
+func TestScanKimiSessionUsageSkipsLogsUntouchedSinceStart(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ path := writeKimiWireLog(t, home, "session_old", "main", kimiWireRecordLine(500, 50, 0, 0))
+ stale := time.Now().Add(-2 * time.Hour)
+ if err := os.Chtimes(path, stale, stale); err != nil {
+ t.Fatalf("chtimes: %v", err)
+ }
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_old", fallbackModel: "unknown"})
+ if acpTokenUsagePresent(usage) {
+ t.Fatalf("re-billed a log from before this turn: %+v", usage)
+ }
+}
+
+// TestScanKimiSessionUsageSkipsMalformedLines: the log is appended to live, so
+// the tail can be a partial write. Partial data beats no data.
+func TestScanKimiSessionUsageSkipsMalformedLines(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ writeKimiWireLog(t, home, "session_m", "main",
+ kimiWireRecordLine(100, 10, 200, 0),
+ `{"type":"usage.record","model":"x","usage":{"inputOther":7`,
+ )
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_m", fallbackModel: "unknown"})
+ if usage.InputTokens != 100 || usage.CacheReadTokens != 200 {
+ t.Fatalf("complete records dropped because of a truncated tail: %+v", usage)
+ }
+}
+
+// fakeKimiACPNoUsageScript reproduces kimi-code 0.33.0 exactly: the
+// session/prompt result carries only stopReason — no `usage` — while the real
+// counters go to the session wire log.
+func fakeKimiACPNoUsageScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"session_e2e"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ dir="$KIMI_CODE_HOME/sessions/wd_test_abc123/session_e2e/agents/main"
+ mkdir -p "$dir"
+ # The scan drops records stamped before the turn began, so the test
+ # injects the timestamp. ` + "`date +%s`" + ` would truncate to the start of
+ # the current second and land before a sub-second startTime.
+ printf '{"type":"usage.record","model":"moonshot-cn/kimi-k2.7-code","usage":{"inputOther":7694,"output":21,"inputCacheRead":14848,"inputCacheCreation":0},"usageScope":"turn","time":%s}\n' "$KIMI_TEST_RECORD_TIME" >> "$dir/wire.jsonl"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+// TestKimiBackendReportsUsageFromWireLog is the end-to-end proof for
+// MUL-5773 / #6448: with an ACP peer that reports no usage at all — which is
+// what kimi-code 0.33.0 actually does — the task still lands on the dashboard
+// with its real token split, keyed by the model the wire log names.
+func TestKimiBackendReportsUsageFromWireLog(t *testing.T) {
+ t.Parallel()
+
+ kimiHome := t.TempDir()
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ writeTestExecutable(t, fakePath, []byte(fakeKimiACPNoUsageScript()))
+
+ backend, err := New("kimi", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{
+ "KIMI_CODE_HOME": kimiHome,
+ // Comfortably after the turn's startTime, so the assertion
+ // tests the scan rather than clock granularity.
+ "KIMI_TEST_RECORD_TIME": strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10),
+ },
+ })
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: 20 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("status=%q error=%q", result.Status, result.Error)
+ }
+
+ usage, ok := result.Usage["moonshot-cn/kimi-k2.7-code"]
+ if !ok {
+ t.Fatalf("expected usage keyed by the wire log's model, got %v", result.Usage)
+ }
+ if usage.InputTokens != 7694 {
+ t.Errorf("InputTokens = %d, want 7694", usage.InputTokens)
+ }
+ if usage.OutputTokens != 21 {
+ t.Errorf("OutputTokens = %d, want 21", usage.OutputTokens)
+ }
+ if usage.CacheReadTokens != 14848 {
+ t.Errorf("CacheReadTokens = %d, want 14848", usage.CacheReadTokens)
+ }
+}
+
+// TestScanKimiSessionUsageSkipsPriorRunOnResume is the double-billing guard:
+// kimi appends to the same wire log when a session is resumed, so the file
+// still holds records the earlier task already reported. Only records stamped
+// after this turn began may be billed.
+func TestScanKimiSessionUsageSkipsPriorRunOnResume(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ turnStart := time.Now()
+ writeKimiWireLog(t, home, "session_r", "main",
+ kimiWireRecordLineAt(turnStart.Add(-time.Hour), 5000, 500, 9000, 0), // previous task
+ kimiWireRecordLineAt(turnStart.Add(time.Second), 120, 12, 340, 0), // this task
+ )
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: turnStart, kimiHome: home, sessionID: "session_r", resumed: true, fallbackModel: "unknown"})
+
+ if usage.InputTokens != 120 || usage.OutputTokens != 12 || usage.CacheReadTokens != 340 {
+ t.Fatalf("re-billed the previous run on resume: %+v", usage)
+ }
+}
+
+// TestScanKimiSessionUsageUntimedRecords pins the fallback for a hypothetical
+// future format that drops the timestamp: bill it on a fresh session, drop it
+// on a resume rather than risk charging twice.
+func TestScanKimiSessionUsageUntimedRecords(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ resumed bool
+ want int64
+ }{
+ {name: "fresh session bills untimed records", resumed: false, want: 100},
+ {name: "resumed session drops untimed records", resumed: true, want: 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ home := t.TempDir()
+ writeKimiWireLog(t, home, "session_u", "main",
+ `{"type":"usage.record","model":"m","usage":{"inputOther":100,"output":0,"inputCacheRead":0,"inputCacheCreation":0}}`)
+
+ usage := kimiScanTotal(kimiUsageScan{startTime: time.Now().Add(-time.Minute), kimiHome: home, sessionID: "session_u", resumed: tc.resumed, fallbackModel: "unknown"})
+ if usage.InputTokens != tc.want {
+ t.Errorf("InputTokens = %d, want %d", usage.InputTokens, tc.want)
+ }
+ })
+ }
+}
+
+// TestScanKimiSessionUsageSplitsByModel: a subagent may run a different model
+// from the main agent. Folding both into one bucket prices one of them wrong —
+// cache-read alone spans a 10x range across kimi models.
+func TestScanKimiSessionUsageSplitsByModel(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ now := time.Now()
+ writeKimiWireLog(t, home, "session_mm", "main",
+ kimiWireRecordLineFor("moonshot-cn/kimi-k3", now, 1000, 100, 2000, 0))
+ writeKimiWireLog(t, home, "session_mm", "subagent-1",
+ kimiWireRecordLineFor("moonshot-cn/kimi-k2.5", now, 30, 3, 40, 0))
+
+ byModel := scanKimiSessionUsage(kimiUsageScan{
+ startTime: now.Add(-time.Minute), kimiHome: home,
+ sessionID: "session_mm", fallbackModel: "unknown",
+ })
+
+ if len(byModel) != 2 {
+ t.Fatalf("expected one bucket per model, got %v", byModel)
+ }
+ if got := byModel["moonshot-cn/kimi-k3"]; got.InputTokens != 1000 || got.CacheReadTokens != 2000 {
+ t.Errorf("k3 bucket = %+v", got)
+ }
+ if got := byModel["moonshot-cn/kimi-k2.5"]; got.InputTokens != 30 || got.CacheReadTokens != 40 {
+ t.Errorf("k2.5 bucket = %+v", got)
+ }
+}
+
+// TestScanKimiSessionUsageFallbackModel: a record with no model of its own is
+// billed to the model the task asked for, not dropped.
+func TestScanKimiSessionUsageFallbackModel(t *testing.T) {
+ t.Parallel()
+
+ home := t.TempDir()
+ writeKimiWireLog(t, home, "session_f", "main",
+ fmt.Sprintf(`{"type":"usage.record","usage":{"inputOther":42,"output":1,"inputCacheRead":0,"inputCacheCreation":0},"time":%d}`,
+ time.Now().UnixMilli()))
+
+ byModel := scanKimiSessionUsage(kimiUsageScan{
+ startTime: time.Now().Add(-time.Minute), kimiHome: home,
+ sessionID: "session_f", fallbackModel: "picked-model",
+ })
+ if got := byModel["picked-model"]; got.InputTokens != 42 {
+ t.Fatalf("expected the fallback model to be billed, got %v", byModel)
+ }
+}
+
+// TestKimiSessionRootPrefersConfiguredThenEnv pins the discovery order.
+// The kimi subprocess inherits os.Environ() via buildEnv, so a KIMI_CODE_HOME
+// exported to the daemon relocates kimi's sessions without ever reaching
+// cfg.Env — reading only cfg.Env would scan the wrong directory.
+func TestKimiSessionRootPrefersConfiguredThenEnv(t *testing.T) {
+ configured := t.TempDir()
+ fromEnv := t.TempDir()
+ for _, dir := range []string{configured, fromEnv} {
+ if err := os.MkdirAll(filepath.Join(dir, "sessions"), 0o755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ }
+ t.Setenv("KIMI_CODE_HOME", fromEnv)
+
+ if got, want := kimiSessionRoot(configured), filepath.Join(configured, "sessions"); got != want {
+ t.Errorf("explicit config should win: got %q, want %q", got, want)
+ }
+ if got, want := kimiSessionRoot(""), filepath.Join(fromEnv, "sessions"); got != want {
+ t.Errorf("ambient KIMI_CODE_HOME should be used: got %q, want %q", got, want)
+ }
+}
+
+// TestKimiSessionWireLogsRejectsTraversal: the session id comes from the
+// agent and is joined into a path.
+func TestKimiSessionWireLogsRejectsTraversal(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ for _, id := range []string{"", ".", "..", "../escape", "a/b"} {
+ if got := kimiSessionWireLogs(root, id); got != nil {
+ t.Errorf("sessionID %q should be rejected, got %v", id, got)
+ }
+ }
+}