Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

attribute nested Kimi CLI usage to its own provider; confirm Cursor writes no transcript (#6045)

[._.]/ Adam Eivycf59eebac567
diff --git a/server/lib/README.md b/server/lib/README.md
index f7c91b8111..a798e8f51b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -221,7 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerModelAliases.js` | HAND-AUTHORED canonical→executable model aliases for one provider route (#6369) — the correction surface for a `modelMap` a refresh could only fill with what it could VERIFY. Observed aliases (`ai_route_bindings.model_map`) and user overrides (`model_alias_overrides`) are stored apart and merged on READ by `effectiveModelAliases` (`{ ...observed, ...overrides }`), which is what lets a hand-authored alias outlast the next refresh; `applyModelAliasPatch` is the three-valued edit (absent preserves, a string sets, `null` is the only thing that removes); `staleModelAliases` reports — never repairs — an override naming a spelling the record no longer lists, and makes no claim at all about a route listing no models; `connectionCatalogModels` is the union an alias write re-derives the shared catalog from, so a correction actually reaches the model menus; `modelAliasRevision` is the stale-edit fingerprint, reusing `routeSettingsRevision` because `ai_route_bindings` has no revision column. Pure: no I/O. |
| `providerRouteRecipes.js` | Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of `providerConnections.js`, which reads an existing record. `buildRouteRecord({harnessId, mode, providerId, name, connection})` materializes a connection's endpoint, credentials and backend marker into a DISABLED `data/providers.json` record through `PROVIDER_HARNESSES[].recipe`; `mintRouteIds` allocates readable ids keeping the `<stem>` / `<stem>-tui` pairing `providerModeGroups` recognizes; `bindingBlocker` is the pre-write refusal (no recipe, unsupported mode, a transport the backend does not declare, a credential the program requires); `CREATABLE_CONNECTION_KINDS` / `connectionKindLabel` / `connectionKindMarkers` bound the backends a route can honestly describe (`slotstream` and `vendor` deliberately excluded); `bindingProtocol` names the wire a binding needs. Pure: no I/O, no spawn, no provider call.
| `providerRouteSettings.js` | The MODE-OVERRIDE half of a provider route (#6369) — the route-owned fields a human tunes per execution mode (`args`, `timeout`, `effort` and the `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`/`ultraModel` pins), mirroring what the toolkit's `sharedModeUpdates` already declares mode-specific. `ROUTE_SETTING_FIELDS` / `ROUTE_SETTING_KEYS` / `routeSettingKeys(mode)` name the set (`args` reaches cli/tui only); `routeSettingsFor(provider)` reads it off a record with absent and cleared collapsing to `null`; `routeSettingsSchema` is the wire shape `GET /api/providers/management` publishes; `unsupportedRouteSettings` rejects a key the route's mode does not accept; and `routeSettingsRevision` is the stale-edit fingerprint — a hash of the values as they are in providers.json rather than a graph row revision, so an edit made through `/ai/edit/:providerId` is caught too. Connection-owned values and execution consent (`enabled`) are deliberately absent. Pure: no I/O.
-| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
+| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `parseKimiWireLog`/`parseKimiSessionIndex` (`~/.kimi-code/sessions/.../agents/<id>/wire.jsonl`, indexed by `~/.kimi-code/session_index.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Kimi's `usage.record` lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one `wire.jsonl` per agent — a subagent's spend is never in its parent's file. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. |
| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `modelPinIsOffered(provider, model)` (the ONE rule for validating a stored model pin against a provider record: an empty `models` array and a local daemon's cached snapshot are both pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |
diff --git a/server/lib/providerTranscriptUsage.js b/server/lib/providerTranscriptUsage.js
index 3a8259c43c..89434129e9 100644
--- a/server/lib/providerTranscriptUsage.js
+++ b/server/lib/providerTranscriptUsage.js
@@ -17,6 +17,11 @@
* `event_msg`/`token_count` lines carry a CUMULATIVE `total_token_usage`
* plus the per-turn `last_token_usage`.
*
+ * Kimi Code — ~/.kimi-code/sessions/wd_.../session_.../agents/<id>/wire.jsonl
+ * Indexed by the global ~/.kimi-code/session_index.jsonl. `usage.record`
+ * lines carry real per-call billed usage as a discrete delta — see the
+ * section below for the full shape and how it was confirmed.
+ *
* Both formats have a de-duplication hazard that makes naive summing wrong by
* a large factor, documented at each parser. Both parsers are pure (text in,
* totals out), tolerant of truncated trailing lines (a session still being
@@ -720,3 +725,155 @@ export function parseAgyHistory(jsonlText) {
}
return out;
}
+
+/**
+ * ---------------------------------------------------------------------------
+ * Kimi Code CLI (`kimi`)
+ * ---------------------------------------------------------------------------
+ *
+ * `~/.kimi-code/session_index.jsonl` — a single GLOBAL, append-only log of
+ * every session ever created on the machine (every cwd, not just one):
+ * `{ sessionId, sessionDir, workDir }`, `workDir` the exact (unslugified) cwd
+ * the session started in. Unlike Claude's project-slug directory or Grok's
+ * `encodeURIComponent(cwd)` folder, there is no cwd-derived directory name to
+ * decode — `sessions/wd_<basename>_<hash>/` exists, but the hash suffix is
+ * undocumented, so this index is the supported lookup.
+ *
+ * `<sessionDir>/agents/<agentId>/wire.jsonl` — one JSON record per line,
+ * append-only, `type` names the record and every line carries `time` (epoch
+ * ms, a NUMBER — not an ISO string like Claude's). `main` is the top-level
+ * agent; a spawned subagent gets its own `agents/<subAgentId>/` directory and
+ * its OWN wire.jsonl — confirmed from the CLI's own embedded context-recovery
+ * documentation string: "agents/main/ is the main agent; each subagent has
+ * its own agents/<agentId>/wire.jsonl. A parent's log holds only the Agent
+ * tool call and the subagent's returned result — the subagent's own steps are
+ * in its own file." So a session's real cost is the SUM over every agent
+ * directory beneath it, not `main` alone.
+ *
+ * Billed usage lives in `usage.record` lines:
+ * { type: 'usage.record', agentId, model,
+ * usage: { inputOther, output, inputCacheRead, inputCacheCreation },
+ * usageScope: 'turn'|'session', time }
+ * `model` and the `usage` shape were confirmed by reading the shipped CLI
+ * binary's bundled source (`usageRecordSchema`, `UsageAgentModel`, and the
+ * `addUsage`/`inputTotal` reducers in `packages/agent-core-v2/src/agent/usage`)
+ * — no live successful call was available to verify end-to-end when this was
+ * written (#6045), so this is corroborated from source, not from an observed
+ * response. Each record is a DISCRETE per-call delta: `UsageAgentModel.record()`
+ * ADDS every new record onto a running total rather than replacing it, so —
+ * unlike Codex's cumulative rollout — there is no snapshot-vs-delta trap; every
+ * in-window record is simply summed. `inputOther` is already the FRESH
+ * (uncached) portion (`inputTotal(usage) = inputOther + inputCacheRead +
+ * inputCacheCreation`), so it maps straight onto `tokensIn` with no
+ * cache-inclusive split to undo, unlike Grok's `inputTokens`.
+ *
+ * No id distinguishes one `usage.record` from another, so the dedupe/claim key
+ * is content-derived exactly like the Claude parser's keyless-line fallback.
+ */
+
+/**
+ * `~/.kimi-code/session_index.jsonl` → one entry per unique `sessionDir`, in
+ * first-seen order. The file is append-only and can carry more than one line
+ * per session (e.g. across a resume), so later duplicates are dropped rather
+ * than overwriting the first `workDir` seen for that directory.
+ *
+ * @param {string} jsonlText raw file contents (may end mid-line)
+ * @returns {Array<{ sessionId: string|null, sessionDir: string, workDir: string|null }>}
+ */
+export function parseKimiSessionIndex(jsonlText) {
+ const seen = new Set();
+ const out = [];
+ for (const entry of parseJsonLines(jsonlText)) {
+ const sessionDir = typeof entry.sessionDir === 'string' ? entry.sessionDir : null;
+ if (!sessionDir || seen.has(sessionDir)) continue;
+ seen.add(sessionDir);
+ out.push({
+ sessionId: typeof entry.sessionId === 'string' ? entry.sessionId : null,
+ sessionDir,
+ workDir: typeof entry.workDir === 'string' ? entry.workDir : null
+ });
+ }
+ return out;
+}
+
+/** One agent's `usage.record` buckets, cache tiers already split by the CLI. */
+const kimiBuckets = (usage) => ({
+ messages: 1,
+ tokensIn: num(usage?.inputOther),
+ tokensOut: num(usage?.output),
+ cacheReadTokens: num(usage?.inputCacheRead),
+ cacheWriteTokens: num(usage?.inputCacheCreation)
+});
+
+/**
+ * Parse one agent's `wire.jsonl` into billed totals from its `usage.record`
+ * lines. Call once per `agents/<agentId>/wire.jsonl` under a session directory
+ * and fold the results — a session's total spans every agent directory it has.
+ *
+ * @param {string} jsonlText raw file contents (may end mid-line)
+ * @param {{ from?: number|null, to?: number|null, exclude?: {has:(k:string)=>boolean}|null }} [opts]
+ * `from`/`to` are epoch-ms bounds (compared directly against each line's own
+ * numeric `time`); `exclude` holds keys already billed to another run.
+ * @returns {{ model: string|null, models: string[], byModel: object,
+ * messages: number, tokensIn: number, tokensOut: number,
+ * cacheReadTokens: number, cacheWriteTokens: number, countedKeys: string[],
+ * records: number }} `records` is the number of `usage.record` lines SEEN
+ * before windowing/claiming — the sentinel that separates "this agent file
+ * never billed anything" (a session that failed or was interrupted before
+ * any call completed — correctly zero, since nothing was actually spent)
+ * from "it did, and this window's share is legitimately zero".
+ */
+export function parseKimiWireLog(jsonlText, { from = null, to = null, exclude = null } = {}) {
+ const totals = emptyTotals();
+ const byModel = new Map();
+ const modelCounts = new Map();
+ const counted = [];
+ const contentSeen = new Map();
+ let records = 0;
+
+ for (const entry of parseJsonLines(jsonlText)) {
+ if (entry.type !== 'usage.record') continue;
+ records += 1;
+ const usage = entry.usage;
+ if (!usage || typeof usage !== 'object') continue;
+
+ const ts = typeof entry.time === 'number' && Number.isFinite(entry.time) ? entry.time : null;
+ if (!inWindow(ts, from, to)) continue;
+
+ const model = typeof entry.model === 'string' && entry.model ? entry.model : null;
+ const bucketKey = model ?? UNKNOWN_MODEL;
+
+ // No id on a usage.record — key it by its own content, the same fallback
+ // the Claude parser uses for a keyless line: stable under insertion, with
+ // an occurrence tiebreaker so two genuinely identical records don't merge.
+ const content = [entry.time ?? '', entry.agentId ?? '', bucketKey, num(usage.inputOther), num(usage.output), num(usage.inputCacheRead), num(usage.inputCacheCreation)].join('|');
+ const occurrence = contentSeen.get(content) ?? 0;
+ contentSeen.set(content, occurrence + 1);
+ const key = `@${content}#${occurrence}`;
+ if (exclude?.has(key)) continue;
+
+ const buckets = kimiBuckets(usage);
+ if (totalTranscriptTokens(buckets) === 0) continue;
+ counted.push(key);
+ for (const field of Object.keys(totals)) totals[field] += buckets[field];
+
+ if (model) modelCounts.set(model, (modelCounts.get(model) || 0) + 1);
+ if (!byModel.has(bucketKey)) byModel.set(bucketKey, emptyTotals());
+ const bucket = byModel.get(bucketKey);
+ for (const field of Object.keys(bucket)) bucket[field] += buckets[field];
+ }
+
+ const models = [...modelCounts.keys()];
+ const chosenModel = models.length
+ ? [...modelCounts.entries()].sort((a, b) => b[1] - a[1])[0][0]
+ : null;
+
+ return {
+ model: chosenModel,
+ models,
+ byModel: Object.fromEntries(byModel),
+ ...totals,
+ countedKeys: counted,
+ records
+ };
+}
diff --git a/server/lib/providerTranscriptUsage.test.js b/server/lib/providerTranscriptUsage.test.js
index 2898fcb145..63e0805536 100644
--- a/server/lib/providerTranscriptUsage.test.js
+++ b/server/lib/providerTranscriptUsage.test.js
@@ -8,6 +8,8 @@ import {
parseCodexRollout,
parseGrokChatHistory,
parseGrokTurns,
+ parseKimiSessionIndex,
+ parseKimiWireLog,
totalTranscriptTokens,
UNKNOWN_MODEL
} from './providerTranscriptUsage.js';
@@ -687,3 +689,112 @@ describe('parseAgyHistory', () => {
]);
});
});
+
+// ---------------------------------------------------------------------------
+// Kimi Code CLI — ~/.kimi-code/
+// ---------------------------------------------------------------------------
+
+const KIMI_MODEL = 'kimi-for-coding';
+
+const kimiUsageRecord = ({ agentId = 'main', model = KIMI_MODEL, time = 1_800_000_000_000, inputOther = 200, output = 40, inputCacheRead = 0, inputCacheCreation = 0 } = {}) => JSON.stringify({
+ type: 'usage.record',
+ agentId,
+ model,
+ usage: { inputOther, output, inputCacheRead, inputCacheCreation },
+ usageScope: 'turn',
+ time
+});
+
+describe('parseKimiWireLog', () => {
+ it('sums usage.record lines with the cache tiers already split', () => {
+ const parsed = parseKimiWireLog(kimiUsageRecord({ inputOther: 500, output: 120, inputCacheRead: 80, inputCacheCreation: 20 }));
+ expect(parsed.tokensIn).toBe(500);
+ expect(parsed.tokensOut).toBe(120);
+ expect(parsed.cacheReadTokens).toBe(80);
+ expect(parsed.cacheWriteTokens).toBe(20);
+ expect(parsed.model).toBe(KIMI_MODEL);
+ expect(parsed.byModel[KIMI_MODEL].tokensOut).toBe(120);
+ });
+
+ it('adds successive records rather than treating them as cumulative snapshots', () => {
+ // Unlike Codex's rollout, each usage.record is already its own delta — a
+ // turn with several LLM calls (tool-loop steps) writes several records,
+ // and summing them is correct rather than a double-count.
+ const text = [
+ kimiUsageRecord({ time: 1_800_000_000_000, output: 100 }),
+ kimiUsageRecord({ time: 1_800_000_001_000, output: 300 })
+ ].join('\n');
+ expect(parseKimiWireLog(text).tokensOut).toBe(400);
+ });
+
+ it('ignores every record type except usage.record', () => {
+ const text = [
+ JSON.stringify({ type: 'llm.request', agentId: 'main', provider: 'openai', time: 1_800_000_000_000 }),
+ JSON.stringify({ type: 'turn.ended', agentId: 'main', reason: 'completed', time: 1_800_000_000_500 }),
+ kimiUsageRecord({ output: 42 })
+ ].join('\n');
+ const parsed = parseKimiWireLog(text);
+ expect(parsed.tokensOut).toBe(42);
+ expect(parsed.records).toBe(1);
+ });
+
+ it('reports zero records for a session interrupted before any call completed', () => {
+ // A quota error or other failure before the response streams writes no
+ // usage.record at all — this IS the correct measured total (nothing was
+ // actually billed), distinct from a transcript that failed to parse.
+ const text = JSON.stringify({ type: 'turn.step.interrupted', agentId: 'main', reason: 'error', time: 1_800_000_000_000 });
+ const parsed = parseKimiWireLog(text);
+ expect(totalTranscriptTokens(parsed)).toBe(0);
+ expect(parsed.records).toBe(0);
+ });
+
+ it('windows records by the numeric epoch-ms time field', () => {
+ const text = [
+ kimiUsageRecord({ time: 1_800_000_000_000, output: 111 }),
+ kimiUsageRecord({ time: 1_800_003_600_000, output: 222 })
+ ].join('\n');
+ const parsed = parseKimiWireLog(text, { from: 1_800_003_000_000, to: 1_800_004_000_000 });
+ expect(parsed.tokensOut).toBe(222);
+ });
+
+ it('skips records another run already claimed', () => {
+ const text = [
+ kimiUsageRecord({ time: 1_800_000_000_000, output: 111 }),
+ kimiUsageRecord({ time: 1_800_000_001_000, output: 222 })
+ ].join('\n');
+ const first = parseKimiWireLog(text);
+ const second = parseKimiWireLog(text, { exclude: new Set(first.countedKeys.slice(0, 1)) });
+ expect(second.tokensOut).toBe(222);
+ });
+
+ it('sums per-model buckets across models, and attributes an unnamed record to UNKNOWN_MODEL', () => {
+ const text = [
+ kimiUsageRecord({ model: KIMI_MODEL, output: 10 }),
+ kimiUsageRecord({ model: 'other-model', time: 1_800_000_001_000, output: 20 }),
+ JSON.stringify({ type: 'usage.record', agentId: 'main', usage: { inputOther: 0, output: 5, inputCacheRead: 0, inputCacheCreation: 0 }, time: 1_800_000_002_000 })
+ ].join('\n');
+ const parsed = parseKimiWireLog(text);
+ expect(parsed.tokensOut).toBe(35);
+ expect(parsed.byModel[UNKNOWN_MODEL].tokensOut).toBe(5);
+ expect(parsed.models.sort()).toEqual([KIMI_MODEL, 'other-model'].sort());
+ });
+
+ it('tolerates a truncated trailing line from a session still being written', () => {
+ const text = `${kimiUsageRecord({ output: 111 })}\n{"type":"usage.record`;
+ expect(parseKimiWireLog(text).tokensOut).toBe(111);
+ });
+});
+
+describe('parseKimiSessionIndex', () => {
+ it('keeps only the first occurrence of each sessionDir', () => {
+ const text = [
+ JSON.stringify({ sessionId: 'session-aaaa', sessionDir: '/home/example/.kimi-code/sessions/wd_repo_aaaa/session_aaaa', workDir: '/work/example-repo' }),
+ JSON.stringify({ sessionId: 'session-aaaa', sessionDir: '/home/example/.kimi-code/sessions/wd_repo_aaaa/session_aaaa', workDir: '/work/example-repo' }),
+ JSON.stringify({ sessionId: 'session-bbbb', sessionDir: '/home/example/.kimi-code/sessions/wd_other_bbbb/session_bbbb', workDir: '/work/other-repo' })
+ ].join('\n');
+ expect(parseKimiSessionIndex(text)).toEqual([
+ { sessionId: 'session-aaaa', sessionDir: '/home/example/.kimi-code/sessions/wd_repo_aaaa/session_aaaa', workDir: '/work/example-repo' },
+ { sessionId: 'session-bbbb', sessionDir: '/home/example/.kimi-code/sessions/wd_other_bbbb/session_bbbb', workDir: '/work/other-repo' }
+ ]);
+ });
+});
diff --git a/server/services/usageReconciler.js b/server/services/usageReconciler.js
index 0aa852dd28..73fbe399b5 100644
--- a/server/services/usageReconciler.js
+++ b/server/services/usageReconciler.js
@@ -53,9 +53,12 @@ import {
parseAgyHistory,
parseGrokChatHistory,
parseGrokTurns,
+ parseKimiSessionIndex,
+ parseKimiWireLog,
totalTranscriptTokens
} from '../lib/providerTranscriptUsage.js';
import { familyForProvider } from '../lib/providerFamilies.js';
+import { commandBasename } from '../lib/providerModels.js';
import { markUsageRunReconciled, recordRunUsage } from './usage.js';
// Widen the correlation window past the recorded run bounds: the CLI writes its
@@ -161,6 +164,7 @@ const GROK_ID = /grok/i;
// `agy` is a three-letter binary name, so it needs word boundaries or it would
// match inside an unrelated id; `antigravity` is the long form of the same CLI.
const AGY_ID = /(^|[^a-z0-9])agy([^a-z0-9]|$)|antigravity/i;
+const KIMI_ID = /kimi/i;
/**
* Which model id to record for a measured bucket.
@@ -212,9 +216,27 @@ function attributedModel(recordedModel, transcriptModel, singleModel) {
*
* The ids match `lib/providerFamilies.js`'s family ids on purpose: a sibling
* session found in a run's workspace is mapped back to an enabled provider
- * through `familyForProvider`, so the two vocabularies have to agree.
+ * through `familyForProvider`, so the two vocabularies have to agree — with
+ * one exception, documented at `resolveFamilyProvider`: `kimi` has no
+ * subscription plan for `familyForProvider` to know about, so it is resolved
+ * there through a small local matcher instead.
+ *
+ * `cursor` is deliberately absent — #6045 gated both `cursor` and `kimi` on
+ * "only if a durable cwd-keyed session store is found", and Cursor CLI
+ * 2026.09.10 has none: `~/.cursor/chats/<hash>/<chatId>/meta.json` is
+ * cwd-keyed but carries only `{ cwd, createdAtMs, updatedAtMs,
+ * hasConversation }` — no per-turn token counts or message text anywhere;
+ * `~/.cursor/ai-tracking/*.db` tracks AI-vs-human code-line attribution for
+ * commit scoring, not token usage. A nested `--review-with cursor` pass still
+ * falls back to the chars/4 estimate. Re-check on a Cursor CLI upgrade that
+ * adds transcript persistence.
+ *
+ * `kimi` IS present — Kimi Code CLI 0.42.0 writes real per-call billed usage
+ * to `~/.kimi-code/sessions/.../agents/<id>/wire.jsonl` (`usage.record`
+ * lines); see the Kimi section of `providerTranscriptUsage.js` for the full
+ * shape and how it was confirmed.
* @param {{ providerId?: string|null, command?: string|null }} run
- * @returns {'claude'|'codex'|'grok'|'agy'|null}
+ * @returns {'claude'|'codex'|'grok'|'agy'|'kimi'|null}
*/
export function transcriptFamily({ providerId = null, command = null } = {}) {
const haystack = `${providerId || ''} ${command || ''}`;
@@ -224,12 +246,13 @@ export function transcriptFamily({ providerId = null, command = null } = {}) {
if (CODEX_ID.test(haystack)) return 'codex';
if (GROK_ID.test(haystack)) return 'grok';
if (AGY_ID.test(haystack)) return 'agy';
+ if (KIMI_ID.test(haystack)) return 'kimi';
if (CLAUDE_ID.test(haystack)) return 'claude';
return null;
}
/** Every family whose CLI writes a readable session store. */
-export const TRANSCRIPT_FAMILIES = ['claude', 'codex', 'grok', 'agy'];
+export const TRANSCRIPT_FAMILIES = ['claude', 'codex', 'grok', 'agy', 'kimi'];
/** `reconcileRunUsage` returns one record or several — normalize to a list. */
const asRecordList = (records) => (Array.isArray(records) ? records : [records]);
@@ -288,7 +311,7 @@ function codexDateDirs(root, fromMs, toMs) {
* @param {string} run.workspacePath cwd the run executed in
* @param {string|null} run.startTime ISO
* @param {string|null} run.endTime ISO
- * @param {'claude'|'codex'|'grok'|'agy'} run.family
+ * @param {'claude'|'codex'|'grok'|'agy'|'kimi'} run.family
* @param {string} [run.home] override for tests
* @returns {Promise<null|{ source: 'measured'|'estimate'|'mixed', family: string,
* sessions: number, model: string|null, messages: number, tokensIn: number,
@@ -485,6 +508,27 @@ export async function readMeasuredUsage({ workspacePath, startTime, endTime, fam
// lets the caller attribute it to the provider's own configured model.
fold({ ...estimated, models: [], byModel: { [UNKNOWN_MODEL]: { ...estimated } } }, 'estimate');
}
+ } else if (family === 'kimi') {
+ // `~/.kimi-code/session_index.jsonl` is a single GLOBAL, append-only index
+ // of every session ever created on this machine — filter by exact `workDir`
+ // rather than trying to decode `sessions/wd_<basename>_<hash>/`, whose hash
+ // suffix is undocumented.
+ const indexText = await tryReadFile(join(home, '.kimi-code', 'session_index.jsonl'));
+ for (const session of indexText ? parseKimiSessionIndex(indexText) : []) {
+ if (!cwdMatches(session.workDir, workspacePath)) continue;
+ // Real usage lives per-AGENT, not per-session: a subagent's own spend is
+ // in its own `agents/<subAgentId>/wire.jsonl`, never the parent's (see the
+ // Kimi section of `providerTranscriptUsage.js`) — sum every agent dir.
+ const agentsRoot = join(session.sessionDir, 'agents');
+ for (const agentId of await listSubdirs(agentsRoot)) {
+ const wirePath = join(agentsRoot, agentId, 'wire.jsonl');
+ const text = await tryReadFile(wirePath);
+ if (!text) continue;
+ const parsed = parseKimiWireLog(text, { from, to, exclude: excludeFor(wirePath) });
+ reserveFrom(wirePath, parsed);
+ fold(parsed);
+ }
+ }
} else {
const sessionsRoot = join(home, '.codex', 'sessions');
for (const dir of codexDateDirs(sessionsRoot, from ?? Date.now(), to ?? from ?? Date.now())) {
@@ -623,6 +667,18 @@ function recordsFromMeasured(providerId, recordedModel, measured, role) {
}];
}
+// `lib/providerFamilies.js` deliberately excludes `kimi` from PROVIDER_FAMILIES
+// (see that file's docblock) because Kimi Code has no subscription plan and no
+// `/usage` panel for `providerUsage.js` to scrape — `familyForProvider` can
+// therefore never return `'kimi'`. This is a TRANSCRIPT family, not a
+// subscription-quota one, so it is matched here directly instead: mirrors the
+// `commandBasename`/id-regex shape `providerFamilies.js` uses for every other
+// family, without adding a `kimi` entry to the quota-scraping FAMILY_FETCHERS
+// registry that array drives.
+const matchesKimiProvider = (provider) => (
+ commandBasename(provider?.command) === 'kimi' || KIMI_ID.test(provider?.id || '')
+);
+
/**
* The enabled provider a sibling family's sessions should be billed to, or null
* when this install has none configured for that family.
@@ -640,8 +696,11 @@ function recordsFromMeasured(providerId, recordedModel, measured, role) {
* @param {object} measured the `readMeasuredUsage` result, for its model names
*/
export function resolveFamilyProvider(providers, family, measured = null) {
+ const matchesFamily = family === 'kimi'
+ ? matchesKimiProvider
+ : (provider) => familyForProvider(provider) === family;
const candidates = (providers || []).filter((provider) => (
- provider?.enabled !== false && familyForProvider(provider) === family
+ provider?.enabled !== false && matchesFamily(provider)
));
const byType = (type) => candidates.filter((provider) => provider.type === type);
const pool = byType('cli').length ? byType('cli') : byType('tui');
diff --git a/server/services/usageReconciler.test.js b/server/services/usageReconciler.test.js
index 8a5a3c337e..e6b8d62cda 100644
--- a/server/services/usageReconciler.test.js
+++ b/server/services/usageReconciler.test.js
@@ -79,6 +79,36 @@ const writeCodexRollout = async (dateParts, file, text) => {
await writeFile(join(dir, file), text);
};
+const KIMI_MODEL = 'kimi-for-coding';
+
+const kimiUsageRecordLine = ({ agentId = 'main', model = KIMI_MODEL, timeMs, inputOther = 200, output = 40, inputCacheRead = 0, inputCacheCreation = 0 }) => JSON.stringify({
+ type: 'usage.record',
+ agentId,
+ model,
+ usage: { inputOther, output, inputCacheRead, inputCacheCreation },
+ usageScope: 'turn',
+ time: timeMs
+});
+
+/**
+ * `~/.kimi-code/session_index.jsonl` (global) plus one session directory with
+ * an `agents/<agentId>/wire.jsonl` per entry in `agents`.
+ */
+const writeKimiSession = async ({ sessionId = 'session-aaaa', cwd = WORKSPACE, agents = { main: [] } }) => {
+ const sessionDir = join(home, '.kimi-code', 'sessions', 'wd_example_aaaa111111', `session_${sessionId}`);
+ await mkdir(sessionDir, { recursive: true });
+ await writeFile(
+ join(home, '.kimi-code', 'session_index.jsonl'),
+ `${JSON.stringify({ sessionId, sessionDir, workDir: cwd })}\n`,
+ { flag: 'a' }
+ );
+ for (const [agentId, lines] of Object.entries(agents)) {
+ const agentDir = join(sessionDir, 'agents', agentId);
+ await mkdir(agentDir, { recursive: true });
+ await writeFile(join(agentDir, 'wire.jsonl'), lines.join('\n'));
+ }
+};
+
beforeEach(async () => {
home = await mkdtemp(join(tmpdir(), 'portos-usage-'));
vi.clearAllMocks();
@@ -114,9 +144,15 @@ describe('transcriptFamily', () => {
expect(transcriptFamily({ providerId: 'custom', command: '/usr/local/bin/agy' })).toBe('agy');
});
+ it('maps kimi provider ids to the kimi family', () => {
+ expect(transcriptFamily({ providerId: 'kimi-cli' })).toBe('kimi');
+ expect(transcriptFamily({ providerId: 'custom', command: '/usr/local/bin/kimi' })).toBe('kimi');
+ });
+
it('returns null for providers that write no transcript', () => {
// `legacy` would match the `agy` binary name without word boundaries.
- for (const providerId of ['ollama', 'lmstudio', 'kimi', 'legacy', '', null]) {
+ // `cursor` writes no transcript at all (confirmed absent, #6045).
+ for (const providerId of ['ollama', 'lmstudio', 'cursor', 'legacy', '', null]) {
expect(transcriptFamily({ providerId })).toBeNull();
}
});
@@ -238,6 +274,85 @@ describe('readMeasuredUsage', () => {
});
expect(result?.tokensOut).toBe(40);
});
+
+ it('finds a kimi session by session_index.jsonl and sums its usage.record lines', async () => {
+ const timeMs = Date.parse('2026-07-01T10:05:00.000Z');
+ await writeKimiSession({
+ agents: { main: [kimiUsageRecordLine({ timeMs, inputOther: 200, output: 40, inputCacheRead: 50 })] }
+ });
+
+ const result = await readMeasuredUsage({
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z',
+ family: 'kimi',
+ home
+ });
+
+ expect(result).toMatchObject({
+ source: 'measured',
+ sessions: 1,
+ tokensIn: 200,
+ tokensOut: 40,
+ cacheReadTokens: 50,
+ model: KIMI_MODEL
+ });
+ });
+
+ it('sums a subagent wire.jsonl separately from the main agent', async () => {
+ const timeMs = Date.parse('2026-07-01T10:05:00.000Z');
+ await writeKimiSession({
+ agents: {
+ main: [kimiUsageRecordLine({ agentId: 'main', timeMs, output: 40 })],
+ 'subagent-1': [kimiUsageRecordLine({ agentId: 'subagent-1', timeMs, output: 15 })]
+ }
+ });
+
+ const result = await readMeasuredUsage({
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z',
+ family: 'kimi',
+ home
+ });
+ expect(result?.tokensOut).toBe(55);
+ expect(result?.sessions).toBe(2);
+ });
+
+ it('ignores a kimi session from a different workDir', async () => {
+ const timeMs = Date.parse('2026-07-01T10:05:00.000Z');
+ await writeKimiSession({
+ cwd: '/work/other-repo',
+ agents: { main: [kimiUsageRecordLine({ timeMs })] }
+ });
+
+ const result = await readMeasuredUsage({
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z',
+ family: 'kimi',
+ home
+ });
+ expect(result).toBeNull();
+ });
+
+ it('bills nothing for a kimi session interrupted before any call completed', async () => {
+ // A session that failed/aborted before streaming a response (e.g. a quota
+ // error) writes no `usage.record` line at all — correctly zero, since
+ // nothing was actually billed by the provider.
+ await writeKimiSession({
+ agents: { main: [JSON.stringify({ type: 'turn.ended', agentId: 'main', reason: 'failed', time: Date.parse('2026-07-01T10:05:00.000Z') })] }
+ });
+
+ const result = await readMeasuredUsage({
+ workspacePath: WORKSPACE,
+ startTime: '2026-07-01T10:00:00.000Z',
+ endTime: '2026-07-01T10:10:00.000Z',
+ family: 'kimi',
+ home
+ });
+ expect(result).toBeNull();
+ });
});
describe('reconcileRunUsage', () => {
@@ -972,6 +1087,7 @@ const GROK_MODEL = 'example-grok-model';
const GROK_PROVIDER = { id: 'grok-cli', type: 'cli', command: 'grok', enabled: true, defaultModel: GROK_MODEL };
const AGY_PROVIDER = { id: 'antigravity-cli', type: 'cli', command: 'agy', enabled: true, defaultModel: 'example-agy-model' };
const CLAUDE_PROVIDER = { id: 'claude-code', type: 'cli', command: 'claude', enabled: true, defaultModel: 'claude-opus-5' };
+const KIMI_PROVIDER = { id: 'kimi-cli', type: 'cli', command: 'kimi', enabled: true, defaultModel: KIMI_MODEL };
const grokTurnLine = ({ promptId = 'prompt-1', ms, input = 15_000, cachedRead = 11_000, output = 1_800 }) => JSON.stringify({
timestamp: Math.round(ms / 1000),
@@ -1057,6 +1173,14 @@ describe('resolveFamilyProvider', () => {
expect(resolveFamilyProvider([{ ...GROK_PROVIDER, enabled: false }], 'grok')).toBeNull();
expect(resolveFamilyProvider([CLAUDE_PROVIDER], 'grok')).toBeNull();
});
+
+ it('resolves a kimi provider by command, even though it has no subscription-quota family', () => {
+ // `lib/providerFamilies.js` deliberately has no `kimi` entry (no plan to
+ // meter) — this must not make it unresolvable as a sibling-billing target.
+ expect(resolveFamilyProvider([KIMI_PROVIDER], 'kimi')?.id).toBe('kimi-cli');
+ expect(resolveFamilyProvider([{ ...KIMI_PROVIDER, enabled: false }], 'kimi')).toBeNull();
+ expect(resolveFamilyProvider([CLAUDE_PROVIDER], 'kimi')).toBeNull();
+ });
});
describe('grok sessions', () => {
@@ -1125,6 +1249,35 @@ describe('grok sessions', () => {
});
});
+describe('kimi sessions', () => {
+ const kimiRun = { providerId: 'kimi-cli', model: KIMI_MODEL, workspacePath: WORKSPACE, ...RUN_WINDOW };
+
+ it('measures a first-class kimi run from its usage.record lines', async () => {
+ await writeKimiSession({ agents: { main: [kimiUsageRecordLine({ timeMs: IN_WINDOW_MS, inputOther: 500, output: 120, inputCacheRead: 80 })] } });
+ const [record] = await reconcileRunUsage(kimiRun, { tokensIn: 1, tokensOut: 1 }, { home });
+ expect(record.source).toBe('measured');
+ expect(record.providerId).toBe('kimi-cli');
+ expect(record.tokensIn).toBe(500);
+ expect(record.cacheReadTokens).toBe(80);
+ expect(record.tokensOut).toBe(120);
+ expect(record.model).toBe(KIMI_MODEL);
+ });
+
+ it('reports no measured usage for a session that never completed a call', async () => {
+ await writeKimiSession({ agents: { main: [] } });
+ const record = await reconcileRunUsage(kimiRun, { tokensIn: 3, tokensOut: 4 }, { home });
+ expect(record.source).toBe('estimate');
+ expect(record.tokensIn).toBe(3);
+ });
+
+ it('ignores a session from another workspace', async () => {
+ await writeKimiSession({ cwd: '/tmp/other-workspace', agents: { main: [kimiUsageRecordLine({ timeMs: IN_WINDOW_MS })] } });
+ const record = await reconcileRunUsage(kimiRun, { tokensIn: 7, tokensOut: 9 }, { home });
+ expect(record.source).toBe('estimate');
+ expect(record.tokensIn).toBe(7);
+ });
+});
+
describe('nested sibling-family attribution', () => {
it('bills a nested grok review to grok, not to the Claude parent', async () => {
await writeClaudeSession('a.jsonl', [
@@ -1146,6 +1299,24 @@ describe('nested sibling-family attribution', () => {
expect(byProvider['grok-cli'].source).toBe('measured');
});
+ it('bills a nested kimi review to kimi, not to the Claude parent (#6045)', async () => {
+ await writeClaudeSession('a.jsonl', [
+ claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })
+ ]);
+ await writeKimiSession({ agents: { main: [kimiUsageRecordLine({ timeMs: IN_WINDOW_MS, inputOther: 300, output: 90 })] } });
+
+ const records = await reconcileRunUsage(claudeRun, { tokensIn: 1, tokensOut: 1 }, {
+ home,
+ providers: [CLAUDE_PROVIDER, KIMI_PROVIDER]
+ });
+ const byProvider = Object.fromEntries(records.map((record) => [record.providerId, record]));
+ expect(Object.keys(byProvider).sort()).toEqual(['claude-code', 'kimi-cli']);
+ expect(byProvider['claude-code'].tokensOut).toBe(50);
+ expect(byProvider['kimi-cli'].tokensIn).toBe(300);
+ expect(byProvider['kimi-cli'].tokensOut).toBe(90);
+ expect(byProvider['kimi-cli'].source).toBe('measured');
+ });
+
it('bills a nested Antigravity review as an estimate on the agy provider', async () => {
await writeClaudeSession('a.jsonl', [
claudeAssistant({ id: 'm1', timestamp: '2026-07-01T10:05:00.000Z' })