Skip to content

Commit 69fbca0

Browse files
M1nt-Ch0c0claude
andauthored
fix(kimi): support Kimi Code new wire format (#1362)
Kimi Code (`~/.kimi-code`) emits a new `wire.jsonl` schema that the old adapter could not parse, so its usage was silently dropped (#1261). - Detect `~/.kimi-code` and the deeper layout `sessions/<ws>/<session>/agents/<agent>/wire.jsonl` (5 path components) alongside the legacy 3-component layout. - Parse top-level `type == "usage.record"` lines: camelCase token fields (`inputOther`, `inputCacheRead`, `inputCacheCreation`), `time` in milliseconds, and `model` prefixed with `kimi-code/` (stripped for pricing lookup). Skip cumulative `usageScope == "session"` records. - Deserialize `time` leniently so a float- or string-encoded timestamp degrades to the file-mtime fallback instead of dropping the whole line. - Walk the correct number of parents in `kimi_root_from_wire_path` for the deeper layout so config resolution looks at the right root. - Keep full backward compatibility with the old StatusUpdate format. - Update the Kimi guide and data-source docs for `~/.kimi-code`. Fixes #1261 Co-authored-by: Claude Opus 4.8 <[email protected]>
1 parent 2e30ce3 commit 69fbca0

7 files changed

Lines changed: 234 additions & 56 deletions

File tree

‎docs/guide/environment-variables.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ ccusage detects supported data source files from conventional locations by defau
1919
| `GOOSE_PATH_ROOT` | Goose | Standard Goose data roots |
2020
| `OPENCLAW_DIR` | OpenClaw | `~/.openclaw` |
2121
| `KILO_DATA_DIR` | Kilo | `~/.local/share/kilo` |
22-
| `KIMI_DATA_DIR` | Kimi | `~/.kimi` |
22+
| `KIMI_DATA_DIR` | Kimi | `~/.kimi`, `~/.kimi-code` |
2323
| `QWEN_DATA_DIR` | Qwen | `~/.qwen` |
2424
| `COPILOT_OTEL_FILE_EXPORTER_PATH` | Copilot CLI | Explicit `.jsonl` file |
2525
| `GEMINI_DATA_DIR` | Gemini CLI | `~/.gemini/tmp` |

‎docs/guide/getting-started.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ If ccusage shows no data, check:
172172
- pi-agent: `${PI_AGENT_DIR:-~/.pi/agent/sessions}`
173173
- Goose: standard Goose data roots or `GOOSE_PATH_ROOT`
174174
- Kilo: `${KILO_DATA_DIR:-~/.local/share/kilo}`
175-
- Kimi: `${KIMI_DATA_DIR:-~/.kimi}`
175+
- Kimi: `${KIMI_DATA_DIR:-~/.kimi}` (also scans `~/.kimi-code`)
176176
- OpenClaw: `${OPENCLAW_DIR:-~/.openclaw}` (also scans `~/.clawdbot`, `~/.moltbot`, `~/.moldbot`)
177177
- Qwen: `${QWEN_DATA_DIR:-~/.qwen}`
178178
- GitHub Copilot CLI: `~/.copilot/otel/*.jsonl` or `COPILOT_OTEL_FILE_EXPORTER_PATH`

‎docs/guide/index.md‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -72,23 +72,23 @@ Each data source page covers the details that only apply to that source, includi
7272

7373
ccusage reads from local coding CLI data directories:
7474

75-
| Agent | ID | Default data location |
76-
| ------------ | ---------- | ----------------------------------------------- |
77-
| Claude Code | `claude` | `~/.config/claude/projects/`, `~/.claude/` |
78-
| Codex | `codex` | `${CODEX_HOME:-~/.codex}` |
79-
| OpenCode | `opencode` | `${OPENCODE_DATA_DIR:-~/.local/share/opencode}` |
80-
| Amp | `amp` | `${AMP_DATA_DIR:-~/.local/share/amp}` |
81-
| Droid | `droid` | `${DROID_SESSIONS_DIR:-~/.factory/sessions}` |
82-
| Codebuff | `codebuff` | `${CODEBUFF_DATA_DIR:-~/.config/manicode}` |
83-
| Hermes Agent | `hermes` | `${HERMES_HOME:-~/.hermes}/state.db` |
84-
| pi-agent | `pi` | `${PI_AGENT_DIR:-~/.pi/agent/sessions}` |
85-
| Goose | `goose` | Standard Goose data roots or `GOOSE_PATH_ROOT` |
86-
| OpenClaw | `openclaw` | `${OPENCLAW_DIR:-~/.openclaw}` |
87-
| Kilo | `kilo` | `${KILO_DATA_DIR:-~/.local/share/kilo}` |
88-
| Kimi | `kimi` | `${KIMI_DATA_DIR:-~/.kimi}` |
89-
| Qwen | `qwen` | `${QWEN_DATA_DIR:-~/.qwen}` |
90-
| Copilot CLI | `copilot` | `~/.copilot/otel/*.jsonl` |
91-
| Gemini CLI | `gemini` | `${GEMINI_DATA_DIR:-~/.gemini/tmp}` |
75+
| Agent | ID | Default data location |
76+
| ------------ | ---------- | ------------------------------------------------- |
77+
| Claude Code | `claude` | `~/.config/claude/projects/`, `~/.claude/` |
78+
| Codex | `codex` | `${CODEX_HOME:-~/.codex}` |
79+
| OpenCode | `opencode` | `${OPENCODE_DATA_DIR:-~/.local/share/opencode}` |
80+
| Amp | `amp` | `${AMP_DATA_DIR:-~/.local/share/amp}` |
81+
| Droid | `droid` | `${DROID_SESSIONS_DIR:-~/.factory/sessions}` |
82+
| Codebuff | `codebuff` | `${CODEBUFF_DATA_DIR:-~/.config/manicode}` |
83+
| Hermes Agent | `hermes` | `${HERMES_HOME:-~/.hermes}/state.db` |
84+
| pi-agent | `pi` | `${PI_AGENT_DIR:-~/.pi/agent/sessions}` |
85+
| Goose | `goose` | Standard Goose data roots or `GOOSE_PATH_ROOT` |
86+
| OpenClaw | `openclaw` | `${OPENCLAW_DIR:-~/.openclaw}` |
87+
| Kilo | `kilo` | `${KILO_DATA_DIR:-~/.local/share/kilo}` |
88+
| Kimi | `kimi` | `${KIMI_DATA_DIR:-~/.kimi}` (also `~/.kimi-code`) |
89+
| Qwen | `qwen` | `${QWEN_DATA_DIR:-~/.qwen}` |
90+
| Copilot CLI | `copilot` | `~/.copilot/otel/*.jsonl` |
91+
| Gemini CLI | `gemini` | `${GEMINI_DATA_DIR:-~/.gemini/tmp}` |
9292

9393
The tool automatically detects available data and aggregates all supported coding CLIs by default.
9494
Each source-specific environment variable can also contain comma-separated directories, which lets unified reports combine current profiles and archives.

‎docs/guide/kimi/index.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ ccusage daily
2222

2323
## Data Location
2424

25-
The CLI reads Kimi wire JSONL files from `KIMI_DATA_DIR` (defaults to `~/.kimi`). `KIMI_DATA_DIR` can be one directory or a comma-separated list of directories.
25+
The CLI reads Kimi wire JSONL files from `KIMI_DATA_DIR` (defaults to `~/.kimi` and `~/.kimi-code`). `KIMI_DATA_DIR` can be one directory or a comma-separated list of directories.
2626

2727
```sh
2828
KIMI_DATA_DIR="$HOME/.kimi,/backup/kimi" ccusage kimi daily
@@ -32,6 +32,7 @@ Expected files are discovered under:
3232

3333
```text
3434
~/.kimi/sessions/<group-id>/<session-id>/wire.jsonl
35+
~/.kimi-code/sessions/<workspace-id>/<session-id>/agents/<agent-id>/wire.jsonl
3536
```
3637

3738
## Supported Reports
@@ -44,12 +45,12 @@ Expected files are discovered under:
4445

4546
## Token Mapping
4647

47-
- **Input tokens** - `token_usage.input_other`
48-
- **Output tokens** - `token_usage.output`
49-
- **Cache read tokens** - `token_usage.input_cache_read`
50-
- **Cache creation tokens** - `token_usage.input_cache_creation`
48+
- **Input tokens** - `token_usage.input_other` (or `usage.inputOther` in Kimi Code logs)
49+
- **Output tokens** - `token_usage.output` (or `usage.output`)
50+
- **Cache read tokens** - `token_usage.input_cache_read` (or `usage.inputCacheRead`)
51+
- **Cache creation tokens** - `token_usage.input_cache_creation` (or `usage.inputCacheCreation`)
5152

52-
Only `StatusUpdate` messages with non-zero token usage are included.
53+
Only `StatusUpdate` messages with non-zero token usage are included. Kimi Code logs instead emit `usage.record` lines; only turn-scoped records are counted, since session-scoped records are cumulative totals.
5354

5455
## Cost Calculation
5556

@@ -64,5 +65,5 @@ Kimi rows do not store recorded USD cost, so ccusage estimates cost from token c
6465
## Troubleshooting
6566

6667
::: details No Kimi usage data found
67-
Ensure the data directory exists at `~/.kimi/sessions/`. Set `KIMI_DATA_DIR` if your Kimi data lives elsewhere or in multiple archive roots.
68+
Ensure the data directory exists at `~/.kimi/sessions/` or `~/.kimi-code/sessions/`. Set `KIMI_DATA_DIR` if your Kimi data lives elsewhere or in multiple archive roots.
6869
:::

‎rust/crates/ccusage/src/adapter/kimi/loader.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,31 @@ mod tests {
8686
assert_eq!(entries[0].data.message.usage.cache_read_input_tokens, 10);
8787
}
8888

89+
#[test]
90+
fn loads_kimi_code_usage_record_format() {
91+
let fixture = fs_fixture!({
92+
"sessions/workspace/session-b/agents/agent-1/wire.jsonl": [
93+
r#"{"type":"usage.record","model":"kimi-code/kimi-for-coding","usage":{"inputOther":3064,"output":76,"inputCacheRead":14848,"inputCacheCreation":0},"usageScope":"turn","time":1782113184943}"#,
94+
r#"{"type":"usage.record","model":"kimi-code/kimi-for-coding","usage":{"inputOther":5000,"output":200,"inputCacheRead":20000,"inputCacheCreation":100},"usageScope":"session","time":1782113185000}"#,
95+
]
96+
.join("\n"),
97+
});
98+
let _cleanup = EnvVarGuard::set(KIMI_DATA_DIR_ENV, fixture.root());
99+
let shared = SharedArgs {
100+
timezone: Some("UTC".to_string()),
101+
..SharedArgs::default()
102+
};
103+
let entries = load_entries(&shared, &PricingMap::load_embedded()).unwrap();
104+
105+
assert_eq!(entries.len(), 1, "session-scoped record must be skipped");
106+
assert_eq!(entries[0].session_id.as_ref(), "session-b");
107+
assert_eq!(entries[0].model.as_deref(), Some("kimi-for-coding"));
108+
assert_eq!(entries[0].data.message.usage.input_tokens, 3064);
109+
assert_eq!(entries[0].data.message.usage.output_tokens, 76);
110+
assert_eq!(entries[0].data.message.usage.cache_read_input_tokens, 14848);
111+
assert_eq!(entries[0].data.message.usage.cache_creation_input_tokens, 0);
112+
}
113+
89114
#[test]
90115
fn skips_malformed_and_zero_token_wire_lines() {
91116
let fixture = fs_fixture!({

‎rust/crates/ccusage/src/adapter/kimi/parser.rs‎

Lines changed: 149 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,22 @@ struct KimiConfig {
3131
struct KimiWireLine {
3232
#[serde(default, deserialize_with = "jsonl::non_empty_string")]
3333
r#type: Option<String>,
34+
// old format
3435
message: Option<KimiWireMessage>,
3536
#[serde(default, deserialize_with = "jsonl::lenient_f64")]
3637
timestamp: Option<f64>,
38+
// new Kimi Code format
39+
#[serde(default, deserialize_with = "jsonl::non_empty_string")]
40+
model: Option<String>,
41+
usage: Option<KimiCodeUsage>,
42+
#[serde(
43+
rename = "usageScope",
44+
default,
45+
deserialize_with = "jsonl::non_empty_string"
46+
)]
47+
usage_scope: Option<String>,
48+
#[serde(default, deserialize_with = "jsonl::lenient_i64")]
49+
time: Option<i64>,
3750
}
3851

3952
/// The `message` block carried by a Kimi wire line.
@@ -67,6 +80,30 @@ struct KimiTokenUsage {
6780
total: u64,
6881
}
6982

83+
#[derive(Debug, Default, Deserialize)]
84+
struct KimiCodeUsage {
85+
#[serde(
86+
rename = "inputOther",
87+
default,
88+
deserialize_with = "jsonl::lenient_u64"
89+
)]
90+
input_other: u64,
91+
#[serde(default, deserialize_with = "jsonl::lenient_u64")]
92+
output: u64,
93+
#[serde(
94+
rename = "inputCacheCreation",
95+
default,
96+
deserialize_with = "jsonl::lenient_u64"
97+
)]
98+
input_cache_creation: u64,
99+
#[serde(
100+
rename = "inputCacheRead",
101+
default,
102+
deserialize_with = "jsonl::lenient_u64"
103+
)]
104+
input_cache_read: u64,
105+
}
106+
70107
#[derive(Debug, Clone)]
71108
pub(super) struct KimiUsageEntry {
72109
timestamp: TimestampMs,
@@ -85,9 +122,8 @@ pub(super) fn read_wire_file(path: &Path) -> Result<Vec<KimiUsageEntry>> {
85122
let model = read_model_from_config(path);
86123
let fallback_timestamp = file_modified_timestamp(path);
87124
let content = fs::read(path)?;
88-
// Usable Kimi wire lines are `StatusUpdate` records carrying a
89-
// `token_usage` payload, so require both substrings before JSON parsing.
90-
let prefilter = LinePrefilter::all(&[br#""StatusUpdate""#, br#""token_usage""#]);
125+
// Usable Kimi wire lines carry either `token_usage` (old format) or `usage.record` (new).
126+
let prefilter = LinePrefilter::any(&[br#""token_usage""#, br#""usage.record""#]);
91127
Ok(jsonl::records::<KimiWireLine>(&content, Some(&prefilter))
92128
.filter_map(|line| wire_line_to_entry(&line, path, &model, fallback_timestamp))
93129
.collect::<Vec<_>>())
@@ -107,12 +143,25 @@ fn read_model_from_config(file_path: &Path) -> String {
107143
}
108144

109145
fn kimi_root_from_wire_path(file_path: &Path) -> Option<PathBuf> {
110-
file_path
111-
.parent()?
112-
.parent()?
113-
.parent()?
114-
.parent()
115-
.map(Path::to_path_buf)
146+
// Old layout: root/sessions/<group>/<session>/wire.jsonl
147+
// New layout: root/sessions/<ws>/<session>/agents/<agent>/wire.jsonl
148+
let agent_dir = file_path.parent()?;
149+
if agent_dir.parent()?.file_name()?.to_str() == Some("agents") {
150+
agent_dir
151+
.parent()?
152+
.parent()?
153+
.parent()?
154+
.parent()?
155+
.parent()
156+
.map(Path::to_path_buf)
157+
} else {
158+
file_path
159+
.parent()?
160+
.parent()?
161+
.parent()?
162+
.parent()
163+
.map(Path::to_path_buf)
164+
}
116165
}
117166

118167
fn file_modified_timestamp(path: &Path) -> TimestampMs {
@@ -131,29 +180,79 @@ fn wire_line_to_entry(
131180
model: &str,
132181
fallback_timestamp: TimestampMs,
133182
) -> Option<KimiUsageEntry> {
134-
if line.r#type.as_deref() == Some("metadata") {
183+
match line.r#type.as_deref() {
184+
Some("usage.record") => wire_line_to_entry_new(line, file_path, fallback_timestamp),
185+
Some("metadata") => None,
186+
_ => wire_line_to_entry_old(line, file_path, model, fallback_timestamp),
187+
}
188+
}
189+
190+
fn wire_line_to_entry_new(
191+
line: &KimiWireLine,
192+
file_path: &Path,
193+
fallback_timestamp: TimestampMs,
194+
) -> Option<KimiUsageEntry> {
195+
// Only aggregate turn-level records; session records are cumulative totals.
196+
if line.usage_scope.as_deref() != Some("turn") {
197+
return None;
198+
}
199+
let usage_counts = line.usage.as_ref()?;
200+
let usage = TokenUsageRaw {
201+
input_tokens: usage_counts.input_other,
202+
output_tokens: usage_counts.output,
203+
cache_creation_input_tokens: usage_counts.input_cache_creation,
204+
cache_read_input_tokens: usage_counts.input_cache_read,
205+
speed: None,
206+
cache_creation: None,
207+
};
208+
let (usage, extra_total_tokens) = apply_total_token_fallback(usage, 0, 0);
209+
if crate::total_usage_tokens(usage) + extra_total_tokens == 0 {
135210
return None;
136211
}
212+
let timestamp = line
213+
.time
214+
.map(TimestampMs::from_millis)
215+
.unwrap_or(fallback_timestamp);
216+
let model = line.model.as_deref().unwrap_or(DEFAULT_MODEL);
217+
let model = model
218+
.strip_prefix("kimi-code/")
219+
.unwrap_or(model)
220+
.to_string();
221+
Some(KimiUsageEntry {
222+
timestamp,
223+
timestamp_text: crate::format_rfc3339_millis(timestamp),
224+
session_id: extract_session_id(file_path),
225+
model,
226+
message_id: None,
227+
input_tokens: usage.input_tokens,
228+
output_tokens: usage.output_tokens,
229+
cache_creation_tokens: usage.cache_creation_input_tokens,
230+
cache_read_tokens: usage.cache_read_input_tokens,
231+
extra_total_tokens,
232+
})
233+
}
234+
235+
fn wire_line_to_entry_old(
236+
line: &KimiWireLine,
237+
file_path: &Path,
238+
model: &str,
239+
fallback_timestamp: TimestampMs,
240+
) -> Option<KimiUsageEntry> {
137241
let message = line.message.as_ref()?;
138242
if message.r#type.as_deref() != Some("StatusUpdate") {
139243
return None;
140244
}
141245
let payload = message.payload.as_ref()?;
142246
let token_usage = payload.token_usage.as_ref()?;
143-
let input_tokens = token_usage.input_other;
144-
let output_tokens = token_usage.output;
145-
let cache_creation_tokens = token_usage.input_cache_creation;
146-
let cache_read_tokens = token_usage.input_cache_read;
147-
let total_tokens = token_usage.total;
148247
let usage = TokenUsageRaw {
149-
input_tokens,
150-
output_tokens,
151-
cache_creation_input_tokens: cache_creation_tokens,
152-
cache_read_input_tokens: cache_read_tokens,
248+
input_tokens: token_usage.input_other,
249+
output_tokens: token_usage.output,
250+
cache_creation_input_tokens: token_usage.input_cache_creation,
251+
cache_read_input_tokens: token_usage.input_cache_read,
153252
speed: None,
154253
cache_creation: None,
155254
};
156-
let (usage, extra_total_tokens) = apply_total_token_fallback(usage, 0, total_tokens);
255+
let (usage, extra_total_tokens) = apply_total_token_fallback(usage, 0, token_usage.total);
157256
if crate::total_usage_tokens(usage) + extra_total_tokens == 0 {
158257
return None;
159258
}
@@ -187,8 +286,20 @@ fn timestamp_from_seconds(seconds: f64) -> Option<TimestampMs> {
187286
}
188287

189288
fn extract_session_id(file_path: &Path) -> String {
190-
file_path
191-
.parent()
289+
// Old layout: sessions/<group>/<session>/wire.jsonl
290+
// New layout: sessions/<ws>/<session>/agents/<agent>/wire.jsonl
291+
let parent = file_path.parent();
292+
let session_dir = if parent
293+
.and_then(|p| p.parent())
294+
.and_then(Path::file_name)
295+
.and_then(|n| n.to_str())
296+
== Some("agents")
297+
{
298+
parent.and_then(|p| p.parent()).and_then(|p| p.parent())
299+
} else {
300+
parent
301+
};
302+
session_dir
192303
.and_then(Path::file_name)
193304
.and_then(|name| name.to_str())
194305
.filter(|name| !name.is_empty())
@@ -328,6 +439,22 @@ mod tests {
328439
use super::*;
329440
use ccusage_test_support::fs_fixture;
330441

442+
#[test]
443+
fn kimi_root_resolves_correctly_for_both_path_layouts() {
444+
let fixture = fs_fixture!({
445+
"sessions/group/session-a/wire.jsonl": "",
446+
"sessions/ws/session-b/agents/agent-1/wire.jsonl": "",
447+
});
448+
let old_path = fixture.path("sessions/group/session-a/wire.jsonl");
449+
let new_path = fixture.path("sessions/ws/session-b/agents/agent-1/wire.jsonl");
450+
451+
let old_root = kimi_root_from_wire_path(&old_path).unwrap();
452+
let new_root = kimi_root_from_wire_path(&new_path).unwrap();
453+
454+
assert_eq!(old_root, fixture.root().to_path_buf());
455+
assert_eq!(new_root, fixture.root().to_path_buf());
456+
}
457+
331458
#[test]
332459
fn falls_back_to_total_tokens_when_kimi_parts_are_missing() {
333460
let fixture = fs_fixture!({

0 commit comments

Comments
 (0)